From 65516eb8b991ca73e2bf7c4ebe5f999474f77482 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=83=B3=E4=B8=8D=E5=87=BA=E5=88=AB=E5=90=8D?= Date: Sat, 11 Sep 2021 17:44:43 +0800 Subject: [PATCH 01/18] L1 & L2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 想不出别名 --- common/include/ipc/ipc_def.h | 56 +++ .../ipc/model/ipc_authenticate_device_req.h | 65 +++ .../ipc/model/ipc_check_authenticate_req.h | 40 ++ .../model/ipc_get_authenticationparam_rsp.h | 41 ++ .../ipc/model/ipc_get_trustdevice_req.h | 40 ++ .../ipc/model/ipc_get_trustdevice_rsp.h | 44 ++ .../ipc/model/ipc_notify_auth_result_req.h | 75 ++++ .../model/ipc_notify_check_auth_result_req.h | 64 +++ .../ipc/model/ipc_notify_device_found_req.h | 53 +++ .../ipc/model/ipc_notify_device_state_req.h | 53 +++ .../model/ipc_notify_discover_result_req.h | 53 +++ .../ipc/model/ipc_notify_dmfa_result_req.h | 55 +++ .../ipc/model/ipc_register_listener_req.h | 62 +++ common/include/ipc/model/ipc_req.h | 42 ++ common/include/ipc/model/ipc_rsp.h | 42 ++ .../ipc/model/ipc_set_useroperation_req.h | 41 ++ .../ipc/model/ipc_start_discovery_req.h | 42 ++ .../ipc/model/ipc_stop_discovery_req.h | 42 ++ .../native_cpp/include/ipc/ipc_client.h | 37 ++ .../native_cpp/include/ipc/ipc_client_proxy.h | 41 ++ .../include/ipc/lite/ipc_client_manager.h | 42 ++ .../ipc/lite/ipc_client_server_proxy.h | 45 ++ .../include/ipc/lite/ipc_client_stub.h | 43 ++ .../include/ipc/standard/ipc_client_manager.h | 58 +++ .../ipc/standard/ipc_client_server_proxy.h | 39 ++ .../include/ipc/standard/ipc_client_stub.h | 40 ++ .../include/ipc/standard/ipc_remote_broker.h | 38 ++ .../include/notify/device_manager_notify.h | 75 ++++ .../native_cpp/src/ipc/ipc_client_proxy.cpp | 48 +++ .../src/ipc/lite/ipc_client_manager.cpp | 92 +++++ .../src/ipc/lite/ipc_client_server_proxy.cpp | 134 ++++++ .../src/ipc/lite/ipc_client_stub.cpp | 57 +++ .../src/ipc/lite/ipc_cmd_parser.cpp | 287 +++++++++++++ .../src/ipc/standard/ipc_client_manager.cpp | 152 +++++++ .../ipc/standard/ipc_client_server_proxy.cpp | 47 +++ .../src/ipc/standard/ipc_client_stub.cpp | 45 ++ .../src/ipc/standard/ipc_cmd_parser.cpp | 390 ++++++++++++++++++ .../src/notify/device_manager_notify.cpp | 295 +++++++++++++ .../include/ipc/ipc_server_adapter.h | 53 +++ .../include/ipc/ipc_server_listener_adapter.h | 43 ++ .../include/ipc/lite/ipc_server_listener.h | 41 ++ .../include/ipc/lite/ipc_server_listenermgr.h | 50 +++ .../include/ipc/lite/ipc_server_stub.h | 26 ++ .../ipc/standard/ipc_server_client_proxy.h | 35 ++ .../ipc/standard/ipc_server_listener.h | 36 ++ .../include/ipc/standard/ipc_server_stub.h | 76 ++++ .../src/ipc/ipc_server_adapter.cpp | 189 +++++++++ .../src/ipc/ipc_server_listener_adapter.cpp | 129 ++++++ .../src/ipc/lite/ipc_cmd_parser.cpp | 215 ++++++++++ .../src/ipc/lite/ipc_server_listener.cpp | 90 ++++ .../src/ipc/lite/ipc_server_listenermgr.cpp | 65 +++ .../src/ipc/lite/ipc_server_main.cpp | 52 +++ .../src/ipc/lite/ipc_server_stub.cpp | 238 +++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 364 ++++++++++++++++ .../ipc/standard/ipc_server_client_proxy.cpp | 48 +++ .../src/ipc/standard/ipc_server_listener.cpp | 48 +++ .../src/ipc/standard/ipc_server_stub.cpp | 197 +++++++++ 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 | 148 +++++++ 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 ++++ 67 files changed, 5647 insertions(+) create mode 100644 common/include/ipc/ipc_def.h create mode 100644 common/include/ipc/model/ipc_authenticate_device_req.h create mode 100644 common/include/ipc/model/ipc_check_authenticate_req.h create mode 100644 common/include/ipc/model/ipc_get_authenticationparam_rsp.h create mode 100644 common/include/ipc/model/ipc_get_trustdevice_req.h create mode 100644 common/include/ipc/model/ipc_get_trustdevice_rsp.h create mode 100644 common/include/ipc/model/ipc_notify_auth_result_req.h create mode 100644 common/include/ipc/model/ipc_notify_check_auth_result_req.h create mode 100644 common/include/ipc/model/ipc_notify_device_found_req.h create mode 100644 common/include/ipc/model/ipc_notify_device_state_req.h create mode 100644 common/include/ipc/model/ipc_notify_discover_result_req.h create mode 100644 common/include/ipc/model/ipc_notify_dmfa_result_req.h create mode 100644 common/include/ipc/model/ipc_register_listener_req.h create mode 100644 common/include/ipc/model/ipc_req.h create mode 100644 common/include/ipc/model/ipc_rsp.h create mode 100644 common/include/ipc/model/ipc_set_useroperation_req.h create mode 100644 common/include/ipc/model/ipc_start_discovery_req.h create mode 100644 common/include/ipc/model/ipc_stop_discovery_req.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/ipc_client.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_manager.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_server_proxy.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_stub.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_manager.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_server_proxy.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_stub.h create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_remote_broker.h create mode 100644 interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/ipc_client_proxy.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_server_proxy.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_stub.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp create mode 100644 interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp create mode 100644 services/devicemanagerservice/include/ipc/ipc_server_adapter.h create mode 100644 services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h create mode 100644 services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h create mode 100644 services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h create mode 100644 services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp create mode 100644 services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp create mode 100644 services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp create mode 100644 services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp 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/include/ipc/ipc_def.h b/common/include/ipc/ipc_def.h new file mode 100644 index 000000000..e35af6f2c --- /dev/null +++ b/common/include/ipc/ipc_def.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DEVICE_MANAGER_IPC_DEF_H +#define DEVICE_MANAGER_IPC_DEF_H + +namespace OHOS { +namespace DistributedHardware { +#define DEVICE_MANAGER_SERVICE_NAME "dev_mgr_svc" +#define MAX_DM_IPC_LEN 4096 + +#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) + +enum IpcCmdID { + REGISTER_DEVICE_MANAGER_LISTENER = 0, + UNREGISTER_DEVICE_MANAGER_LISTENER, + GET_TRUST_DEVICE_LIST, + START_DEVICE_DISCOVER, + STOP_DEVICE_DISCOVER, + AUTHENTICATE_DEVICE, + CHECK_AUTHENTICATION, + SERVER_DEVICE_STATE_NOTIFY, + SERVER_DEVICE_FOUND, + SERVER_DISCOVER_FINISH, + SERVER_AUTH_RESULT, + SERVER_CHECK_AUTH_RESULT, + SERVER_GET_AUTHENTCATION_INFO, + SERVER_USER_AUTHORIZATION_OPERATION, + SERVER_DEVICEMANAGER_FA_NOTIFY, +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // DEVICE_MANAGER_IPC_DEF_H diff --git a/common/include/ipc/model/ipc_authenticate_device_req.h b/common/include/ipc/model/ipc_authenticate_device_req.h new file mode 100644 index 000000000..f4f066b3f --- /dev/null +++ b/common/include/ipc/model/ipc_authenticate_device_req.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_AUTHENTICATE_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_AUTHENTICATE_DEVICE_REQ_H + +#include "ipc_req.h" + +#include "dm_device_info.h" +#include "dm_app_image_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcAuthenticateDeviceReq : public IpcReq { +DECLARE_IPC_MODEL(IpcAuthenticateDeviceReq); +public: + const DmDeviceInfo& GetDeviceInfo() const + { + return deviceInfo_; + } + + void SetDeviceInfo(const DmDeviceInfo &deviceInfo) + { + deviceInfo_ = deviceInfo; + } + + const DmAppImageInfo& GetAppImageInfo() const + { + return appImageInfo_; + } + + void SetAppImageInfo(const DmAppImageInfo &appImageInfo) + { + appImageInfo_ = appImageInfo; + } + + const std::string& GetExtra() const + { + return extra_; + } + + void SetExtra(std::string &extra) + { + extra_ = extra; + } +private: + DmDeviceInfo deviceInfo_; + DmAppImageInfo appImageInfo_; + std::string extra_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..ea136b421 --- /dev/null +++ b/common/include/ipc/model/ipc_check_authenticate_req.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcCheckAuthenticateReq : public IpcReq { +DECLARE_IPC_MODEL(IpcCheckAuthenticateReq); +public: + const std::string& GetAuthPara() const + { + return authPara_; + } + + void SetAuthPara(std::string &authPara) + { + authPara_ = authPara; + } +private: + std::string authPara_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CHECK_AUTHENTICATE_REQ_H diff --git a/common/include/ipc/model/ipc_get_authenticationparam_rsp.h b/common/include/ipc/model/ipc_get_authenticationparam_rsp.h new file mode 100644 index 000000000..b12c39f68 --- /dev/null +++ b/common/include/ipc/model/ipc_get_authenticationparam_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_AUTH_PARAM_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_GET_AUTH_PARAM_RSP_H + +#include "ipc_rsp.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetAuthParamRsp : public IpcRsp { +DECLARE_IPC_MODEL(IpcGetAuthParamRsp); +public: + const DmAuthParam& GetAuthParam() const + { + return authParam_; + } + + void SetAuthParam(DmAuthParam &authParam) + { + authParam_ = authParam; + } +private: + DmAuthParam authParam_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_GET_AUTH_PARAM_RSP_H \ No newline at end of file diff --git a/common/include/ipc/model/ipc_get_trustdevice_req.h b/common/include/ipc/model/ipc_get_trustdevice_req.h new file mode 100644 index 000000000..695d87186 --- /dev/null +++ b/common/include/ipc/model/ipc_get_trustdevice_req.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_GET_TRUST_DEVICE_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_GET_TRUST_DEVICE_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetTrustdeviceReq : public IpcReq { +DECLARE_IPC_MODEL(IpcGetTrustdeviceReq); +public: + const std::string& GetExtra() const + { + return extra_; + } + + void SetExtra(std::string &extra) + { + extra_ = extra; + } +private: + std::string extra_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..6df09e883 --- /dev/null +++ b/common/include/ipc/model/ipc_get_trustdevice_rsp.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_GET_TRUSTDEVICE_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_GET_TRUSTDEVICE_RSP_H + +#include + +#include "dm_device_info.h" + +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetTrustdeviceRsp : public IpcRsp { +DECLARE_IPC_MODEL(IpcGetTrustdeviceRsp); +public: + std::vector GetDeviceVec() const + { + return deviceVec_; + } + + void SetDeviceVec(std::vector& deviceVec) + { + deviceVec_ = deviceVec; + } +private: + std::vector deviceVec_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..5fb8e53f7 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_auth_result_req.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_AUTH_RESULT_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_AUTH_RESULT_REQ_H + +#include + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyAuthResultReq : public IpcReq { +DECLARE_IPC_MODEL(IpcNotifyAuthResultReq); +public: + std::string GetDeviceId() const + { + return deviceId_; + } + + void SetDeviceId(std::string& deviceId) + { + deviceId_ = deviceId; + } + + int32_t GetPinToken() const + { + return pinToken_; + } + + void SetPinToken(int32_t pinToken) + { + pinToken_ = pinToken; + } + + int32_t GetStatus() const + { + return status_; + } + + void SetStatus(int32_t status) + { + status_ = status; + } + + int32_t GetReason() const + { + return reason_; + } + + void SetReason(int32_t reason) + { + reason_ = reason; + } +private: + std::string deviceId_; + int32_t pinToken_; + int32_t status_; + int32_t reason_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..f98db1e21 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_check_auth_result_req.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H + +#include + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyCheckAuthResultReq : public IpcReq { +DECLARE_IPC_MODEL(IpcNotifyCheckAuthResultReq); +public: + std::string GetDeviceId() const + { + return deviceId_; + } + + void SetDeviceId(std::string& deviceId) + { + deviceId_ = deviceId; + } + + int32_t GetResult() const + { + return result_; + } + + void SetResult(int32_t result) + { + result_ = result; + } + + int32_t GetFlag() const + { + return flag_; + } + + void SetFlag(int32_t flag) + { + flag_ = flag; + } +private: + std::string deviceId_; + int32_t result_; + int32_t flag_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_NOTIFY_CHECK_AUTH_RESULT_REQ_H diff --git a/common/include/ipc/model/ipc_notify_device_found_req.h b/common/include/ipc/model/ipc_notify_device_found_req.h new file mode 100644 index 000000000..7ffb99d88 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_device_found_req.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_FOUND_REQ_H +#define OHOS_DEVICE_MANAGER_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); +public: + const DmDeviceInfo& GetDeviceInfo() const + { + return dmDeviceInfo_; + } + + void SetDeviceInfo(DmDeviceInfo& dmDeviceInfo) + { + dmDeviceInfo_ = dmDeviceInfo; + } + + uint16_t GetSubscribeId() const + { + return subscribeId_; + } + + void SetSubscribeId(uint16_t subscribeId) + { + subscribeId_ = subscribeId; + } +private: + uint16_t subscribeId_; + DmDeviceInfo dmDeviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..2ae13ea04 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_device_state_req.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DEVICE_STATE_REQ_H +#define OHOS_DEVICE_MANAGER_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); +public: + int32_t GetDeviceState() const + { + return deviceState_; + } + + void SetDeviceState(int32_t deviceState) + { + deviceState_ = deviceState; + } + + const DmDeviceInfo& GetDeviceInfo() const + { + return dmDeviceInfo_; + } + + void SetDeviceInfo(DmDeviceInfo& dmDeviceInfo) + { + dmDeviceInfo_ = dmDeviceInfo; + } +private: + int32_t deviceState_; + DmDeviceInfo dmDeviceInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..00ea2e5d8 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_discover_result_req.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_NOTIFY_DISCOVER_RESULT_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_NOTIFY_DISCOVER_RESULT_REQ_H + +#include + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyDiscoverResultReq : public IpcReq { +DECLARE_IPC_MODEL(IpcNotifyDiscoverResultReq); +public: + uint16_t GetSubscribeId() const + { + return subscribeId_; + } + + void SetSubscribeId(uint16_t subscribeId) + { + subscribeId_ = subscribeId; + } + + int32_t GetResult() const + { + return result_; + } + + void SetResult(int32_t result) + { + result_ = result; + } +private: + uint16_t subscribeId_; + int32_t result_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..adbcf86cd --- /dev/null +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_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 GetPkgName() const + { + return PackageName_; + } + + void SetPkgName(std::string& pkgName) + { + PackageName_ = pkgName; + } + + std::string GetJsonParam() const + { + return JsonParam_; + } + + void SetJsonParam(std::string& JsonParam) + { + JsonParam_ = JsonParam; + } + + +private: + std::string PackageName_; + std::string JsonParam_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..67690a5b8 --- /dev/null +++ b/common/include/ipc/model/ipc_register_listener_req.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_IPC_REGISTER_LISTENER_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_REGISTER_LISTENER_REQ_H + +#include "ipc_req.h" + +#ifdef LITE_DEVICE +#include "liteipc_adapter.h" +#else +#include "iremote_stub.h" +#endif + +namespace OHOS { +namespace DistributedHardware { +class IpcRegisterListenerReq : public IpcReq { +DECLARE_IPC_MODEL(IpcRegisterListenerReq); +public: +#ifdef LITE_DEVICE + SvcIdentity GetSvcIdentity() const + { + return svcIdentity_; + } + + void SetSvcIdentity(SvcIdentity svcIdentity) + { + svcIdentity_ = svcIdentity; + } +#else + sptr GetListener() const + { + return listener_; + } + + void SetListener(sptr listener) + { + listener_ = listener; + } +#endif +private: +#ifdef LITE_DEVICE + SvcIdentity svcIdentity_; +#else + sptr listener_; +#endif +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_REGISTER_LISTENER_REQ_H diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h new file mode 100644 index 000000000..ac6e99d80 --- /dev/null +++ b/common/include/ipc/model/ipc_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_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_REQ_H + +#include + +#include "ipc_def.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcReq { +DECLARE_IPC_MODEL(IpcReq); +public: + const std::string& GetPkgName() const + { + return pkgName_; + } + + void SetPkgName(std::string &pkgName) + { + pkgName_ = pkgName; + } +private: + std::string pkgName_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_REQ_H diff --git a/common/include/ipc/model/ipc_rsp.h b/common/include/ipc/model/ipc_rsp.h new file mode 100644 index 000000000..14394280b --- /dev/null +++ b/common/include/ipc/model/ipc_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_DEVICE_MANAGER_IPC_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_RSP_H + +#include + +#include "ipc_def.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcRsp { +DECLARE_IPC_MODEL(IpcRsp); +public: + int32_t GetErrCode() const + { + return errCode_; + } + + void SetErrCode(int32_t errCode) + { + errCode_ = errCode; + } +private: + int32_t errCode_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..7c7416955 --- /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_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..341641e61 --- /dev/null +++ b/common/include/ipc/model/ipc_start_discovery_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_START_DISCOVERY_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_START_DISCOVERY_REQ_H + +#include "ipc_req.h" + +#include "dm_subscribe_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcStartDiscoveryReq : public IpcReq { +DECLARE_IPC_MODEL(IpcStartDiscoveryReq); +public: + const DmSubscribeInfo& GetSubscribeInfo() const + { + return subscribeInfo_; + } + + void SetSubscribeInfo(DmSubscribeInfo &subscribeInfo) + { + subscribeInfo_ = subscribeInfo; + } +private: + DmSubscribeInfo subscribeInfo_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..3497ec6f3 --- /dev/null +++ b/common/include/ipc/model/ipc_stop_discovery_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_STOP_DISCOVERY_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_STOP_DISCOVERY_REQ_H + +#include + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcStopDiscoveryReq : public IpcReq { +DECLARE_IPC_MODEL(IpcStopDiscoveryReq); +public: + uint16_t GetSubscribeId() const + { + return subscribeId_; + } + + void SetSubscribeId(uint16_t subscribeId) + { + subscribeId_ = subscribeId; + } +private: + uint16_t subscribeId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_STOP_DISCOVERY_REQ_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 new file mode 100644 index 000000000..818746ff7 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client.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_DEVICE_MANAGER_IPC_CLIENT_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_H + +#include +#include +#include + +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +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 SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_H \ No newline at end of file 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 new file mode 100644 index 000000000..faa9e1a4b --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.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_CLIENT_PROXY_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_PROXY_H + +#include +#include + +#include "ipc_client.h" +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcClientProxy : public IpcClient { +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 SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); +private: + std::shared_ptr ipcClientManager_ {nullptr}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..997b5d39b --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_manager.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_CLIENT_MANAGER_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H + +#include +#include +#include + +#include "ipc_client.h" +#include "ipc_client_server_proxy.h" + +namespace OHOS { +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 SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; +private: + bool IsInit(std::string &pkgName); +private: + IpcClientServerProxy serverProxy_; + std::set packageInitSet_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H \ No newline at end of file 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 new file mode 100644 index 000000000..d7497c55c --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_server_proxy.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H + +#include +#include +#include + +#include "iproxy_client.h" +#include "liteipc_adapter.h" +#include "samgr_lite.h" + +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcClientServerProxy { +public: + int32_t Init(); + int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); +private: + IClientProxy *GetServerProxy(void); + int32_t RegisterServerDeathCb(void); +private: + std::mutex lock_; + IClientProxy *serviceProxy_ {nullptr}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..672e4cb89 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/lite/ipc_client_stub.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H + +#include +#include + +#include "liteipc_adapter.h" + +#include "single_instance.h" + +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}; + SvcIdentity clientIdentity_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..422f29728 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_manager.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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_CLIENT_MANAGER_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_MANAGER_H + +#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" + +namespace OHOS { +namespace DistributedHardware { +class DmDeathRecipient : public IRemoteObject::DeathRecipient { +public: + void OnRemoteDied(const wptr &remote) override; + DmDeathRecipient() = default; + ~DmDeathRecipient() = default; +}; + +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 SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; +private: + bool IsInit(std::string &pkgName); + int32_t ClientInit(); +private: + std::mutex lock_; + std::map> dmListener_; + sptr dmInterface_ {nullptr}; + sptr dmRecipient_ {nullptr}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_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 new file mode 100644 index 000000000..3fd0586cd --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_server_proxy.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H + +#include +#include + +#include "iremote_proxy.h" +#include "ipc_remote_broker.h" +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcClientServerProxy : public IRemoteProxy { +public: + explicit IpcClientServerProxy(const sptr &impl) : IRemoteProxy(impl) {}; + ~IpcClientServerProxy() {}; + int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_SERVER_PROXY_H 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 new file mode 100644 index 000000000..61633f6e8 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_client_stub.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_CLIENT_STUB_H +#define OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H + +#include +#include + +#include "iremote_stub.h" +#include "iremote_broker.h" + +#include "ipc_remote_broker.h" +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcClientStub : public IRemoteStub { +public: + IpcClientStub() {}; + ~IpcClientStub() {}; + int32_t OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_CLIENT_STUB_H 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 new file mode 100644 index 000000000..b2b8618c7 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/ipc_remote_broker.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_DEVICE_MANAGER_IPC_REMOTE_BROKER_H +#define OHOS_DEVICE_MANAGER_IPC_REMOTE_BROKER_H + +#include +#include + +#include "iremote_broker.h" + +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcRemoteBroker : public OHOS::IRemoteBroker { +public: + virtual ~IpcRemoteBroker() {} + virtual int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) = 0; +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.devicemanager"); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_REMOTE_BROKER_H 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 new file mode 100644 index 000000000..14dc0dcf6 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_NOTIFY_H +#define OHOS_DEVICE_MANAGER_NOTIFY_H + +#include +#include +#include +#include + +#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); +public: + void RegisterDeathRecipientCallback(std::string &pkgName, std::shared_ptr dmInitCallback); + void UnRegisterDeathRecipientCallback(std::string &pkgName); + void RegisterDeviceStateCallback(std::string &pkgName, std::shared_ptr callback); + void UnRegisterDeviceStateCallback(std::string &pkgName); + void RegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId, + std::shared_ptr callback); + void UnRegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId); + void RegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId, + std::shared_ptr callback); + void UnRegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId); + void UnRegisterPackageCallback(std::string &pkgName); + void RegisterCheckAuthenticationCallback(std::string &pkgName, std::string &authPara, + std::shared_ptr callback); + void UnRegisterCheckAuthenticationCallback(std::string &pkgName); + void RegisterDeviceManagerFaCallback(std::string &packageName, + std::shared_ptr callback); + void UnRegisterDeviceManagerFaCallback(std::string &pkgName); + +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 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> dmInitCallback_; + std::map> dmFaCallback_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_NOTIFY_H 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 new file mode 100644 index 000000000..77cf6559d --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/ipc_client_proxy.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_client_proxy.h" + +#include "device_manager_log.h" +#include "device_manager_errno.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcClientProxy::Init(std::string &pkgName) +{ + if (ipcClientManager_ == nullptr) { + return DEVICEMANAGER_NULLPTR; + } + return ipcClientManager_->Init(pkgName); +} + +int32_t IpcClientProxy::UnInit(std::string &pkgName) +{ + if (ipcClientManager_ == nullptr) { + return DEVICEMANAGER_NULLPTR; + } + return ipcClientManager_->UnInit(pkgName); +} + +int32_t IpcClientProxy::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + if (req == nullptr || rsp == nullptr || ipcClientManager_ == nullptr) { + DMLOG(DM_LOG_INFO, "req,rsp or ipc client is null"); + return DEVICEMANAGER_NULLPTR; + } + return ipcClientManager_->SendRequest(cmdCode, req, rsp); +} +} // namespace DistributedHardware +} // namespace OHOS 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 new file mode 100644 index 000000000..26551b435 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_client_manager.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +#include "ipc_client_stub.h" +#include "ipc_register_listener_req.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcClientManager::Init(std::string &pkgName) +{ + if (IsInit(pkgName)) { + DMLOG(DM_LOG_INFO, "already init"); + return DEVICEMANAGER_OK; + } + if (serverProxy_.Init() != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "server proxy init failed."); + return DEVICEMANAGER_INIT_FAILED; + } + if (IpcClientStub::GetInstance().Init() != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "ipcclientstub init failed."); + return DEVICEMANAGER_INIT_FAILED; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetSvcIdentity(IpcClientStub::GetInstance().GetSvcIdentity()); + int32_t ret = serverProxy_.SendCmd(REGISTER_DEVICE_MANAGER_LISTENER, req, rsp); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); + return ret; + } + ret = rsp->GetErrCode(); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "DeviceManager::InitDeviceManager completed, pkgName: %s, ret=%d", pkgName.c_str(), ret); + return ret; + } + packageInitSet_.emplace(pkgName); + return DEVICEMANAGER_OK; +} + +int32_t IpcClientManager::UnInit(std::string &pkgName) +{ + DMLOG(DM_LOG_INFO, "UnInitDeviceManager in, pkgName %s", pkgName.c_str()); + if (!IsInit(pkgName)) { + return DEVICEMANAGER_FAILED; + } + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + int32_t ret = serverProxy_.SendCmd(UNREGISTER_DEVICE_MANAGER_LISTENER, req, rsp); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); + return ret; + } + packageInitSet_.erase(pkgName); + DMLOG(DM_LOG_INFO, "UnInitDeviceManager SUCCESS"); + return DEVICEMANAGER_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 serverProxy_.SendCmd(cmdCode, req, rsp); +} + +bool IpcClientManager::IsInit(std::string &pkgName) +{ + return (packageInitSet_.count(pkgName) > 0); +} +} // namespace DistributedHardware +} // namespace OHOS 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 new file mode 100644 index 000000000..88a0464dc --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_server_proxy.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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_client_server_proxy.h" + +#include "device_manager_log.h" +#include "device_manager_errno.h" +#include "device_manager_notify.h" + +#include "ipc_def.h" +#include "ipc_cmd_register.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const int32_t INVALID_CB_ID = 0xFF; +} +static uint32_t g_deathCbId = INVALID_CB_ID; +static SvcIdentity g_svcIdentity; +static std::shared_ptr pCurRsp; + +void __attribute__((weak)) HOS_SystemInit(void) +{ + SAMGR_Bootstrap(); + return; +} + +int32_t DMDeathCallback(const IpcContext *ctx, void *ipcMsg, IpcIo *data, void *arg) +{ + (void)ctx; + (void)ipcMsg; + (void)data; + (void)arg; + DMLOG(DM_LOG_INFO, "ATTENTION SERVICE (%s) DEAD !!!\n", DEVICE_MANAGER_SERVICE_NAME); + UnregisterDeathCallback(g_svcIdentity, g_deathCbId); + g_deathCbId = INVALID_CB_ID; + g_svcIdentity.handle = 0; + g_svcIdentity.token = 0; + g_svcIdentity.cookie = 0; + DeviceManagerNotify::GetInstance().OnRemoteDied(); + return DEVICEMANAGER_OK; +} + +static int32_t SendCmdResultCb(IOwner owner, int 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; +} + +IClientProxy *IpcClientServerProxy::GetServerProxy(void) +{ + IClientProxy *clientProxy = nullptr; + IUnknown *iUnknown = nullptr; + + DMLOG(DM_LOG_INFO, "start get client proxy"); + iUnknown = SAMGR_GetInstance()->GetDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME); + if (iUnknown == nullptr) { + return nullptr; + } + if (iUnknown->QueryInterface(iUnknown, CLIENT_PROXY_VER, (void **)&clientProxy) != DEVICEMANAGER_OK || + clientProxy == nullptr) { + DMLOG(DM_LOG_ERROR, "QueryInterface failed"); + } + return clientProxy; +} + +int IpcClientServerProxy::RegisterServerDeathCb(void) +{ + g_svcIdentity = SAMGR_GetRemoteIdentity(DEVICE_MANAGER_SERVICE_NAME, nullptr); + g_deathCbId = INVALID_CB_ID; + if (RegisterDeathCallback(nullptr, g_svcIdentity, DMDeathCallback, nullptr, &g_deathCbId) != EC_SUCCESS) { + DMLOG(DM_LOG_ERROR, "reg death callback failed"); + return DEVICEMANAGER_FAILED; + } + return DEVICEMANAGER_OK; +} + +int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + DMLOG(DM_LOG_INFO, "SendCmd:%d", cmdCode); + uint8_t data[MAX_DM_IPC_LEN] = {0}; + IpcIo request; + + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, request, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_FAILED; + } + { + std::lock_guard autoLock(lock_); + pCurRsp = rsp; + if (serviceProxy_ != nullptr && + serviceProxy_->Invoke(serviceProxy_, cmdCode, &request, &cmdCode, SendCmdResultCb) != 0) { + DMLOG(DM_LOG_ERROR, "serviceProxy_ invoke failed."); + return DEVICEMANAGER_FAILED; + } + } + DMLOG(DM_LOG_INFO, "SendCmd:%d end", cmdCode); + return DEVICEMANAGER_OK; +} + +int32_t IpcClientServerProxy::Init(void) +{ + if (serviceProxy_ != nullptr) { + DMLOG(DM_LOG_INFO, "ServerProxy already Init"); + return DEVICEMANAGER_OK; + } + HOS_SystemInit(); + serviceProxy_ = GetServerProxy(); + if (serviceProxy_ == nullptr) { + DMLOG(DM_LOG_ERROR, "get ipc client proxy failed"); + return DEVICEMANAGER_FAILED; + } + if (RegisterServerDeathCb() != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "register server death cb failed"); + return DEVICEMANAGER_FAILED; + } + DMLOG(DM_LOG_INFO, "ServerProxyInit ok"); + return DEVICEMANAGER_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 new file mode 100644 index 000000000..9ae99e19a --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_stub.cpp @@ -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. + */ + +#include "ipc_client_stub.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" +#include "device_manager_notify.h" + +#include "ipc_def.h" +#include "ipc_cmd_register.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcClientStub); + +static int32_t ClientIpcInterfaceMsgHandle(const IpcContext *ctx, void *ipcMsg, IpcIo *io, void *arg) +{ + (void)arg; + if (ipcMsg == nullptr || io == nullptr || ctx == nullptr) { + DMLOG(DM_LOG_ERROR, "invalid param"); + return DEVICEMANAGER_INVALID_PARAM; + } + + uint32_t code = 0; + GetCode(ipcMsg, &code); + DMLOG(DM_LOG_INFO, "receive ipc transact code(%u)", code); + return IpcCmdRegister::GetInstance().OnIpcCmd(code, *io, *ctx, ipcMsg); +} + +int32_t IpcClientStub::Init() +{ + std::lock_guard autoLock(lock_); + if (bInit) { + return DEVICEMANAGER_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; +} +} // 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 new file mode 100644 index 000000000..79dc594be --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp @@ -0,0 +1,287 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ipc_def.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" +#include "device_manager_notify.h" + +#include "dm_device_info.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_get_trustdevice_req.h" +#include "ipc_get_trustdevice_rsp.h" +#include "ipc_authenticate_device_req.h" +#include "ipc_check_authenticate_req.h" + +namespace OHOS { +namespace DistributedHardware { +ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + SvcIdentity svcIdentity = pReq->GetSvcIdentity(); + + IpcIoInit(&request, buffer, buffLen, 1); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushSvc(&request, &svcIdentity); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(REGISTER_DEVICE_MANAGER_LISTENER, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::string pkgName = pBaseReq->GetPkgName(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +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(); + std::string extra = pReq->GetExtra(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushString(&request, extra.c_str()); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + int32_t deviceNum = IpcIoPopInt32(&reply); + uint32_t deviceTotalSize = deviceNum * (int32_t)sizeof(DmDeviceInfo); + + if (deviceTotalSize > 0) { + std::vector deviceInfoVec; + DmDeviceInfo *pDmDeviceinfo = (DmDeviceInfo *)IpcIoPopFlatObj(&reply, &deviceTotalSize); + if (pDmDeviceinfo == nullptr) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList read node info failed!"); + pRsp->SetErrCode(DEVICEMANAGER_IPC_TRANSACTION_FAILED); + return DEVICEMANAGER_IPC_TRANSACTION_FAILED; + } + for (int32_t i = 0; i < deviceNum; ++i) { + pDmDeviceinfo = pDmDeviceinfo + i; + deviceInfoVec.emplace_back(*pDmDeviceinfo); + } + pRsp->SetDeviceVec(deviceInfoVec); + } + 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(); + const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushFlatObj(&request, &dmSubscribeInfo, sizeof(DmSubscribeInfo)); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushUint16(&request, subscribeId); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +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(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushString(&request, extra.c_str()); + IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); + // L1 暂时没有考虑appimage校验(8k限制) + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(CHECK_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(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, authPara.c_str()); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(CHECK_AUTHENTICATION, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply, const IpcContext &ctx, void *ipcMsg) +{ + size_t len = 0; + 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); + if (pkgName == "" || len == 0 || deviceInfo == NULL) { + DMLOG(DM_LOG_ERROR, "OnDeviceOnline, get para failed"); + FreeBuffer(&ctx, ipcMsg); + return; + } + switch (deviceState) { + case DEVICE_STATE_ONLINE: + DeviceManagerNotify::GetInstance().OnDeviceOnline(pkgName, *deviceInfo); + break; + case DEVICE_STATE_OFFLINE: + DeviceManagerNotify::GetInstance().OnDeviceOffline(pkgName, *deviceInfo); + break; + case DEVICE_INFO_CHANGED: + DeviceManagerNotify::GetInstance().OnDeviceChanged(pkgName, *deviceInfo); + break; + default: + DMLOG(DM_LOG_ERROR, "unknown device state:%d", deviceState); + break; + } + FreeBuffer(&ctx, ipcMsg); +} + +ON_IPC_CMD(SERVER_DEVICE_FOUND, IpcIo &reply, const IpcContext &ctx, void *ipcMsg) +{ + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(&reply, &len); + uint16_t subscribeId = IpcIoPopUint16(&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"); + FreeBuffer(&ctx, ipcMsg); + return; + } + DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, *deviceInfo); + FreeBuffer(&ctx, ipcMsg); +} + +ON_IPC_CMD(SERVER_DISCOVER_FINISH, IpcIo &reply, const IpcContext &ctx, void *ipcMsg) +{ + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(&reply, &len); + uint16_t subscribeId = IpcIoPopUint16(&reply); + int32_t failedReason = IpcIoPopInt32(&reply); + + if (pkgName == "" || len == 0) { + DMLOG(DM_LOG_ERROR, "OnDiscoverySuccess, get para failed"); + FreeBuffer(&ctx, ipcMsg); + return; + } + if (failedReason == DEVICEMANAGER_OK) { + DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); + } else { + DeviceManagerNotify::GetInstance().OnDiscoverFailed(pkgName, subscribeId, failedReason); + } + FreeBuffer(&ctx, ipcMsg); +} + +ON_IPC_CMD(SERVER_AUTH_RESULT, IpcIo &reply, const IpcContext &ctx, void *ipcMsg) +{ + size_t len = 0; + 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 status = IpcIoPopInt32(&reply); + int32_t reason = IpcIoPopInt32(&reply); + + if (pkgName == "" || len == 0 || deviceId == "" || devIdLen == 0) { + DMLOG(DM_LOG_ERROR, "OnAuthResult, get para failed"); + FreeBuffer(&ctx, ipcMsg); + return; + } + DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, pinToken, status, reason); + FreeBuffer(&ctx, ipcMsg); +} + +ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, IpcIo &reply, const IpcContext &ctx, void *ipcMsg) +{ + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(&reply, &len); + size_t devIdLen = 0; + std::string deviceId = (const char *)IpcIoPopString(&reply, &devIdLen); + int32_t resultCode = IpcIoPopInt32(&reply); + int32_t flag = IpcIoPopInt32(&reply); + + if (pkgName == "" || len == 0 || deviceId == "" || devIdLen == 0) { + DMLOG(DM_LOG_ERROR, "OnAuthResult, get para failed"); + FreeBuffer(&ctx, ipcMsg); + return; + } + DeviceManagerNotify::GetInstance().OnCheckAuthResult(pkgName, deviceId, resultCode, flag); + FreeBuffer(&ctx, ipcMsg); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp new file mode 100644 index 000000000..26d9fb927 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.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 "ipc_client_manager.h" + +#include "ipc_remote_broker.h" +#include "iremote_object.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" +#include "device_manager_notify.h" + +#include "ipc_register_listener_req.h" + +namespace OHOS { +namespace DistributedHardware { +void DmDeathRecipient::OnRemoteDied(const wptr &remote) +{ + (void)remote; + DMLOG(DM_LOG_WARN, "DmDeathRecipient : OnRemoteDied"); + DeviceManagerNotify::GetInstance().OnRemoteDied(); +} + +int32_t IpcClientManager::ClientInit() +{ + DMLOG(DM_LOG_INFO, "InitDeviceManagerService start"); + if (dmInterface_ != nullptr) { + DMLOG(DM_LOG_INFO, "DeviceManagerService Already Init"); + return DEVICEMANAGER_OK; + } + + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + DMLOG(DM_LOG_ERROR, "Get SystemAbilityManager Failed"); + return DEVICEMANAGER_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; + } + + if (dmRecipient_ == nullptr) { + dmRecipient_ = sptr(new DmDeathRecipient()); + } + if (!object->AddDeathRecipient(dmRecipient_)) { + DMLOG(DM_LOG_ERROR, "InitDeviceManagerService: AddDeathRecipient Failed"); + } + dmInterface_ = iface_cast(object); + DMLOG(DM_LOG_INFO, "DeviceManager::InitDeviceManagerService completed"); + return DEVICEMANAGER_OK; +} + +int32_t IpcClientManager::Init(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + int32_t ret = ClientInit(); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "InitDeviceManager Failed with ret %d", ret); + return ret; + } + if (dmListener_.count(pkgName) > 0) { + DMLOG(DM_LOG_INFO, "dmListener_ Already Init"); + return DEVICEMANAGER_OK; + } + + sptr listener = sptr(new IpcClientStub()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetListener(listener); + ret = dmInterface_->SendCmd(REGISTER_DEVICE_MANAGER_LISTENER, req, rsp); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "InitDeviceManager: RegisterDeviceManagerListener Failed with ret %d", ret); + return ret; + } + ret = rsp->GetErrCode(); + if (ret != DEVICEMANAGER_OK) { + return ret; + } + dmListener_[pkgName] = listener; + DMLOG(DM_LOG_INFO, "completed, pkgName: %s", pkgName.c_str()); + return DEVICEMANAGER_OK; +} + +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; + } + + std::lock_guard autoLock(lock_); + if (dmListener_.count(pkgName) > 0) { + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + int32_t ret = dmInterface_->SendCmd(UNREGISTER_DEVICE_MANAGER_LISTENER, req, rsp); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "UnRegisterDeviceManagerListener Failed with ret %d", ret); + return ret; + } + dmListener_.erase(pkgName); + } + if (dmListener_.empty()) { + dmInterface_ = nullptr; + dmRecipient_ = nullptr; + } + DMLOG(DM_LOG_INFO, "completed, pkgName: %s", pkgName.c_str()); + return DEVICEMANAGER_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 dmInterface_->SendCmd(cmdCode, req, rsp); +} + +bool IpcClientManager::IsInit(std::string &pkgName) +{ + if (dmInterface_ == nullptr) { + DMLOG(DM_LOG_ERROR, "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()); + return false; + } + return true; +} +} // namespace DistributedHardware +} // 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 new file mode 100644 index 000000000..75d0d1923 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_server_proxy.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_client_server_proxy.h" + +#include "ipc_cmd_register.h" +#include "ipc_types.h" + +#include "device_manager_log.h" +#include "device_manager_errno.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcClientServerProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DMLOG(DM_LOG_ERROR, "remote service null"); + return DEVICEMANAGER_NULLPTR; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_FAILED; + } + if (remote->SendRequest(cmdCode, data, reply, option) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); + return DEVICEMANAGER_IPC_FAILED; + } + return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/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 new file mode 100644 index 000000000..cbe30dd5b --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_stub.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_client_stub.h" + +#include "ipc_skeleton.h" +#include "ipc_types.h" + +#include "ipc_cmd_register.h" + +#include "device_manager_log.h" +#include "device_manager_errno.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcClientStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + DMLOG(DM_LOG_INFO, "code = %d, flags= %d.", code, option.GetFlags()); + if (IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply) == DEVICEMANAGER_OK) { + return DEVICEMANAGER_OK; + } + DMLOG(DM_LOG_WARN, "unsupport code: %d", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} + +int32_t IpcClientStub::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + DMLOG(DM_LOG_ERROR, "error"); + return DEVICEMANAGER_OK; +} +} // 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 new file mode 100644 index 000000000..88217e1bd --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -0,0 +1,390 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "securec.h" +#include "constants.h" +#include "device_manager_errno.h" +#include "device_manager_log.h" +#include "device_manager_notify.h" + +#include "ipc_def.h" +#include "ipc_register_listener_req.h" +#include "ipc_start_discovery_req.h" +#include "ipc_stop_discovery_req.h" +#include "ipc_get_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" + +namespace OHOS { +namespace DistributedHardware { +ON_IPC_SET_REQUEST(REGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + sptr listener = pReq->GetListener(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteRemoteObject(listener)) { + DMLOG(DM_LOG_ERROR, "write listener failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::string pkgName = pBaseReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write papam failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(GET_TRUST_DEVICE_LIST, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkg failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteString(extra)) { + DMLOG(DM_LOG_ERROR, "write extra failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, MessageParcel &reply, std::shared_ptr 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) { + std::vector deviceInfoVec; + DmDeviceInfo *pDmDeviceinfo = (DmDeviceInfo *)reply.ReadRawData(deviceTotalSize); + if (pDmDeviceinfo == nullptr) { + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList read node info failed!"); + pRsp->SetErrCode(DEVICEMANAGER_IPC_TRANSACTION_FAILED); + return DEVICEMANAGER_IPC_TRANSACTION_FAILED; + } + for (int32_t i = 0; i < deviceTotalSize; ++i) { + pDmDeviceinfo = pDmDeviceinfo + i; + deviceInfoVec.emplace_back(*pDmDeviceinfo); + } + pRsp->SetDeviceVec(deviceInfoVec); + } + pRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo))) { + DMLOG(DM_LOG_ERROR, "write subscribe info failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt16(subscribeId)) { + DMLOG(DM_LOG_ERROR, "write subscribeId failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(AUTHENTICATE_DEVICE, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string extra = pReq->GetExtra(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + DmAppImageInfo imageInfo = pReq->GetAppImageInfo(); + + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteString(extra)) { + DMLOG(DM_LOG_ERROR, "write extra failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { + DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + int32_t appIconLen = imageInfo.GetAppIconLen(); + int32_t appThumbnailLen = imageInfo.GetAppThumbnailLen(); + if (!data.WriteInt32(appIconLen)) { + DMLOG(DM_LOG_ERROR, "write imageinfo appicon len failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(appThumbnailLen)) { + DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnailLen failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (appIconLen > 0 && !data.WriteRawData(imageInfo.GetAppIcon(), appIconLen)) { + DMLOG(DM_LOG_ERROR, "write imageinfo appIcon failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (appThumbnailLen > 0 && !data.WriteRawData(imageInfo.GetAppThumbnail(), appThumbnailLen)) { + DMLOG(DM_LOG_ERROR, "write imageinfo appThumbnail failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(AUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(CHECK_AUTHENTICATION, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string authPara = pReq->GetAuthPara(); + if (!data.WriteString(authPara)) { + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(CHECK_AUTHENTICATION, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + DmDeviceState deviceState = static_cast(data.ReadInt32()); + DmDeviceInfo dmDeviceInfo; + 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; + } + switch (deviceState) { + case DEVICE_STATE_ONLINE: + DeviceManagerNotify::GetInstance().OnDeviceOnline(pkgName, dmDeviceInfo); + break; + case DEVICE_STATE_OFFLINE: + DeviceManagerNotify::GetInstance().OnDeviceOffline(pkgName, dmDeviceInfo); + break; + case DEVICE_INFO_CHANGED: + DeviceManagerNotify::GetInstance().OnDeviceChanged(pkgName, dmDeviceInfo); + break; + default: + DMLOG(DM_LOG_ERROR, "unknown device state:%d", deviceState); + break; + } + reply.WriteInt32(DEVICEMANAGER_OK); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_DEVICE_FOUND, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + uint16_t subscribeId = data.ReadInt16(); + DmDeviceInfo dmDeviceInfo; + 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; + } + DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, dmDeviceInfo); + reply.WriteInt32(DEVICEMANAGER_OK); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_DISCOVER_FINISH, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + uint16_t subscribeId = data.ReadInt16(); + int32_t failedReason = data.ReadInt32(); + + if (failedReason == DEVICEMANAGER_OK) { + DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); + } else { + DeviceManagerNotify::GetInstance().OnDiscoverFailed(pkgName, subscribeId, failedReason); + } + reply.WriteInt32(DEVICEMANAGER_OK); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string deviceId = data.ReadString(); + int32_t pinToken = data.ReadInt32(); + int32_t status = data.ReadInt32(); + int32_t reason = data.ReadInt32(); + + DeviceManagerNotify::GetInstance().OnAuthResult(pkgName, deviceId, pinToken, status, reason); + reply.WriteInt32(DEVICEMANAGER_OK); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string deviceId = data.ReadString(); + int32_t resultCode = data.ReadInt32(); + int32_t flag = data.ReadInt32(); + + DeviceManagerNotify::GetInstance().OnCheckAuthResult(pkgName, deviceId, resultCode, flag); + reply.WriteInt32(DEVICEMANAGER_OK); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_GET_AUTHENTCATION_INFO, std::shared_ptr pBaseReq, MessageParcel& data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagename = pReq->GetPkgName(); + if (!data.WriteString(packagename)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, MessageParcel& reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + DmAuthParam authParam; + authParam.direction = reply.ReadInt32(); + authParam.authType = reply.ReadInt32(); + if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { + authParam.pinToken = reply.ReadInt32(); + pRsp->SetAuthParam(authParam); + return DEVICEMANAGER_OK; + } + + authParam.packageName = reply.ReadString(); + authParam.appName = reply.ReadString(); + authParam.appDescription = reply.ReadString(); + authParam.business = reply.ReadInt32(); + authParam.pincode = reply.ReadInt32(); + + int32_t appIconLen = reply.ReadInt32(); + uint8_t *appIconBuffer = nullptr; + int32_t appThumbnailLen = reply.ReadInt32(); + uint8_t *appThumbBuffer = nullptr; + if (appIconLen > 0) { + appIconBuffer = (uint8_t *)reply.ReadRawData(appIconLen); + } + if (appThumbnailLen > 0) { + appThumbBuffer = (uint8_t *)reply.ReadRawData(appThumbnailLen); + } + authParam.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); + pRsp->SetAuthParam(authParam); + return DEVICEMANAGER_OK; +} + +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; +} +} // 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 new file mode 100644 index 000000000..bf8961b57 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_notify.h" + +#include "device_manager_log.h" +#include "device_manager_errno.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, + std::shared_ptr dmInitCallback) +{ + std::lock_guard autoLock(lock_); + dmInitCallback_[pkgName] = dmInitCallback; +} + +void DeviceManagerNotify::UnRegisterDeathRecipientCallback(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + dmInitCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDeviceStateCallback(std::string &pkgName, + std::shared_ptr callback) +{ + std::lock_guard autoLock(lock_); + deviceStateCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceStateCallback(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + deviceStateCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDiscoverCallback(std::string &pkgName, uint16_t subscribeId, + std::shared_ptr callback) +{ + std::lock_guard autoLock(lock_); + if (deviceDiscoverCallbacks_.count(pkgName) == 0) { + deviceDiscoverCallbacks_[pkgName] = std::map>(); + } + deviceDiscoverCallbacks_[pkgName][subscribeId] = callback; +} + +void DeviceManagerNotify::UnRegisterDiscoverCallback(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); + } + } +} + +void DeviceManagerNotify::RegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId, + std::shared_ptr callback) +{ + std::lock_guard autoLock(lock_); + if (authenticateCallback_.count(pkgName) == 0) { + authenticateCallback_[pkgName] = std::map>(); + } + authenticateCallback_[pkgName][deviceId] = callback; +} + +void DeviceManagerNotify::UnRegisterAuthenticateCallback(std::string &pkgName, std::string &deviceId) +{ + std::lock_guard autoLock(lock_); + if (authenticateCallback_.count(pkgName) > 0) { + authenticateCallback_[pkgName].erase(deviceId); + if (authenticateCallback_[pkgName].empty()) { + authenticateCallback_.erase(pkgName); + } + } +} + +void DeviceManagerNotify::UnRegisterPackageCallback(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + deviceStateCallback_.erase(pkgName); + deviceDiscoverCallbacks_.erase(pkgName); + authenticateCallback_.erase(pkgName); + dmInitCallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterCheckAuthenticationCallback(std::string &pkgName, std::string &authPara, + std::shared_ptr callback) +{ + std::lock_guard autoLock(lock_); + if (checkauthcallback_.count(pkgName) == 0) { + checkauthcallback_[pkgName] = std::map>(); + } + checkauthcallback_[pkgName][authPara] = callback; +} + +void DeviceManagerNotify::UnRegisterCheckAuthenticationCallback(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + deviceStateCallback_.erase(pkgName); + deviceDiscoverCallbacks_.erase(pkgName); + authenticateCallback_.erase(pkgName); + dmInitCallback_.erase(pkgName); + checkauthcallback_.erase(pkgName); +} + +void DeviceManagerNotify::RegisterDeviceManagerFaCallback(std::string &packageName, + std::shared_ptr callback) +{ + std::lock_guard autoLock(lock_); + dmFaCallback_[packageName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceManagerFaCallback(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + dmFaCallback_.erase(pkgName); +} + + +void DeviceManagerNotify::OnRemoteDied() +{ + DMLOG(DM_LOG_WARN, "DeviceManager : OnRemoteDied"); + for (auto iter : dmInitCallback_) { + iter.second->OnRemoteDied(); + } +} + +void DeviceManagerNotify::OnDeviceOnline(std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + DMLOG(DM_LOG_INFO, "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"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceOnline(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceOffline(std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + DMLOG(DM_LOG_INFO, "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"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceOffline(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceChanged(std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + DMLOG(DM_LOG_INFO, "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"); + return; + } + deviceStateCallback_[pkgName]->OnDeviceChanged(deviceInfo); +} + +void DeviceManagerNotify::OnDeviceFound(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"); + return; + } + std::map>& discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceFound: no register discoverCallback for subscribeId %d", + subscribeId); + return; + } + iter->second->OnDeviceFound(subscribeId, deviceInfo); +} + +void DeviceManagerNotify::OnDiscoverFailed(std::string &pkgName, uint16_t subscribeId, int32_t failedReason) +{ + DMLOG(DM_LOG_INFO, "DeviceManager OnDiscoverFailed pkgName:%s, subscribeId %d, reason %d", + pkgName.c_str(), subscribeId, failedReason); + std::lock_guard autoLock(lock_); + if (deviceDiscoverCallbacks_.count(pkgName) == 0) { + DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverFailed: no register discoverCallback for this package"); + return; + } + std::map>& discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverFailed: no register discoverCallback for subscribeId %d", + subscribeId); + return; + } + iter->second->OnDiscoverFailed(subscribeId, failedReason); +} + +void DeviceManagerNotify::OnDiscoverySuccess(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"); + return; + } + std::map>& discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter == discoverCallMap.end()) { + DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverySuccess: no register discoverCallback 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) +{ + DMLOG(DM_LOG_INFO, "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"); + 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 "); + return; + } + iter->second->OnAuthResult(deviceId, pinToken, 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) +{ + 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) { + DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register authCallback for this package"); + return; + } + std::map>& CheckAuthCallmap = checkauthcallback_[pkgName]; + auto iter = CheckAuthCallmap.find(deviceId); + if (iter == CheckAuthCallmap.end()) { + DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register CheckAuthCallmap for deviceID"); + return; + } + iter->second->OnCheckAuthResult(deviceId, resultCode, flag); + checkauthcallback_[pkgName].erase(deviceId); + if (checkauthcallback_[pkgName].empty()) { + 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); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/include/ipc/ipc_server_adapter.h b/services/devicemanagerservice/include/ipc/ipc_server_adapter.h new file mode 100644 index 000000000..b371e03a4 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/ipc_server_adapter.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H + +#include + +#include "dm_app_image_info.h" +#include "dm_device_info.h" +#include "dm_subscribe_info.h" + +#include "hichain_connector.h" + +#include "single_instance.h" +#include "softbus_adapter.h" +#include "ability_manager_interface.h" +#include "want.h" +#include "ipc_server_adapter.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerAdapter { +DECLARE_SINGLE_INSTANCE(IpcServerAdapter); +public: + int32_t ModuleInit(); + int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, DmDeviceInfo **info, int32_t *infoNum); + int32_t StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &dmSubscribeInfo); + int32_t StopDiscovery(std::string &pkgName, uint16_t subscribeId); + int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, + const DmAppImageInfo &imageInfo, std::string &extra); + int32_t CheckAuthentication(std::string &authPara); + int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam); + int32_t SetUserOperation(std::string &pkgName, int32_t action); + static int32_t GenRandInt(int32_t minPinToken, int32_t maxPinToken); +private: + int32_t CheckParamValid(nlohmann::json &extraJson, const DmAppImageInfo &imageInfo); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_ADAPTER_H diff --git a/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h b/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h new file mode 100644 index 000000000..e4b3e357d --- /dev/null +++ b/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H + +#include "discovery_service.h" + +#include "ipc_server_listener.h" + +#include "single_instance.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerListenerAdapter { +DECLARE_SINGLE_INSTANCE(IpcServerListenerAdapter); +public: + void OnDeviceStateChange(DmDeviceState state, DmDeviceInfo &deviceInfo); + void OnDeviceFound(std::string &pkgName, uint16_t originId, DmDeviceInfo &deviceInfo); + void OnDiscoverFailed(std::string &pkgName, uint16_t originId, DiscoveryFailReason failReason); + void OnDiscoverySuccess(std::string &pkgName, uint16_t originId); + void OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, uint32_t status, uint32_t reason); + void OnCheckAuthResult(std::string &pkgName, std::string &deviceId, int32_t resultCode, int32_t flag); + void OnFaCall(std::string &pkgName, std::string ¶mJson); +private: + IpcServerListener ipcServerListener_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_ADAPTER_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.h new file mode 100644 index 000000000..9503191aa --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listener.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_SERVER_LISTENER_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H + +#include + +#include "ipc_req.h" +#include "ipc_rsp.h" + +#include "ipc_server_listenermgr.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerListener { +public: + IpcServerListener() = default; + virtual ~IpcServerListener() = default; +public: + int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); +private: + void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity); + int32_t GetIdentityByPkgName(std::string &name, SvcIdentity *svc); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h new file mode 100644 index 000000000..3e39f8cce --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h @@ -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. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H + +#include +#include +#include +#include + +#include "liteipc_adapter.h" +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +typedef struct CommonSvcId { + unsigned int handle; + unsigned int token; + unsigned int cookie; + IpcContext *ipcCtx; + unsigned int cbId; +}CommonSvcId; + +class IpcServerListenermgr { +DECLARE_SINGLE_INSTANCE(IpcServerListenermgr); +public: + int32_t RegisterListener(std::string &pkgName, const CommonSvcId *svcId); + int32_t GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId); + int32_t UnregisterListener(std::string &pkgName); + const std::map &GetAllListeners(); +private: + std::map dmListenerMap_; + std::mutex lock_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_MGR_H diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h new file mode 100644 index 000000000..9baa73d4a --- /dev/null +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_stub.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H + +#include + +#include "liteipc_adapter.h" + +int32_t IpcServerStubInit(void); +int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply); +int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply); +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h new file mode 100644 index 000000000..15b5e44a4 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_client_proxy.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H + +#include "ipc_remote_broker.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerClientProxy : public IRemoteProxy { +public: + explicit IpcServerClientProxy(const sptr &impl) + : IRemoteProxy(impl) {}; + ~IpcServerClientProxy() {}; + int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; +private: + static inline BrokerDelegator delegator_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_CLIENT_PROXY_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h new file mode 100644 index 000000000..3737b7cde --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_listener.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H + +#include + +#include "ipc_req.h" +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcServerListener { +public: + IpcServerListener() = default; + virtual ~IpcServerListener() = default; +public: + int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_LISTENER_H diff --git a/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.h new file mode 100644 index 000000000..4e653eb97 --- /dev/null +++ b/services/devicemanagerservice/include/ipc/standard/ipc_server_stub.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_DEVICE_MANAGER_IPC_SERVER_STUB_H +#define OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H + +#include +#include +#include +#include +#include + +#include "nlohmann/json.hpp" + +#include "system_ability.h" +#include "thread_pool.h" +#include "iremote_stub.h" +#include "ipc_remote_broker.h" + +#include "single_instance.h" +#include "hichain_connector.h" + +namespace OHOS { +namespace DistributedHardware { +enum class ServiceRunningState { + STATE_NOT_START, + STATE_RUNNING +}; + +class AppDeathRecipient : public IRemoteObject::DeathRecipient { +public: + void OnRemoteDied(const wptr &remote) override; + AppDeathRecipient() = default; + ~AppDeathRecipient() = default; +}; + +class IpcServerStub : public SystemAbility, public IRemoteStub { +DECLARE_SYSTEM_ABILITY(IpcServerStub); +DECLARE_SINGLE_INSTANCE_BASE(IpcServerStub); +public: + void OnStart() override; + void OnStop() override; + int32_t OnRemoteRequest(uint32_t code, + MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + int32_t SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) override; + int32_t RegisterDeviceManagerListener(std::string &pkgName, sptr listener); + int32_t UnRegisterDeviceManagerListener(std::string &pkgName); + ServiceRunningState QueryServiceState() const; + const std::map> &GetDmListener(); + const sptr GetDmListener(std::string pkgName) const; +private: + IpcServerStub(); + ~IpcServerStub() = default; + bool Init(); +private: + bool registerToService_; + ServiceRunningState state_; + std::mutex listenerLock_; + std::map> appRecipient_; + std::map> dmListener_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_SERVER_STUB_H diff --git a/services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp b/services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp new file mode 100644 index 000000000..095dcebda --- /dev/null +++ b/services/devicemanagerservice/src/ipc/ipc_server_adapter.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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) +{ + DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); + NodeBasicInfo *nodeInfo = nullptr; + int32_t ret = SoftbusAdapter::GetTrustDevices(pkgName, &nodeInfo, infoNum); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "DM_GetSoftbusTrustDevices failed with ret %d", ret); + return ret; + } + *info = nullptr; + if (*infoNum > 0) { + *info = (DmDeviceInfo *)malloc(sizeof(DmDeviceInfo) * (*infoNum)); + } + for (int32_t i = 0; i < *infoNum; ++i) { + NodeBasicInfo *nodeBasicInfo = nodeInfo + i; + DmDeviceInfo *deviceInfo = *info + i; + + (void)memcpy_s(deviceInfo->deviceId, sizeof(deviceInfo->deviceId), nodeBasicInfo->networkId, + std::min(sizeof(deviceInfo->deviceId), sizeof(nodeBasicInfo->networkId))); + (void)memcpy_s(deviceInfo->deviceName, sizeof(deviceInfo->deviceName), nodeBasicInfo->deviceName, + std::min(sizeof(deviceInfo->deviceName), sizeof(nodeBasicInfo->deviceName))); + deviceInfo->deviceTypeId = (DMDeviceType)nodeBasicInfo->deviceTypeId; + } + FreeNodeInfo(nodeInfo); + DMLOG(DM_LOG_INFO, "success, pkgName:%s, deviceCount %d", pkgName.c_str(), *infoNum); + return DEVICEMANAGER_OK; +} + +int32_t IpcServerAdapter::StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &dmSubscribeInfo) +{ + DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), + (int32_t)dmSubscribeInfo.subscribeId); + + DMLOG(DM_LOG_INFO, "capability: %s", dmSubscribeInfo.capability); + SubscribeInfo subscribeInfo; + + subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; + subscribeInfo.mode = (DiscoverMode)dmSubscribeInfo.mode; + subscribeInfo.medium = (ExchanageMedium)dmSubscribeInfo.medium; + subscribeInfo.freq = (ExchangeFreq)dmSubscribeInfo.freq; + subscribeInfo.isSameAccount = dmSubscribeInfo.isSameAccount; + subscribeInfo.isWakeRemote = dmSubscribeInfo.isWakeRemote; + subscribeInfo.capability = dmSubscribeInfo.capability; + subscribeInfo.capabilityData = nullptr; + subscribeInfo.dataLen = 0; + return SoftbusAdapter::StartDiscovery(pkgName, &subscribeInfo); +} + +int32_t IpcServerAdapter::StopDiscovery(std::string &pkgName, uint16_t subscribeId) +{ + DMLOG(DM_LOG_INFO, "In, pkgName: %s, subscribeId %d", pkgName.c_str(), (int32_t)subscribeId); + return SoftbusAdapter::StopDiscovery(pkgName, subscribeId); +} + +int32_t IpcServerAdapter::AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, + const DmAppImageInfo &imageInfo, std::string &extra) +{ + if (pkgName.empty() || extra.empty()) { + DMLOG(DM_LOG_ERROR, "invalid para"); + return DEVICEMANAGER_INVALID_VALUE; + } + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (jsonObject.is_discarded()) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice extra jsonStr error"); + return DEVICEMANAGER_INVALID_VALUE; + } + int32_t ret = CheckParamValid(jsonObject, imageInfo); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "AuthenticateDevice para invalid, ret %d", ret); + return ret; + } + DMLOG(DM_LOG_INFO, "AuthenticateDevice In, pkgName: %s, deviceId %s", pkgName.c_str(), + GetAnonyString(deviceInfo.deviceId).c_str()); + + AuthManager::GetInstance().AuthDeviceGroup(pkgName, deviceInfo, imageInfo, extra); + return DEVICEMANAGER_OK; +} + +int32_t IpcServerAdapter::CheckAuthentication(std::string &authPara) +{ + if (authPara.empty()) { + DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication check authPara failed"); + return DEVICEMANAGER_INVALID_VALUE; + } + DMLOG(DM_LOG_INFO, " DeviceManagerIpcAdapter::CheckAuthentication"); + return AuthManager::GetInstance().CheckAuthentication(authPara); +} + +int32_t IpcServerAdapter::GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) +{ + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "invalid para"); + return DEVICEMANAGER_INVALID_VALUE; + } + + DmAbilityManager::GetInstance().StartAbilityDone(); + AuthManager::GetInstance().GetAuthenticationParam(authParam); + return DEVICEMANAGER_OK; +} + +int32_t IpcServerAdapter::SetUserOperation(std::string &pkgName, int32_t action) +{ + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "invalid para"); + return DEVICEMANAGER_INVALID_VALUE; + } + + AuthManager::GetInstance().OnUserOperate(action); + return SUCCESS; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp b/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp new file mode 100644 index 000000000..fe29635d2 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_listener_adapter.h" + +#include + +#include "securec.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" +#include "anonymous_string.h" + +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_check_auth_result_req.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_discover_result_req.h" +#include "ipc_notify_dmfa_result_req.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcServerListenerAdapter); + +void IpcServerListenerAdapter::OnDeviceStateChange(DmDeviceState state, DmDeviceInfo &deviceInfo) +{ + DMLOG(DM_LOG_INFO, "OnDeviceStateChange"); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetDeviceState(state); + pReq->SetDeviceInfo(deviceInfo); + ipcServerListener_.SendAll(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); +} + +void IpcServerListenerAdapter::OnDeviceFound(std::string &pkgName, uint16_t originId, + DmDeviceInfo &deviceInfo) +{ + DMLOG(DM_LOG_INFO, "call OnDeviceFound for %s, originId %d, deviceId %s", + pkgName.c_str(), originId, GetAnonyString(std::string(deviceInfo.deviceId)).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetSubscribeId(originId); + pReq->SetDeviceInfo(deviceInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); +} + +void IpcServerListenerAdapter::OnDiscoverFailed(std::string &pkgName, uint16_t originId, + DiscoveryFailReason failReason) +{ + DMLOG(DM_LOG_INFO, "OnDiscoverFailed"); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetSubscribeId(originId); + pReq->SetResult(failReason); + ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); +} + +void IpcServerListenerAdapter::OnDiscoverySuccess(std::string &pkgName, uint16_t originId) +{ + DMLOG(DM_LOG_INFO, "OnDiscoverySuccess"); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetSubscribeId(originId); + pReq->SetResult(DEVICEMANAGER_OK); + ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); +} + +void IpcServerListenerAdapter::OnAuthResult(std::string &pkgName, std::string &deviceId, int32_t pinToken, + uint32_t status, uint32_t reason) +{ + DMLOG(DM_LOG_INFO, "%s, package: %s, deviceId: %s", __FUNCTION__, pkgName.c_str(), + GetAnonyString(deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetDeviceId(deviceId); + pReq->SetPinToken(pinToken); + pReq->SetStatus(status); + pReq->SetReason(reason); + ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); +} + +void IpcServerListenerAdapter::OnCheckAuthResult(std::string &pkgName, std::string &authParam, int32_t resultCode, + int32_t flag) +{ + DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", + GetAnonyString(authParam).c_str(), resultCode); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + + pReq->SetPkgName(pkgName); + pReq->SetDeviceId(authParam); + pReq->SetResult(resultCode); + pReq->SetFlag(flag); + ipcServerListener_.SendRequest(SERVER_CHECK_AUTH_RESULT, pReq, pRsp); +} + +void IpcServerListenerAdapter::OnFaCall(std::string &pkgName, std::string ¶mJson) +{ + DMLOG(DM_LOG_INFO, "OnFaCallSuccess"); + 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 new file mode 100644 index 000000000..b4e185050 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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" + +#include "ipc_def.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_check_auth_result_req.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_discover_result_req.h" +#include "ipc_server_adapter.h" +#include "ipc_server_stub.h" + +namespace OHOS { +namespace DistributedHardware { +ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t deviceState = pReq->GetDeviceState(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushInt32(&request, deviceState); + IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushUint16(&request, subscribeId); + IpcIoPushFlatObj(&request, &deviceInfo, sizeof(DmDeviceInfo)); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + int32_t result = pReq->GetResult(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushUint16(&request, subscribeId); + IpcIoPushInt32(&request, result); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + int32_t pinToken = pReq->GetPinToken(); + int32_t status = pReq->GetStatus(); + int32_t reason = pReq->GetReason(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushString(&request, deviceId.c_str()); + IpcIoPushInt32(&request, pinToken); + IpcIoPushInt32(&request, status); + IpcIoPushInt32(&request, reason); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, IpcIo &request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + int32_t result = pReq->GetResult(); + int32_t flag = pReq->GetFlag(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushString(&request, deviceId.c_str()); + IpcIoPushInt32(&request, result); + IpcIoPushInt32(&request, flag); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) +{ + DMLOG(DM_LOG_INFO, "enter GetTrustedDeviceList."); + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(&req, &len); + std::string extra = (const char *)IpcIoPopString(&req, &len); + DmDeviceInfo *info = nullptr; + int32_t infoNum = 0; + int32_t ret = IpcServerAdapter::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); + IpcIoPushInt32(&reply, infoNum); + if (infoNum > 0) { + IpcIoPushFlatObj(&reply, info, sizeof(DmDeviceInfo) * infoNum); + free(info); + } + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(REGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) +{ + RegisterDeviceManagerListener(&req, &reply); +} + +ON_IPC_SERVER_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, IpcIo &req, IpcIo &reply) +{ + UnRegisterDeviceManagerListener(&req, &reply); +} + +ON_IPC_SERVER_CMD(START_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) +{ + DMLOG(DM_LOG_INFO, "StartDeviceDiscovery service listener."); + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(&req, &len); + uint32_t size = 0; + DmSubscribeInfo *pDmSubscribeInfo = (DmSubscribeInfo*)IpcIoPopFlatObj(&req, &size); + + int32_t ret = IpcServerAdapter::GetInstance().StartDeviceDiscovery(pkgName, *pDmSubscribeInfo); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) +{ + DMLOG(DM_LOG_INFO, "StopDeviceDiscovery service listener."); + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(&req, &len); + uint16_t subscribeId = IpcIoPopUint16(&req); + int32_t ret = IpcServerAdapter::GetInstance().StopDiscovery(pkgName, subscribeId); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(AUTHENTICATE_DEVICE, IpcIo &req, IpcIo &reply) +{ + DMLOG(DM_LOG_INFO, "AuthenticateDevice service listener."); + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(&req, &len); + size_t extraLen = 0; + std::string extra = (const char *)IpcIoPopString(&req, &extraLen); + uint32_t size; + DmDeviceInfo *deviceInfo = (DmDeviceInfo*)IpcIoPopFlatObj(&req, &size); + DmAppImageInfo imageInfo(nullptr, 0, nullptr, 0); + int32_t ret = IpcServerAdapter::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); + IpcIoPushInt32(&reply, ret); +} + +ON_IPC_SERVER_CMD(CHECK_AUTHENTICATION, IpcIo &req, IpcIo &reply) +{ + DMLOG(DM_LOG_INFO, "CheckAuthentication service listener."); + size_t authParaLen = 0; + std::string authPara = (const char *)IpcIoPopString(&req, &authParaLen); + int32_t ret = IpcServerAdapter::GetInstance().CheckAuthentication(authPara); + IpcIoPushInt32(&reply, ret); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp new file mode 100644 index 000000000..ad2141de8 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listener.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_listener.h" + +#include "device_manager_log.h" +#include "device_manager_errno.h" + +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_server_listenermgr.h" +#include "ipc_server_adapter.h" + +namespace OHOS { +namespace DistributedHardware { +void IpcServerListener::CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity) +{ + identity->handle = svcId->handle; + identity->token = svcId->token; + identity->cookie = svcId->cookie; +#ifdef __LINUX__ + identity->ipcContext = svcId->ipcCtx; +#endif +} + +int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity *svc) +{ + CommonSvcId svcId; + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(name, &svcId) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "get identity failed."); + return DEVICEMANAGER_FAILED; + } + CommonSvcToIdentity(&svcId, svc); + return DEVICEMANAGER_OK; +} + +int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + std::string pkgName = req->GetPkgName(); + SvcIdentity svc; + if (GetIdentityByPkgName(pkgName, &svc) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "ondevice found callback get listener failed."); + return DEVICEMANAGER_FAILED; + } + + IpcIo io; + uint8_t data[MAX_DM_IPC_LEN] = {0}; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_DEBUG, "SetRequest failed cmdCode:%d", cmdCode); + return DEVICEMANAGER_FAILED; + } + if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); + } + return DEVICEMANAGER_OK; +} + +int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); + for (auto &kv : listenerMap) { + SvcIdentity svc; + IpcIo io; + uint8_t data[MAX_DM_IPC_LEN] = {0}; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_DEBUG, "SetRequest failed cmdCode:%d", cmdCode); + continue; + } + CommonSvcId svcId = kv.second; + CommonSvcToIdentity(&svcId, &svc); + if (::SendRequest(nullptr, svc, cmdCode, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_DEBUG, "SendRequest failed cmdCode:%d", cmdCode); + } + } + return DEVICEMANAGER_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp new file mode 100644 index 000000000..59aec4fda --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_listenermgr.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_listenermgr.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcServerListenermgr); + +int32_t IpcServerListenermgr::RegisterListener(std::string &pkgName, const CommonSvcId *svcId) +{ + if (pkgName == "" || svcId == nullptr) { + DMLOG(DM_LOG_ERROR, "invalid param"); + return DEVICEMANAGER_FAILED; + } + DMLOG(DM_LOG_INFO, "new listener register:%s", pkgName.c_str()); + std::lock_guard autoLock(lock_); + dmListenerMap_[pkgName] = *svcId; + return DEVICEMANAGER_OK; +} + +int32_t IpcServerListenermgr::GetListenerByPkgName(std::string &pkgName, CommonSvcId *svcId) +{ + if (pkgName == "" || svcId == nullptr) { + DMLOG(DM_LOG_ERROR, "invalid param"); + return DEVICEMANAGER_FAILED; + } + std::lock_guard autoLock(lock_); + std::map::iterator iter = dmListenerMap_.find(pkgName); + if (iter == dmListenerMap_.end()) { + DMLOG(DM_LOG_ERROR, "listener not found for pkg:%s", pkgName.c_str()); + return DEVICEMANAGER_FAILED; + } + *svcId = iter->second; + return DEVICEMANAGER_OK; +} + +int32_t IpcServerListenermgr::UnregisterListener(std::string &pkgName) +{ + std::lock_guard autoLock(lock_); + dmListenerMap_.erase(pkgName); + return DEVICEMANAGER_OK; +} + +const std::map &IpcServerListenermgr::GetAllListeners() +{ + return dmListenerMap_; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.cpp new file mode 100644 index 000000000..c31c4a7ac --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_main.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 +#include + +#include "device_manager_log.h" +#include "device_manager_errno.h" + +#include "ipc_server_stub.h" +#include "ipc_server_adapter.h" + +using namespace OHOS::DistributedHardware; + +static void InitAll() +{ + const int32_t DM_SERVICE_INIT_DELAY = 5; + + sleep(DM_SERVICE_INIT_DELAY); + if (IpcServerStubInit() != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "IpcServerStubInit failed"); + return; + } + if (IpcServerAdapter::GetInstance().ModuleInit() != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "module init failed"); + return; + } + DMLOG(DM_LOG_INFO, "DM ipc server Init success"); +} + +int32_t main(int32_t argc, char *argv[]) +{ + (void)argc; + (void)argv; + InitAll(); + while (1) { + pause(); + } + return 0; +} \ No newline at end of file diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp new file mode 100644 index 000000000..a14342da7 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_stub.h" + +#include "securec.h" + +#include "liteipc_adapter.h" +#include "ohos_init.h" +#include "samgr_lite.h" +#include "iproxy_server.h" + +#include "device_manager_log.h" +#include "device_manager_errno.h" +#include "dm_subscribe_info.h" + +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_server_listenermgr.h" +#include "ipc_server_adapter.h" + +namespace { + const int32_t WAIT_FOR_SERVER = 2; + const int32_t STACK_SIZE = 0x800; + const int32_t QUEUE_SIZE = 20; +} + +using namespace OHOS::DistributedHardware; + +struct DefaultFeatureApi { + INHERIT_SERVER_IPROXY; +}; + +struct DeviceManagerSamgrService { + INHERIT_SERVICE; + INHERIT_IUNKNOWNENTRY(DefaultFeatureApi); + Identity identity; +}; + +static int32_t DeathCb(const IpcContext *context, void *ipcMsg, IpcIo *data, void *arg) +{ + (void)context; + (void)ipcMsg; + (void)data; + if (arg == NULL) { + DMLOG(DM_LOG_ERROR, "package name is NULL."); + return DEVICEMANAGER_INVALID_PARAM; + } + CommonSvcId svcId = {0}; + std::string pkgName = (const char *)arg; + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "not found client by package name."); + free(arg); + arg = NULL; + return DEVICEMANAGER_FAILED; + } + IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); + free(arg); + arg = NULL; +#ifdef __LINUX__ + BinderRelease(svcId.ipcCtx, svcId.handle); +#endif + SvcIdentity sid = {0}; + sid.handle = svcId.handle; + sid.token = svcId.token; + sid.cookie = svcId.cookie; + UnregisterDeathCallback(sid, svcId.cbId); + + return DEVICEMANAGER_OK; +} + +int32_t RegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) +{ + DMLOG(DM_LOG_INFO, "register service listener."); + size_t len = 0; + int32_t ret = DEVICEMANAGER_OK; + uint8_t *name = IpcIoPopString(req, &len); + SvcIdentity *svc = IpcIoPopSvc(req); + if (name == NULL || svc == NULL || len == 0) { + DMLOG(DM_LOG_ERROR, "get para failed"); + IpcIoPushInt32(reply, ret); + return DEVICEMANAGER_OK; + } + + CommonSvcId svcId = {0}; + svcId.handle = svc->handle; + svcId.token = svc->token; + svcId.cookie = svc->cookie; + + SvcIdentity sid = *svc; +#ifdef __LINUX__ + svcId.ipcCtx = svc->ipcContext; + BinderAcquire(svcId.ipcCtx, svcId.handle); + free(svc); + svc = NULL; +#endif + + char *pkgName = (char *)malloc(len + 1); + if (pkgName == NULL) { + DMLOG(DM_LOG_ERROR, "malloc failed!"); + IpcIoPushInt32(reply, DEVICEMANAGER_FAILED); + return DEVICEMANAGER_FAILED; + } + if (strcpy_s(pkgName, len + 1, (const char *)name) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "strcpy_s failed!"); + free(pkgName); + IpcIoPushInt32(reply, DEVICEMANAGER_FAILED); + return DEVICEMANAGER_FAILED; + } + uint32_t cbId = 0; + RegisterDeathCallback(NULL, sid, DeathCb, pkgName, &cbId); + svcId.cbId = cbId; + std::string strPkgName = (const char *)name; + ret = IpcServerListenermgr::GetInstance().RegisterListener(strPkgName, &svcId); + IpcIoPushInt32(reply, ret); + return DEVICEMANAGER_OK; +} + +int32_t UnRegisterDeviceManagerListener(IpcIo *req, IpcIo *reply) +{ + DMLOG(DM_LOG_INFO, "unregister service listener."); + size_t len = 0; + std::string pkgName = (const char *)IpcIoPopString(req, &len); + if (pkgName == "" || len == 0) { + DMLOG(DM_LOG_ERROR, "get para failed"); + return DEVICEMANAGER_FAILED; + } + + CommonSvcId svcId = {0}; + if (IpcServerListenermgr::GetInstance().GetListenerByPkgName(pkgName, &svcId) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "not found listener by package name."); + return DEVICEMANAGER_FAILED; + } + int32_t ret = IpcServerListenermgr::GetInstance().UnregisterListener(pkgName); + if (ret == DEVICEMANAGER_OK) { +#ifdef __LINUX__ + BinderRelease(svcId.ipcCtx, svcId.handle); +#endif + SvcIdentity sid = {0}; + sid.handle = svcId.handle; + sid.token = svcId.token; + sid.cookie = svcId.cookie; + ret = UnregisterDeathCallback(sid, svcId.cbId); + } + IpcIoPushInt32(reply, ret); + return DEVICEMANAGER_OK; +} + +static const char *GetName(Service *service) +{ + (void)service; + return DEVICE_MANAGER_SERVICE_NAME; +} + +static BOOL Initialize(Service *service, Identity identity) +{ + if (service == NULL) { + DMLOG(DM_LOG_WARN, "invalid param"); + return FALSE; + } + + DeviceManagerSamgrService *mgrService = (DeviceManagerSamgrService *)service; + mgrService->identity = identity; + return TRUE; +} + +static BOOL MessageHandle(Service *service, Request *request) +{ + if ((service == NULL) || (request == NULL)) { + DMLOG(DM_LOG_WARN, "invalid param"); + return FALSE; + } + return TRUE; +} + +static TaskConfig GetTaskConfig(Service *service) +{ + (void)service; + TaskConfig config = {LEVEL_HIGH, PRI_BELOW_NORMAL, STACK_SIZE, QUEUE_SIZE, SHARED_TASK}; + return config; +} + +static int32_t OnRemoteRequest(IServerProxy *iProxy, int funcId, void *origin, + IpcIo *req, IpcIo *reply) +{ + DMLOG(DM_LOG_INFO, "Receive funcId:%d", funcId); + (void)origin; + return IpcCmdRegister::GetInstance().OnIpcServerCmd(funcId, *req, *reply); +} + +static void HOS_SystemInit(void) +{ + SAMGR_Bootstrap(); + return; +} + +int32_t IpcServerStubInit(void) +{ + HOS_SystemInit(); + return DEVICEMANAGER_OK; +} + +static void DevMgrSvcInit(void) +{ + sleep(WAIT_FOR_SERVER); + static DeviceManagerSamgrService service = { + .GetName = GetName, + .Initialize = Initialize, + .MessageHandle = MessageHandle, + .GetTaskConfig = GetTaskConfig, + SERVER_IPROXY_IMPL_BEGIN, + .Invoke = OnRemoteRequest, + IPROXY_END, + }; + + if (!SAMGR_GetInstance()->RegisterService((Service *)&service)) { + DMLOG(DM_LOG_ERROR, "%s, RegisterService failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + if (!SAMGR_GetInstance()->RegisterDefaultFeatureApi(DEVICE_MANAGER_SERVICE_NAME, GET_IUNKNOWN(service))) { + DMLOG(DM_LOG_ERROR, "%s, RegisterDefaultFeatureApi failed", DEVICE_MANAGER_SERVICE_NAME); + return; + } + DMLOG(DM_LOG_INFO, "%s, init success", DEVICE_MANAGER_SERVICE_NAME); +} +SYSEX_SERVICE_INIT(DevMgrSvcInit); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp new file mode 100644 index 000000000..a2378158c --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -0,0 +1,364 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "constants.h" +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "ipc_notify_auth_result_req.h" +#include "ipc_notify_check_auth_result_req.h" +#include "ipc_notify_device_found_req.h" +#include "ipc_notify_device_state_req.h" +#include "ipc_notify_discover_result_req.h" +#include "ipc_server_adapter.h" +#include "ipc_server_stub.h" +#include "ipc_notify_dmfa_result_req.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +namespace OHOS { +namespace DistributedHardware { +ON_IPC_SET_REQUEST(SERVER_DEVICE_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t deviceState = pReq->GetDeviceState(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(deviceState)) { + DMLOG(DM_LOG_ERROR, "write state failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { + DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DEVICE_FOUND, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt16(subscribeId)) { + DMLOG(DM_LOG_ERROR, "write subscribeId failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteRawData(&deviceInfo, sizeof(DmDeviceInfo))) { + DMLOG(DM_LOG_ERROR, "write deviceInfo failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_FOUND, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_DISCOVER_FINISH, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + uint16_t subscribeId = pReq->GetSubscribeId(); + int32_t result = pReq->GetResult(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt16(subscribeId)) { + DMLOG(DM_LOG_ERROR, "write subscribeId failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DISCOVER_FINISH, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + int32_t pinToken = pReq->GetPinToken(); + int32_t status = pReq->GetStatus(); + int32_t reason = pReq->GetReason(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteString(deviceId)) { + DMLOG(DM_LOG_ERROR, "write deviceId failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(pinToken)) { + DMLOG(DM_LOG_ERROR, "write pinToken failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(status)) { + DMLOG(DM_LOG_ERROR, "write status failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(reason)) { + DMLOG(DM_LOG_ERROR, "write reason failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_CHECK_AUTH_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string deviceId = pReq->GetDeviceId(); + int32_t result = pReq->GetResult(); + int32_t flag = pReq->GetFlag(); + if (!data.WriteString(pkgName)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteString(deviceId)) { + DMLOG(DM_LOG_ERROR, "write deviceId failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteInt32(flag)) { + DMLOG(DM_LOG_ERROR, "write flag failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_CHECK_AUTH_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(GET_TRUST_DEVICE_LIST, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string extra = data.ReadString(); + DMLOG(DM_LOG_INFO, "pkgName:%s, extra:%s", pkgName.c_str(), extra.c_str()); + DmDeviceInfo *info = nullptr; + int32_t infoNum = 0; + int32_t result = IpcServerAdapter::GetInstance().GetTrustedDeviceList(pkgName, extra, &info, &infoNum); + reply.WriteInt32(infoNum); + if (infoNum > 0 && info != nullptr) { + if (!reply.WriteRawData(info, sizeof(DmDeviceInfo) * infoNum)) { + DMLOG(DM_LOG_ERROR, "write subscribeInfo failed"); + } + free(info); + } + if (!reply.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + sptr listener = data.ReadRemoteObject(); + int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + if (!reply.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + if (!reply.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + DmSubscribeInfo *subscribeInfo = (DmSubscribeInfo *)data.ReadRawData(sizeof(DmSubscribeInfo)); + DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeInfo->subscribeId); + int32_t result = IpcServerAdapter::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo); + if (!reply.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + uint16_t subscribeId = data.ReadInt32(); + DMLOG(DM_LOG_INFO, "pkgName:%s, subscribeId: %d", pkgName.c_str(), subscribeId); + int32_t result = IpcServerAdapter::GetInstance().StopDiscovery(pkgName, subscribeId); + if (!reply.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string extra = data.ReadString(); + DmDeviceInfo *deviceInfo = (DmDeviceInfo *)data.ReadRawData(sizeof(DmDeviceInfo)); + int32_t appIconLen = data.ReadInt32(); + int32_t appThumbnailLen = data.ReadInt32(); + uint8_t *appIcon = appIconLen > 0? (uint8_t *)data.ReadRawData(appIconLen) : nullptr; + uint8_t *appThumbnail = appThumbnailLen > 0? (uint8_t *)data.ReadRawData(appThumbnailLen) : nullptr; + DmAppImageInfo imageInfo(appIcon, appIconLen, appThumbnail, appThumbnailLen); + int32_t result = IpcServerAdapter::GetInstance().AuthenticateDevice(pkgName, *deviceInfo, imageInfo, extra); + if (!reply.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(CHECK_AUTHENTICATION, MessageParcel &data, MessageParcel &reply) +{ + std::string authPara = data.ReadString(); + int32_t result = IpcServerAdapter::GetInstance().CheckAuthentication(authPara); + if (!reply.WriteInt32(result)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &reply) +{ + std::string packName = data.ReadString(); + DmAuthParam authParam; + int32_t ret = DEVICEMANAGER_OK; + DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); + IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); + if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { + if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + !reply.WriteInt32(authParam.pinToken)) { + DMLOG(DM_LOG_ERROR,"DeviceManagerStub::wirte client fail"); + ret = DEVICEMANAGER_WRITE_FAILED; + } + return ret; + } + + int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); + int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); + if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + !reply.WriteString(authParam.packageName) || !reply.WriteString(authParam.appName) || + !reply.WriteString(authParam.appDescription) || !reply.WriteInt32(authParam.business) || + !reply.WriteInt32(authParam.pincode) || !reply.WriteInt32(appIconLen) || + !reply.WriteInt32(appThumbnailLen)) { + DMLOG(DM_LOG_ERROR, "write reply failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + + if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { + if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)){ + DMLOG(DM_LOG_ERROR, "write appIcon failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + } + + if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { + if (!reply.WriteRawData(authParam.imageinfo.GetAppThumbnail(), appThumbnailLen)) { + DMLOG(DM_LOG_ERROR, "write appThumbnail failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + } + + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParcel &reply) +{ + std::string packageName = data.ReadString(); + int32_t action = data.ReadInt32(); + int result = IpcServerAdapter::GetInstance().SetUserOperation(packageName, action); + + if (!reply.WriteInt32(action)) { + DMLOG(DM_LOG_ERROR, "write result failed"); + return DEVICEMANAGER_WRITE_FAILED; + } + return result; + +} +ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) +{ + DMLOG(DM_LOG_INFO, "OnFaCallBack"); + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagname = pReq->GetPkgName(); + std::string paramJson = pReq->GetJsonParam(); + if (!data.WriteString(packagname)) { + DMLOG(DM_LOG_ERROR, "write pkgName failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + if (!data.WriteString(paramJson)) + { + DMLOG(DM_LOG_ERROR, "write paramJson failed"); + return DEVICEMANAGER_FLATTEN_OBJECT; + } + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, MessageParcel& reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DEVICEMANAGER_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp new file mode 100644 index 000000000..6dc1a24c1 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_client_proxy.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_client_proxy.h" + +#include "ipc_types.h" + +#include "ipc_cmd_register.h" +#include "ipc_def.h" +#include "device_manager_log.h" +#include "device_manager_errno.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcServerClientProxy::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + sptr remote = Remote(); + if (remote == nullptr) { + DMLOG(DM_LOG_ERROR, "remote service null"); + return DEVICEMANAGER_NULLPTR; + } + + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_FAILED; + } + if (remote->SendRequest(cmdCode, data, reply, option) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "SendRequest fail, cmd:%d", cmdCode); + return DEVICEMANAGER_IPC_FAILED; + } + return IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp new file mode 100644 index 000000000..e08eaeab5 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_listener.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_listener.h" +#include "ipc_server_stub.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + std::string pkgName = req->GetPkgName(); + sptr listener = IpcServerStub::GetInstance().GetDmListener(pkgName); + if (listener == nullptr) { + DMLOG(DM_LOG_INFO, "cannot get listener for package:%s.", pkgName.c_str()); + return DEVICEMANAGER_NULLPTR; + } + return listener->SendCmd(cmdCode, req, rsp); +} + +int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + std::map> listeners = IpcServerStub::GetInstance().GetDmListener(); + for (auto iter : listeners) { + auto pkgName = iter.first; + auto remote = iter.second; + req->SetPkgName(pkgName); + sptr listener = iface_cast(remote); + listener->SendCmd(cmdCode, req, rsp); + } + return DEVICEMANAGER_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp new file mode 100644 index 000000000..c259394f5 --- /dev/null +++ b/services/devicemanagerservice/src/ipc/standard/ipc_server_stub.cpp @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_server_stub.h" + +#include +#include + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" + +#include "device_manager_errno.h" +#include "device_manager_log.h" + +#include "ipc_server_adapter.h" +#include "ipc_cmd_register.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(IpcServerStub); + +const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&IpcServerStub::GetInstance()); + +IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true) +{ + registerToService_ = false; + state_ = ServiceRunningState::STATE_NOT_START; +} + +void IpcServerStub::OnStart() +{ + DMLOG(DM_LOG_INFO, "IpcServerStub::OnStart start"); + if (state_ == ServiceRunningState::STATE_RUNNING) { + DMLOG(DM_LOG_DEBUG, "IpcServerStub has already started."); + return; + } + if (!Init()) { + DMLOG(DM_LOG_ERROR, "failed to init IpcServerStub"); + return; + } + state_ = ServiceRunningState::STATE_RUNNING; +} + +bool IpcServerStub::Init() +{ + DMLOG(DM_LOG_INFO, "IpcServerStub::Init ready to init."); + if (!registerToService_) { + bool ret = Publish(this); + if (!ret) { + DMLOG(DM_LOG_ERROR, "IpcServerStub::Init Publish failed!"); + return false; + } + registerToService_ = true; + } + + std::thread {[] { + IpcServerAdapter::GetInstance().ModuleInit(); + }}.detach(); + return true; +} + +void IpcServerStub::OnStop() +{ + DMLOG(DM_LOG_INFO, "IpcServerStub::OnStop ready to stop service."); + state_ = ServiceRunningState::STATE_NOT_START; + registerToService_ = false; +} + +int32_t IpcServerStub::OnRemoteRequest(uint32_t code, + MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + DMLOG(DM_LOG_INFO, "code = %d, flags= %d.", code, option.GetFlags()); + int32_t ret = DEVICEMANAGER_OK; + ret = IpcCmdRegister::GetInstance().OnIpcCmd(code, data, reply); + if (ret == DEVICEMANAGER_IPC_NOT_REGISTER_FUNC) { + DMLOG(DM_LOG_WARN, "unsupport code: %d", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return ret; +} + +int32_t IpcServerStub::SendCmd(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +{ + return DEVICEMANAGER_OK; +} + +ServiceRunningState IpcServerStub::QueryServiceState() const +{ + return state_; +} + +int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr listener) +{ + if (pkgName.empty() || listener == nullptr) { + DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); + return DEVICEMANAGER_NULLPTR; + } + + DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); + std::lock_guard autoLock(listenerLock_); + auto iter = dmListener_.find(pkgName); + if (iter != dmListener_.end()) { + DMLOG(DM_LOG_INFO, "RegisterDeviceManagerListener: listener already exists"); + return DEVICEMANAGER_OK; + } + + sptr appRecipient = sptr(new AppDeathRecipient()); + if (!listener->AddDeathRecipient(appRecipient)) { + DMLOG(DM_LOG_ERROR, "RegisterDeviceManagerListener: AddDeathRecipient Failed"); + } + dmListener_[pkgName] = listener; + appRecipient_[pkgName] = appRecipient; + return DEVICEMANAGER_OK; +} + +int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) +{ + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "Error: parameter invalid"); + return DEVICEMANAGER_NULLPTR; + } + + DMLOG(DM_LOG_INFO, "In, pkgName: %s", pkgName.c_str()); + std::lock_guard autoLock(listenerLock_); + auto listenerIter = dmListener_.find(pkgName); + if (listenerIter == dmListener_.end()) { + DMLOG(DM_LOG_INFO, "UnRegisterDeviceManagerListener: listener not exists"); + return DEVICEMANAGER_OK; + } + + auto recipientIter = appRecipient_.find(pkgName); + if (recipientIter == appRecipient_.end()) { + DMLOG(DM_LOG_INFO, "UnRegisterDeviceManagerListener: appRecipient not exists"); + dmListener_.erase(pkgName); + return DEVICEMANAGER_OK; + } + + auto listener = listenerIter->second; + auto appRecipient = recipientIter->second; + listener->RemoveDeathRecipient(appRecipient); + appRecipient_.erase(pkgName); + dmListener_.erase(pkgName); + return DEVICEMANAGER_OK; +} + +const std::map> &IpcServerStub::GetDmListener() +{ + return dmListener_; +} + +const sptr IpcServerStub::GetDmListener(std::string pkgName) const +{ + auto iter = dmListener_.find(pkgName); + if (iter == dmListener_.end()) { + return nullptr; + } + auto remote = iter->second; + sptr dmListener = iface_cast(remote); + return dmListener; +} + +void AppDeathRecipient::OnRemoteDied(const wptr &remote) +{ + DMLOG(DM_LOG_WARN, "AppDeathRecipient: OnRemoteDied"); + std::map> listeners = IpcServerStub::GetInstance().GetDmListener(); + std::string pkgName; + for (auto iter : listeners) { + if (iter.second == remote.promote()) { + pkgName = iter.first; + break; + } + } + if (pkgName.empty()) { + DMLOG(DM_LOG_ERROR, "AppDeathRecipient: OnRemoteDied, no pkgName matched"); + return; + } + DMLOG(DM_LOG_INFO, "AppDeathRecipient: OnRemoteDied for %s", pkgName.c_str()); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/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..6b52515aa --- /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, paraB, paraC) \ + static void IpcCmdProcess##cmdCode(paraA, paraB, paraC); \ + struct IpcRegisterCmdProcessFunc##cmdCode { \ + IpcRegisterCmdProcessFunc##cmdCode() \ + { \ + IpcCmdRegister::GetInstance().RegisterCmdProcessFunc(cmdCode, IpcCmdProcess##cmdCode); \ + } \ + }; \ + IpcRegisterCmdProcessFunc##cmdCode g_IpcRegisterCmdProcessFunc##cmdCode; \ + static void IpcCmdProcess##cmdCode(paraA, paraB, paraC) \ + +#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, const IpcContext &ctx, void *ipcMsg); +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, const IpcContext &ctx, void *ipcMsg); + 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..c3fdd4f3e --- /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 int INT32_SHORT_ID_LENGTH = 20; + const int INT32_PLAINTEXT_LENGTH = 4; + const int 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 int 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..11797a01e --- /dev/null +++ b/utils/src/cipher/encrypt_utils.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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, int plainTextLen, uint8_t *cipherText, + int cipherTextLen, int *outLen) +{ + 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) +{ + (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) +{ + if (szOut == nullptr || szOutLen <= 2) { + return false; + } + szOut[--szOutLen] = 0; + GetRandomData((uint8_t*)szOut, szOutLen); + const int NUMBER_COUNT = 10; + const int ALPHA_COUNT = 26; + int M = numberOnly ? NUMBER_COUNT : (NUMBER_COUNT + 2 * ALPHA_COUNT); + for (int i = 0; i < szOutLen; i++) { + // 0~9,A~Z,a~z + unsigned int idx = ((unsigned int)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..8faa2a22b --- /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, const IpcContext &ctx, void *ipcMsg) +{ + 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, ctx, ipcMsg); + 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 053007bf8dc7c278fed357177018b8ed876c9bbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=83=B3=E4=B8=8D=E5=87=BA=E5=88=AB=E5=90=8D?= Date: Sat, 11 Sep 2021 19:07:13 +0800 Subject: [PATCH 02/18] L1 & L2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 想不出别名 --- .../ipc/model/ipc_notify_dmfa_result_req.h | 2 -- .../include/notify/device_manager_notify.h | 5 ++--- .../src/ipc/lite/ipc_client_server_proxy.cpp | 1 + .../src/ipc/standard/ipc_cmd_parser.cpp | 14 +++++++------- utils/src/cipher/encrypt_utils.cpp | 16 +++++++++------- 5 files changed, 19 insertions(+), 19 deletions(-) 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 adbcf86cd..b76d26ba7 100644 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -44,8 +44,6 @@ public: { JsonParam_ = JsonParam; } - - private: std::string PackageName_; std::string JsonParam_; 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 14dc0dcf6..d49118a88 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,9 +46,8 @@ public: std::shared_ptr callback); void UnRegisterCheckAuthenticationCallback(std::string &pkgName); void RegisterDeviceManagerFaCallback(std::string &packageName, - std::shared_ptr callback); + std::shared_ptr callback); void UnRegisterDeviceManagerFaCallback(std::string &pkgName); - public: void OnRemoteDied(); void OnDeviceOnline(std::string &pkgName, const DmDeviceInfo &deviceInfo); @@ -60,7 +59,7 @@ 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); + void OnFaCall(std::string &pkgName, std::string ¶mJson); private: std::mutex lock_; std::map> deviceStateCallback_; 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 88a0464dc..922844c70 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 @@ -55,6 +55,7 @@ int32_t DMDeathCallback(const IpcContext *ctx, void *ipcMsg, IpcIo *data, void * static int32_t SendCmdResultCb(IOwner owner, int code, IpcIo *reply) { + (void)code; int32_t cmdCode = *(int32_t *)owner; DMLOG(DM_LOG_INFO, "SendCmdResultCb code:%d", cmdCode); (void)IpcCmdRegister::GetInstance().ReadResponse(cmdCode, *reply, pCurRsp); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index a2378158c..15935bb99 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -285,13 +285,14 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re std::string packName = data.ReadString(); DmAuthParam authParam; int32_t ret = DEVICEMANAGER_OK; - DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); + DMLOG(DM_LOG_ERROR, "GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + 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; + DMLOG(DM_LOG_ERROR, "wirte client fail"); + ret = DEVICEMANAGER_WRITE_FAILED; } return ret; } @@ -320,7 +321,6 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re return DEVICEMANAGER_WRITE_FAILED; } } - return DEVICEMANAGER_OK; } @@ -329,14 +329,14 @@ ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParc std::string packageName = data.ReadString(); int32_t action = data.ReadInt32(); int result = IpcServerAdapter::GetInstance().SetUserOperation(packageName, action); - + if (!reply.WriteInt32(action)) { DMLOG(DM_LOG_ERROR, "write result failed"); return DEVICEMANAGER_WRITE_FAILED; } return result; - } + ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, MessageParcel& data) { DMLOG(DM_LOG_INFO, "OnFaCallBack"); diff --git a/utils/src/cipher/encrypt_utils.cpp b/utils/src/cipher/encrypt_utils.cpp index 11797a01e..c97fc6934 100644 --- a/utils/src/cipher/encrypt_utils.cpp +++ b/utils/src/cipher/encrypt_utils.cpp @@ -98,7 +98,7 @@ int32_t EncryptUtils::GetRandomData(uint8_t *randStr, uint32_t len) } int32_t EncryptUtils::MbedtlsEncrypt(const uint8_t *plainText, int plainTextLen, uint8_t *cipherText, - int cipherTextLen, int *outLen) + int32_t cipherTextLen, int32_t *outLen) { if (memcpy_s(cipherText, cipherTextLen, plainText, plainTextLen) != DEVICEMANAGER_OK) { return DEVICEMANAGER_COPY_FAILED; @@ -119,17 +119,19 @@ int32_t EncryptUtils::MbedtlsDecrypt(const uint8_t *cipherText, int32_t cipherTe bool EncryptUtils::MbedtlsGenRandomStr(char *szOut, int32_t szOutLen, bool numberOnly) { - if (szOut == nullptr || szOutLen <= 2) { + 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 int NUMBER_COUNT = 10; - const int ALPHA_COUNT = 26; - int M = numberOnly ? NUMBER_COUNT : (NUMBER_COUNT + 2 * ALPHA_COUNT); - for (int i = 0; i < szOutLen; i++) { + 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 - unsigned int idx = ((unsigned int)szOut[i] % M); + uint32_t idx = ((uint32_t)szOut[i] % M); char base; if (idx < NUMBER_COUNT) { base = '0'; -- Gitee From 0a3abc43bd061c51fd3e1933aa01716cb25f4903 Mon Sep 17 00:00:00 2001 From: yuqianyuan Date: Sat, 11 Sep 2021 21:42:24 +0800 Subject: [PATCH 03/18] add files Signed-off-by: yuqianyuan --- common/include/constants.h | 159 +++++ common/include/device_manager_errno.h | 61 ++ .../include/device_manager_log.h | 55 +- common/{utils => }/include/single_instance.h | 2 +- devicemanager.gni | 6 + interfaces/inner_kits/native_cpp/BUILD.gn | 150 ++-- .../native_cpp/include/device_manager.h | 65 +- .../include/device_manager_callback.h | 20 +- .../native_cpp/include/device_manager_impl.h | 60 ++ .../include/device_manager_listener_stub.h | 64 -- .../native_cpp/include/device_manager_proxy.h | 49 -- .../native_cpp/include/dm_app_image_info.h | 129 ++++ .../native_cpp/include/dm_device_info.h | 39 +- .../native_cpp/include/dm_subscribe_info.h | 51 +- .../native_cpp/include/idevice_manager.h | 55 -- .../native_cpp/src/device_manager.cpp | 293 +------- .../native_cpp/src/device_manager_impl.cpp | 293 ++++++++ .../src/device_manager_listener_stub.cpp | 303 -------- .../native_cpp/src/device_manager_proxy.cpp | 316 --------- interfaces/kits/js/BUILD.gn | 40 +- interfaces/kits/js/include/dm_native_event.h | 2 +- .../kits/js/include/native_devicemanager_js.h | 88 ++- interfaces/kits/js/src/dm_native_event.cpp | 22 +- .../kits/js/src/native_devicemanager_js.cpp | 668 ++++++++++++++---- ohos.build | 8 +- services/devicemanagerservice/BUILD.gn | 232 ++++-- .../include/ability/dm_ability_manager.h | 119 ++-- .../hichain_connector.h} | 213 +++--- .../include/device_manager_listener_proxy.h | 44 -- .../include/device_manager_service.h | 98 --- .../msg_codec.h} | 98 ++- .../include/message/msg_head.h | 48 ++ .../include/message/msg_request_auth.h | 83 +++ .../msg_response_auth.h} | 113 +-- .../include/message/msg_sync_group.h | 77 +- .../auth_manager.h} | 110 +-- .../include/requestauth/request_session.h | 77 ++ .../include/requestauth/response_session.h | 126 ++-- .../include/softbus/softbus_adapter.h | 78 +- .../include/softbus/softbus_session.h | 111 ++- .../src/ability/dm_ability_manager.cpp | 94 +++ .../src/auth/hichain_connector.cpp | 415 +++++++++++ .../src/authdemo/device_client_channel.cpp | 166 ----- .../src/authdemo/device_server_channel.cpp | 205 ------ .../src/authdemo/hichain_adapter.cpp | 384 ---------- .../src/device_manager_listener_proxy.cpp | 294 -------- .../src/device_manager_service.cpp | 291 -------- .../src/device_manager_stub.cpp | 205 ------ .../src/ipc/standard/ipc_cmd_parser.cpp | 1 - .../src/message/msg_codec.cpp | 99 +++ .../src/message/msg_head.cpp | 102 +-- .../src/message/msg_request_auth.cpp | 375 ++++++++++ .../src/message/msg_response_auth.cpp | 160 +++++ .../src/message/msg_sync_group.cpp | 40 ++ .../src/requestauth/auth_manager.cpp | 238 +++++++ .../src/requestauth/request_session.cpp | 255 +++++++ .../src/requestauth/response_session.cpp | 291 ++++++++ .../src/softbus/softbus_adapter.cpp | 623 ++++++++-------- .../src/softbus/softbus_session.cpp | 230 ++++++ .../src/util/anonymous_string.cpp | 71 -- utils/BUILD.gn | 127 ++++ 61 files changed, 5174 insertions(+), 4117 deletions(-) create mode 100644 common/include/constants.h create mode 100644 common/include/device_manager_errno.h rename services/devicemanagerservice/include/util/anonymous_string.h => common/include/device_manager_log.h (67%) rename common/{utils => }/include/single_instance.h (96%) create mode 100644 interfaces/inner_kits/native_cpp/include/device_manager_impl.h delete mode 100644 interfaces/inner_kits/native_cpp/include/device_manager_listener_stub.h delete mode 100644 interfaces/inner_kits/native_cpp/include/device_manager_proxy.h create mode 100644 interfaces/inner_kits/native_cpp/include/dm_app_image_info.h delete mode 100644 interfaces/inner_kits/native_cpp/include/idevice_manager.h create mode 100644 interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp delete mode 100644 interfaces/inner_kits/native_cpp/src/device_manager_listener_stub.cpp delete mode 100644 interfaces/inner_kits/native_cpp/src/device_manager_proxy.cpp rename common/log/include/device_manager_log.h => services/devicemanagerservice/include/ability/dm_ability_manager.h (41%) rename services/devicemanagerservice/include/{authdemo/hichain_adapter.h => auth/hichain_connector.h} (38%) delete mode 100644 services/devicemanagerservice/include/device_manager_listener_proxy.h delete mode 100644 services/devicemanagerservice/include/device_manager_service.h rename services/devicemanagerservice/include/{authdemo/device_server_channel.h => message/msg_codec.h} (38%) create mode 100644 services/devicemanagerservice/include/message/msg_head.h create mode 100644 services/devicemanagerservice/include/message/msg_request_auth.h rename services/devicemanagerservice/include/{authdemo/device_client_channel.h => message/msg_response_auth.h} (38%) rename common/utils/include/device_manager_errno.h => services/devicemanagerservice/include/message/msg_sync_group.h (49%) rename services/devicemanagerservice/include/{device_manager_stub.h => requestauth/auth_manager.h} (31%) create mode 100644 services/devicemanagerservice/include/requestauth/request_session.h rename interfaces/inner_kits/native_cpp/include/idevice_manager_listener.h => services/devicemanagerservice/include/requestauth/response_session.h (32%) rename interfaces/inner_kits/native_cpp/src/dm_subscribe_info.cpp => services/devicemanagerservice/include/softbus/softbus_session.h (37%) create mode 100644 services/devicemanagerservice/src/ability/dm_ability_manager.cpp create mode 100644 services/devicemanagerservice/src/auth/hichain_connector.cpp delete mode 100644 services/devicemanagerservice/src/authdemo/device_client_channel.cpp delete mode 100644 services/devicemanagerservice/src/authdemo/device_server_channel.cpp delete mode 100644 services/devicemanagerservice/src/authdemo/hichain_adapter.cpp delete mode 100644 services/devicemanagerservice/src/device_manager_listener_proxy.cpp delete mode 100644 services/devicemanagerservice/src/device_manager_service.cpp delete mode 100644 services/devicemanagerservice/src/device_manager_stub.cpp create mode 100644 services/devicemanagerservice/src/message/msg_codec.cpp rename interfaces/inner_kits/native_cpp/src/dm_device_info.cpp => services/devicemanagerservice/src/message/msg_head.cpp (47%) create mode 100644 services/devicemanagerservice/src/message/msg_request_auth.cpp create mode 100644 services/devicemanagerservice/src/message/msg_response_auth.cpp create mode 100644 services/devicemanagerservice/src/message/msg_sync_group.cpp create mode 100644 services/devicemanagerservice/src/requestauth/auth_manager.cpp create mode 100644 services/devicemanagerservice/src/requestauth/request_session.cpp create mode 100644 services/devicemanagerservice/src/requestauth/response_session.cpp create mode 100644 services/devicemanagerservice/src/softbus/softbus_session.cpp delete mode 100644 services/devicemanagerservice/src/util/anonymous_string.cpp create mode 100644 utils/BUILD.gn diff --git a/common/include/constants.h b/common/include/constants.h new file mode 100644 index 000000000..d9e21679c --- /dev/null +++ b/common/include/constants.h @@ -0,0 +1,159 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_CONSTANTS_H +#define OHOS_DEVICE_MANAGER_CONSTANTS_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { + const std::string TARGET_PKG_NAME_KEY = "targetPkgName"; + const std::string HOST_PKG_NAME_KEY = "hostPackageName"; + + const int32_t LOG_MAX_LEN = 512; + const int32_t MIN_PIN_TOKEN = 10000000; + const int32_t MAX_PIN_TOKEN = 90000000; + const int32_t MIN_PIN_CODE = 100000; + const int32_t MAX_PIN_CODE = 999999; + const int32_t TOKEN_LEN = 9; + + const int32_t FAIL = -1; + const int32_t SUCCESS = 0; + const int32_t ERROR_INPUT_PARA_EMPTY = 2000; + const int32_t ERROR_INPUT_PARA_INVALID = 2001; + const int32_t ERROR_TARGET_PKG_NAME_NULL = 2002; + const int32_t ERROR_PKG_NAME_NOT_ON_DISCOVERY = 2003; + const int32_t ERROR_START_REMOTE_DM = 2006; + const int32_t ERROR_OPEN_CHANNEL_FAIL = 2008; + const int32_t ERROR_SEND_COMMAND_FAIL = 2009; + const int32_t ERROR_CHANNEL_BROKEN = 2010; + const int32_t ERROR_DUPLICATE_REQUEST = 2011; + const int32_t ERROR_TIME_OUT = 2012; + const int32_t ERROR_REQUEST_CANCEL = 2013; + const int32_t ERROR_USER_REJECT = 2015; + const int32_t ERROR_USER_BUSY = 2016; + const int32_t ERROR_API_NOT_SUPPORT = 2018; + const int32_t ERROR_SESSION_NOT_EXIT = 2019; + const int32_t ERROR_CREAT_GROUP_FAIL = 2020; + const int32_t ERROR_JOIN_GROUP_FAIL = 2021; + const int32_t ERROR_GET_LOCAL_DEVICE_INFO_FAIL = 2022; + const int32_t ERROR_CHECK_AUTH_FAIL = 2023; + const int32_t ERROR_NETWORK_UNAVAILABLE = 2028; + const int32_t ERROR_DEVICE_INFO_NULL = 2030; + const int32_t ERROR_APP_NAME_NULL = 2031; + const int32_t ERROR_APP_DESCRIPTION_INVALID = 2032; + const int32_t ERROR_APP_ICON_INVALID = 2033; + const int32_t ERROR_APP_THUMBNAIL_INVALID = 2034; + const int32_t ERROR_FA_START_FAIL = 2100; + + const int32_t ENCRYPT_TAG_LEN = 32; + + const std::string TAG_REQUESTER = "REQUESTER"; + const std::string TAG_TOKEN = "TOKEN"; + const std::string TAG_HOST = "HOST"; + const std::string TAG_TARGET = "TARGET"; + const std::string TAG_VISIBILITY = "VISIBILITY"; + const std::string TAG_GROUPIDS = "GROUPIDLIST"; + const std::string TAG_REPLY = "REPLY"; + const std::string TAG_NET_ID = "NETID"; + const std::string TAG_GROUP_ID = "GROUPID"; + const std::string TAG_GROUP_NAME = "GROUPNAME"; + const std::string TAG_REQUEST_ID = "REQUESTID"; + const std::string TAG_DEVICE_ID = "DEVICEID"; + const std::string TAG_DEVICE_TYPE = "DEVICETYPE"; + const std::string TAG_APP_NAME = "APPNAME"; + const std::string TAG_APP_DESCRIPTION = "APPDESC"; + const std::string TAG_APP_ICON = "APPICON"; + const std::string TAG_APP_THUMBNAIL = "APPTHUM"; + const std::string TAG_INDEX = "INDEX"; + const std::string TAG_SLICE_NUM = "SLICE"; + const std::string TAG_THUMBNAIL_SIZE = "THUMSIZE"; + const std::string TAG_AUTH_TYPE = "AUTHTYPE"; + + const std::string TAG_VER = "ITF_VER"; + const std::string TAG_TYPE = "MSG_TYPE"; + const std::string DM_ITF_VER = "1.0"; + const std::string TAG = "DM_MSG_CODEC"; + + // GroupConstants + const int32_t GROUP_VISIBILITY_IS_PUBLIC = -1; + const int32_t GROUP_VISIBILITY_IS_PRIVATE = 0; + const std::string REQUEST_AUTH_ADD_ID = "REQUEST_AUTH_ADD_ID"; + const std::string INVITATE_AUTH_ADD_ID = "INVITE_AUTH_ADD_ID"; + const int32_t PIN_CODE_INVALID = -1; + + // AuthConstants + const int32_t AUTH_SESSION_SIDE_SERVER = 0; + const int32_t AUTH_SESSION_SIDE_CLIENT = 1; + const int32_t SESSION_TYPE_IS_DEVICE_AUTH = 0; + const int32_t SESSION_TYPE_IS_APP_AUTH = 1; + const int32_t SESSION_REPLY_UNKNOWN = -1; + const int32_t SESSION_REPLY_ACCEPT = 0; + const int32_t SESSION_REPLY_CANCEL = 1; + const int32_t SESSION_REPLY_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; + + // DmService constants + const int32_t MSG_MAX_SIZE = 45 * 1024; + const int32_t DES_SLICE_MAX_NUM = 5; + const int32_t ABILITY_ON = 1; + const int32_t ABILITY_INVALID = -1; + const int32_t DES_MAX_LEN = 256; + const int32_t ICON_MAX_LEN = 32 * 1024; + const int32_t THUMB_MAX_LEN = 153 * 1024; + + const int32_t DEVICE_UUID_LENGTH = 65; + const int32_t GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP = 1; + const int32_t GROUP_TYPE_PEER_TO_PEER_GROUP = 256; + + const int32_t GROUP_VISIBILITY_PUBLIC = -1; + + const int32_t BUSINESS_FA_MIRGRATION = 0; + const int32_t BUSINESS_RESOURCE_ACCESS = 1; +} +} +#endif diff --git a/common/include/device_manager_errno.h b/common/include/device_manager_errno.h new file mode 100644 index 000000000..ab01276d9 --- /dev/null +++ b/common/include/device_manager_errno.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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/services/devicemanagerservice/include/util/anonymous_string.h b/common/include/device_manager_log.h similarity index 67% rename from services/devicemanagerservice/include/util/anonymous_string.h rename to common/include/device_manager_log.h index dd58b7384..fa0f776a3 100644 --- a/services/devicemanagerservice/include/util/anonymous_string.h +++ b/common/include/device_manager_log.h @@ -1,26 +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 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 +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_LOG_H +#define OHOS_DEVICE_MANAGER_LOG_H + +#include + +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +#define DMLOG(level, fmt, ...) DMLog(level, \ + (std::string("[") + DH_LOG_TAG + "][" + __FUNCTION__ + "]:" + fmt).c_str(), ##__VA_ARGS__) +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_LOG_H diff --git a/common/utils/include/single_instance.h b/common/include/single_instance.h similarity index 96% rename from common/utils/include/single_instance.h rename to common/include/single_instance.h index f149f90e7..a76aa07e2 100644 --- a/common/utils/include/single_instance.h +++ b/common/include/single_instance.h @@ -19,7 +19,7 @@ namespace OHOS { namespace DistributedHardware { #define DECLARE_SINGLE_INSTANCE_BASE(className) \ -public: \ +public: \ static className & GetInstance(); \ private: \ className(const className&) = delete; \ diff --git a/devicemanager.gni b/devicemanager.gni index 179cd6027..83db3519b 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -16,7 +16,13 @@ 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" +build_flags = [ + "-Werror", + "-Wall", + ] \ 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 dde1bdd95..275b19bc6 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -11,70 +11,116 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/ohos.gni") +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -config("dmnativeinnerkit_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "include", - "${common_path}/log/include", - "${common_path}/utils/include", - ] +if (defined(ohos_lite)) { + shared_library("devicemanagersdk") { + include_dirs = [ + "include", + "include/ipc", + "include/ipc/lite", + "include/notify", + "${utils_path}/include/log", + "${utils_path}/include/ipc/lite", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${common_path}/include", + ] + include_dirs += [ + "//utils/native/lite/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + "//third_party/json/include", + ] - cflags = [ - "-Wall", - "-Werror", - "-Wdate-time", - "-Wfloat-equal", - "-Wshadow", - "-Wformat=2", - "-fdata-sections", - "-ffunction-sections", - "-Os", - ] + sources = [ + "src/device_manager.cpp", + "src/device_manager_impl.cpp", + "src/ipc/ipc_client_proxy.cpp", + "src/ipc/lite/ipc_client_manager.cpp", + "src/ipc/lite/ipc_client_server_proxy.cpp", + "src/ipc/lite/ipc_client_stub.cpp", + "src/ipc/lite/ipc_cmd_parser.cpp", + "src/notify/device_manager_notify.cpp", + ] - cflags_cc = [ - "-Os", - ] -} + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit\"", + "LOG_DOMAIN=0xD004100", + ] -config("dmnativeinnerkit_public_config") { - include_dirs = [ "include" ] -} + cflags_cc = build_flags -ohos_shared_library("devicemanagersdk") { - sources = [ - "src/device_manager_proxy.cpp", - "src/device_manager_listener_stub.cpp", - "src/device_manager.cpp", - "src/dm_device_info.cpp", - "src/dm_subscribe_info.cpp", + deps = [ + "${utils_path}:devicemanagerutils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//foundation/communication/ipc_lite:liteipc_adapter", + "//foundation/distributedschedule/samgr_lite/samgr:samgr", + "//third_party/bounds_checking_function:libsec_shared", + "//utils/native/lite:utils", + ] + } +} else { + ohos_shared_library("devicemanagersdk") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "include", + "include/ipc/standard", + "include/ipc", + "include/notify", + "${utils_path}/include/log", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${utils_path}/include/ipc/standard", + "${common_path}/include", + "//third_party/json/include", ] - configs = [ ":dmnativeinnerkit_config" ] + sources = [ + "src/device_manager.cpp", + "src/device_manager_impl.cpp", + "src/ipc/ipc_client_proxy.cpp", + "src/ipc/standard/ipc_client_manager.cpp", + "src/ipc/standard/ipc_client_server_proxy.cpp", + "src/ipc/standard/ipc_client_stub.cpp", + "src/ipc/standard/ipc_cmd_parser.cpp", + "src/notify/device_manager_notify.cpp", + ] - public_configs = [ ":dmnativeinnerkit_public_config" ] + cflags_cc = build_flags - deps = [ "//utils/native/base:utils" ] + deps = [ + "${utils_path}:devicemanagerutils", + "//utils/native/base:utils", + ] - defines = [ - "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004100", - ] + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit\"", + "LOG_DOMAIN=0xD004100", + ] - external_deps = [ - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", - ] + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] - subsystem_name = "distributedhardware" + subsystem_name = "distributedhardware" - part_name = "device_manager_base" + part_name = "device_manager_base" + } } diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index a21f8a14c..5b8572dbf 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -13,54 +13,41 @@ * limitations under the License. */ -#ifndef OHOS_DEVICE_MANAGER_H -#define OHOS_DEVICE_MANAGER_H -#include "iremote_object.h" +#ifndef DEVICE_MANAGER_H +#define DEVICE_MANAGER_H -#include +#include +#include #include "device_manager_callback.h" -#include "device_manager_listener_stub.h" -#include "idevice_manager.h" -#include "single_instance.h" #include "dm_subscribe_info.h" +#include "dm_app_image_info.h" namespace OHOS { namespace DistributedHardware { -class DmDeathRecipient : public IRemoteObject::DeathRecipient { -public: - void OnRemoteDied(const wptr& remote) override; - DmDeathRecipient() = default; - ~DmDeathRecipient() = default; -}; - class DeviceManager { -friend class DmDeathRecipient; -DECLARE_SINGLE_INSTANCE(DeviceManager); public: - int32_t InitDeviceManager(std::string &packageName, std::shared_ptr dmInitCallback); - int32_t UnInitDeviceManager(std::string &packageName); - int32_t GetTrustedDeviceList(std::string &packageName, std::string &extra, - std::vector &deviceList); - int32_t RegisterDevStateCallback(std::string &packageName, std::string &extra, - std::shared_ptr callback); - int32_t UnRegisterDevStateCallback(std::string &packageName); - int32_t StartDeviceDiscovery(std::string &packageName, DmSubscribeInfo &subscribeInfo, - std::shared_ptr callback); - int32_t StopDeviceDiscovery(std::string &packageName, uint16_t subscribeId); - int32_t AuthenticateDevice(std::string &packageName, const DmDeviceInfo &deviceInfo, std::string &extra, - std::shared_ptr callback); - -private: - int32_t InitDeviceManagerService(); - bool IsInit(std::string &packageName); - -private: - std::mutex lock_; - sptr dmInterface_; - sptr dmRecipient_; - std::map> dmListener_; - std::map> dmInitCallback_; + static DeviceManager& GetInstance(); +public: + virtual int32_t InitDeviceManager(std::string &pkgName, std::shared_ptr dmInitCallback) = 0; + virtual int32_t UnInitDeviceManager(std::string &pkgName) = 0; + virtual int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, + std::vector &deviceList) = 0; + virtual int32_t RegisterDevStateCallback(std::string &pkgName, std::string &extra, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDevStateCallback(std::string &pkgName) = 0; + virtual int32_t StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &subscribeInfo, + std::shared_ptr callback) = 0; + virtual int32_t StopDeviceDiscovery(std::string &pkgName, uint16_t subscribeId) = 0; + virtual int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, + const DmAppImageInfo &imageInfo, std::string &extra, std::shared_ptr callback) = 0; + virtual int32_t CheckAuthentication(std::string &pkgName, std::string &authPara, + std::shared_ptr callback) = 0; + virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) = 0; + virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) = 0; + virtual int32_t RegisterDeviceManagerFaCallback(std::string &packageName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDeviceManagerFaCallback(std::string &pkgName) = 0; }; } // 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 58aff430f..a8ea7fb6a 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -15,6 +15,10 @@ #ifndef OHOS_DEVICE_MANAGER_CALLBACK_H #define OHOS_DEVICE_MANAGER_CALLBACK_H + +#include +#include + #include "dm_device_info.h" namespace OHOS { @@ -39,13 +43,25 @@ public: virtual ~DiscoverCallback() {} virtual void OnDiscoverySuccess(uint16_t subscribeId) = 0; virtual void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) = 0; - virtual void OnDeviceFound(uint16_t subscribeId, DmDeviceInfo &deviceInfo) = 0; + virtual void OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) = 0; }; class AuthenticateCallback { public: virtual ~AuthenticateCallback() {} - virtual void OnAuthResult(std::string &deviceId, int32_t status, int32_t reason) = 0; + virtual void OnAuthResult(std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) = 0; +}; + +class CheckAuthCallback { +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; }; } // 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 new file mode 100644 index 000000000..8e46f12fb --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IMPL_H +#define OHOS_DEVICE_MANAGER_IMPL_H + +#include + +#include "device_manager.h" + +#include "ipc_client_proxy.h" +#include "ipc_client_manager.h" + +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerImpl : public DeviceManager { +DECLARE_SINGLE_INSTANCE(DeviceManagerImpl); +public: + virtual int32_t InitDeviceManager(std::string &pkgName, + std::shared_ptr dmInitCallback) override; + virtual int32_t UnInitDeviceManager(std::string &pkgName) override; + virtual int32_t GetTrustedDeviceList(std::string &pkgName, std::string &extra, + std::vector &deviceList) override; + virtual int32_t RegisterDevStateCallback(std::string &pkgName, std::string &extra, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDevStateCallback(std::string &pkgName) override; + virtual int32_t StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &subscribeInfo, + std::shared_ptr callback) override; + virtual int32_t StopDeviceDiscovery(std::string &pkgName, uint16_t subscribeId) override; + virtual int32_t AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, + const DmAppImageInfo &imageInfo, std::string &extra, + std::shared_ptr callback) override; + virtual int32_t CheckAuthentication(std::string &pkgName, std::string &authPara, + std::shared_ptr callback) override; + virtual int32_t GetAuthenticationParam(std::string &pkgName, DmAuthParam &authParam) override; + virtual int32_t SetUserOperation(std::string &pkgName, int32_t action) override; + virtual int32_t RegisterDeviceManagerFaCallback(std::string &packageName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDeviceManagerFaCallback(std::string &pkgName) override; +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/device_manager_listener_stub.h b/interfaces/inner_kits/native_cpp/include/device_manager_listener_stub.h deleted file mode 100644 index 600b96457..000000000 --- a/interfaces/inner_kits/native_cpp/include/device_manager_listener_stub.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DEVICE_MANAGER_LISTENER_STUB_H -#define OHOS_DEVICE_MANAGER_LISTENER_STUB_H - -#include -#include "iremote_stub.h" -#include "idevice_manager_listener.h" - -#include "device_manager_callback.h" - -namespace OHOS { -namespace DistributedHardware { -class DeviceManagerListenerStub : public IRemoteStub { -public: - DeviceManagerListenerStub(); - ~DeviceManagerListenerStub(); - int32_t OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option) override; - int32_t OnDeviceOnline(std::string &packageName, const DmDeviceInfo &deviceInfo) override; - int32_t OnDeviceOffline(std::string &packageName, const DmDeviceInfo &deviceInfo) override; - int32_t OnDeviceChanged(std::string &packageName, const DmDeviceInfo &deviceInfo) override; - int32_t OnDeviceFound(std::string &packageName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo) override; - int32_t OnDiscoverFailed(std::string &packageName, uint16_t subscribeId, int32_t failedReason) override; - int32_t OnDiscoverySuccess(std::string &packageName, uint16_t subscribeId) override; - int32_t OnAuthResult(std::string &packageName, std::string &deviceId, int32_t status, int32_t reason) override; - void AddDeviceStateCallback(std::shared_ptr callback); - void RemoveDeviceStateCallback(); - void AddDiscoverCallback(uint16_t subscribeId, std::shared_ptr callback); - void RemoveDiscoverCallback(uint16_t subscribeId); - void AddAuthenticateCallback(std::string deviceId, std::shared_ptr callback); - -private: - template - int32_t GetParcelableInfo(MessageParcel &reply, T &parcelableInfo); - int32_t OnDeviceOnlineInner(MessageParcel &data, MessageParcel &reply); - int32_t OnDeviceOfflineInner(MessageParcel &data, MessageParcel &reply); - int32_t OnDeviceChangedInner(MessageParcel &data, MessageParcel &reply); - int32_t OnDeviceFoundInner(MessageParcel &data, MessageParcel &reply); - int32_t OnDiscoverFailedInner(MessageParcel &data, MessageParcel &reply); - int32_t OnDiscoverySuccessInner(MessageParcel &data, MessageParcel &reply); - int32_t OnAuthResultInner(MessageParcel &data, MessageParcel &reply); - - using ListenerFunc = int32_t (DeviceManagerListenerStub::*)(MessageParcel& data, MessageParcel& reply); - std::map memberFuncMap_; - std::shared_ptr deviceStateCallback_; - std::map> deviceDiscoverCallbacks_; - std::map> authenticateCallback_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LISTENER_STUB_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_proxy.h b/interfaces/inner_kits/native_cpp/include/device_manager_proxy.h deleted file mode 100644 index 8d8a9755f..000000000 --- a/interfaces/inner_kits/native_cpp/include/device_manager_proxy.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_DEVICE_MANAGER_PROXY_H -#define OHOS_DEVICE_MANAGER_PROXY_H - -#include "idevice_manager.h" -#include "iremote_proxy.h" - -namespace OHOS { -namespace DistributedHardware { -class DeviceManagerProxy : public IRemoteProxy { -public: - explicit DeviceManagerProxy(const sptr& impl) : IRemoteProxy(impl) {}; - ~DeviceManagerProxy() {}; - - int32_t GetTrustedDeviceList(std::string &packageName, std::string &extra, - std::vector &deviceList) override; - int32_t RegisterDeviceManagerListener(std::string &packageName, sptr listener) override; - int32_t UnRegisterDeviceManagerListener(std::string &packageName) override; - int32_t RegisterDeviceStateCallback(std::string &packageName, std::string &extra) override; - int32_t UnRegisterDeviceStateCallback(std::string &packageName) override; - int32_t StartDeviceDiscovery(std::string &packageName, DmSubscribeInfo &subscribeInfo) override; - int32_t StopDeviceDiscovery(std::string &packageName, uint16_t subscribeId) override; - int32_t AuthenticateDevice(std::string &packageName, const DmDeviceInfo &deviceInfo, std::string &extra) override; - -private: - template - int32_t GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); - bool WriteInterfaceToken(MessageParcel &data); - -private: - static inline BrokerDelegator delegator_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_PROXY_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 new file mode 100644 index 000000000..d9d18c8b3 --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/dm_app_image_info.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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_APP_IMAGE_INFO_H +#define OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H + +#include + +#include "securec.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAppImageInfo { +public: + DmAppImageInfo() = default; + explicit DmAppImageInfo(uint8_t *appIcon_, int32_t appIconLen_, uint8_t *appThumbnail_, int32_t appThumbnailLen_) + { + SaveData(appIcon_, appIconLen_, appThumbnail_, appThumbnailLen_); + } + + void Reset(uint8_t *appIcon_, int32_t appIconLen_, uint8_t *appThumbnail_, int32_t appThumbnailLen_) + { + SaveData(appIcon_, appIconLen_, appThumbnail_, appThumbnailLen_); + } + + ~DmAppImageInfo() + { + if (appIcon != nullptr) { + delete[] appIcon; + appIcon = nullptr; + } + if (appThumbnail != nullptr) { + delete[] appThumbnail; + appThumbnail = nullptr; + } + } + + DmAppImageInfo(const DmAppImageInfo &other) + { + if (this != &other) { + *this = other; + } + } + + DmAppImageInfo& operator= (const DmAppImageInfo &other) + { + if (this != &other) { + SaveData(other.GetAppIcon(), other.GetAppIconLen(), other.GetAppThumbnail(), other.GetAppThumbnailLen()); + } + return *this; + } + + DmAppImageInfo(DmAppImageInfo&&) = delete; + DmAppImageInfo& operator= (DmAppImageInfo&&) = delete; + + int32_t GetAppIconLen() const + { + return appIconLen; + } + + const uint8_t *GetAppIcon() const + { + return appIcon; + } + + int32_t GetAppThumbnailLen() const + { + return appThumbnailLen; + } + + const uint8_t *GetAppThumbnail() const + { + return appThumbnail; + } +private: + void SaveData(const uint8_t *appIcon_, int32_t appIconLen_, const uint8_t *appThumbnail_, int32_t appThumbnailLen_) + { + if (appIconLen_ > 0 && appIconLen_ < ICON_MAX_LEN && appIcon_ != nullptr) { + if (appIconLen < appIconLen_) { + if (appIcon != nullptr && appIconLen > 0) { + delete[] appIcon; + appIcon = nullptr; + appIconLen = 0; + } + appIcon = new (std::nothrow) uint8_t[appIconLen_] {0}; + } + if (appIcon != nullptr) { + appIconLen = appIconLen_; + (void)memcpy_s(appIcon, appIconLen, appIcon_, appIconLen_); + } + } + if (appThumbnailLen_ > 0 && appThumbnailLen_ < THUMB_MAX_LEN && appThumbnail_ != nullptr) { + if (appThumbnailLen < appThumbnailLen_) { + if (appThumbnail != nullptr && appThumbnailLen > 0) { + delete[] appThumbnail; + appThumbnail = nullptr; + appThumbnailLen = 0; + } + appThumbnail = new (std::nothrow) uint8_t[appThumbnailLen_] {0}; + } + if (appThumbnail != nullptr) { + appThumbnailLen = appThumbnailLen_; + (void)memcpy_s(appThumbnail, appThumbnailLen, appThumbnail_, appThumbnailLen_); + } + } + } +private: + int32_t appIconLen {0}; + uint8_t *appIcon {nullptr}; + int32_t appThumbnailLen {0}; + uint8_t *appThumbnail {nullptr}; + const int32_t ICON_MAX_LEN = 32 * 1024; + const int32_t THUMB_MAX_LEN = 153 * 1024; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_APP_IMAGE_INFO_H 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 58952222e..45ccf822c 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -16,11 +16,16 @@ #ifndef OHOS_DEVICE_MANAGER_DEVICE_INFO_H #define OHOS_DEVICE_MANAGER_DEVICE_INFO_H -#include "parcel.h" +#include + +#include "dm_app_image_info.h" + +#define DM_MAX_DEVICE_ID_LEN (96) +#define DM_MAX_DEVICE_NAME_LEN (65) namespace OHOS { namespace DistributedHardware { -enum DMDeviceType : uint8_t { +typedef enum DMDeviceType { DEVICE_TYPE_UNKNOWN = 0x00, DEVICE_TYPE_WIFI_CAMERA = 0x08, DEVICE_TYPE_AUDIO = 0x0A, @@ -30,22 +35,32 @@ enum DMDeviceType : uint8_t { DEVICE_TYPE_WATCH = 0x6D, DEVICE_TYPE_CAR = 0x83, DEVICE_TYPE_TV = 0x9C, -}; +} DMDeviceType; -enum DmDeviceState : uint8_t { +typedef enum DmDeviceState { DEVICE_STATE_UNKNOWN = 0, DEVICE_STATE_ONLINE = 1, DEVICE_STATE_OFFLINE = 2, -}; + DEVICE_INFO_CHANGED = 3, +} DmDeviceState; -struct DmDeviceInfo : public Parcelable { - std::string deviceId; - std::string deviceName; +typedef struct DmDeviceInfo { + char deviceId[DM_MAX_DEVICE_ID_LEN]; + char deviceName[DM_MAX_DEVICE_NAME_LEN]; DMDeviceType deviceTypeId; - bool ReadFromParcel(Parcel &parcel); - virtual bool Marshalling(Parcel &parcel) const override; - static DmDeviceInfo *Unmarshalling(Parcel &parcel); -}; +} DmDeviceInfo; + +typedef struct DmAuthParam { + 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; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DEVICE_MANAGER_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 2a6f982ee..9e4b24499 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h @@ -16,49 +16,51 @@ #ifndef OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H #define OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H -#include "parcel.h" +#include + +#define DM_MAX_DEVICE_CAPABILITY_LEN 65 namespace OHOS { namespace DistributedHardware { -enum DmDiscoverMode : int32_t { +typedef enum DmDiscoverMode { /* Passive */ - DISCOVER_MODE_PASSIVE = 0x55, + DM_DISCOVER_MODE_PASSIVE = 0x55, /* Proactive */ - DISCOVER_MODE_ACTIVE = 0xAA -}; + DM_DISCOVER_MODE_ACTIVE = 0xAA +} DmDiscoverMode; -enum DmExchangeMedium : int32_t { +typedef enum DmExchangeMedium { /** Automatic medium selection */ - AUTO = 0, + DM_AUTO = 0, /** Bluetooth */ - BLE = 1, + DM_BLE = 1, /** Wi-Fi */ - COAP = 2, + DM_COAP = 2, /** USB */ - USB = 3, - MEDIUM_BUTT -}; + DM_USB = 3, + DM_MEDIUM_BUTT +} DmExchangeMedium; /** * @brief Enumerates frequencies for publishing services. * * This enumeration applies only to Bluetooth and is not supported currently. */ -enum DmExchangeFreq : int32_t { +typedef enum DmExchangeFreq { /** Low */ - LOW = 0, + DM_LOW = 0, /** Medium */ - MID = 1, + DM_MID = 1, /** High */ - HIGH = 2, + DM_HIGH = 2, /** Super-high */ - SUPER_HIGH = 3, - FREQ_BUTT -}; + DM_SUPER_HIGH = 3, + DM_FREQ_BUTT +} DmExchangeFreq; -const std::string DM_CAPABILITY_DDMP = "ddmpCapability"; +const static char *DM_CAPABILITY_OSD = "osdCapability"; -struct DmSubscribeInfo : public Parcelable { +typedef struct DmSubscribeInfo { /** Service ID */ uint16_t subscribeId; /** Discovery mode for service subscription. For details, see {@link DmDiscoverMode}. */ @@ -72,11 +74,8 @@ struct DmSubscribeInfo : public Parcelable { /** find the sleeping devices */ bool isWakeRemote; /** Service subscription capability. */ - std::string capability; - bool ReadFromParcel(Parcel &parcel); - virtual bool Marshalling(Parcel &parcel) const override; - static DmSubscribeInfo *Unmarshalling(Parcel &parcel); -}; + char capability[DM_MAX_DEVICE_CAPABILITY_LEN]; +} DmSubscribeInfo; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DEVICE_MANAGER_SUBSCRIBE_INFO_H diff --git a/interfaces/inner_kits/native_cpp/include/idevice_manager.h b/interfaces/inner_kits/native_cpp/include/idevice_manager.h deleted file mode 100644 index b71235000..000000000 --- a/interfaces/inner_kits/native_cpp/include/idevice_manager.h +++ /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. - */ - -#ifndef OHOS_DEVICE_MANAGER_INTERFACE_H -#define OHOS_DEVICE_MANAGER_INTERFACE_H - -#include "iremote_broker.h" -#include "dm_device_info.h" -#include "dm_subscribe_info.h" - -namespace OHOS { -namespace DistributedHardware { -enum { - REGISTER_DEVICE_MANAGER_LISTENER = 0, - UNREGISTER_DEVICE_MANAGER_LISTENER = 1, - REGISTER_DEVICE_STATE_CALLBACK = 2, - UNREGISTER_DEVICE_STATE_CALLBACK = 3, - GET_TRUST_DEVICE_LIST = 4, - START_DEVICE_DISCOVER = 5, - STOP_DEVICE_DISCOVER = 6, - AUTHENTICATE_DEVICE = 7, -}; - -class IDeviceManager : public OHOS::IRemoteBroker { -public: - virtual ~IDeviceManager() {} - virtual int32_t GetTrustedDeviceList(std::string &packageName, std::string &extra, - std::vector &deviceList) = 0; - virtual int32_t RegisterDeviceManagerListener(std::string &packageName, sptr listener) = 0; - virtual int32_t UnRegisterDeviceManagerListener(std::string &packageName) = 0; - virtual int32_t RegisterDeviceStateCallback(std::string &packageName, std::string &extra) = 0; - virtual int32_t UnRegisterDeviceStateCallback(std::string &packageName) = 0; - virtual int32_t StartDeviceDiscovery(std::string &packageName, DmSubscribeInfo &subscribeInfo) = 0; - virtual int32_t StopDeviceDiscovery(std::string &packageName, uint16_t subscribeId) = 0; - virtual int32_t AuthenticateDevice(std::string &packageName, const DmDeviceInfo &deviceInfo, - std::string &extra) = 0; - -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.devicemanager"); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_INTERFACE_H diff --git a/interfaces/inner_kits/native_cpp/src/device_manager.cpp b/interfaces/inner_kits/native_cpp/src/device_manager.cpp index 65da53e98..baececb7b 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager.cpp @@ -15,300 +15,13 @@ #include "device_manager.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -#include "device_manager_errno.h" -#include "device_manager_log.h" +#include "device_manager_impl.h" namespace OHOS { namespace DistributedHardware { -IMPLEMENT_SINGLE_INSTANCE(DeviceManager); - -int32_t DeviceManager::InitDeviceManagerService() -{ - HILOGI("DeviceManager::InitDeviceManagerService start"); - if (dmInterface_ != nullptr) { - HILOGI("DeviceManagerService Already Init"); - return ERR_OK; - } - - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr == nullptr) { - HILOGE("Get SystemAbilityManager Failed"); - return ERR_NO_INIT; - } - - auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); - if (object == nullptr) { - HILOGE("Get DeviceManager SystemAbility Failed"); - return ERR_DEVICEMANAGER_SERVICE_NOT_READY; - } - - if (dmRecipient_ == nullptr) { - dmRecipient_ = sptr(new DmDeathRecipient()); - } - - if (!object->AddDeathRecipient(dmRecipient_)) { - HILOGE("InitDeviceManagerService: AddDeathRecipient Failed"); - } - - dmInterface_ = iface_cast(object); - HILOGI("DeviceManager::InitDeviceManagerService completed"); - return ERR_OK; -} - -bool DeviceManager::IsInit(std::string &packageName) -{ - if (dmInterface_ == nullptr) { - HILOGE("DeviceManager not Init"); - return false; - } - - if (dmListener_.find(packageName) == dmListener_.end()) { - HILOGE("dmListener_ not Init for %{public}s", packageName.c_str()); - return false; - } - return true; -} - -int32_t DeviceManager::InitDeviceManager(std::string &packageName, std::shared_ptr dmInitCallback) -{ - HILOGI("DeviceManager::InitDeviceManager start, packageName: %{public}s", packageName.c_str()); - if (packageName.empty() || dmInitCallback == nullptr) { - HILOGE("InitDeviceManager error: Invalid parameter"); - return ERR_INVALID_VALUE; - } - - HILOGI("InitDeviceManager in, packageName %{public}s", packageName.c_str()); - std::lock_guard autoLock(lock_); - int32_t ret = InitDeviceManagerService(); - if (ret != ERR_OK) { - HILOGE("InitDeviceManager Failed with ret %{public}d", ret); - return ret; - } - - auto iter = dmListener_.find(packageName); - if (iter != dmListener_.end()) { - HILOGI("dmListener_ Already Init"); - dmInitCallback_[packageName] = dmInitCallback; - return ERR_OK; - } - - sptr listener = sptr(new DeviceManagerListenerStub()); - ret = dmInterface_->RegisterDeviceManagerListener(packageName, listener); - if (ret != ERR_OK) { - HILOGE("InitDeviceManager: RegisterDeviceManagerListener Failed with ret %{public}d", ret); - return ret; - } - - dmListener_[packageName] = listener; - dmInitCallback_[packageName] = dmInitCallback; - - HILOGI("DeviceManager::InitDeviceManager completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -int32_t DeviceManager::UnInitDeviceManager(std::string &packageName) -{ - HILOGI("DeviceManager::UnInitDeviceManager start, packageName: %{public}s", packageName.c_str()); - if (packageName.empty()) { - HILOGE("InitDeviceManager error: Invalid parameter"); - return ERR_INVALID_VALUE; - } - - HILOGI("UnInitDeviceManager in, packageName %{public}s", packageName.c_str()); - std::lock_guard autoLock(lock_); - if (dmInterface_ == nullptr) { - HILOGE("DeviceManager not Init"); - return ERR_NO_INIT; - } - - auto iter = dmListener_.find(packageName); - if (iter != dmListener_.end()) { - int32_t ret = dmInterface_->UnRegisterDeviceManagerListener(packageName); - if (ret != ERR_OK) { - HILOGE("UnInitDeviceManager: UnRegisterDeviceManagerListener Failed with ret %{public}d", ret); - return ret; - } - dmListener_.erase(packageName); - dmInitCallback_.erase(packageName); - } - - if (dmListener_.empty()) { - dmRecipient_ = nullptr; - dmInterface_ = nullptr; - } - HILOGI("DeviceManager::UnInitDeviceManager completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -int32_t DeviceManager::GetTrustedDeviceList(std::string &packageName, std::string &extra, - std::vector &deviceList) -{ - HILOGI("DeviceManager::GetTrustedDeviceList start, packageName: %{public}s", packageName.c_str()); - if (packageName.empty()) { - HILOGE("Invalid para"); - return ERR_INVALID_VALUE; - } - - if (!IsInit(packageName)) { - HILOGE("DeviceManager not Init for %{public}s", packageName.c_str()); - return ERR_NO_INIT; - } - - HILOGI("GetTrustedDeviceList in, packageName %{public}s", packageName.c_str()); - int32_t ret = dmInterface_->GetTrustedDeviceList(packageName, extra, deviceList); - if (ret != ERR_OK) { - HILOGE("RegisterDevStateCallback Failed with ret %{public}d", ret); - return ret; - } - HILOGI("DeviceManager::GetTrustedDeviceList completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -int32_t DeviceManager::RegisterDevStateCallback(std::string &packageName, std::string &extra, - std::shared_ptr callback) -{ - HILOGI("DeviceManager::RegisterDevStateCallback start, packageName: %{public}s", packageName.c_str()); - if (packageName.empty() || callback == nullptr) { - HILOGE("Invalid para"); - return ERR_INVALID_VALUE; - } - - if (!IsInit(packageName)) { - HILOGE("DeviceManager not Init for %{public}s", packageName.c_str()); - return ERR_NO_INIT; - } - - HILOGI("RegisterDevStateCallback in, packageName %{public}s", packageName.c_str()); - int32_t ret = dmInterface_->RegisterDeviceStateCallback(packageName, extra); - if (ret != ERR_OK) { - HILOGE("RegisterDevStateCallback Failed with ret %{public}d", ret); - return ret; - } - - std::lock_guard autoLock(lock_); - dmListener_[packageName]->AddDeviceStateCallback(callback); - HILOGI("DeviceManager::RegisterDevStateCallback completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -int32_t DeviceManager::UnRegisterDevStateCallback(std::string &packageName) -{ - HILOGI("DeviceManager::UnRegisterDevStateCallback start, packageName: %{public}s", packageName.c_str()); - if (packageName.empty()) { - HILOGE("Invalid para"); - return ERR_INVALID_VALUE; - } - - if (!IsInit(packageName)) { - HILOGE("DeviceManager not Init for %{public}s", packageName.c_str()); - return ERR_NO_INIT; - } - - HILOGI("UnRegisterDevStateCallback in, packageName %{public}s", packageName.c_str()); - int32_t ret = dmInterface_->UnRegisterDeviceStateCallback(packageName); - if (ret != ERR_OK) { - HILOGE("UnRegisterDeviceStateCallback Failed with ret %{public}d", ret); - return ret; - } - - std::lock_guard autoLock(lock_); - dmListener_[packageName]->RemoveDeviceStateCallback(); - HILOGI("DeviceManager::UnRegisterDevStateCallback completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -int32_t DeviceManager::StartDeviceDiscovery(std::string &packageName, DmSubscribeInfo &subscribeInfo, - std::shared_ptr callback) -{ - HILOGI("DeviceManager::StartDeviceDiscovery start, packageName: %{public}s", packageName.c_str()); - if (packageName.empty() || callback == nullptr) { - HILOGE("Invalid para"); - return ERR_INVALID_VALUE; - } - - if (!IsInit(packageName)) { - HILOGE("DeviceManager not Init for %{public}s", packageName.c_str()); - return ERR_NO_INIT; - } - - HILOGI("StartDeviceDiscovery in, packageName %{public}s", packageName.c_str()); - { - std::lock_guard autoLock(lock_); - dmListener_[packageName]->AddDiscoverCallback(subscribeInfo.subscribeId, callback); - } - int32_t ret = dmInterface_->StartDeviceDiscovery(packageName, subscribeInfo); - if (ret != ERR_OK) { - HILOGE("StartDeviceDiscovery Failed with ret %{public}d", ret); - return ret; - } - - HILOGI("DeviceManager::StartDeviceDiscovery completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -int32_t DeviceManager::StopDeviceDiscovery(std::string &packageName, uint16_t subscribeId) -{ - HILOGI("DeviceManager::StopDeviceDiscovery start , packageName: %{public}s", packageName.c_str()); - if (packageName.empty()) { - HILOGE("Invalid para"); - return ERR_INVALID_VALUE; - } - - if (!IsInit(packageName)) { - HILOGE("DeviceManager not Init for %{public}s", packageName.c_str()); - return ERR_NO_INIT; - } - - HILOGI("StopDeviceDiscovery in, packageName %{public}s", packageName.c_str()); - int32_t ret = dmInterface_->StopDeviceDiscovery(packageName, subscribeId); - if (ret != ERR_OK) { - HILOGE("StopDeviceDiscovery Failed with ret %{public}d", ret); - return ret; - } - - std::lock_guard autoLock(lock_); - dmListener_[packageName]->RemoveDiscoverCallback(subscribeId); - HILOGI("DeviceManager::StopDeviceDiscovery completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -int32_t DeviceManager::AuthenticateDevice(std::string &packageName, const DmDeviceInfo &deviceInfo, std::string &extra, - std::shared_ptr callback) -{ - HILOGI("DeviceManager::AuthenticateDevice start , packageName: %{public}s", packageName.c_str()); - if (packageName.empty()) { - HILOGE("Invalid para"); - return ERR_INVALID_VALUE; - } - - if (!IsInit(packageName)) { - HILOGE("DeviceManager not Init for %{public}s", packageName.c_str()); - return ERR_NO_INIT; - } - - HILOGI("AuthenticateDevice in, packageName %{public}s", packageName.c_str()); - int32_t ret = dmInterface_->AuthenticateDevice(packageName, deviceInfo, extra); - if (ret != ERR_OK) { - HILOGE("AuthenticateDevice Failed with ret %{public}d", ret); - return ret; - } - - std::lock_guard autoLock(lock_); - dmListener_[packageName]->AddAuthenticateCallback(deviceInfo.deviceId, callback); - HILOGI("DeviceManager::AuthenticateDevice completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; -} - -void DmDeathRecipient::OnRemoteDied(const wptr& remote) +DeviceManager& DeviceManager::GetInstance() { - (void)remote; - HILOGW("DmDeathRecipient : OnRemoteDied"); - for (auto iter : DeviceManager::GetInstance().dmInitCallback_) { - iter.second->OnRemoteDied(); - } + return DeviceManagerImpl::GetInstance(); } } // 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 new file mode 100644 index 000000000..e2a39db6c --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "device_manager_errno.h" +#include "device_manager_log.h" +#include "device_manager_notify.h" +#include "constants.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" +#include "ipc_req.h" +#include "ipc_start_discovery_req.h" +#include "ipc_stop_discovery_req.h" +#include "ipc_get_authenticationparam_rsp.h" +#include "ipc_set_useroperation_req.h" + +namespace OHOS { +namespace DistributedHardware { +IMPLEMENT_SINGLE_INSTANCE(DeviceManagerImpl); + +int32_t DeviceManagerImpl::InitDeviceManager(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; + } + + int32_t ret = ipcClientProxy_->Init(pkgName); + if (ret != DEVICEMANAGER_OK) { + return ret; + } + DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); + DMLOG(DM_LOG_INFO, "success"); + return DEVICEMANAGER_OK; +} + +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; + } + + int32_t ret = ipcClientProxy_->UnInit(pkgName); + if (ret != DEVICEMANAGER_OK) { + return ret; + } + DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); + DMLOG(DM_LOG_INFO, "DeviceManager::UnInitDeviceManager completed with errcode %d", ret); + return DEVICEMANAGER_OK; +} + +int32_t DeviceManagerImpl::GetTrustedDeviceList(std::string &pkgName, std::string &extra, + std::vector &deviceList) +{ + 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; + } + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetExtra(extra); + if (ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + if (rsp->GetErrCode() == DEVICEMANAGER_OK) { + deviceList = rsp->GetDeviceVec(); + } + DMLOG(DM_LOG_INFO, "DeviceManager::GetTrustedDeviceList completed, pkgName: %s", pkgName.c_str()); + return DEVICEMANAGER_OK; +} + +int32_t DeviceManagerImpl::RegisterDevStateCallback(std::string &pkgName, std::string &extra, + std::shared_ptr callback) +{ + 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; + } + + DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); + DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DEVICEMANAGER_OK; +} + +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; + } + + DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); + DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DEVICEMANAGER_OK; +} + +int32_t DeviceManagerImpl::StartDeviceDiscovery(std::string &pkgName, DmSubscribeInfo &subscribeInfo, + std::shared_ptr callback) +{ + 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; + } + + DMLOG(DM_LOG_INFO, "DeviceManager StartDeviceDiscovery in, pkgName %s", pkgName.c_str()); + DeviceManagerNotify::GetInstance().RegisterDiscoverCallback(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) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "DeviceManager StartDeviceDiscovery Failed with ret %d", ret); + return ret; + } + return DEVICEMANAGER_OK; +} + +int32_t DeviceManagerImpl::StopDeviceDiscovery(std::string &pkgName, uint16_t subscribeId) +{ + 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; + } + + DMLOG(DM_LOG_INFO, "StopDeviceDiscovery in, pkgName %s", pkgName.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + if (ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DEVICEMANAGER_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; +} + +int32_t DeviceManagerImpl::AuthenticateDevice(std::string &pkgName, const DmDeviceInfo &deviceInfo, + const DmAppImageInfo &imageInfo, std::string &extra, std::shared_ptr callback) +{ + 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; + } + + 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->SetDeviceInfo(deviceInfo); + req->SetAppImageInfo(imageInfo); + if (ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DEVICEMANAGER_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; +} + +int32_t DeviceManagerImpl::CheckAuthentication(std::string &pkgName, std::string &authPara, + std::shared_ptr callback) +{ + 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; + } + 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) { + return DEVICEMANAGER_IPC_FAILED; + } + + int32_t ret = rsp->GetErrCode(); + if (ret != DEVICEMANAGER_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; +} + +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) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + authParam = rsp->GetAuthParam(); + return DEVICEMANAGER_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) != DEVICEMANAGER_OK) { + return DEVICEMANAGER_IPC_FAILED; + } + int32_t ret = rsp->GetErrCode(); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "CheckAuthentication Failed with ret %d", ret); + return ret; + } + return DEVICEMANAGER_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 DEVICEMANAGER_INVALID_VALUE; + } + DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(packageName, callback); + DMLOG(DM_LOG_INFO, "DeviceManager::RegisterDevStateCallback completed, pkgName: %s", packageName.c_str()); + return DEVICEMANAGER_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 DEVICEMANAGER_INVALID_VALUE; + } + DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); + DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDevStateCallback completed, pkgName: %s", pkgName.c_str()); + return DEVICEMANAGER_OK; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_listener_stub.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_listener_stub.cpp deleted file mode 100644 index e3fc817a7..000000000 --- a/interfaces/inner_kits/native_cpp/src/device_manager_listener_stub.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_manager_listener_stub.h" - -#include "ipc_skeleton.h" -#include "ipc_types.h" - -#include "device_manager_log.h" - -using namespace std; - -namespace OHOS { -namespace DistributedHardware { -DeviceManagerListenerStub::DeviceManagerListenerStub() -{ - memberFuncMap_[ON_DEVICE_ONLINE] = &DeviceManagerListenerStub::OnDeviceOnlineInner; - memberFuncMap_[ON_DEVICE_OFFLINE] = &DeviceManagerListenerStub::OnDeviceOfflineInner; - memberFuncMap_[ON_DEVICE_CHANGE] = &DeviceManagerListenerStub::OnDeviceChangedInner; - memberFuncMap_[ON_DEVICE_FOUND] = &DeviceManagerListenerStub::OnDeviceFoundInner; - memberFuncMap_[ON_DISCOVER_SUCCESS] = &DeviceManagerListenerStub::OnDiscoverySuccessInner; - memberFuncMap_[ON_DISCOVER_FAILED] = &DeviceManagerListenerStub::OnDiscoverFailedInner; - memberFuncMap_[ON_AUTH_RESULT] = &DeviceManagerListenerStub::OnAuthResultInner; -} - -DeviceManagerListenerStub::~DeviceManagerListenerStub() -{ - memberFuncMap_.clear(); -} - -int32_t DeviceManagerListenerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, - MessageOption &option) -{ - HILOGI("code = %{public}d, flags= %{public}d.", code, option.GetFlags()); - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (data.ReadInterfaceToken() != DeviceManagerListenerStub::GetDescriptor()) { - HILOGE("interface token check failed!"); - return ERR_INVALID_STATE; - } - return (this->*memberFunc)(data, reply); - } - HILOGW("unsupport code: %{public}d", code); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} - -template -int32_t DeviceManagerListenerStub::GetParcelableInfo(MessageParcel &reply, T &parcelableInfo) -{ - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - HILOGE("readParcelableInfo failed"); - return ERR_INVALID_VALUE; - } - parcelableInfo = *info; - return ERR_NONE; -} - -int32_t DeviceManagerListenerStub::OnDeviceOnlineInner(MessageParcel &data, MessageParcel &reply) -{ - string packageName = data.ReadString(); - DmDeviceInfo deviceInfo; - int32_t result = GetParcelableInfo(data, deviceInfo); - if (result != ERR_NONE) { - HILOGE("GetParcelableInfo fail, result: %{public}d", result); - reply.WriteInt32(result); - return result; - } - - int32_t ret = OnDeviceOnline(packageName, deviceInfo); - reply.WriteInt32(ret); - return ret; -} - -int32_t DeviceManagerListenerStub::OnDeviceOfflineInner(MessageParcel &data, MessageParcel &reply) -{ - string packageName = data.ReadString(); - DmDeviceInfo deviceInfo; - int32_t result = GetParcelableInfo(data, deviceInfo); - if (result != ERR_NONE) { - HILOGE("GetParcelableInfo fail, result: %{public}d", result); - reply.WriteInt32(result); - return result; - } - - int32_t ret = OnDeviceOffline(packageName, deviceInfo); - reply.WriteInt32(ret); - return ret; -} - -int32_t DeviceManagerListenerStub::OnDeviceChangedInner(MessageParcel &data, MessageParcel &reply) -{ - string packageName = data.ReadString(); - DmDeviceInfo deviceInfo; - int32_t result = GetParcelableInfo(data, deviceInfo); - if (result != ERR_NONE) { - HILOGE("GetParcelableInfo deviceInfo fail, result: %{public}d", result); - reply.WriteInt32(result); - return result; - } - - int32_t ret = OnDeviceChanged(packageName, deviceInfo); - reply.WriteInt32(ret); - return ret; -} - -int32_t DeviceManagerListenerStub::OnDeviceFoundInner(MessageParcel &data, MessageParcel &reply) -{ - string packageName = data.ReadString(); - uint16_t subscribeId = data.ReadInt16(); - DmDeviceInfo deviceInfo; - int32_t result = GetParcelableInfo(data, deviceInfo); - if (result != ERR_NONE) { - HILOGE("GetParcelableInfo fail, result: %{public}d", result); - reply.WriteInt32(result); - return result; - } - - int32_t ret = OnDeviceFound(packageName, subscribeId, deviceInfo); - reply.WriteInt32(ret); - return ret; -} - -int32_t DeviceManagerListenerStub::OnDiscoverFailedInner(MessageParcel &data, MessageParcel &reply) -{ - string packageName = data.ReadString(); - uint16_t subscribeId = data.ReadInt16(); - int32_t failedReason = data.ReadInt32(); - - int32_t ret = OnDiscoverFailed(packageName, subscribeId, failedReason); - reply.WriteInt32(ret); - return ret; -} - -int32_t DeviceManagerListenerStub::OnDiscoverySuccessInner(MessageParcel &data, MessageParcel &reply) -{ - string packageName = data.ReadString(); - uint16_t subscribeId = data.ReadInt16(); - - int32_t ret = OnDiscoverySuccess(packageName, subscribeId); - reply.WriteInt32(ret); - return ret; -} - -int32_t DeviceManagerListenerStub::OnAuthResultInner(MessageParcel &data, MessageParcel &reply) -{ - string packageName = data.ReadString(); - string deviceId = data.ReadString(); - int32_t status = data.ReadInt32(); - int32_t reason = data.ReadInt32(); - - int32_t ret = OnAuthResult(packageName, deviceId, status, reason); - reply.WriteInt32(ret); - return ret; -} - -int32_t DeviceManagerListenerStub::OnDeviceOnline(std::string &packageName, const DmDeviceInfo &deviceInfo) -{ - HILOGI("OnDeviceOnline packageName:%{public}s", packageName.c_str()); - if (deviceStateCallback_ == nullptr) { - HILOGE("OnDeviceOnlinecallback not register"); - return ERR_NULL_OBJECT; - } - deviceStateCallback_->OnDeviceOnline(deviceInfo); - return ERR_OK; -} - -int32_t DeviceManagerListenerStub::OnDeviceOffline(std::string &packageName, const DmDeviceInfo &deviceInfo) -{ - HILOGI("OnDeviceOffline packageName:%{public}s", packageName.c_str()); - if (deviceStateCallback_ == nullptr) { - HILOGE("OnDeviceOnlinecallback not register"); - return ERR_NULL_OBJECT; - } - deviceStateCallback_->OnDeviceOffline(deviceInfo); - return ERR_OK; -} - -int32_t DeviceManagerListenerStub::OnDeviceChanged(std::string &packageName, const DmDeviceInfo &deviceInfo) -{ - HILOGI("OnDeviceChanged packageName:%{public}s", packageName.c_str()); - if (deviceStateCallback_ == nullptr) { - HILOGE("OnDeviceOnlinecallback not register"); - return ERR_NULL_OBJECT; - } - deviceStateCallback_->OnDeviceChanged(deviceInfo); - return ERR_OK; -} - -int32_t DeviceManagerListenerStub::OnDeviceFound(std::string &packageName, uint16_t subscribeId, - const DmDeviceInfo &deviceInfo) -{ - HILOGI("OnDeviceFound packageName:%{public}s, subscribeId:%{public}d.", packageName.c_str(), (int32_t)subscribeId); - auto iter = deviceDiscoverCallbacks_.find(subscribeId); - if (iter == deviceDiscoverCallbacks_.end()) { - HILOGE("OnDeviceFound: no register discoverCallback for subscribeId %{public}d", subscribeId); - return ERR_NULL_OBJECT; - } - auto callback = iter->second; - if (callback == nullptr) { - HILOGE("OnDeviceFound: discoverCallback is nullptr for subscribeId %{public}d", subscribeId); - return ERR_NULL_OBJECT; - } - callback->OnDeviceFound(subscribeId, const_cast(deviceInfo)); - return ERR_OK; -} - -int32_t DeviceManagerListenerStub::OnDiscoverFailed(std::string &packageName, uint16_t subscribeId, - int32_t failedReason) -{ - HILOGI("OnDiscoverFailed packageName:%{public}s, subscribeId %{public}d, reason %{public}d", - packageName.c_str(), subscribeId, failedReason); - auto iter = deviceDiscoverCallbacks_.find(subscribeId); - if (iter == deviceDiscoverCallbacks_.end()) { - HILOGE("OnDiscoverFailed: no register discoverCallback for subscribeId %{public}d", subscribeId); - return ERR_NULL_OBJECT; - } - auto callback = iter->second; - if (callback == nullptr) { - HILOGE("OnDiscoverFailed: discoverCallback is nullptr for subscribeId %{public}d", subscribeId); - return ERR_NULL_OBJECT; - } - callback->OnDiscoverFailed(subscribeId, failedReason); - return ERR_OK; -} - -int32_t DeviceManagerListenerStub::OnDiscoverySuccess(std::string &packageName, uint16_t subscribeId) -{ - HILOGI("OnDiscoverySuccess packageName:%{public}s, subscribeId %{public}d", packageName.c_str(), subscribeId); - auto iter = deviceDiscoverCallbacks_.find(subscribeId); - if (iter == deviceDiscoverCallbacks_.end()) { - HILOGE("OnDiscoverySuccess: no register discoverCallback for subscribeId %{public}d", subscribeId); - return ERR_NULL_OBJECT; - } - auto callback = iter->second; - if (callback == nullptr) { - HILOGE("OnDiscoverySuccess: discoverCallback is nullptr for subscribeId %{public}d", subscribeId); - return ERR_NULL_OBJECT; - } - callback->OnDiscoverySuccess(subscribeId); - return ERR_OK; -} - -int32_t DeviceManagerListenerStub::OnAuthResult(std::string &packageName, std::string &deviceId, int32_t status, - int32_t reason) -{ - HILOGI("OnAuthResult packageName:%{public}s, status %{public}d, reason %{public}d", - packageName.c_str(), status, reason); - auto iter = authenticateCallback_.find(deviceId); - if (iter == authenticateCallback_.end()) { - HILOGE("OnAuthResult: cannot find Auth callback"); - return ERR_NULL_OBJECT; - } - auto callback = iter->second; - if (callback == nullptr) { - HILOGE("OnAuthResult: Auth callback is nullptr"); - return ERR_NULL_OBJECT; - } - callback->OnAuthResult(deviceId, status, reason); - authenticateCallback_.erase(deviceId); - return ERR_OK; -} - -void DeviceManagerListenerStub::AddDeviceStateCallback(std::shared_ptr callback) -{ - deviceStateCallback_ = callback; -} - -void DeviceManagerListenerStub::RemoveDeviceStateCallback() -{ - deviceStateCallback_ = nullptr; -} - -void DeviceManagerListenerStub::AddDiscoverCallback(uint16_t subscribeId, std::shared_ptr callback) -{ - deviceDiscoverCallbacks_[subscribeId] = callback; -} - -void DeviceManagerListenerStub::RemoveDiscoverCallback(uint16_t subscribeId) -{ - deviceDiscoverCallbacks_.erase(subscribeId); -} - -void DeviceManagerListenerStub::AddAuthenticateCallback(std::string deviceId, - std::shared_ptr callback) -{ - authenticateCallback_[deviceId] = callback; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_proxy.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_proxy.cpp deleted file mode 100644 index d5045590c..000000000 --- a/interfaces/inner_kits/native_cpp/src/device_manager_proxy.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_manager_proxy.h" - -#include "ipc_types.h" - -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -bool DeviceManagerProxy::WriteInterfaceToken(MessageParcel &data) -{ - if (!data.WriteInterfaceToken(DeviceManagerProxy::GetDescriptor())) { - HILOGE("write interface token failed"); - return false; - } - return true; -} - -int32_t DeviceManagerProxy::RegisterDeviceManagerListener(std::string &packageName, sptr listener) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteRemoteObject(listener)) { - HILOGE("write callback failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(REGISTER_DEVICE_MANAGER_LISTENER, data, reply, option); - if (error != ERR_NONE) { - HILOGE("RegisterDeviceManagerListener SendRequest fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} - -int32_t DeviceManagerProxy::UnRegisterDeviceManagerListener(std::string &packageName) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(UNREGISTER_DEVICE_MANAGER_LISTENER, data, reply, option); - if (error != ERR_NONE) { - HILOGE("UnRegisterDeviceManagerListener SendRequest fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} - -int32_t DeviceManagerProxy::RegisterDeviceStateCallback(std::string &packageName, std::string &extra) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(extra)) { - HILOGE("write extra failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(REGISTER_DEVICE_STATE_CALLBACK, data, reply, option); - if (error != ERR_NONE) { - HILOGE("RegisterDeviceStateCallback SendRequest fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} - -int32_t DeviceManagerProxy::UnRegisterDeviceStateCallback(std::string &packageName) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(UNREGISTER_DEVICE_STATE_CALLBACK, data, reply, option); - if (error != ERR_NONE) { - HILOGE("UnRegisterDeviceStateCallback SendRequest fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} - -template -int32_t DeviceManagerProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) -{ - int32_t infoSize = reply.ReadInt32(); - for (int32_t i = 0; i < infoSize; i++) { - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - HILOGE("Read Parcelable infos failed"); - return ERR_INVALID_VALUE; - } - parcelableInfos.emplace_back(*info); - } - HILOGI("get parcelable infos success"); - return ERR_NONE; -} - -int32_t DeviceManagerProxy::GetTrustedDeviceList(std::string &packageName, std::string &extra, - std::vector &deviceList) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(extra)) { - HILOGE("write extra failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(GET_TRUST_DEVICE_LIST, data, reply, option); - if (error != ERR_NONE) { - HILOGE("GetTrustedDeviceList SendRequest fail, error: %{public}d", error); - return error; - } - - error = GetParcelableInfos(reply, deviceList); - if (error != ERR_NONE) { - HILOGE("GetTrustedDeviceList GetParcelableInfos fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} - -int32_t DeviceManagerProxy::StartDeviceDiscovery(std::string &packageName, DmSubscribeInfo &subscribeInfo) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteParcelable(&subscribeInfo)) { - HILOGE("write subscribeInfo failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(START_DEVICE_DISCOVER, data, reply, option); - if (error != ERR_NONE) { - HILOGE("StartDeviceDiscovery SendRequest fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} - -int32_t DeviceManagerProxy::StopDeviceDiscovery(std::string &packageName, uint16_t subscribeId) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteInt16(subscribeId)) { - HILOGE("write subscribeInfo failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(STOP_DEVICE_DISCOVER, data, reply, option); - if (error != ERR_NONE) { - HILOGE("StopDeviceDiscovery SendRequest fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} - -int32_t DeviceManagerProxy::AuthenticateDevice(std::string &packageName, const DmDeviceInfo &deviceInfo, - std::string &extra) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteParcelable(&deviceInfo)) { - HILOGE("write deviceInfo failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(extra)) { - HILOGE("write extra failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(AUTHENTICATE_DEVICE, data, reply, option); - if (error != ERR_NONE) { - HILOGE("AuthenticateDevice SendRequest fail, error: %{public}d", error); - return error; - } - return ERR_NONE; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index f2ea6932d..5c6777207 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -14,51 +14,37 @@ import("//build/ohos.gni") import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -config("dmnativejs_config") { - visibility = [ ":*" ] +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", - "${common_path}/log/include", - "${common_path}/utils/include", + "${utils_path}/include/log", + "${common_path}/include/ipc", "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/standard", ] - cflags = [ - "-Wall", - "-Werror", - "-Wdate-time", - "-Wfloat-equal", - "-Wshadow", - "-Wformat=2", - "-fdata-sections", - "-ffunction-sections", - "-Os", - ] - - cflags_cc = [ - "-Os", - ] -} - -ohos_shared_library("devicemanager") { sources = [ - "src/native_devicemanager_js.cpp", "src/dm_native_event.cpp", - ] - - configs = [ ":dmnativejs_config" ] + "src/native_devicemanager_js.cpp", + ] deps = [ - "//utils/native/base:utils", + "${utils_path}:devicemanagerutils", "//foundation/ace/napi:ace_napi", "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//utils/native/base:utils", ] + cflags_cc = build_flags + defines = [ + "HI_LOG_ENABLE", "DH_LOG_TAG=\"devicemanagerkit_js\"", "LOG_DOMAIN=0xD004100", ] diff --git a/interfaces/kits/js/include/dm_native_event.h b/interfaces/kits/js/include/dm_native_event.h index dcffbd1d3..6a3858bdd 100644 --- a/interfaces/kits/js/include/dm_native_event.h +++ b/interfaces/kits/js/include/dm_native_event.h @@ -33,7 +33,7 @@ public: virtual void On(std::string &eventType, napi_value handler); virtual void Off(std::string &eventType); - virtual void OnEvent(const std::string &eventType, size_t argc, const napi_value* argv); + virtual void OnEvent(const std::string &eventType, size_t argc, const napi_value *argv); protected: napi_env env_; diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 872d7b457..c03fc4cd4 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -24,6 +24,8 @@ #include "dm_native_event.h" #include "dm_device_info.h" #include "dm_subscribe_info.h" +#include "nlohmann/json.hpp" +#include "dm_device_info.h" const int DM_NAPI_BUF_LENGTH = 256; @@ -38,6 +40,16 @@ struct AsyncCallbackInfo { int32_t status = -1; }; +struct AuthAsyncCallbackInfo { + napi_env env = nullptr; + + char bundleName[DM_NAPI_BUF_LENGTH] = {0}; + size_t bundleNameLen = 0; + + napi_ref callback = nullptr; + int32_t authType = -1; +}; + enum DmNapiDevStateChangeAction { ONLINE = 0, READY = 1, @@ -72,7 +84,7 @@ class DmNapiDiscoverCallback : public OHOS::DistributedHardware::DiscoverCallbac public: explicit DmNapiDiscoverCallback(std::string &bundleName) : refCount_(0), bundleName_(bundleName) {} virtual ~DmNapiDiscoverCallback() {}; - void OnDeviceFound(uint16_t subscribeId, OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; + void OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) override; void OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) override; void OnDiscoverySuccess(uint16_t subscribeId) override; void IncreaseRefCount(); @@ -88,7 +100,27 @@ class DmNapiAuthenticateCallback : public OHOS::DistributedHardware::Authenticat public: explicit DmNapiAuthenticateCallback(std::string &bundleName) : bundleName_(bundleName) {} virtual ~DmNapiAuthenticateCallback() {}; - void OnAuthResult(std::string &deviceId, int32_t status, int32_t reason) override; + void OnAuthResult(std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) override; + +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 { +public: + explicit DmNapiDeviceManagerFaCallback(std::string &bundleName) : bundleName_(bundleName) {} + virtual ~DmNapiDeviceManagerFaCallback() {}; + void OnCall(std::string ¶mJson) override; private: std::string bundleName_; @@ -105,41 +137,63 @@ public: static napi_value GetTrustedDeviceListSync(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 AuthenticateDeviceSync(napi_env env, napi_callback_info info); + static napi_value AuthenticateDevice(napi_env env, napi_callback_info info); + static napi_value VerifyAuthInfo(napi_env env, napi_callback_info info); static napi_value JsOn(napi_env env, napi_callback_info info); static napi_value JsOff(napi_env env, napi_callback_info info); + static napi_value SetUserOperationSync(napi_env env, napi_callback_info info); + static napi_value GetAuthenticationParamSync(napi_env env, napi_callback_info info); static void HandleCreateDmCallBack(const napi_env &env, AsyncCallbackInfo *asCallbackInfo); static DeviceManagerNapi *GetDeviceManagerNapi(std::string &buldleName); static void CreateDmCallback(std::string &bundleName, std::string &eventType); static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); - static void DeviceInfoToJsArray(const napi_env& env, + static void DeviceInfoToJsArray(const napi_env &env, const std::vector& vecDevInfo, - const int idx, napi_value& arrayResult); - static void SetValueInt32(const napi_env& env, const std::string& fieldStr, const int intValue, - 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, const int bufLen, std::string& fieldRef); - 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, + const int 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 int intValue, + 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 int 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); - static int32_t JsToDmSubscribeInfo(const napi_env& env, const napi_value& object, + 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); - static void JsToDmDeviceInfo(const napi_env& env, const napi_value& object, + 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 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); + 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); + static void JsToDmAuthExtra(const napi_env &env, const napi_value ¶m, nlohmann::json &jsonObj); 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 status, int32_t reason); + 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); private: napi_env env_; napi_ref wrapper_; static napi_ref sConstructor_; std::string bundleName_; + static AuthAsyncCallbackInfo authAsyncCallbackInfo_; + static AuthAsyncCallbackInfo verifyAsyncCallbackInfo_; }; #endif // OHOS_DEVICE_MANAGER_NATIVE_DEVICEMANAGER_JS_H diff --git a/interfaces/kits/js/src/dm_native_event.cpp b/interfaces/kits/js/src/dm_native_event.cpp index d3aca3d17..70084134b 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) { - HILOGI("DmNativeEvent On in for event: %{public}s", eventType.c_str()); + DMLOG(DM_LOG_INFO, "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) { - HILOGI("DmNativeEvent Off in for event: %{public}s", eventType.c_str()); + DMLOG(DM_LOG_INFO, "DmNativeEvent Off in for event: %s", eventType.c_str()); napi_handle_scope scope = nullptr; napi_open_handle_scope(env_, &scope); if (scope == nullptr) { - HILOGE("scope is nullptr"); + DMLOG(DM_LOG_ERROR, "scope is nullptr"); return; } auto iter = eventMap_.find(eventType); if (iter == eventMap_.end()) { - HILOGE("eventType %{public}s not find", eventType.c_str()); + DMLOG(DM_LOG_ERROR, "eventType %s not find", eventType.c_str()); return; } auto listener = iter->second; @@ -66,40 +66,40 @@ void DmNativeEvent::Off(std::string &eventType) napi_close_handle_scope(env_, scope); } -void DmNativeEvent::OnEvent(const std::string &eventType, size_t argc, const napi_value* argv) +void DmNativeEvent::OnEvent(const std::string &eventType, size_t argc, const napi_value *argv) { - HILOGI("OnEvent for %{public}s", eventType.c_str()); + DMLOG(DM_LOG_INFO, "OnEvent for %s", eventType.c_str()); napi_handle_scope scope = nullptr; napi_open_handle_scope(env_, &scope); if (scope == nullptr) { - HILOGE("scope is nullptr"); + DMLOG(DM_LOG_ERROR, "scope is nullptr"); return; } auto iter = eventMap_.find(eventType); if (iter == eventMap_.end()) { - HILOGE("eventType %{public}s not find", eventType.c_str()); + DMLOG(DM_LOG_ERROR, "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) { - HILOGE("napi_get_reference_value thisVar for %{public}s failed, status=%{public}d", eventType.c_str(), status); + DMLOG(DM_LOG_ERROR, "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) { - HILOGE("napi_get_reference_value handler for %{public}s failed, status=%{public}d", eventType.c_str(), status); + DMLOG(DM_LOG_ERROR, "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) { - HILOGE("napi_call_function for %{public}s failed, status=%{public}d", eventType.c_str(), status); + DMLOG(DM_LOG_ERROR, "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 15a9df211..3b7c40e87 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -16,9 +16,11 @@ #include "native_devicemanager_js.h" #include +#include "nlohmann/json.hpp" #include "device_manager.h" #include "device_manager_log.h" +#include "constants.h" using namespace OHOS::DistributedHardware; @@ -33,20 +35,26 @@ 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_DEVICE_AUTH_RESULT = "authResult"; +const std::string DM_NAPI_EVENT_DMFA_CALLBACK = "dmFaCallback"; const std::string DM_NAPI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; const std::string DEVICE_MANAGER_NAPI_CLASS_NAME = "DeviceManager"; const int DM_NAPI_ARGS_ONE = 1; const int DM_NAPI_ARGS_TWO = 2; +const int DM_NAPI_ARGS_THREE = 3; const int DM_NAPI_SUB_ID_MAX = 65535; +const int DM_AUTH_TYPE_PINCODE = 1; +const int DM_AUTH_DIRECTION_CLIENT = 1; + std::map g_deviceManagerMap; std::map> g_initCallbackMap; std::map> g_deviceStateCallbackMap; std::map> g_discoverCallbackMap; std::map> g_authCallbackMap; +std::map> g_checkAuthCallbackMap; +std::map> g_dmfaCallbackMap; } enum DmNapiSubscribeCap { @@ -54,67 +62,68 @@ enum DmNapiSubscribeCap { }; napi_ref DeviceManagerNapi::sConstructor_ = nullptr; +AuthAsyncCallbackInfo DeviceManagerNapi::authAsyncCallbackInfo_ = {0}; +AuthAsyncCallbackInfo DeviceManagerNapi::verifyAsyncCallbackInfo_ = {0}; void DmNapiInitCallback::OnRemoteDied() { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnRemoteDied, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnRemoteDied, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnEvent("serviceDie", 0, nullptr); } -void DmNapiDeviceStateCallback::OnDeviceOnline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) +void DmNapiDeviceStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnDeviceOnline, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnDeviceOnline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::ONLINE, deviceInfo); } -void DmNapiDeviceStateCallback::OnDeviceReady(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) +void DmNapiDeviceStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnDeviceOnline, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnDeviceOnline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::READY, deviceInfo); } -void DmNapiDeviceStateCallback::OnDeviceOffline(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) +void DmNapiDeviceStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnDeviceOffline, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnDeviceOffline, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::OFFLINE, deviceInfo); } -void DmNapiDeviceStateCallback::OnDeviceChanged(const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) +void DmNapiDeviceStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnDeviceChanged, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnDeviceChanged, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } deviceManagerNapi->OnDeviceStateChange(DmNapiDevStateChangeAction::CHANGE, deviceInfo); } -void DmNapiDiscoverCallback::OnDeviceFound(uint16_t subscribeId, - OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) +void DmNapiDiscoverCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnDeviceFound, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnDeviceFound, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } - HILOGI("OnDeviceFound for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); + DMLOG(DM_LOG_INFO, "OnDeviceFound for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); deviceManagerNapi->OnDeviceFound(subscribeId, deviceInfo); } @@ -122,7 +131,7 @@ void DmNapiDiscoverCallback::OnDiscoverFailed(uint16_t subscribeId, int32_t fail { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnDiscoverFailed, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnDiscoverFailed, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } @@ -133,10 +142,10 @@ void DmNapiDiscoverCallback::OnDiscoverySuccess(uint16_t subscribeId) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnDiscoverySuccess, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnDiscoverySuccess, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } - HILOGE("DiscoverySuccess for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); + DMLOG(DM_LOG_INFO, "DiscoverySuccess for %s, subscribeId %d", bundleName_.c_str(), (int32_t)subscribeId); } void DmNapiDiscoverCallback::IncreaseRefCount() @@ -154,14 +163,34 @@ int32_t DmNapiDiscoverCallback::GetRefCount() return refCount_; } -void DmNapiAuthenticateCallback::OnAuthResult(std::string &deviceId, int32_t status, int32_t reason) +void DmNapiAuthenticateCallback::OnAuthResult(std::string &deviceId, int32_t pinToken, 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); +} + +void DmNapiCheckAuthCallback::OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag) +{ + DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); + if (deviceManagerNapi == nullptr) { + DMLOG(DM_LOG_ERROR, "OnCheckAuthResult, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); + return; + } + deviceManagerNapi->OnVerifyResult(deviceId, resultCode, flag); +} + +void DmNapiDeviceManagerFaCallback::OnCall(std::string ¶mJson) { DeviceManagerNapi *deviceManagerNapi = DeviceManagerNapi::GetDeviceManagerNapi(bundleName_); if (deviceManagerNapi == nullptr) { - HILOGE("OnAuthResult, deviceManagerNapi not find for bunderName %{public}s", bundleName_.c_str()); + DMLOG(DM_LOG_ERROR, "OnCall, deviceManagerNapi not find for bunderName %s", bundleName_.c_str()); return; } - deviceManagerNapi->OnAuthResult(deviceId, status, reason); + deviceManagerNapi->OnDmfaCall(paramJson); } DeviceManagerNapi::DeviceManagerNapi(napi_env env, napi_value thisVar) : DmNativeEvent(env, thisVar) @@ -186,8 +215,7 @@ DeviceManagerNapi *DeviceManagerNapi::GetDeviceManagerNapi(std::string &buldleNa return iter->second; } -void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action, - const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) +void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action, const DmDeviceInfo &deviceInfo) { napi_value result; napi_create_object(env_, &result); @@ -203,9 +231,9 @@ void DeviceManagerNapi::OnDeviceStateChange(DmNapiDevStateChangeAction action, OnEvent("deviceStateChange", DM_NAPI_ARGS_ONE, &result); } -void DeviceManagerNapi::OnDeviceFound(uint16_t subscribeId, const OHOS::DistributedHardware::DmDeviceInfo &deviceInfo) +void DeviceManagerNapi::OnDeviceFound(uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { - HILOGI("OnDeviceFound for subscribeId %{public}d", (int32_t)subscribeId); + DMLOG(DM_LOG_INFO, "OnDeviceFound for subscribeId %d", (int32_t)subscribeId); napi_value result; napi_create_object(env_, &result); SetValueInt32(env_, "subscribeId", (int)subscribeId, result); @@ -222,7 +250,7 @@ void DeviceManagerNapi::OnDeviceFound(uint16_t subscribeId, const OHOS::Distribu void DeviceManagerNapi::OnDiscoverFailed(uint16_t subscribeId, int32_t failedReason) { - HILOGI("OnDiscoverFailed for subscribeId %{public}d", (int32_t)subscribeId); + DMLOG(DM_LOG_INFO, "OnDiscoverFailed for subscribeId %d", (int32_t)subscribeId); napi_value result; napi_create_object(env_, &result); SetValueInt32(env_, "subscribeId", (int)subscribeId, result); @@ -230,53 +258,165 @@ void DeviceManagerNapi::OnDiscoverFailed(uint16_t subscribeId, int32_t failedRea OnEvent("discoverFail", DM_NAPI_ARGS_ONE, &result); } -void DeviceManagerNapi::OnAuthResult(const std::string& deviceId, int32_t status, int32_t reason) +void DeviceManagerNapi::OnDmfaCall(const std::string ¶mJson) { - HILOGI("OnAuthResult for status: %{public}d, reason: %{public}d", status, reason); + DMLOG(DM_LOG_INFO, "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::OnAuthResult(const std::string &deviceId, int32_t pinToken, int32_t status, int32_t reason) +{ + DMLOG(DM_LOG_INFO, "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"); + napi_get_undefined(env_, &result[0]); + napi_create_object(env_, &result[1]); + SetValueUtf8String(env_, "deviceId", deviceId, result[1]); + if (authAsyncCallbackInfo_.authType == DM_AUTH_TYPE_PINCODE) { + SetValueInt32(env_, "pinTone", pinToken, result[1]); + } + } else { + DMLOG(DM_LOG_INFO, "OnAuthResult failed"); + napi_create_object(env_, &result[0]); + SetValueInt32(env_, "code", status, result[0]); + SetValueInt32(env_, "reason", reason, result[0]); + napi_get_undefined(env_, &result[1]); + } - SetValueUtf8String(env_, "deviceId", deviceId, result); - SetValueInt32(env_, "status", (int)status, result); - SetValueInt32(env_, "reason", (int)reason, result); - OnEvent("authResult", DM_NAPI_ARGS_ONE, &result); + napi_value callResult = nullptr; + napi_value handler = nullptr; + napi_get_reference_value(env_, authAsyncCallbackInfo_.callback, &handler); + if (handler != nullptr) { + 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"); + } + 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); + napi_value thisVar = nullptr; + napi_get_reference_value(env_, thisVarRef_, &thisVar); + napi_value result[DM_NAPI_ARGS_TWO] = { 0 }; + if (resultCode == 0) { + napi_get_undefined(env_, &result[0]); + napi_create_object(env_, &result[1]); + SetValueUtf8String(env_, "deviceId", deviceId, result[1]); + SetValueInt32(env_, "level", flag, result[1]); + } else { + napi_create_object(env_, &result[0]); + SetValueInt32(env_, "code", resultCode, result[0]); + napi_get_undefined(env_, &result[1]); + } + + napi_value callResult = nullptr; + napi_value handler = nullptr; + napi_get_reference_value(env_, verifyAsyncCallbackInfo_.callback, &handler); + if (handler != nullptr) { + 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"); + } + g_checkAuthCallbackMap.erase(bundleName_); } -void DeviceManagerNapi::SetValueUtf8String(const napi_env &env, const std::string& fieldStr, const std::string& str, - napi_value& result) +void DeviceManagerNapi::SetValueUtf8String(const napi_env &env, const std::string &fieldStr, const std::string &str, + napi_value &result) { napi_value value; napi_create_string_utf8(env, str.c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, fieldStr.c_str(), value); } -void DeviceManagerNapi::SetValueInt32(const napi_env& env, const std::string& fieldStr, const int intValue, - napi_value& result) +void DeviceManagerNapi::SetValueInt32(const napi_env &env, const std::string &fieldStr, const int intValue, + napi_value &result) { napi_value value; 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 int idx, napi_value& arrayResult) +void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, + const std::vector &vecDevInfo, + const int idx, napi_value &arrayResult) { napi_value result; napi_create_object(env, &result); - SetValueUtf8String(env, "deviceId", vecDevInfo[idx].deviceId.c_str(), result); - SetValueUtf8String(env, "deviceName", vecDevInfo[idx].deviceName.c_str(), result); + SetValueUtf8String(env, "deviceId", vecDevInfo[idx].deviceId, result); + SetValueUtf8String(env, "deviceName", vecDevInfo[idx].deviceName, result); SetValueInt32(env, "deviceType", (int)vecDevInfo[idx].deviceTypeId, result); napi_status status = napi_set_element(env, arrayResult, idx, result); if (status != napi_ok) { - HILOGE("DmDeviceInfo To JsArray set element error: %{public}d", status); + DMLOG(DM_LOG_ERROR, "DmDeviceInfo To JsArray set element error: %d", status); + } +} + +void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, + const DmAuthParam &authParam, napi_value ¶mResult) +{ + DMLOG(DM_LOG_INFO, "DmAuthParamToJsAuthParamy in"); + SetValueInt32(env, "authType", authParam.authType, paramResult); + + napi_value extraInfo; + napi_create_object(env, &extraInfo); + SetValueInt32(env, "direction", authParam.direction, extraInfo); + SetValueInt32(env, "pinToken", authParam.pinToken, 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); + int32_t ret = memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), + appIconLen); + if (appIcon != nullptr && ret == 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, - const std::string& fieldStr, const int bufLen, std::string& fieldRef) +void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, + const std::string &fieldStr, char *dest, const int destLen) { bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); @@ -287,26 +427,43 @@ void DeviceManagerNapi::JsObjectToString(const napi_env& env, const napi_value& napi_get_named_property(env, object, fieldStr.c_str(), &field); NAPI_CALL_RETURN_VOID(env, napi_typeof(env, field, &valueType)); NAPI_ASSERT_RETURN_VOID(env, valueType == napi_string, "Wrong argument type. String expected."); - if (bufLen <= 0) { - HILOGE("js object to str bufLen invalid"); - return; - } - std::unique_ptr buf = std::make_unique(bufLen); - if (buf == nullptr) { - HILOGE("js object to str malloc failed"); - return; - } - (void)memset_s(buf.get(), bufLen, 0, bufLen); size_t result = 0; - NAPI_CALL_RETURN_VOID(env, napi_get_value_string_utf8(env, field, buf.get(), bufLen, &result)); - fieldRef = buf.get(); + 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()); + } +} + +std::string DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value ¶m) +{ + DMLOG(DM_LOG_INFO, "JsObjectToString in."); + size_t size = 0; + if (napi_get_value_string_utf8(env, param, nullptr, 0, &size) != napi_ok) { + return ""; + } + if (size == 0) { + return ""; + } + char *buf = new (std::nothrow) char[size + 1]; + if (buf == nullptr) { + return ""; + } + memset_s(buf, (size + 1), 0, (size + 1)); + bool rev = napi_get_value_string_utf8(env, param, buf, size + 1, &size) == napi_ok; + + std::string value; + if (rev) { + value = buf; } else { - HILOGE("devicemanager napi js to str no property: %{public}s", fieldStr.c_str()); + value = ""; } + delete[] buf; + buf = nullptr; + return value; } -void DeviceManagerNapi::JsObjectToInt(const napi_env& env, const napi_value& object, - const std::string& fieldStr, int& fieldRef) +void DeviceManagerNapi::JsObjectToInt(const napi_env &env, const napi_value &object, + const std::string &fieldStr, int &fieldRef) { bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); @@ -319,12 +476,12 @@ void DeviceManagerNapi::JsObjectToInt(const napi_env& env, const napi_value& obj NAPI_ASSERT_RETURN_VOID(env, valueType == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, field, &fieldRef); } else { - HILOGE("devicemanager napi js to int no property: %{public}s", fieldStr.c_str()); + DMLOG(DM_LOG_ERROR, "devicemanager napi js to int no property: %s", fieldStr.c_str()); } } -void DeviceManagerNapi::JsObjectToBool(const napi_env& env, const napi_value& object, - const std::string& fieldStr, bool& fieldRef) +void DeviceManagerNapi::JsObjectToBool(const napi_env &env, const napi_value &object, + const std::string &fieldStr, bool &fieldRef) { bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); @@ -337,17 +494,17 @@ 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 { - HILOGE("devicemanager napi js to bool no property: %{public}s", fieldStr.c_str()); + DMLOG(DM_LOG_ERROR, "devicemanager napi js to bool no property: %s", fieldStr.c_str()); } } -int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env& env, const napi_value& object, - OHOS::DistributedHardware::DmSubscribeInfo& info) +int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_value &object, + DmSubscribeInfo &info) { int subscribeId = -1; JsObjectToInt(env, object, "subscribeId", subscribeId); if (subscribeId < 0 || subscribeId > DM_NAPI_SUB_ID_MAX) { - HILOGE("DeviceManagerNapi::JsToDmSubscribeInfo, subscribeId error, subscribeId: %{public}d ", subscribeId); + DMLOG(DM_LOG_ERROR, "DeviceManagerNapi::JsToDmSubscribeInfo, subscribeId error, subscribeId: %d ", subscribeId); return -1; } @@ -371,25 +528,176 @@ int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env& env, const napi_v int capability = -1; JsObjectToInt(env, object, "capability", capability); if (capability == DmNapiSubscribeCap::DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP) { - info.capability = std::string(DM_CAPABILITY_DDMP); + (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); } return 0; } -void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env& env, const napi_value& object, - OHOS::DistributedHardware::DmDeviceInfo& info) +void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value &object, + DmDeviceInfo &info) { - JsObjectToString(env, object, "deviceId", DM_NAPI_BUF_LENGTH, info.deviceId); - JsObjectToString(env, object, "deviceName", DM_NAPI_BUF_LENGTH, info.deviceName); + JsObjectToString(env, object, "deviceId", info.deviceId, sizeof(info.deviceId)); + JsObjectToString(env, object, "deviceName", info.deviceName, sizeof(info.deviceName)); int deviceType = -1; JsObjectToInt(env, object, "deviceType", deviceType); 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."); + int 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) +{ + DMLOG(DM_LOG_INFO, "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()); + return; + } + + napi_value field; + napi_get_named_property(env, object, fieldStr.c_str(), &field); + napi_typedarray_type type; + size_t length = 0; + 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); + if (type != napi_uint8_array || length == 0 || data == nullptr) { + DMLOG(DM_LOG_ERROR, "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()); + return; + } + if (memcpy_s(*bufferPtr, length, data, length) != 0) { + DMLOG(DM_LOG_ERROR, "memcpy_s failed, filed %s", fieldStr.c_str()); + free(*bufferPtr); + *bufferPtr = nullptr; + return; + } + bufferLen = length; +} + +void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &object, + const std::string &fieldStr, nlohmann::json &jsonObj) +{ + DMLOG(DM_LOG_INFO, "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()); + return; + } + + napi_value jsonField; + napi_get_named_property(env, object, fieldStr.c_str(), &jsonField); + napi_valuetype jsValueType = napi_undefined; + napi_value jsProNameList = nullptr; + 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); + + napi_value jsProName = nullptr; + napi_value jsProValue = nullptr; + for (uint32_t index = 0; index < jsProCount; index++) { + napi_get_element(env, jsProNameList, index, &jsProName); + std::string strProName = JsObjectToString(env, jsProName); + napi_get_named_property(env, jsonField, strProName.c_str(), &jsProValue); + napi_typeof(env, jsProValue, &jsValueType); + 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()); + 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); + 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()); + } else { + jsonObj[strProName] = elementValue; + DMLOG(DM_LOG_INFO, "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()); + break; + } + } + } +} + +void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &object, std::string &extra) +{ + DMLOG(DM_LOG_INFO, "%s called.", __func__); + int authType = -1; + int token = -1; + + JsObjectToInt(env, object, "authType", authType); + JsObjectToInt(env, object, "token", token); + + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = authType; + if (authType == DM_AUTH_TYPE_PINCODE) { + jsonObj[PIN_TOKEN] = token; + } else { + jsonObj[TOKEN] = token; + } + JsToJsonObject(env, object, "extraInfo", jsonObj); + extra = jsonObj.dump(); +} void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &eventType) { - HILOGE("CreateDmCallback for bunderName %{public}s eventType %{public}s", bundleName.c_str(), eventType.c_str()); + DMLOG(DM_LOG_ERROR, "CreateDmCallback for bunderName %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()) { @@ -397,7 +705,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) { - HILOGE("RegisterDevStateCallback failed for bunderName %{public}s", bundleName.c_str()); + DMLOG(DM_LOG_ERROR, "RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; } g_deviceStateCallbackMap[bundleName] = callback; @@ -419,12 +727,17 @@ void DeviceManagerNapi::CreateDmCallback(std::string &bundleName, std::string &e discoverCallback->IncreaseRefCount(); return; } - - if (eventType == DM_NAPI_EVENT_DEVICE_AUTH_RESULT) { - auto iter = g_authCallbackMap.find(bundleName); - if (iter == g_authCallbackMap.end()) { - auto callback = std::make_shared(bundleName); - g_authCallbackMap[bundleName] = callback; + + 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; } @@ -435,12 +748,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()) { - HILOGE("ReleaseDmCallback: cannot find stateCallback for bunderName %{public}s", bundleName.c_str()); + DMLOG(DM_LOG_ERROR, "ReleaseDmCallback: cannot find stateCallback for bunderName %s", bundleName.c_str()); return; } int32_t ret = DeviceManager::GetInstance().UnRegisterDevStateCallback(bundleName); if (ret != 0) { - HILOGE("RegisterDevStateCallback failed for bunderName %{public}s", bundleName.c_str()); + DMLOG(DM_LOG_ERROR, "RegisterDevStateCallback failed for bunderName %s", bundleName.c_str()); return; } g_deviceStateCallbackMap.erase(bundleName); @@ -462,19 +775,74 @@ void DeviceManagerNapi::ReleaseDmCallback(std::string &bundleName, std::string & return; } - if (eventType == DM_NAPI_EVENT_DEVICE_AUTH_RESULT) { - auto iter = g_authCallbackMap.find(bundleName); - if (iter == g_authCallbackMap.end()) { + 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_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)); - g_authCallbackMap.erase(bundleName); + 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) { - HILOGI("GetTrustedDeviceList in"); + DMLOG(DM_LOG_INFO, "GetTrustedDeviceList in"); size_t argc = 0; napi_value thisVar = nullptr; napi_value array = nullptr; @@ -488,7 +856,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) { - HILOGE("GetTrustedDeviceList for bunderName %{public}s failed, ret %{public}d", + DMLOG(DM_LOG_ERROR, "GetTrustedDeviceList for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); return array; } @@ -498,14 +866,14 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba napi_create_array(env, &array); napi_is_array(env, array, &isArray); if (isArray == false) { - HILOGE("napi_create_array fail"); + DMLOG(DM_LOG_ERROR, "napi_create_array fail"); } for (size_t i = 0; i != devList.size(); ++i) { DeviceInfoToJsArray(env, devList, i, array); } } else { - HILOGE("devList is null"); + DMLOG(DM_LOG_ERROR, "devList is null"); } return array; @@ -513,7 +881,7 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListSync(napi_env env, napi_callba napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callback_info info) { - HILOGI("StartDeviceDiscoverSync in"); + DMLOG(DM_LOG_INFO, "StartDeviceDiscoverSync in"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); napi_value result = nullptr; napi_valuetype valueType; @@ -538,7 +906,7 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(deviceManagerWrapper->bundleName_, subInfo, discoverCallback); if (ret != 0) { - HILOGE("StartDeviceDiscovery for bunderName %{public}s failed, ret %{public}d", + DMLOG(DM_LOG_ERROR, "StartDeviceDiscovery for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); return result; } @@ -549,7 +917,7 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback_info info) { - HILOGI("StopDeviceDiscoverSync in"); + DMLOG(DM_LOG_INFO, "StopDeviceDiscoverSync in"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); napi_value result = nullptr; napi_valuetype valueType; @@ -565,7 +933,7 @@ napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(deviceManagerWrapper->bundleName_, (int16_t)subscribeId); if (ret != 0) { - HILOGE("StopDeviceDiscovery for bunderName %{public}s failed, ret %{public}d", + DMLOG(DM_LOG_ERROR, "StopDeviceDiscovery for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); return result; } @@ -574,14 +942,25 @@ napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback return result; } -napi_value DeviceManagerNapi::AuthenticateDeviceSync(napi_env env, napi_callback_info info) +napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_info info) { - HILOGI("AuthenticateDeviceSync in"); - GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); + DMLOG(DM_LOG_INFO, "AuthenticateDevice in"); + GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); napi_value result = nullptr; - napi_valuetype valueType; - napi_typeof(env, argv[0], &valueType); - NAPI_ASSERT(env, valueType == napi_object, "Wrong argument type. Object expected."); + napi_valuetype deviceInfoType; + napi_typeof(env, argv[0], &deviceInfoType); + NAPI_ASSERT(env, deviceInfoType == napi_object, "Wrong argument type. Object expected."); + + napi_valuetype authparamType; + napi_typeof(env, argv[1], &authparamType); + NAPI_ASSERT(env, authparamType == napi_object, "Wrong argument type. Object expected."); + + napi_valuetype eventHandleType = napi_undefined; + napi_typeof(env, argv[2], &eventHandleType); + NAPI_ASSERT(env, eventHandleType == napi_function, "Wrong argument type. Function expected."); + + authAsyncCallbackInfo_.env = env; + napi_create_reference(env, argv[2], 1, &authAsyncCallbackInfo_.callback); DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); @@ -597,13 +976,56 @@ napi_value DeviceManagerNapi::AuthenticateDeviceSync(napi_env env, napi_callback DmDeviceInfo deviceInfo; JsToDmDeviceInfo(env, argv[0], deviceInfo); - std::string extra = ""; + DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); + std::string extra; + JsToDmAppImageInfoAndDmExtra(env, argv[1], appImageInfo, extra, authAsyncCallbackInfo_.authType); + int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, deviceInfo, - extra, authCallback); + appImageInfo, extra, authCallback); if (ret != 0) { - HILOGE("AuthenticateDevice for bunderName %{public}s failed, ret %{public}d", + DMLOG(DM_LOG_ERROR, "AuthenticateDevice for bunderName %s failed, ret %d", + deviceManagerWrapper->bundleName_.c_str(), ret); + } + + napi_get_undefined(env, &result); + return result; +} + +napi_value DeviceManagerNapi::VerifyAuthInfo(napi_env env, napi_callback_info info) +{ + DMLOG(DM_LOG_INFO, "VerifyAuthInfo in"); + GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); + napi_value result = nullptr; + 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."); + + verifyAsyncCallbackInfo_.env = env; + napi_create_reference(env, argv[1], 1, &verifyAsyncCallbackInfo_.callback); + + DeviceManagerNapi *deviceManagerWrapper = nullptr; + napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + + std::shared_ptr verifyCallback = nullptr; + auto iter = g_checkAuthCallbackMap.find(deviceManagerWrapper->bundleName_); + if (iter == g_checkAuthCallbackMap.end()) { + verifyCallback = std::make_shared(deviceManagerWrapper->bundleName_); + g_checkAuthCallbackMap[deviceManagerWrapper->bundleName_] = verifyCallback; + } else { + verifyCallback = iter->second; + } + std::string authParam; + JsToDmAuthInfo(env, argv[0], authParam); + + int32_t ret = DeviceManager::GetInstance().CheckAuthentication(deviceManagerWrapper->bundleName_, + authParam, verifyCallback); + if (ret != 0) { + DMLOG(DM_LOG_ERROR, "VerifyAuthInfo for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); - return result; } napi_get_undefined(env, &result); @@ -612,7 +1034,7 @@ napi_value DeviceManagerNapi::AuthenticateDeviceSync(napi_env env, napi_callback napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) { - HILOGI("JsOn in"); + DMLOG(DM_LOG_INFO, "JsOn in"); GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2"); @@ -635,7 +1057,7 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - HILOGI("JsOn for bunderName %{public}s, eventType %{public}s ", deviceManagerWrapper->bundleName_.c_str(), + DMLOG(DM_LOG_INFO, "JsOn for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); deviceManagerWrapper->On(eventType, argv[1]); CreateDmCallback(deviceManagerWrapper->bundleName_, eventType); @@ -647,7 +1069,7 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) { - HILOGI("JsOff in"); + DMLOG(DM_LOG_INFO, "JsOff in"); GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); size_t requireArgc = 1; NAPI_ASSERT(env, argc >= requireArgc, "Wrong number of arguments, required 1"); @@ -673,7 +1095,7 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - HILOGI("JsOff for bunderName %{public}s, eventType %{public}s ", deviceManagerWrapper->bundleName_.c_str(), + DMLOG(DM_LOG_INFO, "JsOff for bunderName %s, eventType %s ", deviceManagerWrapper->bundleName_.c_str(), eventType.c_str()); deviceManagerWrapper->Off(eventType); ReleaseDmCallback(deviceManagerWrapper->bundleName_, eventType); @@ -685,7 +1107,7 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_info info) { - HILOGI("ReleaseDeviceManager in"); + DMLOG(DM_LOG_INFO, "ReleaseDeviceManager in"); size_t argc = 0; napi_value thisVar = nullptr; napi_value result = nullptr; @@ -695,10 +1117,10 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); - HILOGI("ReleaseDeviceManager for bunderName %{public}s", deviceManagerWrapper->bundleName_.c_str()); + DMLOG(DM_LOG_INFO, "ReleaseDeviceManager for bunderName %s", deviceManagerWrapper->bundleName_.c_str()); int32_t ret = DeviceManager::GetInstance().UnInitDeviceManager(deviceManagerWrapper->bundleName_); if (ret != 0) { - HILOGE("ReleaseDeviceManager for bunderName %{public}s failed, ret %{public}d", + DMLOG(DM_LOG_ERROR, "ReleaseDeviceManager for bunderName %s failed, ret %d", deviceManagerWrapper->bundleName_.c_str(), ret); napi_create_uint32(env, ret, &result); return result; @@ -709,6 +1131,7 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i g_deviceStateCallbackMap.erase(deviceManagerWrapper->bundleName_); g_discoverCallbackMap.erase(deviceManagerWrapper->bundleName_); g_authCallbackMap.erase(deviceManagerWrapper->bundleName_); + g_checkAuthCallbackMap.erase(deviceManagerWrapper->bundleName_); napi_get_undefined(env, &result); return result; } @@ -725,7 +1148,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) { - HILOGE("InitDeviceManager for bunderName %{public}s failed", bundleName.c_str()); + DMLOG(DM_LOG_ERROR, "InitDeviceManager for bunderName %s failed", bundleName.c_str()); return; } g_initCallbackMap[bundleName] = initCallback; @@ -741,12 +1164,12 @@ 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) { - HILOGE("Create DeviceManagerNapi for bunderName %{public}s failed", asCallbackInfo->bundleName); + DMLOG(DM_LOG_ERROR, "Create DeviceManagerNapi for bunderName %s failed", asCallbackInfo->bundleName); asCallbackInfo->status = -1; } if (asCallbackInfo->status == 0) { - HILOGI("InitDeviceManager for bunderName %{public}s success", asCallbackInfo->bundleName); + DMLOG(DM_LOG_INFO, "InitDeviceManager for bunderName %s success", asCallbackInfo->bundleName); napi_get_undefined(env, &result[0]); napi_value callback = nullptr; napi_value callResult = nullptr; @@ -754,7 +1177,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 { - HILOGI("InitDeviceManager for bunderName %{public}s failed", asCallbackInfo->bundleName); + DMLOG(DM_LOG_INFO, "InitDeviceManager for bunderName %s failed", asCallbackInfo->bundleName); napi_value message = nullptr; napi_create_object(env, &result[0]); napi_create_int32(env, asCallbackInfo->status, &message); @@ -771,7 +1194,7 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_info info) { - HILOGI("CreateDeviceManager in"); + DMLOG(DM_LOG_INFO, "CreateDeviceManager in"); GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); NAPI_ASSERT(env, argc >= DM_NAPI_ARGS_TWO, "Wrong number of arguments, required 2"); @@ -798,7 +1221,7 @@ napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_in napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) { - HILOGI("DeviceManagerNapi Constructor in"); + DMLOG(DM_LOG_INFO, "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"); @@ -810,7 +1233,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); - HILOGI("create DeviceManagerNapi for packageName:%{public}s", bundleName); + DMLOG(DM_LOG_INFO, "create DeviceManagerNapi for packageName:%s", bundleName); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); obj->bundleName_ = std::string(bundleName); g_deviceManagerMap[obj->bundleName_] = obj; @@ -833,7 +1256,10 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getTrustedDeviceListSync", GetTrustedDeviceListSync), DECLARE_NAPI_FUNCTION("startDeviceDiscovery", StartDeviceDiscoverSync), DECLARE_NAPI_FUNCTION("stopDeviceDiscovery", StopDeviceDiscoverSync), - DECLARE_NAPI_FUNCTION("authenticateDevice", AuthenticateDeviceSync), + DECLARE_NAPI_FUNCTION("authenticateDevice", AuthenticateDevice), + DECLARE_NAPI_FUNCTION("verifyAuthInfo", VerifyAuthInfo), + DECLARE_NAPI_FUNCTION("setUserOperation", SetUserOperationSync), + DECLARE_NAPI_FUNCTION("getAuthenticationParam", GetAuthenticationParamSync), DECLARE_NAPI_FUNCTION("on", JsOn), DECLARE_NAPI_FUNCTION("off", JsOff) }; @@ -842,14 +1268,14 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) DECLARE_NAPI_STATIC_FUNCTION("createDeviceManager", CreateDeviceManager), }; - HILOGD("DeviceManagerNapi::Init() is called!"); + DMLOG(DM_LOG_DEBUG, "DeviceManagerNapi::Init() is called!"); NAPI_CALL(env, napi_define_class(env, DEVICE_MANAGER_NAPI_CLASS_NAME.c_str(), NAPI_AUTO_LENGTH, Constructor, nullptr, sizeof(dmProperties) / sizeof(dmProperties[0]), dmProperties, &dmClass)); 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)); - HILOGI("All props and functions are configured.."); + DMLOG(DM_LOG_INFO, "All props and functions are configured.."); return exports; } @@ -858,7 +1284,7 @@ napi_value DeviceManagerNapi::Init(napi_env env, napi_value exports) */ static napi_value Export(napi_env env, napi_value exports) { - HILOGI("Export() is called!"); + DMLOG(DM_LOG_INFO, "Export() is called!"); DeviceManagerNapi::Init(env, exports); return exports; } @@ -881,6 +1307,6 @@ static napi_module g_dmModule = { */ extern "C" __attribute__((constructor)) void RegisterModule(void) { - HILOGI("RegisterModule() is called!"); + DMLOG(DM_LOG_INFO, "RegisterModule() is called!"); napi_module_register(&g_dmModule); } diff --git a/ohos.build b/ohos.build index 66b59c67a..a5ba6d594 100644 --- a/ohos.build +++ b/ohos.build @@ -9,13 +9,17 @@ "header": { "header_base": "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", "header_files": [ - "device_manager_proxy.h", - "idevice_manager.h" + "device_manager.h", + "device_manager_callback.h", + "dm_device_info.h", + "dm_subscribe_info.h", + "dm_app_image_info.h" ] } } ], "module_list": [ + "//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/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 35ff65151..a4aeac7b8 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -11,83 +11,179 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/ohos.gni") +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} + import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -config("dmservice_config") { - visibility = [ ":*" ] - include_dirs = [ - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "include", - "include/softbus", - "include/authdemo", - "include/util", - "${common_path}/log/include", - "${common_path}/utils/include", - "${innerkits_path}/native_cpp/include", - "//base/security/deviceauth/interfaces/innerkits", - "//third_party/json/include", - "//base/startup/syspara_lite/adapter/native/syspara/include", - ] +if (defined(ohos_lite)) { + executable("devicemanagerservice") { + include_dirs = [ + "include", + "include/ability", + "include/softbus", + "include/requestauth", + "include/auth", + "include/ipc", + "include/message", + "include/ipc/lite", + "${utils_path}/include/cipher", + "${utils_path}/include/log", + "${utils_path}/include/ipc/lite", + "${utils_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${common_path}/include", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc/lite", + ] - cflags = [ - "-Wall", - "-Werror", - "-Wdate-time", - "-Wfloat-equal", - "-Wshadow", - "-Wformat=2", - "-fvisibility=hidden", - "-fdata-sections", - "-ffunction-sections", - "-Os", - ] + 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", + ] - cflags_cc = [ - "-fvisibility-inlines-hidden", - "-Os", - ] -} + sources = [ + "src/ability/dm_ability_manager.cpp", + "src/auth/hichain_connector.cpp", + "src/ipc/ipc_server_adapter.cpp", + "src/ipc/ipc_server_listener_adapter.cpp", + "src/ipc/lite/ipc_cmd_parser.cpp", + "src/ipc/lite/ipc_server_listener.cpp", + "src/ipc/lite/ipc_server_listenermgr.cpp", + "src/ipc/lite/ipc_server_main.cpp", + "src/ipc/lite/ipc_server_stub.cpp", + "src/message/msg_codec.cpp", + "src/message/msg_head.cpp", + "src/message/msg_request_auth.cpp", + "src/message/msg_response_auth.cpp", + "src/message/msg_sync_group.cpp", + "src/requestauth/auth_manager.cpp", + "src/requestauth/request_session.cpp", + "src/requestauth/response_session.cpp", + "src/softbus/softbus_adapter.cpp", + "src/softbus/softbus_session.cpp", + ] + + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerservice\"", + "LOG_DOMAIN=0xD004100", + ] + + cflags_cc = build_flags + + deps = [ + "${utils_path}:devicemanagerutils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//base/security/deviceauth/services:deviceauth_sdk", + "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/communication/dsoftbus/sdk:softbus_client", + "//foundation/communication/ipc_lite:liteipc_adapter", + "//foundation/distributedschedule/samgr_lite/samgr:samgr", + "//third_party/bounds_checking_function:libsec_shared", + "//third_party/mbedtls:mbedtls_shared", + "//utils/native/lite:utils", + ] + } +} else { + ohos_shared_library("devicemanagerservice") { + include_dirs = [ + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "include", + "include/ability", + "include/softbus", + "include/requestauth", + "include/auth", + "include/ipc", + "include/message", + "include/ipc/standard", + "${utils_path}/include/cipher", + "${utils_path}/include/log", + "${utils_path}/include", + "${utils_path}/include/ipc/standard", + "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc/standard", + "//base/security/deviceauth/interfaces/innerkits", + "//base/startup/syspara_lite/adapter/native/syspara/include", + "//third_party/json/include", + ] -ohos_shared_library("devicemanagerservice") { - sources = [ - "src/device_manager_service.cpp", - "src/device_manager_stub.cpp", - "src/device_manager_listener_proxy.cpp", - "src/softbus/softbus_adapter.cpp", - "src/authdemo/device_client_channel.cpp", - "src/authdemo/device_server_channel.cpp", - "src/authdemo/hichain_adapter.cpp", - "src/util/anonymous_string.cpp", - ] + sources = [ + "src/ability/dm_ability_manager.cpp", + "src/auth/hichain_connector.cpp", + "src/ipc/ipc_server_adapter.cpp", + "src/ipc/ipc_server_listener_adapter.cpp", + "src/ipc/standard/ipc_cmd_parser.cpp", + "src/ipc/standard/ipc_server_client_proxy.cpp", + "src/ipc/standard/ipc_server_listener.cpp", + "src/ipc/standard/ipc_server_stub.cpp", + "src/message/msg_codec.cpp", + "src/message/msg_head.cpp", + "src/message/msg_request_auth.cpp", + "src/message/msg_response_auth.cpp", + "src/message/msg_sync_group.cpp", + "src/requestauth/auth_manager.cpp", + "src/requestauth/request_session.cpp", + "src/requestauth/response_session.cpp", + "src/softbus/softbus_adapter.cpp", + "src/softbus/softbus_session.cpp", + ] - configs = [ ":dmservice_config" ] + deps = [ + "${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", + ] - deps = [ - "//utils/native/base:utils", - "${innerkits_path}/native_cpp:devicemanagersdk", - "//base/security/deviceauth/services:deviceauth_sdk", - ] + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerservice\"", + "LOG_DOMAIN=0xD004100", + ] - defines = [ - "DH_LOG_TAG=\"devicemanager\"", - "LOG_DOMAIN=0xD004100", - ] + cflags_cc = build_flags - 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_L2:samgr_proxy", - "dsoftbus_standard:softbus_client", - "startup_l2:syspara", - ] + 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" + subsystem_name = "distributedhardware" - part_name = "device_manager_base" + part_name = "device_manager_base" + } } diff --git a/common/log/include/device_manager_log.h b/services/devicemanagerservice/include/ability/dm_ability_manager.h similarity index 41% rename from common/log/include/device_manager_log.h rename to services/devicemanagerservice/include/ability/dm_ability_manager.h index 2350623f2..17a9337d5 100644 --- a/common/log/include/device_manager_log.h +++ b/services/devicemanagerservice/include/ability/dm_ability_manager.h @@ -1,54 +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_LOG_H -#define OHOS_DEVICE_MANAGER_LOG_H -#include "hilog/log.h" - -namespace OHOS { -namespace DistributedHardware { -static constexpr OHOS::HiviewDFX::HiLogLabel DM_LABEL = {LOG_CORE, LOG_DOMAIN, DH_LOG_TAG}; - -#define PRINT_LOG(Level, fmt, ...) \ - OHOS::HiviewDFX::HiLog::Level(DM_LABEL, "[%{public}s] " fmt, __FUNCTION__, ##__VA_ARGS__) - -#ifdef HILOGD -#undef HILOGD -#endif - -#ifdef HILOGI -#undef HILOGI -#endif - -#ifdef HILOGW -#undef HILOGW -#endif - -#ifdef HILOGE -#undef HILOGE -#endif - -#ifdef HILOGF -#undef HILOGF -#endif - -#define HILOGD(fmt, ...) PRINT_LOG(Debug, fmt, ##__VA_ARGS__) -#define HILOGI(fmt, ...) PRINT_LOG(Info, fmt, ##__VA_ARGS__) -#define HILOGW(fmt, ...) PRINT_LOG(Warn, fmt, ##__VA_ARGS__) -#define HILOGE(fmt, ...) PRINT_LOG(Error, fmt, ##__VA_ARGS__) -#define HILOGF(fmt, ...) PRINT_LOG(Fatal, fmt, ##__VA_ARGS__) -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LOG_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_ABILITY_MANAGER_H +#define OHOS_DM_ABILITY_MANAGER_H + +#include +#include +#include +#include + +#include "single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +enum AbilityRole : int32_t { + ABILITY_ROLE_PASSIVE = 0, + ABILITY_ROLE_INITIATIVE = 1, + ABILITY_ROLE_UNKNOWN = 2 +}; + +enum AbilityStatus : int32_t { + ABILITY_STATUS_FAILED = 0, + ABILITY_STATUS_SUCCESS = 1, + ABILITY_STATUS_START = 2 +}; + +typedef enum FaAction { + USER_OPERATION_TYPE_ALLOW_AUTH = 0, + USER_OPERATION_TYPE_CANCEL_AUTH = 1, + USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT = 2, + USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY = 3, + USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT = 4 +} FaAction; + +class DmAbilityManager { +DECLARE_SINGLE_INSTANCE(DmAbilityManager); +public: + AbilityRole GetAbilityRole(); + AbilityStatus StartAbility(AbilityRole role); + void StartAbilityDone(); + +private: + void waitForTimeout(uint32_t timeout_s); + +private: + sem_t mSem_; + AbilityStatus mStatus_; + AbilityRole mAbilityStatus_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/services/devicemanagerservice/include/authdemo/hichain_adapter.h b/services/devicemanagerservice/include/auth/hichain_connector.h similarity index 38% rename from services/devicemanagerservice/include/authdemo/hichain_adapter.h rename to services/devicemanagerservice/include/auth/hichain_connector.h index 55ca7e5b2..18829cb61 100644 --- a/services/devicemanagerservice/include/authdemo/hichain_adapter.h +++ b/services/devicemanagerservice/include/auth/hichain_connector.h @@ -1,114 +1,99 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_HICHAIN_ADAPTER_H -#define OHOS_HICHAIN_ADAPTER_H - -#include -#include -#include -#include -#include - -#include "device_auth.h" -#include "event_handler.h" -#include "nlohmann/json.hpp" -#include "thread_pool.h" - -#include "device_client_channel.h" -#include "device_server_channel.h" -#include "single_instance.h" - -namespace OHOS { -namespace DistributedHardware { -enum { - SUCCESS = 0, - GROUP_CREATE_FAILED = 1, - MEMBER_ADD_FAILED = 2, - CREATE_CHANNEL_FAILED = 3, -}; - -struct DeviceReqInfo { - std::string deviceId; - std::string ipAddr; - short port; -}; - -class BindCallback { -public: - virtual void onBindSuccess(std::string deviceId, const char* returnData) = 0; - virtual void onBindFailed(std::string deviceId, int32_t errorCode) = 0; - virtual void onUnBindSuccess(std::string /* deviceId */, const char* /* returnData */) {} - virtual void onUnBindFailed(std::string /* deviceId */, int32_t /* errorCode*/) {} - virtual ~BindCallback() {} -}; - -class HichainAuthCallBack { -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, int operationCode, const char *returnData); - static void onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn); - static char* onBindRequest(int64_t requestId, int operationCode, const char *reqParams); -}; - -class HichainAdapter { -DECLARE_SINGLE_INSTANCE(HichainAdapter); -public: - int Init(); - - int32_t Bind(const DeviceReqInfo& devReqInfo, std::shared_ptr callback, bool sync = false); - - void OnBindSuccess(int64_t requestId, const char* returnData); - void OnBindFailed(int64_t requestId, int32_t errorCode); - - void UnBind(const std::string& deviceId); - void OnUnBindFinished(); - - bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); - - void OnGroupCreated(int64_t requestId, const char *groupInfo); - - char* OnBindRequest(int64_t requestId, int operationCode, const char *reqParams); - -private: - std::string GetGroupIdByName(int32_t groupType, const std::string& groupName); - int32_t CreateGroup(int64_t requestId); - int32_t AddMemeber(int64_t requestId, std::string& groupId, const std::string& pinCode); - int64_t GenRequestId(); - -private: - std::atomic requestIdIndex_ {0}; - std::map bindingDeviceMap_; - std::map> clientBindReqMap_; - std::map> bindCallBackMap_; - const DeviceGroupManager* deviceGroupManager_ = nullptr; - std::unique_ptr deviceServerInst_; - mutable ThreadPool threadPool_; - - DeviceAuthCallback deviceAuthCallback_ = { - .onTransmit = HichainAuthCallBack::onTransmit, - .onSessionKeyReturned = HichainAuthCallBack::onSessionKeyReturned, - .onFinish = HichainAuthCallBack::onFinish, - .onError = HichainAuthCallBack::onError, - .onRequest = HichainAuthCallBack::onBindRequest, - }; - - // call back for socket channel - std::function onError_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_HICHAIN_ADAPTER_H \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_HICHAIN_CONNECTOR_H +#define OHOS_HICHAIN_CONNECTOR_H + +#include +#include +#include + +#include "nlohmann/json.hpp" + +#include "device_auth.h" + +#include "single_instance.h" +#include "msg_response_auth.h" + +namespace OHOS { +namespace DistributedHardware { +enum { + HICHAIN_SUCCESS = 0, + GROUP_CREATE_FAILED = 1, + MEMBER_ADD_FAILED = 2, + CREATE_CHANNEL_FAILED = 3, +}; + +struct GroupInfo { + std::string groupName; + std::string groupId; + std::string groupOwner; + int32_t groupType; + int32_t groupVisibility; + + GroupInfo() : groupName(""), groupId(""), groupOwner(""), groupType(0), groupVisibility(0) {} +}; + +void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo); + +class GroupCreateCallback { +public: + virtual void OnGroupCreated(int64_t requestId, const std::string &groupId) = 0; +}; + +class HichainAuthenCallBack { +public: + static bool onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); + static void onSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); + static void onFinish(int64_t requestId, int operationCode, const char *returnData); + static void onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn); + static char *onRequest(int64_t requestId, int operationCode, const char *reqParams); +}; + +class HichainConnector { +DECLARE_SINGLE_INSTANCE(HichainConnector); +public: + int Init(); + bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); + int64_t GenRequestId(); + void RegisterConnectorCallback(std::shared_ptr callback); + int32_t CreateGroup(int64_t requestId, const std::string &groupName); + int32_t AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth); + void NotifyHostOnCheckAuthResult(int errorCode); + 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); + +private: + std::string GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth); + bool IsGroupInfoInvalid(GroupInfo &group); + +private: + std::atomic requestIdIndex_ {0}; + std::shared_ptr groupCreateCallback_ = nullptr; + const DeviceGroupManager *deviceGroupManager_ = nullptr; + DeviceAuthCallback deviceAuthCallback_ = { + .onTransmit = nullptr, + .onFinish = HichainAuthenCallBack::onFinish, + .onError = HichainAuthenCallBack::onError, + .onRequest = HichainAuthenCallBack::onRequest, + }; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_HICHAIN_ADAPTER_H diff --git a/services/devicemanagerservice/include/device_manager_listener_proxy.h b/services/devicemanagerservice/include/device_manager_listener_proxy.h deleted file mode 100644 index d32f7837a..000000000 --- a/services/devicemanagerservice/include/device_manager_listener_proxy.h +++ /dev/null @@ -1,44 +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_LISTENER_PROXY_H -#define OHOS_DEVICE_MANAGER_LISTENER_PROXY_H - -#include "idevice_manager_listener.h" -#include "iremote_proxy.h" - -namespace OHOS { -namespace DistributedHardware { -class DeviceManagerListenerProxy : public IRemoteProxy { -public: - explicit DeviceManagerListenerProxy(const sptr& impl) - : IRemoteProxy(impl) {}; - ~DeviceManagerListenerProxy() {}; - int32_t OnDeviceOnline(std::string &packageName, const DmDeviceInfo &deviceInfo) override; - int32_t OnDeviceOffline(std::string &packageName, const DmDeviceInfo &deviceInfo) override; - int32_t OnDeviceChanged(std::string &packageName, const DmDeviceInfo &deviceInfo) override; - int32_t OnDeviceFound(std::string &packageName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo) override; - int32_t OnDiscoverFailed(std::string &packageName, uint16_t subscribeId, int32_t failedReason) override; - int32_t OnDiscoverySuccess(std::string &packageName, uint16_t subscribeId) override; - int32_t OnAuthResult(std::string &packageName, std::string &deviceId, int32_t status, int32_t reason) override; -private: - bool WriteInterfaceToken(MessageParcel &data); - -private: - static inline BrokerDelegator delegator_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LISTENER_PROXY_H diff --git a/services/devicemanagerservice/include/device_manager_service.h b/services/devicemanagerservice/include/device_manager_service.h deleted file mode 100644 index af19ab97e..000000000 --- a/services/devicemanagerservice/include/device_manager_service.h +++ /dev/null @@ -1,98 +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_SERVICE_H -#define OHOS_DEVICE_MANAGER_SERVICE_H - -#include -#include -#include -#include -#include -#include "system_ability.h" -#include "thread_pool.h" -#include "iremote_stub.h" -#include "idevice_manager.h" -#include "idevice_manager_listener.h" -#include "device_manager_stub.h" -#include "single_instance.h" -#include "hichain_adapter.h" - -namespace OHOS { -namespace DistributedHardware { -enum class ServiceRunningState { - STATE_NOT_START, - STATE_RUNNING -}; - -enum DmBindStatus : uint32_t { - STATE_BIND_SUCCESS, - STATE_BIND_FAILD -}; - -class AppDeathRecipient : public IRemoteObject::DeathRecipient { -public: - void OnRemoteDied(const wptr& remote) override; - AppDeathRecipient() = default; - ~AppDeathRecipient() = default; -}; - -class HiChainBindCallback : public BindCallback { -public: - void onBindSuccess(std::string deviceId, const char* returnData) override; - void onBindFailed(std::string deviceId, int32_t errorCode) override; -}; - -class DeviceManagerService : public SystemAbility, public DeviceManagerStub { -friend class HiChainBindCallback; -DECLARE_SYSTEM_ABILITY(DeviceManagerService); -DECLARE_SINGLE_INSTANCE_BASE(DeviceManagerService); -public: - DeviceManagerService(); - ~DeviceManagerService() = default; - void OnStart() override; - void OnStop() override; - ServiceRunningState QueryServiceState() const; - - int32_t GetTrustedDeviceList(std::string &packageName, std::string &extra, - std::vector &deviceList) override; - int32_t RegisterDeviceManagerListener(std::string &packageName, sptr listener) override; - int32_t UnRegisterDeviceManagerListener(std::string &packageName) override; - int32_t RegisterDeviceStateCallback(std::string &packageName, std::string &extra) override; - int32_t UnRegisterDeviceStateCallback(std::string &packageName) override; - int32_t StartDeviceDiscovery(std::string &packageName, DmSubscribeInfo &subscribeInfo) override; - int32_t StopDeviceDiscovery(std::string &packageName, uint16_t subscribeId) override; - int32_t AuthenticateDevice(std::string &packageName, const DmDeviceInfo &deviceInfo, std::string &extra) override; - const std::map>& GetDmListener(); - const sptr GetDmListener(std::string packageName) const; - -private: - bool Init(); - void RegisterDeviceStateListener(); - -private: - bool registerToService_; - ServiceRunningState state_; - mutable ThreadPool threadPool_; - std::mutex listenerLock_; - std::shared_ptr hichainBindCallback_; - std::map> appRecipient_; - std::map> dmListener_; - std::map devStateCallbackParas_; - std::map authCallbackParas_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_SERVICE_H diff --git a/services/devicemanagerservice/include/authdemo/device_server_channel.h b/services/devicemanagerservice/include/message/msg_codec.h similarity index 38% rename from services/devicemanagerservice/include/authdemo/device_server_channel.h rename to services/devicemanagerservice/include/message/msg_codec.h index 6e3b279fc..7c51a2de6 100644 --- a/services/devicemanagerservice/include/authdemo/device_server_channel.h +++ b/services/devicemanagerservice/include/message/msg_codec.h @@ -1,53 +1,45 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DEVICE_SERVER_CHANNEL_H -#define OHOS_DEVICE_SERVER_CHANNEL_H - -#include -#include -#include - -#include "device_auth.h" - -namespace OHOS { -namespace DistributedHardware { -class DeviceServerChannel { -public: - DeviceServerChannel(const DeviceGroupManager& deviceGroupManager, - std::function onError) - : socketFd_(-1), clientFd_(-1), deviceGroupManager_(deviceGroupManager), onError_(onError) {} - ~DeviceServerChannel(); - - DeviceServerChannel()=delete; - DeviceServerChannel(const DeviceServerChannel&)=delete; - DeviceServerChannel &operator=(const DeviceServerChannel&)=delete; - -public: - int32_t Start(const int32_t port); - bool Send(const char* data, const int32_t dataLen); - void Receive(); - void OnDataReceived(const char* data, const int32_t dataLen); - void ResetConnection(); - -private: - int32_t socketFd_; - int32_t clientFd_; - const DeviceGroupManager& deviceGroupManager_; - std::function onError_; -}; -} -} -#endif \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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); +}; +} +} +#endif diff --git a/services/devicemanagerservice/include/message/msg_head.h b/services/devicemanagerservice/include/message/msg_head.h new file mode 100644 index 000000000..b79b99f3e --- /dev/null +++ b/services/devicemanagerservice/include/message/msg_head.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_MSG_HEAD_H +#define OHOS_MSG_HEAD_H + +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace DistributedHardware { +enum DmMsgType : int32_t { + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_REQ_AUTH = 100, + MSG_TYPE_INVITE_AUTH_INFO = 102, + MSG_TYPE_RESP_AUTH = 200, + MSG_TYPE_JOIN_AUTH_INFO = 201, + MSG_TYPE_CHANNEL_CLOSED = 300, + MSG_TYPE_SYNC_GROUP = 400, + MSG_TYPE_AUTH_BY_PIN = 500, +}; + +class MsgHead { +public: + MsgHead(): mMsgType_(0), mItfVer_("") {}; + MsgHead(int32_t msg): mMsgType_(msg), mItfVer_("") {}; + ~MsgHead() = default; + void Encode(nlohmann::json &json); + static std::shared_ptr Decode(nlohmann::json &json); + int32_t GetMsgType(); +private: + int32_t mMsgType_; + std::string mItfVer_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/devicemanagerservice/include/message/msg_request_auth.h b/services/devicemanagerservice/include/message/msg_request_auth.h new file mode 100644 index 000000000..c02fd17b5 --- /dev/null +++ b/services/devicemanagerservice/include/message/msg_request_auth.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_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() {}; + 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); + void GetDecodeAppInfo(const std::string appString, uint8_t **outBuffer, int32_t &outBufferLen); + int32_t GetMsgSlice(); + int32_t GetMsgCnt(); + std::string GetRequestDeviceId(); + +private: + std::string ToHexString(int32_t value); + std::string EncodeDevInfo(); + static int32_t DecodeFirstPackageMsg(nlohmann::json &json, std::shared_ptr msg); + static void DecodeDeviceInfo(nlohmann::json &json, std::shared_ptr msg); + static std::string StringSub(std::string &thumbStr, int32_t start, int32_t length); + int32_t GetEncodedAppInfo(const uint8_t *dataSrc, size_t srcLen, std::string &outString); + 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); + +public: + std::shared_ptr mHead_; + std::string mHostPkg_; + std::string mTargetPkg_; + std::string mDeviceName_; + std::string mToken_; + std::string mDeviceId_; + std::string mDeviceType_; + std::string mAppName_; + std::string mAppDescription_; + std::string mAppIcon_; + std::string mAppThumbnail_; + int32_t mAuthType_; + int32_t mGroupVisibility_; + int32_t mMsgSlice_; + int32_t mMsgCnt_ = 0; + int32_t mThumbnailSize_; + int32_t mAppIconSize_; +}; +} +} + + +#endif diff --git a/services/devicemanagerservice/include/authdemo/device_client_channel.h b/services/devicemanagerservice/include/message/msg_response_auth.h similarity index 38% rename from services/devicemanagerservice/include/authdemo/device_client_channel.h rename to services/devicemanagerservice/include/message/msg_response_auth.h index dac934e17..8694aadbf 100644 --- a/services/devicemanagerservice/include/authdemo/device_client_channel.h +++ b/services/devicemanagerservice/include/message/msg_response_auth.h @@ -1,53 +1,60 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DEVICE_CLIENT_CHANNEL_H -#define OHOS_DEVICE_CLIENT_CHANNEL_H - -#include -#include - -#include "device_auth.h" - -namespace OHOS { -namespace DistributedHardware { -class DeviceClientChannel { -public: - DeviceClientChannel(int64_t requestId, const DeviceGroupManager& deviceGroupManager, - std::function onError) - : requestId_(requestId), socketFd_(-1), deviceGroupManager_(deviceGroupManager), onError_(onError) {} - ~DeviceClientChannel(); - - DeviceClientChannel()=delete; - DeviceClientChannel(const DeviceClientChannel&)=delete; - DeviceClientChannel &operator=(const DeviceClientChannel&)=delete; - -public: - int32_t Connect(const std::string& ip, short port); - bool Send(const char* data, const int32_t dataLen); - void Receive(void); - void OnDataReceived(const char* data, const int32_t dataLen); - void ResetConnection(); - -private: - int64_t requestId_; - int32_t socketFd_; - const DeviceGroupManager& deviceGroupManager_; - // call back for socket channel - std::function onError_; -}; -} -} -#endif \ No newline at end of file +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR 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 "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_; + int32_t mReply_; + std::string mNetId_; + std::string mGroupId_; + std::string mGroupName_; + std::string mDeviceId_; + int32_t mPinCode_; + int64_t mRequestId_; + std::vector mSyncGroupList_; +}; +} +} +#endif diff --git a/common/utils/include/device_manager_errno.h b/services/devicemanagerservice/include/message/msg_sync_group.h similarity index 49% rename from common/utils/include/device_manager_errno.h rename to services/devicemanagerservice/include/message/msg_sync_group.h index e2b8cf2c5..eb7961895 100644 --- a/common/utils/include/device_manager_errno.h +++ b/services/devicemanagerservice/include/message/msg_sync_group.h @@ -1,36 +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_ERRNO_H -#define OHOS_DEVICE_MANAGER_ERRNO_H -#include "errors.h" - -namespace OHOS { -namespace DistributedHardware { -enum { - DISTRIBUTEDHARDWARE_MODULE_DEVICEMANAGER = 0x00 -}; - -// Error code for Common -constexpr ErrCode DEVICE_MANAGER_ERR_OFFSET = ErrCodeOffset(SUBSYS_DISTRIBUTEDHARDWARE, - DISTRIBUTEDHARDWARE_MODULE_DEVICEMANAGER); -enum { - ERR_DEVICEMANAGER_OPERATION_FAILED = DEVICE_MANAGER_ERR_OFFSET + 1, - ERR_DEVICEMANAGER_SERVICE_NOT_READY = DEVICE_MANAGER_ERR_OFFSET + 2, - ERR_DEVICEMANAGER_DEVICE_ALREADY_TRUSTED = DEVICE_MANAGER_ERR_OFFSET + 3, -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LOG_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_MSG_SYNC_GROUP_H +#define OHOS_MSG_SYNC_GROUP_H + +#include +#include + +#include "nlohmann/json.hpp" + +#include "msg_head.h" + +namespace OHOS { +namespace DistributedHardware { +class MsgSyncGroup { +public: + MsgSyncGroup(std::vector &groupList, std::string &deviceId); + ~MsgSyncGroup() = default; + void Encode(nlohmann::json &json); + +private: + std::shared_ptr mHead_; + std::string mDeviceId_; + std::vector mGroupIdList_; +}; +} +} +#endif \ No newline at end of file diff --git a/services/devicemanagerservice/include/device_manager_stub.h b/services/devicemanagerservice/include/requestauth/auth_manager.h similarity index 31% rename from services/devicemanagerservice/include/device_manager_stub.h rename to services/devicemanagerservice/include/requestauth/auth_manager.h index db5555468..8778a44bc 100644 --- a/services/devicemanagerservice/include/device_manager_stub.h +++ b/services/devicemanagerservice/include/requestauth/auth_manager.h @@ -1,48 +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_STUB_H -#define OHOS_DEVICE_MANAGER_STUB_H - -#include -#include "iremote_stub.h" -#include "idevice_manager.h" - -namespace OHOS { -namespace DistributedHardware { -class DeviceManagerStub : public IRemoteStub { -public: - DeviceManagerStub(); - ~DeviceManagerStub(); - int32_t OnRemoteRequest(uint32_t code, - MessageParcel &data, MessageParcel &reply, MessageOption &option) override; -private: - int32_t RegisterDeviceManagerListenerInner(MessageParcel &data, MessageParcel &reply); - int32_t UnRegisterDeviceManagerListenerInner(MessageParcel &data, MessageParcel &reply); - int32_t RegisterDeviceStateCallbackInner(MessageParcel &data, MessageParcel &reply); - int32_t UnRegisterDeviceStateCallbackInner(MessageParcel &data, MessageParcel &reply); - int32_t GetTrustedDeviceListInner(MessageParcel &data, MessageParcel &reply); - int32_t StartDeviceDiscoveryInner(MessageParcel &data, MessageParcel &reply); - int32_t StopDeviceDiscoveryInner(MessageParcel &data, MessageParcel &reply); - int32_t AuthenticateDeviceInner(MessageParcel &data, MessageParcel &reply); - template - int32_t GetParcelableInfo(MessageParcel &reply, T &parcelableInfo); - bool EnforceInterceToken(MessageParcel &data); - using CmdProcFunc = int32_t (DeviceManagerStub::*)(MessageParcel &data, MessageParcel &reply); - std::map memberFuncMap_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_STUB_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_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(); + +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_ = ""; + 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 new file mode 100644 index 000000000..2595bf6f6 --- /dev/null +++ b/services/devicemanagerservice/include/requestauth/request_session.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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, const DmDeviceInfo &devReqInfo, const DmAppImageInfo &imageInfo, + std::string &extrasJson); + ~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); + +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: + int32_t mSessionType_; + int32_t mStatus_; + std::string mHostPkgName_; + std::string mTargetPkgName; + std::string mToken_; + int32_t mPinToken_; + DmDeviceInfo mDevInfo_; + DmAppImageInfo mImageInfo_; + long long mChannelId_; + bool mIsChannelOpened_ {false}; + std::string mRemoteDeviceId_; + std::string mRemoteNetId_; + std::string mRemoteGroupId_; + std::string mRemoteGroupName_; + long long mRequestId_; + std::shared_ptr responseMsgPtr_; +}; +} +} +#endif diff --git a/interfaces/inner_kits/native_cpp/include/idevice_manager_listener.h b/services/devicemanagerservice/include/requestauth/response_session.h similarity index 32% rename from interfaces/inner_kits/native_cpp/include/idevice_manager_listener.h rename to services/devicemanagerservice/include/requestauth/response_session.h index bf55490d3..fb547b9f3 100644 --- a/interfaces/inner_kits/native_cpp/include/idevice_manager_listener.h +++ b/services/devicemanagerservice/include/requestauth/response_session.h @@ -1,50 +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_DEVICE_MANAGER_LISTENER_INTERFACE_H -#define OHOS_DEVICE_MANAGER_LISTENER_INTERFACE_H - -#include "iremote_broker.h" -#include "dm_device_info.h" - -namespace OHOS { -namespace DistributedHardware { -enum { - ON_DEVICE_ONLINE = 0, - ON_DEVICE_OFFLINE = 1, - ON_DEVICE_CHANGE = 2, - ON_DEVICE_FOUND = 3, - ON_DISCOVER_SUCCESS = 4, - ON_DISCOVER_FAILED = 5, - ON_AUTH_RESULT = 6, -}; - -class IDeviceManagerListener : public OHOS::IRemoteBroker { -public: - virtual ~IDeviceManagerListener() {} - virtual int32_t OnDeviceOnline(std::string &packageName, const DmDeviceInfo &deviceInfo) = 0; - virtual int32_t OnDeviceOffline(std::string &packageName, const DmDeviceInfo &deviceInfo) = 0; - virtual int32_t OnDeviceChanged(std::string &packageName, const DmDeviceInfo &deviceInfo) = 0; - virtual int32_t OnDeviceFound(std::string &packageName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo) = 0; - virtual int32_t OnDiscoverFailed(std::string &packageName, uint16_t subscribeId, int32_t failedReason) = 0; - virtual int32_t OnDiscoverySuccess(std::string &packageName, uint16_t subscribeId) = 0; - virtual int32_t OnAuthResult(std::string &packageName, std::string &deviceId, int32_t status, int32_t reason) = 0; - -public: - DECLARE_INTERFACE_DESCRIPTOR(u"ohos.distributedhardware.devicemanagerlistener"); -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DEVICE_MANAGER_LISTENER_INTERFACE_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_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" + +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 GroupCreateCallback, 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 BuildAuthenticationInfo(DmAuthParam &authParam); + void OnReceiveMsg(long long channelId, std::string &message); + long long GetRequestId(); + int32_t GetPinCodeByReqId(int64_t requestId); + bool IsMyChannelId(long long channelId); + +private: + void Release(); + int32_t DecodeReqMsg(std::string &message); + int32_t StartFaService(); + std::string GenerateGroupName(); + void OnUserConfirm(); + void OnUserReject(int32_t errorCode); + void CancelDisplay(); + int32_t GeneratePincode(); + +public: + 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_; +}; +} // namespace DistributedHardware +} // namespace OHOS + + +#endif diff --git a/services/devicemanagerservice/include/softbus/softbus_adapter.h b/services/devicemanagerservice/include/softbus/softbus_adapter.h index 6d0ba83dc..63fc95b3d 100644 --- a/services/devicemanagerservice/include/softbus/softbus_adapter.h +++ b/services/devicemanagerservice/include/softbus/softbus_adapter.h @@ -17,68 +17,60 @@ #define OHOS_DEVICE_MANAGER_SOFTBUS_ADAPTER_H #include +#include #include #include #include "softbus_bus_center.h" #include "discovery_service.h" #include "dm_device_info.h" #include "dm_subscribe_info.h" -#include "single_instance.h" namespace OHOS { namespace DistributedHardware { -struct SubscribeInfoAdapter { - SubscribeInfo info; - uint16_t subscribeIdOrigin; - uint16_t subscribeIdPrefix; +class PublishServiceCallBack { +public: + static void OnPublishSuccess(int32_t publishId); + static void OnPublishFail(int32_t publishId, PublishFailReason reason); }; class SoftbusAdapter { -DECLARE_SINGLE_INSTANCE(SoftbusAdapter); public: - static int32_t GetSoftbusTrustDevices(const std::string &packageName, std::string &extra, - std::vector &deviceList); - void RegSoftBusDeviceStateListener(); - int32_t StartSoftbusDiscovery(std::string &packageName, DmSubscribeInfo &info); - int32_t StopSoftbusDiscovery(std::string &packageName, uint16_t subscribeId); - static void OnSoftbusDeviceOffline(NodeBasicInfo *info); + 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(int subscribeId, DiscoveryFailReason failReason); - static void OnSoftbusDiscoverySuccess(int subscribeId); - static void OnSoftbusJoinLNNResult(ConnectionAddr *addr, const char *networkId, int32_t retCode); - static void OnSoftbusLeaveLNNResult(const char *networkId, int32_t retCode); - const std::map>>& GetsubscribeInfos(); - int32_t SoftbusJoinLnn(std::string devId); - int32_t SoftbusLeaveLnn(std::string networkId); - int32_t GetConnectionIpAddr(std::string deviceId, std::string &ipAddr); - static bool IsDeviceOnLine(std::string &deviceId); - + static void OnSoftbusDiscoverFailed(int32_t subscribeId, DiscoveryFailReason failReason); + static void OnSoftbusDiscoverySuccess(int32_t subscribeId); private: - static void OnSoftBusDeviceStateChange(DmDeviceState state, NodeBasicInfo *info); - std::string GetPackageNameBySubscribeId(uint16_t subscribeId); - bool GetsubscribeIdAdapter(std::string packageName, int16_t originId, int32_t &adapterId); - bool GetPackageNameBySubscribeId(int32_t adapterId, std::string &packageName); - void SaveDiscoverDeviceInfo(const DeviceInfo *deviceInfo); - void RemoveDiscoverDeviceInfo(const std::string deviceId); - + 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: - std::map>> subscribeInfos_; - std::map> discoverDeviceInfoMap_; - std::vector> discoverDeviceInfoVector_; - std::atomic subscribeIdPrefix {0}; - INodeStateCb softbusNodeStateCb = { - .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED, - .onNodeOnline = OnSoftBusDeviceOnline, - .onNodeOffline = OnSoftbusDeviceOffline, - .onNodeBasicInfoChanged = OnSoftbusDeviceInfoChanged - }; - IDiscoveryCallback softbusDiscoverCallback = { - .OnDeviceFound = OnSoftbusDeviceFound, - .OnDiscoverFailed = OnSoftbusDiscoverFailed, - .OnDiscoverySuccess = OnSoftbusDiscoverySuccess + 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 diff --git a/interfaces/inner_kits/native_cpp/src/dm_subscribe_info.cpp b/services/devicemanagerservice/include/softbus/softbus_session.h similarity index 37% rename from interfaces/inner_kits/native_cpp/src/dm_subscribe_info.cpp rename to services/devicemanagerservice/include/softbus/softbus_session.h index 0bba105f1..71b699376 100644 --- a/interfaces/inner_kits/native_cpp/src/dm_subscribe_info.cpp +++ b/services/devicemanagerservice/include/softbus/softbus_session.h @@ -1,58 +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_subscribe_info.h" - -namespace OHOS { -namespace DistributedHardware { -bool DmSubscribeInfo::ReadFromParcel(Parcel &parcel) -{ - subscribeId = parcel.ReadInt16(); - mode = (DmDiscoverMode)parcel.ReadInt32(); - medium = (DmExchangeMedium)parcel.ReadInt32(); - freq = (DmExchangeFreq)parcel.ReadInt32(); - isSameAccount = parcel.ReadBool(); - isWakeRemote = parcel.ReadBool(); - capability = parcel.ReadString(); - return true; -} - -DmSubscribeInfo *DmSubscribeInfo::Unmarshalling(Parcel &parcel) -{ - DmSubscribeInfo *info = new (std::nothrow) DmSubscribeInfo(); - if (info == nullptr) { - return nullptr; - } - - if (!info->ReadFromParcel(parcel)) { - delete info; - info = nullptr; - } - return info; -} - -bool DmSubscribeInfo::Marshalling(Parcel &parcel) const -{ - parcel.WriteInt16(subscribeId); - parcel.WriteInt32((int32_t)mode); - parcel.WriteInt32((int32_t)medium); - parcel.WriteInt32((uint8_t)freq); - parcel.WriteBool(isSameAccount); - parcel.WriteBool(isWakeRemote); - parcel.WriteString(capability); - return true; -} -} // namespace DistributedHardware -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H +#define OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H + +#include +#include +#include + +#include "session.h" +#include "single_instance.h" +#include "softbus_common.h" + +namespace OHOS { +namespace DistributedHardware { +class SoftbusSession { +DECLARE_SINGLE_INSTANCE_BASE(SoftbusSession); +public: + int32_t Start(); + int32_t OnSessionOpened(int32_t sessionId, int32_t result); + void OnSessionClosed(int32_t sessionId); + void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + void CloseSession(int32_t sessionId); + int32_t SendMessages(const char *deviceId, std::vector &messages); + int32_t SendMsg(int32_t sessionId, std::string &message); + void GetPeerDeviceId(int32_t sessionId, std::string &peerDevId); +private: + SoftbusSession() = default; + ~SoftbusSession(); +private: + int32_t SendData(int32_t sessionId, const void *data, int32_t len); +private: + const char *PKG_NAME = "com.huawei.devicemanager"; + const char *SESSION_NAME = "com.huawei.devicemanager.resident"; + std::set sessionIdSet_; + std::vector messages_ {}; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_SOFTBUS_SESSION_H diff --git a/services/devicemanagerservice/src/ability/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/dm_ability_manager.cpp new file mode 100644 index 000000000..b9d310e3a --- /dev/null +++ b/services/devicemanagerservice/src/ability/dm_ability_manager.cpp @@ -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. + */ + +#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 "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"; + + mStatus_ = AbilityStatus::ABILITY_STATUS_START; + AAFwk::Want want; + AppExecFwk::ElementName element(deviceId, bundleName, abilityName); + want.SetElement(element); + + AAFwk::AbilityManagerClient::GetInstance()->Connect(); + ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); + if (result == OHOS::ERR_OK) { + DMLOG(DM_LOG_INFO, "Start Ability succeed"); + } else { + DMLOG(DM_LOG_INFO, "Start Ability faild"); + mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; + return mStatus_; + } + + waitForTimeout(ABILITY_START_TIMEOUT); + return mStatus_; +} + +void DmAbilityManager::waitForTimeout(uint32_t timeout_s) +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout_s; + sem_timedwait(&mSem_, &ts); +} + +void DmAbilityManager::StartAbilityDone() +{ + mStatus_ = AbilityStatus::ABILITY_STATUS_SUCCESS; + sem_post(&mSem_); +} +} +} diff --git a/services/devicemanagerservice/src/auth/hichain_connector.cpp b/services/devicemanagerservice/src/auth/hichain_connector.cpp new file mode 100644 index 000000000..fe9da1279 --- /dev/null +++ b/services/devicemanagerservice/src/auth/hichain_connector.cpp @@ -0,0 +1,415 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hichain_connector.h" + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" + +#include "parameter.h" + +#include "anonymous_string.h" +#include "device_manager_log.h" +#include "encrypt_utils.h" +#include "softbus_adapter.h" +#include "constants.h" +#include "ipc_server_listener_adapter.h" +#include "ipc_check_authenticate_req.h" +#include "softbus_session.h" +#include "auth_manager.h" + +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 = "com.huawei.devicemanager"; +const std::string DEVICE_MANAGER_GROUPNAME = "DMPeerToPeerGroup"; + +const int64_t MIN_REQUEST_ID = 1000000000; +const int64_t MAX_REQUEST_ID = 9999999999; +const int32_t FIELD_EXPIRE_TIME_VALUE = 7; +} + +IMPLEMENT_SINGLE_INSTANCE(HichainConnector); + +void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo) +{ + if (jsonObject.find(FIELD_GROUP_NAME) != jsonObject.end()) { + groupInfo.groupName = jsonObject.at(FIELD_GROUP_NAME).get(); + } + + if (jsonObject.find(FIELD_GROUP_ID) != jsonObject.end()) { + groupInfo.groupId = jsonObject.at(FIELD_GROUP_ID).get(); + } + + if (jsonObject.find(FIELD_GROUP_OWNER) != jsonObject.end()) { + groupInfo.groupOwner = jsonObject.at(FIELD_GROUP_OWNER).get(); + } + + if (jsonObject.find(FIELD_GROUP_TYPE) != jsonObject.end()) { + groupInfo.groupType = jsonObject.at(FIELD_GROUP_TYPE).get(); + } + + if (jsonObject.find(FIELD_GROUP_VISIBILITY) != jsonObject.end()) { + groupInfo.groupVisibility = jsonObject.at(FIELD_GROUP_VISIBILITY).get(); + } +} + +int HichainConnector::Init() +{ + DMLOG(DM_LOG_INFO, "HichainConnector::init, init device auth service."); + InitDeviceAuthService(); + + deviceGroupManager_ = GetGmInstance(); + if (deviceGroupManager_ == nullptr) { + DMLOG(DM_LOG_INFO, "HichainConnector::init, failed to init group manager!"); + return -1; + } + deviceGroupManager_->regCallback(DEVICE_MANAGER_APP.c_str(), &deviceAuthCallback_); + DMLOG(DM_LOG_INFO, "HichainConnector::init, init hichain adapter success."); + return 0; +} + +int64_t HichainConnector::GenRequestId() +{ + return EncryptUtils::GenRandLongLong(MIN_REQUEST_ID, MAX_REQUEST_ID); +} + +int32_t HichainConnector::CreateGroup(int64_t requestId, const std::string &groupName) +{ + if (deviceGroupManager_ == nullptr) { + DMLOG(DM_LOG_ERROR, "HichainConnector::CreateGroup group manager is null, requestId %lld.", requestId); + return FAIL; + } + + DMLOG(DM_LOG_INFO, "HichainConnector::CreateGroup requestId %lld", requestId); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string sLocalDeviceID = localDeviceId; + + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + jsonObj[FIELD_DEVICE_ID] = sLocalDeviceID; + jsonObj[FIELD_GROUP_NAME] = groupName; + jsonObj[FIELD_USER_TYPE] = 0; + jsonObj[FIELD_GROUP_VISIBILITY] = GROUP_VISIBILITY_PUBLIC; + jsonObj[FIELD_EXPIRE_TIME] = FIELD_EXPIRE_TIME_VALUE; + int32_t ret = deviceGroupManager_->createGroup(requestId, DEVICE_MANAGER_APP.c_str(), jsonObj.dump().c_str()); + if (ret != 0) { + DMLOG(DM_LOG_ERROR, "Faild to start CreateGroup task, ret: %d, requestId %lld.", ret, requestId); + return ret; + } + + return SUCCESS; +} + +void HichainConnector::RegisterConnectorCallback(std::shared_ptr callback) +{ + groupCreateCallback_ = callback; +} + +void HichainConnector::OnGroupCreated(int64_t requestId, const std::string &returnData) +{ + if (groupCreateCallback_ == nullptr) { + DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated groupCreateCallback_ not registe."); + return; + } + + nlohmann::json jsonObject = nlohmann::json::parse(returnData); + if (jsonObject.is_discarded()) { + DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated returnData not json."); + groupCreateCallback_->OnGroupCreated(requestId, ""); + return; + } + + if (jsonObject.find(FIELD_GROUP_ID) == jsonObject.end()) { + DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated failed to get groupId."); + groupCreateCallback_->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()); + groupCreateCallback_->OnGroupCreated(requestId, groupId); +} + +int32_t HichainConnector::AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth) +{ + DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber"); + if (deviceGroupManager_ == nullptr) { + DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber group manager is null."); + return -1; + } + + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string connectInfo = GetConnectPara(deviceId, msgResponseAuth); + + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = msgResponseAuth->GetGroupId(); + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + jsonObj[FIELD_PIN_CODE] = std::to_string(msgResponseAuth->GetPinCode()).c_str(); + jsonObj[FIELD_IS_ADMIN] = false; + jsonObj[FIELD_DEVICE_ID] = localDeviceId; + jsonObj[FIELD_GROUP_NAME] = msgResponseAuth->GetGroupName(); + jsonObj[FIELD_CONNECT_PARAMS] = connectInfo.c_str(); + std::string tmpStr = jsonObj.dump(); + + DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber completed"); + return deviceGroupManager_->addMemberToGroup(msgResponseAuth->GetRequestId(), DEVICE_MANAGER_APP.c_str(), + tmpStr.c_str()); +} + +std::string HichainConnector::GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth) +{ + ConnectionAddr *addrInfo = SoftbusAdapter::GetConnectAddr(deviceId); + if (addrInfo == nullptr) { + DMLOG(DM_LOG_ERROR, "HichainConnector::GetConnectPara addrInfo error"); + return ""; + } + + DMLOG(DM_LOG_ERROR, "HichainConnector::GetConnectPara get addrInfo"); + nlohmann::json jsonPara; + jsonPara[DEVICE_ID] = msgResponseAuth->GetDeviceId(); + if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { + DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is ETH"); + jsonPara[ETH_IP] = addrInfo->info.ip.ip; + jsonPara[ETH_PORT] = addrInfo->info.ip.port; + } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) { + DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is WIFI"); + jsonPara[WIFI_IP] = addrInfo->info.ip.ip; + jsonPara[WIFI_PORT] = addrInfo->info.ip.port; + } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) { + DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is br"); + jsonPara[BR_MAC] = addrInfo->info.br.brMac; + } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) { + DMLOG(DM_LOG_INFO, "HichainConnector::AddMemeber addr type is ble"); + jsonPara[BLE_MAC] = addrInfo->info.ble.bleMac; + } else { + DMLOG(DM_LOG_ERROR, "HichainConnector::AddMemeber addrInfo not right"); + return ""; + } + return jsonPara.dump(); +} + +void HichainConnector::GetRelatedGroups(std::string deviceId, std::vector &groupList) +{ + DMLOG(DM_LOG_INFO, "HichainConnector::GetRelatedGroups Start to get local related groups."); + uint32_t groupNum = 0; + char *returnGroups = nullptr; + int ret = deviceGroupManager_->getRelatedGroups(DEVICE_MANAGER_APP.c_str(), deviceId.c_str(), + &returnGroups, &groupNum); + if (ret != 0) { + DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups faild , ret: %d.", ret); + return; + } + + if (returnGroups == nullptr) { + DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups faild , returnGroups is nullptr"); + return; + } + + if (groupNum == 0) { + DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups group failed, groupNum is 0."); + return; + } + + std::string relatedGroups = std::string(returnGroups); + nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups); + if (jsonObject.is_discarded()) { + DMLOG(DM_LOG_ERROR, "returnGroups parse error"); + return; + } + + std::vector groupInfos = jsonObject.get>(); + if (groupInfos.size() == 0) { + DMLOG(DM_LOG_ERROR, "HichainConnector::GetRelatedGroups group failed, groupInfos is empty."); + return; + } + + groupList = groupInfos; + return; +} + +void HichainConnector::GetSyncGroupList(std::vector &groupList, std::vector &syncGroupList) +{ + if (groupList.empty()) { + DMLOG(DM_LOG_ERROR, "groupList is empty."); + return; + } + + for (auto group : groupList) { + if (IsGroupInfoInvalid(group)) { + continue; + } + syncGroupList.push_back(group.groupId); + } +} + +bool HichainConnector::IsGroupInfoInvalid(GroupInfo &group) +{ + if (group.groupType == GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP || group.groupVisibility == GROUP_VISIBILITY_PUBLIC || + group.groupOwner != DEVICE_MANAGER_APP) { + return true; + } + return false; +} + +void HichainConnector::SyncGroups(std::string deviceId, std::vector &remoteGroupIdList) +{ + std::vector groupInfoList; + GetRelatedGroups(deviceId, groupInfoList); + for (auto &groupInfo : groupInfoList) { + if (IsGroupInfoInvalid(groupInfo)) { + continue; + } + + auto iter = std::find(remoteGroupIdList.begin(), remoteGroupIdList.end(), groupInfo.groupId); + if (iter == remoteGroupIdList.end()) { + (void)DelMemberFromGroup(groupInfo.groupId, deviceId); + } + } +} + +int32_t HichainConnector::DelMemberFromGroup(std::string groupId, std::string deviceId) +{ + int64_t requestId = GenRequestId(); + DMLOG(DM_LOG_INFO, "Start to delete memeber from group, requestId %lld, deviceId %s, groupId %s", + requestId, GetAnonyString(deviceId).c_str(), GetAnonyString(groupId).c_str()); + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = groupId; + jsonObj[FIELD_DELETE_ID] = deviceId; + std::string deleteParams = jsonObj.dump(); + + int ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DEVICE_MANAGER_APP.c_str(), deleteParams.c_str()); + if (ret != 0) { + DMLOG(DM_LOG_ERROR, "HichainConnector::DelMemberFromGroup faild , ret: %d.", ret); + return ret; + } + return 0; +} + +void HichainConnector::DeleteGroup(std::string &groupId) +{ + int64_t requestId = GenRequestId(); + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = groupId; + std::string disbandParams = jsonObj.dump(); + + int ret = deviceGroupManager_->deleteGroup(requestId, DEVICE_MANAGER_APP.c_str(), disbandParams.c_str()); + if (ret != 0) { + DMLOG(DM_LOG_ERROR, "HichainConnector::DeleteGroup faild , ret: %d.", ret); + } +} + +void HichainAuthenCallBack::onFinish(int64_t requestId, int 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().NotifyHostOnCheckAuthResult(SUCCESS); + } + + if (operationCode == GroupOperationCode::GROUP_CREATE) { + DMLOG(DM_LOG_INFO, "Create group success"); + std::string returnStr = returnData; + HichainConnector::GetInstance().OnGroupCreated(requestId, returnStr); + } + + 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, int operationCode, int 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().NotifyHostOnCheckAuthResult(FAIL); + } + + if (operationCode == GroupOperationCode::GROUP_CREATE) { + DMLOG(DM_LOG_ERROR, "Create group failed"); + HichainConnector::GetInstance().NotifyHostOnCheckAuthResult(FAIL); + } + + 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, int 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; +} + +void HichainConnector::NotifyHostOnCheckAuthResult(int errorCode) +{ + DMLOG(DM_LOG_INFO, "notify host result, errorcode: %d", errorCode); + std::string hostPkgName = "com.ohos.devicemanagerui"; + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + + std::string authParam = AuthManager::GetInstance().GetAuthPara(); + IpcServerListenerAdapter::GetInstance().OnCheckAuthResult(hostPkgName, authParam, errorCode, 0); +} +} +} diff --git a/services/devicemanagerservice/src/authdemo/device_client_channel.cpp b/services/devicemanagerservice/src/authdemo/device_client_channel.cpp deleted file mode 100644 index f1ccaea7b..000000000 --- a/services/devicemanagerservice/src/authdemo/device_client_channel.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_client_channel.h" - -#include -#include - -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include - -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { - constexpr int32_t CLIENT_DATA_BUFFER_LENGTH = 2048; - const int32_t RECV_DATA_TIMEOUT = 5; - const int32_t REQUEST_ID_LENGTH = 10; -} - -DeviceClientChannel::~DeviceClientChannel() -{ - if (socketFd_ != -1) { - close(socketFd_); - socketFd_ = -1; - } -} - -int32_t DeviceClientChannel::Connect(const std::string& ip, short port) -{ - HILOGI("DeviceClientChannel::Connect begin to connect to server."); - int32_t socketFd = socket(AF_INET, SOCK_STREAM, 0); - if (socketFd == -1) { - HILOGE("DeviceClientChannel::Connect create socket failed, errMsg: %{public}s.", strerror(errno)); - return -1; - } - - struct sockaddr_in addr; - if (memset_s(&addr, sizeof(addr), 0, sizeof(addr)) != EOK) { - HILOGE("DeviceClientChannel::Connect error init addr."); - close(socketFd); - return -1; - } - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = inet_addr(ip.c_str()); - addr.sin_port = htons(port); - - int32_t ret = connect(socketFd, (struct sockaddr*) &addr, sizeof(addr)); - if (ret == -1) { - HILOGE("DeviceClientChannel::Connect connet server failed, errMsg: %{public}s.", strerror(errno)); - close(socketFd); - return -1; - } - - socketFd_ = socketFd; - HILOGI("DeviceClientChannel::Connect connect to server, fd: %{public}d.", socketFd_); - - // wait five seconds, if recv none, release the connection - struct timeval timeout = {RECV_DATA_TIMEOUT, 0}; - setsockopt(socketFd_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval)); - return 0; -} - -bool DeviceClientChannel::Send(const char* data, const int32_t dataLen) -{ - // The client needs to add requestId to the header of the data - std::stringstream reqIdStr; - reqIdStr << requestId_; - - int32_t sendDataLen = dataLen + REQUEST_ID_LENGTH; - std::unique_ptr sendData = std::make_unique(sendDataLen); - if (memset_s(sendData.get(), sendDataLen, 0, sendDataLen) != EOK) { - HILOGE("DeviceClientChannel::Send error init send data."); - return false; - } - - if (memcpy_s(sendData.get(), sendDataLen, reqIdStr.str().c_str(), REQUEST_ID_LENGTH) != EOK) { - HILOGE("DeviceClientChannel::Send error init requestId."); - return false; - } - - if (memcpy_s(sendData.get() + REQUEST_ID_LENGTH, sendDataLen - REQUEST_ID_LENGTH, data, dataLen) != EOK) { - HILOGE("DeviceClientChannel::Send error init data."); - return false; - } - - int32_t ret = send(socketFd_, sendData.get(), sendDataLen, 0); - if (ret == -1) { - HILOGE("DeviceClientChannel::send data failed, errMsg: %{public}s.", strerror(errno)); - return false; - } - - HILOGI("DeviceClientChannel::send data, size:%{public}d.", ret); - return true; -} - -void DeviceClientChannel::Receive() -{ - HILOGI("DeviceClientChannel::Receive data, socketFd:%{public}d.", socketFd_); - char dataBuf[CLIENT_DATA_BUFFER_LENGTH] = {0}; - - while (socketFd_ != -1) { - (void)memset_s(dataBuf, sizeof(dataBuf), 0, sizeof(dataBuf)); - int32_t rc = recv(socketFd_, dataBuf, sizeof(dataBuf), 0); - if (rc == 0) { - HILOGE("DeviceClientChannel::Receive error, client shutdown, socketFd_:%{public}d, errMsg: %{public}s.", - socketFd_, strerror(errno)); - close(socketFd_); - socketFd_ = -1; - break; - } else if (rc == -1 || rc == EAGAIN) { - HILOGE("DeviceClientChannel::Receive data failed, socketFd_:%{public}d, errMsg: %{public}s.", - socketFd_, strerror(errno)); - close(socketFd_); - socketFd_ = -1; - break; - } else { - HILOGI("DeviceClientChannel::Receive data, socketFd_:%{public}d, size:%{public}d.", socketFd_, rc); - OnDataReceived(dataBuf, rc); - } - } - HILOGI("DeviceClientChannel::Receive data end, socketFd:%{public}d.", socketFd_); -} - -void DeviceClientChannel::OnDataReceived(const char* data, const int32_t dataLen) -{ - int ret = deviceGroupManager_.processData(requestId_, (uint8_t *) data, dataLen); - HILOGI("DeviceClientChannel::OnDataReceived process data, ret:%{public}d, dataLen:%{public}d.", ret, dataLen); - if (ret != 0) { - close(socketFd_); - socketFd_ = -1; - onError_(requestId_, 0, ret, nullptr); - } -} - -void DeviceClientChannel::ResetConnection() -{ - HILOGI("DeviceClientChannel::ResetConnection bind finished, release connection."); - close(socketFd_); - socketFd_ = -1; -} -} -} \ No newline at end of file diff --git a/services/devicemanagerservice/src/authdemo/device_server_channel.cpp b/services/devicemanagerservice/src/authdemo/device_server_channel.cpp deleted file mode 100644 index af142ff3c..000000000 --- a/services/devicemanagerservice/src/authdemo/device_server_channel.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_server_channel.h" - -#include -#include - -#include -#include - -#include -#include - -#include -#include - -#include - -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { - const int32_t DATA_BUFFER_LENGTH = 2048; - const int32_t REQUEST_ID_LENGTH = 10; - const int32_t LISTENING_QUEUE_LEN = 10; - const int64_t MIN_REQUEST_ID = 1000000000; - const int32_t RECV_DATA_TIMEOUT = 5; -} - -DeviceServerChannel::~DeviceServerChannel() -{ - if (socketFd_ != -1) { - close(socketFd_); - socketFd_ = -1; - } - - if (clientFd_ != -1) { - close(clientFd_); - clientFd_ = -1; - } -} - -int32_t DeviceServerChannel::Start(const int32_t port) -{ - HILOGI("DeviceServerChannel::Start begin to start server."); - if (port <= 0) { - HILOGE("DeviceServerChannel::start port is invalid."); - return -1; - } - - int32_t socketFd = socket(AF_INET, SOCK_STREAM, 0); - if (socketFd == -1) { - HILOGE("DeviceServerChannel::start create socket failed, errMsg: %{public}s.", strerror(errno)); - return -1; - } - - struct sockaddr_in addr; - if (memset_s(&addr, sizeof(addr), 0, sizeof(addr)) != EOK) { - HILOGE("DeviceServerChannel::Start error init addr."); - close(socketFd); - return -1; - } - addr.sin_family = AF_INET; - addr.sin_addr.s_addr = INADDR_ANY; - addr.sin_port = htons(port); - - int32_t ret = bind(socketFd, (struct sockaddr*) &addr, sizeof(addr)); - if (ret == -1) { - HILOGE("DeviceServerChannel::start bind addr failed, errMsg: %{public}s.", strerror(errno)); - close(socketFd); - return -1; - } - - socketFd_ = socketFd; - HILOGI("DeviceServerChannel::start bind addr success, fd:%{public}d.", socketFd_); - - ret = listen(socketFd_, LISTENING_QUEUE_LEN); - if (ret == -1) { - HILOGE("DeviceServerChannel::start listen port failed, errMsg: %{public}s.", strerror(errno)); - close(socketFd_); - socketFd_ = -1; - return -1; - } - - return 0; -} - -void DeviceServerChannel::Receive() -{ - HILOGI("DeviceServerChannel::receive begin to listen client connecting."); - struct sockaddr_in client_addr; - socklen_t len = sizeof(client_addr); - - while (true) { - int32_t fd = accept(socketFd_, (struct sockaddr*) &client_addr, &len); - if (fd == -1) { - HILOGE("DeviceServerChannel::receive accept connect failed, errMsg: %{public}s.", strerror(errno)); - continue; - } - - if (clientFd_ != -1) { - HILOGW("DeviceServerChannel::receive another client is connected, close new connect."); - close(fd); - continue; - } - - HILOGI("DeviceServerChannel::receive new client in."); - clientFd_ = fd; - - // wait five seconds, if recv none, release the connection - struct timeval timeout = {RECV_DATA_TIMEOUT, 0}; - setsockopt(clientFd_, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval)); - - // demo project, blocked here to receive data, informal solution, will be discard later - char dataBuf[DATA_BUFFER_LENGTH] = {0}; - while (clientFd_ != -1) { - if (memset_s(dataBuf, sizeof(dataBuf), 0, sizeof(dataBuf)) != EOK) { - HILOGE("DeviceServerChannel::receive error init data buf."); - close(clientFd_); - clientFd_ = -1; - break; - } - - int32_t rc = recv(clientFd_, dataBuf, sizeof(dataBuf), 0); - if (rc == 0) { - HILOGE("DeviceServerChannel::receive error, client shutdown."); - close(clientFd_); - clientFd_ = -1; - break; - } else if (rc == -1 || rc == EAGAIN) { - HILOGE("DeviceServerChannel::receive receive data failed, errMsg: %{public}s.", strerror(errno)); - close(clientFd_); - clientFd_ = -1; - break; - } else { - HILOGI("DeviceServerChannel::receive receive data, size:%{public}d.", rc); - OnDataReceived(dataBuf, rc); - } - } - } -} - -void DeviceServerChannel::OnDataReceived(const char* data, const int32_t dataLen) -{ - HILOGI("DeviceServerChannel::OnDataReceived dataLen:%{public}d.", dataLen); - if (dataLen < REQUEST_ID_LENGTH) { - HILOGI("DeviceServerChannel::OnDataReceived error, data is invalid."); - return; - } - - // the client adds requestId to the header of data, the server needs to parse the original data - char reqIdChar[REQUEST_ID_LENGTH + 1] = {0}; - (void)memcpy_s(reqIdChar, sizeof(reqIdChar), data, REQUEST_ID_LENGTH); - reqIdChar[REQUEST_ID_LENGTH] = '\0'; - int64_t requestId = strtoll(reqIdChar, nullptr, REQUEST_ID_LENGTH); - if (requestId < MIN_REQUEST_ID) { - HILOGI("DeviceServerChannel::OnDataReceived error, requestId is invalid."); - return; - } - - const char* newData = data + REQUEST_ID_LENGTH; - int len = dataLen - REQUEST_ID_LENGTH; - int ret = deviceGroupManager_.processData(requestId, (const uint8_t *) newData, len); - HILOGI("DeviceServerChannel::OnDataReceived process data, ret:%{public}d, dataLen:%{public}d.", ret, len); - if (ret != 0) { - onError_(requestId, 0, ret, nullptr); - close(clientFd_); - clientFd_ = -1; - } -} - -bool DeviceServerChannel::Send(const char* data, const int32_t dataLen) -{ - int32_t ret = send(clientFd_, data, dataLen, 0); - if (ret == -1) { - HILOGE("DeviceServerChannel::send failed,socket:%{public}d,errMsg: %{public}s.", clientFd_, strerror(errno)); - return false; - } - - HILOGI("DeviceServerChannel::send data,socket:%{public}d, size:%{public}d.", clientFd_, ret); - return true; -} - -void DeviceServerChannel::ResetConnection() -{ - HILOGI("DeviceServerChannel::ResetConnection bind finished, release connection."); - close(clientFd_); - clientFd_ = -1; -} -} -} \ No newline at end of file diff --git a/services/devicemanagerservice/src/authdemo/hichain_adapter.cpp b/services/devicemanagerservice/src/authdemo/hichain_adapter.cpp deleted file mode 100644 index 5ccc74020..000000000 --- a/services/devicemanagerservice/src/authdemo/hichain_adapter.cpp +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "hichain_adapter.h" - -#include -#include -#include -#include - -#include "parameter.h" - -#include "anonymous_string.h" -#include "device_client_channel.h" -#include "device_manager_log.h" -#include "device_server_channel.h" - - -namespace OHOS { -namespace DistributedHardware { -namespace { -// demo solution, may has security issues, later will be replaced by a formal plan -const std::string PIN_CODE = ""; -const int32_t PORT = -1; - -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 DEVICE_UUID_LENGTH = 65; -const int32_t PEER_TO_PEER_GROUP = 256; -const int32_t FIELD_EXPIRE_TIME_VALUE = 90; - -const int32_t THREAD_POOL_NUMBER = 20; -} - -IMPLEMENT_SINGLE_INSTANCE(HichainAdapter); - -int HichainAdapter::Init() -{ - HILOGI("HichainAdapter::init, begin to init hichain adapter."); - if (threadPool_.GetThreadsNum() == 0) { - threadPool_.Start(THREAD_POOL_NUMBER); - } - - bindingDeviceMap_.clear(); - bindCallBackMap_.clear(); - clientBindReqMap_.clear(); - - // call back for socket channel - using std::placeholders::_1; - using std::placeholders::_2; - using std::placeholders::_3; - using std::placeholders::_4; - onError_ = std::bind(HichainAuthCallBack::onError, _1, _2, _3, _4); - - HILOGI("HichainAdapter::init, init device auth service."); - InitDeviceAuthService(); - - // get group auth manager instance, and register callback - deviceGroupManager_ = GetGmInstance(); - if (deviceGroupManager_ == nullptr) { - HILOGE("HichainAdapter::init, failed to init group manager!"); - return -1; - } - deviceGroupManager_->regCallback(DEVICE_MANAGER_APP.c_str(), &deviceAuthCallback_); - - HILOGI("HichainAdapter::init, start socket server channel."); - deviceServerInst_ = std::make_unique(*deviceGroupManager_, onError_); - if (deviceServerInst_->Start(PORT) == -1) { - HILOGE("HichainAdapter::init, failed to start server!"); - return -1; - } - - // start the server channel to receive data - auto receiveFunc = [this]() { - this->deviceServerInst_->Receive(); - }; - threadPool_.AddTask(receiveFunc); - - HILOGI("HichainAdapter::init, init hichain adapter success."); - return 0; -} - -int32_t HichainAdapter::Bind(const DeviceReqInfo& devReqInfo, std::shared_ptr callback, bool sync) -{ - (void)sync; - HILOGI("HichainAdapter::Bind, begin to bind device: %{public}s.", GetAnonyString(devReqInfo.deviceId).c_str()); - for (auto &item : bindingDeviceMap_) { - if (item.second == devReqInfo.deviceId) { - HILOGW("HichainAdapter::bind device is binding, update call back."); - } - } - - int64_t requestId = GenRequestId(); - std::shared_ptr clientChannel = - std::make_shared(requestId, *deviceGroupManager_, onError_); - if (clientChannel->Connect(devReqInfo.ipAddr, PORT) == -1) { - HILOGE("HichainAdapter::bind failed to connect to server, create channel failed."); - return CREATE_CHANNEL_FAILED; - } - - // start the client channel to recevice data - auto receiveFunc = [&clientChannel]() { - clientChannel->Receive(); - }; - threadPool_.AddTask(receiveFunc); - - std::string groupId = GetGroupIdByName(PEER_TO_PEER_GROUP, DEVICE_MANAGER_GROUPNAME); - if (groupId == "") { - HILOGE("HichainAdapter::bind group not exist, begin to create group."); - int32_t ret = CreateGroup(requestId); - if (ret != 0) { - HILOGE("HichainAdapter::bind faild to start create group task, ret: %{public}d.", ret); - return GROUP_CREATE_FAILED; - } - } else { - HILOGE("HichainAdapter::bind group exist, begin to add member."); - int ret = AddMemeber(requestId, groupId, PIN_CODE); - if (ret != 0) { - HILOGE("HichainAdapter::bind faild to start add member task, ret: %{public}d.", ret); - return MEMBER_ADD_FAILED; - } - } - - clientBindReqMap_[requestId] = clientChannel; - bindingDeviceMap_[requestId] = devReqInfo.deviceId; - bindCallBackMap_[requestId] = callback; - return SUCCESS; -} - -std::string HichainAdapter::GetGroupIdByName(int32_t groupType, const std::string& groupName) -{ - HILOGI("HichainAdapter::GetGroupIdByName get group info."); - if (deviceGroupManager_ == nullptr) { - HILOGE("HichainAdapter::GetGroupIdByName group manager is null."); - return ""; - } - - nlohmann::json reqParam; - reqParam[FIELD_GROUP_TYPE] = groupType; - reqParam[FIELD_GROUP_NAME] = groupName; - - char* returnGroupVec = nullptr; - uint32_t groupNum = 0; - int32_t ret = deviceGroupManager_->getGroupInfo(DEVICE_MANAGER_APP.c_str(), reqParam.dump().c_str(), - &returnGroupVec, &groupNum); - if (ret != 0) { - HILOGE("HichainAdapter::GetGroupIdByName failed to get group info, ret=%{public}d.", ret); - return ""; - } - - if (groupNum == 0) { - HILOGE("HichainAdapter::GetGroupIdByName group not exist, return empty."); - return ""; - } - - nlohmann::json groupObj = nlohmann::json::parse(returnGroupVec, nullptr, false); - if (groupObj.is_discarded()) { - HILOGE("HichainAdapter::GetGroupIdByName parse group info error, json invalid."); - return ""; - } - - for (auto& item : groupObj) { - if (item.contains(FIELD_GROUP_ID)) { - return item.at(FIELD_GROUP_ID); - } - } - - HILOGI("HichainAdapter::GetGroupIdByName group info not found, return empty"); - return ""; -} - -int32_t HichainAdapter::CreateGroup(int64_t requestId) -{ - HILOGE("HichainAdapter::CreateGroup requestId:%{public}lld.", requestId); - if (deviceGroupManager_ == nullptr) { - HILOGE("HichainAdapter::CreateGroup group manager is null."); - return -1; - } - - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_TYPE] = PEER_TO_PEER_GROUP; - jsonObj[FIELD_GROUP_NAME] = DEVICE_MANAGER_GROUPNAME; - - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - - jsonObj[FIELD_DEVICE_ID] = localDeviceId; - jsonObj[FIELD_USER_TYPE] = 0; - jsonObj[FIELD_GROUP_VISIBILITY] = -1; - jsonObj[FIELD_EXPIRE_TIME] = FIELD_EXPIRE_TIME_VALUE; - - return deviceGroupManager_->createGroup(requestId, DEVICE_MANAGER_APP.c_str(), jsonObj.dump().c_str()); -} - -int32_t HichainAdapter::AddMemeber(int64_t requestId, std::string& groupId, const std::string& pinCode) -{ - HILOGE("HichainAdapter::AddMemeber requestId:%{public}lld.", requestId); - if (deviceGroupManager_ == nullptr) { - HILOGE("HichainAdapter::AddMemeber group manager is null."); - return -1; - } - - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_ID] = groupId; - jsonObj[FIELD_GROUP_TYPE] = PEER_TO_PEER_GROUP; - jsonObj[FIELD_PIN_CODE] = pinCode; - jsonObj[FIELD_IS_ADMIN] = true; - return deviceGroupManager_->addMemberToGroup(requestId, DEVICE_MANAGER_APP.c_str(), jsonObj.dump().c_str()); -} - -bool HichainAdapter::OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) -{ - HILOGI("HichainAdapter::OnTransmit requestId:%{public}lld, size:%{public}d.", requestId, dataLen); - if (clientBindReqMap_.count(requestId) > 0) { - HILOGI("HichainAdapter::OnTransmit client send to server."); - return clientBindReqMap_[requestId]->Send((const char*) data, dataLen); - } else { - HILOGI("HichainAdapter::OnTransmit server send to client."); - return deviceServerInst_->Send((const char*) data, dataLen); - } -} - -void HichainAdapter::OnGroupCreated(int64_t requestId, const char *groupInfo) -{ - nlohmann::json jsonObject = nlohmann::json::parse(groupInfo); - if (jsonObject.find(FIELD_GROUP_ID) == jsonObject.end()) { - HILOGE("HichainAdapter::onGroupCreated failed to get groupId."); - OnBindFailed(requestId, GROUP_CREATE_FAILED); - return; - } - - std::string groupId = jsonObject.at(FIELD_GROUP_ID).get(); - HILOGI("HichainAdapter::onGroupCreated group create success,groupId:%{public}s.", GetAnonyString(groupId).c_str()); - - // group创建成功之后,需要添加把对端设备添加到创建好的群组中 - int ret = AddMemeber(requestId, groupId, PIN_CODE); - if (ret != 0) { - HILOGE("HichainAdapter::onGroupCreated faild to start add member task, ret: %{public}d.", ret); - OnBindFailed(requestId, MEMBER_ADD_FAILED); - return; - } -} - -char* HichainAdapter::OnBindRequest(int64_t requestId, int operationCode, const char *reqParams) -{ - (void)requestId; - (void)operationCode; - (void)reqParams; - - HILOGI("HichainAdapter::OnBindRequest."); - nlohmann::json jsonObj; - jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = PIN_CODE; - 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 HichainAdapter::OnBindSuccess(int64_t requestId, const char* returnData) -{ - HILOGI("HichainAdapter::OnBindSuccess requestId:%{public}lld,dataLen:%{public}d.", requestId, strlen(returnData)); - if (bindCallBackMap_.count(requestId) == 1) { - bindCallBackMap_[requestId]->onBindSuccess(bindingDeviceMap_[requestId], returnData); - bindCallBackMap_.erase(requestId); - } - - if (clientBindReqMap_.count(requestId) == 1) { - clientBindReqMap_[requestId]->ResetConnection(); - clientBindReqMap_[requestId].reset(); - clientBindReqMap_.erase(requestId); - } - - if (bindingDeviceMap_.count(requestId) == 1) { - bindingDeviceMap_.erase(requestId); - } - - deviceServerInst_->ResetConnection(); -} - -int64_t HichainAdapter::GenRequestId() -{ - int64_t requestId = 0; - do { - requestId = (int64_t)requestIdIndex_ + MIN_REQUEST_ID; - if (requestId > MAX_REQUEST_ID) { - requestId = MIN_REQUEST_ID; - requestIdIndex_ = 0; - } else { - requestIdIndex_++; - } - } while (clientBindReqMap_.count(requestId) != 0); - return requestId; -} - -void HichainAdapter::OnBindFailed(int64_t requestId, int32_t errorCode) -{ - HILOGI("HichainAdapter::OnBindFailed requestId:%{public}lld, errorCode:%{public}d.", requestId, errorCode); - if (bindCallBackMap_.count(requestId) == 1) { - bindCallBackMap_[requestId]->onBindFailed(bindingDeviceMap_[requestId], errorCode); - bindCallBackMap_.erase(requestId); - } - - if (clientBindReqMap_.count(requestId) == 1) { - clientBindReqMap_[requestId].reset(); - clientBindReqMap_.erase(requestId); - } - - if (bindingDeviceMap_.count(requestId) == 1) { - bindingDeviceMap_.erase(requestId); - } -} - -void HichainAdapter::UnBind(const std::string& deviceId) -{ - // reserved interface, to be implemented - (void)deviceId; -} - -void HichainAdapter::OnUnBindFinished() -{ - // reserved interface, to be implemented -} - -bool HichainAuthCallBack::onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) -{ - HILOGI("HichainAuthCallBack::onTransmit requestId:%{public}lld,size:%{public}d.", requestId, dataLen); - return HichainAdapter::GetInstance().OnTransmit(requestId, data, dataLen); -} - -void HichainAuthCallBack::onSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) -{ - (void)requestId; - (void)sessionKey; - HILOGI("HichainAuthCallBack::onSessionKeyReturned size:%{public}d.", sessionKeyLen); -} - -void HichainAuthCallBack::onFinish(int64_t requestId, int operationCode, const char *returnData) -{ - HILOGI("HichainAuthCallBack::onFinish reqId:%{public}lld, operation:%{public}d.", requestId, operationCode); - if (operationCode == GroupOperationCode::GROUP_CREATE) { - HichainAdapter::GetInstance().OnGroupCreated(requestId, returnData); - return; - } - - if (operationCode == GroupOperationCode::MEMBER_INVITE || operationCode == GroupOperationCode::MEMBER_JOIN) { - HichainAdapter::GetInstance().OnBindSuccess(requestId, returnData); - } -} - -void HichainAuthCallBack::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) -{ - (void)errorReturn; - HILOGI("HichainAuthCallBack::onError reqId:%{public}lld, operation:%{public}d, errorCode:%{public}d.", - requestId, operationCode, errorCode); - HichainAdapter::GetInstance().OnBindFailed(requestId, errorCode); -} - -char* HichainAuthCallBack::onBindRequest(int64_t requestId, int operationCode, const char *reqParams) -{ - HILOGI("HichainAuthCallBack::onBindRequest reqId:%{public}lld, operation: %{public}d.", requestId, operationCode); - return HichainAdapter::GetInstance().OnBindRequest(requestId, operationCode, reqParams); -} -} -} diff --git a/services/devicemanagerservice/src/device_manager_listener_proxy.cpp b/services/devicemanagerservice/src/device_manager_listener_proxy.cpp deleted file mode 100644 index d721ef705..000000000 --- a/services/devicemanagerservice/src/device_manager_listener_proxy.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_manager_listener_proxy.h" - -#include "ipc_types.h" - -#include "device_manager_log.h" - -namespace OHOS { -namespace DistributedHardware { -bool DeviceManagerListenerProxy::WriteInterfaceToken(MessageParcel &data) -{ - if (!data.WriteInterfaceToken(DeviceManagerListenerProxy::GetDescriptor())) { - HILOGE("write interface token failed"); - return false; - } - return true; -} - -int32_t DeviceManagerListenerProxy::OnDeviceOnline(std::string &packageName, const DmDeviceInfo &deviceInfo) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteParcelable(&deviceInfo)) { - HILOGE("write deviceInfo failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(ON_DEVICE_ONLINE, data, reply, option); - if (error != ERR_NONE) { - HILOGE("OnDeviceOnline SendRequest fail, error: %{public}d", error); - return error; - } - - return ERR_NONE; -} - -int32_t DeviceManagerListenerProxy::OnDeviceOffline(std::string &packageName, const DmDeviceInfo &deviceInfo) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteParcelable(&deviceInfo)) { - HILOGE("write deviceInfo failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(ON_DEVICE_OFFLINE, data, reply, option); - if (error != ERR_NONE) { - HILOGE("OnDeviceOffline SendRequest fail, error: %{public}d", error); - return error; - } - - return ERR_NONE; -} - -int32_t DeviceManagerListenerProxy::OnDeviceChanged(std::string &packageName, const DmDeviceInfo &deviceInfo) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteParcelable(&deviceInfo)) { - HILOGE("write deviceInfo failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(ON_DEVICE_CHANGE, data, reply, option); - if (error != ERR_NONE) { - HILOGE("OnDeviceChanged SendRequest fail, error: %{public}d", error); - return error; - } - - return ERR_NONE; -} - -int32_t DeviceManagerListenerProxy::OnDeviceFound(std::string &packageName, uint16_t subscribeId, - const DmDeviceInfo &deviceInfo) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteInt16(subscribeId)) { - HILOGE("write subscribeId failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteParcelable(&deviceInfo)) { - HILOGE("write deviceInfo failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(ON_DEVICE_FOUND, data, reply, option); - if (error != ERR_NONE) { - HILOGE("OnDeviceFound SendRequest fail, error: %{public}d", error); - return error; - } - - return ERR_NONE; -} - -int32_t DeviceManagerListenerProxy::OnDiscoverFailed(std::string &packageName, uint16_t subscribeId, - int32_t failedReason) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteInt16(subscribeId)) { - HILOGE("write subscribeId failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteInt32(failedReason)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(ON_DISCOVER_FAILED, data, reply, option); - if (error != ERR_NONE) { - HILOGE("OnDiscoverFailed SendRequest fail, error: %{public}d", error); - return error; - } - - return ERR_NONE; -} - -int32_t DeviceManagerListenerProxy::OnDiscoverySuccess(std::string &packageName, uint16_t subscribeId) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteInt16(subscribeId)) { - HILOGE("write subscribeId failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(ON_DISCOVER_SUCCESS, data, reply, option); - if (error != ERR_NONE) { - HILOGE("OnDiscoverySuccess SendRequest fail, error: %{public}d", error); - return error; - } - - return ERR_NONE; -} - -int32_t DeviceManagerListenerProxy::OnAuthResult(std::string &packageName, std::string &deviceId, int32_t status, - int32_t reason) -{ - sptr remote = Remote(); - if (remote == nullptr) { - HILOGE("remote service null"); - return ERR_NULL_OBJECT; - } - - MessageParcel data; - MessageParcel reply; - MessageOption option; - if (!WriteInterfaceToken(data)) { - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(packageName)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteString(deviceId)) { - HILOGE("write packageName failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteInt32(status)) { - HILOGE("write status failed"); - return ERR_FLATTEN_OBJECT; - } - - if (!data.WriteInt32(reason)) { - HILOGE("write reason failed"); - return ERR_FLATTEN_OBJECT; - } - - int32_t error = remote->SendRequest(ON_AUTH_RESULT, data, reply, option); - if (error != ERR_NONE) { - HILOGE("OnAuthResult SendRequest fail, error: %{public}d", error); - return error; - } - - return ERR_NONE; -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_service.cpp b/services/devicemanagerservice/src/device_manager_service.cpp deleted file mode 100644 index 5da977ab7..000000000 --- a/services/devicemanagerservice/src/device_manager_service.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_manager_service.h" - -#include "if_system_ability_manager.h" -#include "ipc_skeleton.h" -#include "ipc_types.h" -#include "iservice_registry.h" -#include "string_ex.h" -#include "system_ability_definition.h" - -#include "anonymous_string.h" -#include "device_manager_errno.h" -#include "device_manager_log.h" -#include "softbus_adapter.h" - -#include "hichain_adapter.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { - const int32_t THREAD_POOL_TASK_NUM = 1; -} - -IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); - -const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&DeviceManagerService::GetInstance()); - -DeviceManagerService::DeviceManagerService() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true) -{ - registerToService_ = false; - state_ = ServiceRunningState::STATE_NOT_START; - hichainBindCallback_ = std::make_shared(); -} - -void DeviceManagerService::OnStart() -{ - HILOGI("DeviceManagerService::OnStart start"); - if (state_ == ServiceRunningState::STATE_RUNNING) { - HILOGD("DeviceManagerService has already started."); - return; - } - if (!Init()) { - HILOGE("failed to init DeviceManagerService"); - return; - } - state_ = ServiceRunningState::STATE_RUNNING; -} - -bool DeviceManagerService::Init() -{ - HILOGI("DeviceManagerService::Init ready to init."); - if (!registerToService_) { - bool ret = Publish(this); - if (!ret) { - HILOGE("DeviceManagerService::Init Publish failed!"); - return false; - } - registerToService_ = true; - } - if (threadPool_.GetThreadsNum() == 0) { - threadPool_.Start(THREAD_POOL_TASK_NUM); - } - RegisterDeviceStateListener(); - return true; -} - -void DeviceManagerService::OnStop() -{ - HILOGI("DeviceManagerService::OnStop ready to stop service."); - state_ = ServiceRunningState::STATE_NOT_START; - registerToService_ = false; -} - -ServiceRunningState DeviceManagerService::QueryServiceState() const -{ - return state_; -} - -void DeviceManagerService::RegisterDeviceStateListener() -{ - auto registerFunc = []() { - SoftbusAdapter::GetInstance().RegSoftBusDeviceStateListener(); - HichainAdapter::GetInstance().Init(); - }; - threadPool_.AddTask(registerFunc); -} - -int32_t DeviceManagerService::RegisterDeviceManagerListener(std::string &packageName, sptr listener) -{ - if (packageName.empty() || listener == nullptr) { - HILOGE("Error: parameter invalid"); - return ERR_NULL_OBJECT; - } - - HILOGI("In, packageName: %{public}s", packageName.c_str()); - std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(packageName); - if (iter != dmListener_.end()) { - HILOGI("RegisterDeviceManagerListener: listener already exists"); - return ERR_NONE; - } - - sptr appRecipient = sptr(new AppDeathRecipient()); - if (!listener->AddDeathRecipient(appRecipient)) { - HILOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); - } - dmListener_[packageName] = listener; - appRecipient_[packageName] = appRecipient; - return ERR_NONE; -} - -int32_t DeviceManagerService::UnRegisterDeviceManagerListener(std::string &packageName) -{ - if (packageName.empty()) { - HILOGE("Error: parameter invalid"); - return ERR_NULL_OBJECT; - } - - HILOGI("In, packageName: %{public}s", packageName.c_str()); - std::lock_guard autoLock(listenerLock_); - auto listenerIter = dmListener_.find(packageName); - if (listenerIter == dmListener_.end()) { - HILOGI("UnRegisterDeviceManagerListener: listener not exists"); - return ERR_NONE; - } - - auto recipientIter = appRecipient_.find(packageName); - if (recipientIter == appRecipient_.end()) { - HILOGI("UnRegisterDeviceManagerListener: appRecipient not exists"); - dmListener_.erase(packageName); - return ERR_NONE; - } - - auto listener = listenerIter->second; - auto appRecipient = recipientIter->second; - listener->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(packageName); - dmListener_.erase(packageName); - return ERR_NONE; -} - -int32_t DeviceManagerService::RegisterDeviceStateCallback(std::string &packageName, std::string &extra) -{ - HILOGI("In, packageName: %{public}s", packageName.c_str()); - devStateCallbackParas_[packageName] = extra; - return ERR_NONE; -} - -int32_t DeviceManagerService::UnRegisterDeviceStateCallback(std::string &packageName) -{ - HILOGI("In, packageName: %{public}s", packageName.c_str()); - devStateCallbackParas_.erase(packageName); - return ERR_NONE; -} - -int32_t DeviceManagerService::GetTrustedDeviceList(std::string &packageName, std::string &extra, - std::vector &deviceList) -{ - HILOGI("In, packageName: %{public}s", packageName.c_str()); - return SoftbusAdapter::GetSoftbusTrustDevices(packageName, extra, deviceList); -} - -int32_t DeviceManagerService::StartDeviceDiscovery(std::string &packageName, DmSubscribeInfo &subscribeInfo) -{ - HILOGI("In, packageName: %{public}s, subscribeId %{public}d", packageName.c_str(), - (int32_t)subscribeInfo.subscribeId); - return SoftbusAdapter::GetInstance().StartSoftbusDiscovery(packageName, subscribeInfo); -} - -int32_t DeviceManagerService::StopDeviceDiscovery(std::string &packageName, uint16_t subscribeId) -{ - HILOGI("In, packageName: %{public}s, subscribeId %{public}d", packageName.c_str(), (int32_t)subscribeId); - return SoftbusAdapter::GetInstance().StopSoftbusDiscovery(packageName, subscribeId); -} - -int32_t DeviceManagerService::AuthenticateDevice(std::string &packageName, const DmDeviceInfo &deviceInfo, - std::string &extra) -{ - (void)extra; - - std::string deviceId = deviceInfo.deviceId; - if (SoftbusAdapter::IsDeviceOnLine(deviceId)) { - HILOGI("AuthenticateDevice, deviceId is already in trusted list, return."); - return ERR_DEVICEMANAGER_DEVICE_ALREADY_TRUSTED; - } - - DeviceReqInfo devReqInfo; - devReqInfo.deviceId = deviceId; - HILOGI("AuthenticateDevice In, packageName: %{public}s, deviceId %{public}s", packageName.c_str(), - GetAnonyString(deviceId).c_str()); - int32_t ret = SoftbusAdapter::GetInstance().GetConnectionIpAddr(deviceId, devReqInfo.ipAddr); - if (ret != ERR_OK) { - HILOGE("AuthenticateDevice Error: can not find ip by deviceId."); - return ret; - } - - authCallbackParas_[deviceId] = packageName; - return HichainAdapter::GetInstance().Bind(devReqInfo, hichainBindCallback_, false); -} - -const std::map>& DeviceManagerService::GetDmListener() -{ - return dmListener_; -} - -const sptr DeviceManagerService::GetDmListener(std::string packageName) const -{ - auto iter = dmListener_.find(packageName); - if (iter == dmListener_.end()) { - return nullptr; - } - auto remote = iter->second; - sptr dmListener = iface_cast(remote); - return dmListener; -} - -void AppDeathRecipient::OnRemoteDied(const wptr& remote) -{ - HILOGW("AppDeathRecipient: OnRemoteDied"); - std::map> listeners = DeviceManagerService::GetInstance().GetDmListener(); - std::string packageName; - for (auto iter : listeners) { - if (iter.second == remote.promote()) { - packageName = iter.first; - break; - } - } - - if (packageName.empty()) { - HILOGE("AppDeathRecipient: OnRemoteDied, no packageName matched"); - return; - } - - HILOGI("AppDeathRecipient: OnRemoteDied for %{public}s", packageName.c_str()); - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(packageName); -} - - -void HiChainBindCallback::onBindSuccess(std::string deviceId, const char *returnData) -{ - (void)returnData; - HILOGI("onBindSuccess, DM bind succeed, deviceId: %{public}s", GetAnonyString(deviceId).c_str()); - auto res = DeviceManagerService::GetInstance().authCallbackParas_; - auto iter = res.find(deviceId); - if (iter == res.end()) { - HILOGE("onBindSuccess deviceInfo not found by deviceId."); - return; - } - - std::string packageName = iter->second; - sptr dmListener = DeviceManagerService::GetInstance().GetDmListener(packageName); - if (dmListener != nullptr) { - dmListener->OnAuthResult(packageName, deviceId, DmBindStatus::STATE_BIND_SUCCESS, ERR_NONE); - } - - int32_t ret = SoftbusAdapter::GetInstance().SoftbusJoinLnn(deviceId); - HILOGI("onBindSuccess, DM bind succeed, joinlnn ret=%{public}d.", ret); -} - -void HiChainBindCallback::onBindFailed(std::string deviceId, int32_t errorCode) -{ - HILOGI("onBindFailed, DM bind failed, deviceId: %{public}s, errorCode: %{public}d", - GetAnonyString(deviceId).c_str(), errorCode); - auto res = DeviceManagerService::GetInstance().authCallbackParas_; - auto iter = res.find(deviceId); - if (iter == res.end()) { - HILOGE("onBindFailed deviceInfo not found by deviceId."); - return; - } - - std::string packageName = iter->second; - sptr dmListener = DeviceManagerService::GetInstance().GetDmListener(packageName); - - dmListener->OnAuthResult(packageName, deviceId, DmBindStatus::STATE_BIND_FAILD, errorCode); -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/devicemanagerservice/src/device_manager_stub.cpp b/services/devicemanagerservice/src/device_manager_stub.cpp deleted file mode 100644 index 9ab1bf5ca..000000000 --- a/services/devicemanagerservice/src/device_manager_stub.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_manager_stub.h" - -#include "ipc_skeleton.h" -#include "ipc_types.h" - - -#include "device_manager_log.h" - -using namespace std; - -namespace OHOS { -namespace DistributedHardware { -DeviceManagerStub::DeviceManagerStub() -{ - memberFuncMap_[GET_TRUST_DEVICE_LIST] = &DeviceManagerStub::GetTrustedDeviceListInner; - memberFuncMap_[REGISTER_DEVICE_MANAGER_LISTENER] = &DeviceManagerStub::RegisterDeviceManagerListenerInner; - memberFuncMap_[UNREGISTER_DEVICE_MANAGER_LISTENER] = &DeviceManagerStub::UnRegisterDeviceManagerListenerInner; - memberFuncMap_[REGISTER_DEVICE_STATE_CALLBACK] = &DeviceManagerStub::RegisterDeviceStateCallbackInner; - memberFuncMap_[UNREGISTER_DEVICE_STATE_CALLBACK] = &DeviceManagerStub::UnRegisterDeviceStateCallbackInner; - memberFuncMap_[START_DEVICE_DISCOVER] = &DeviceManagerStub::StartDeviceDiscoveryInner; - memberFuncMap_[STOP_DEVICE_DISCOVER] = &DeviceManagerStub::StopDeviceDiscoveryInner; - memberFuncMap_[AUTHENTICATE_DEVICE] = &DeviceManagerStub::AuthenticateDeviceInner; -} - -DeviceManagerStub::~DeviceManagerStub() -{ - memberFuncMap_.clear(); -} - -int32_t DeviceManagerStub::OnRemoteRequest(uint32_t code, - MessageParcel& data, MessageParcel &reply, MessageOption &option) -{ - HILOGI("code = %{public}d, flags= %{public}d.", code, option.GetFlags()); - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - if (!EnforceInterceToken(data)) { - HILOGE("interface token check failed!"); - return ERR_INVALID_STATE; - } - return (this->*memberFunc)(data, reply); - } - } - HILOGW("unsupport code: %{public}d", code); - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} - -int32_t DeviceManagerStub::RegisterDeviceManagerListenerInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - sptr listener = data.ReadRemoteObject(); - int32_t result = RegisterDeviceManagerListener(packageName, listener); - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -int32_t DeviceManagerStub::UnRegisterDeviceManagerListenerInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - int32_t result = UnRegisterDeviceManagerListener(packageName); - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -int32_t DeviceManagerStub::RegisterDeviceStateCallbackInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - string extra = data.ReadString(); - HILOGI("packageName:%{public}s, extra:%{public}s", packageName.c_str(), extra.c_str()); - int32_t result = RegisterDeviceStateCallback(packageName, extra); - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -int32_t DeviceManagerStub::UnRegisterDeviceStateCallbackInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - HILOGI("packageName:%{public}s", packageName.c_str()); - int32_t result = UnRegisterDeviceStateCallback(packageName); - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -int32_t DeviceManagerStub::GetTrustedDeviceListInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - string extra = data.ReadString(); - HILOGI("packageName:%{public}s, extra:%{public}s", packageName.c_str(), extra.c_str()); - std::vector devInfos; - int32_t result = GetTrustedDeviceList(packageName, extra, devInfos); - reply.WriteInt32(devInfos.size()); - for (auto &it : devInfos) { - if (!reply.WriteParcelable(&it)) { - return ERR_INVALID_VALUE; - } - } - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -template -int32_t DeviceManagerStub::GetParcelableInfo(MessageParcel &reply, T &parcelableInfo) -{ - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - HILOGE("readParcelableInfo failed"); - return ERR_INVALID_VALUE; - } - parcelableInfo = *info; - return ERR_NONE; -} - -int32_t DeviceManagerStub::StartDeviceDiscoveryInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - DmSubscribeInfo subscribeInfo; - int32_t result = GetParcelableInfo(data, subscribeInfo); - if (result != ERR_NONE) { - HILOGE("GetParcelableInfo fail, result: %{public}d", result); - reply.WriteInt32(result); - return result; - } - - HILOGI("packageName:%{public}s, subscribeId: %{public}d", packageName.c_str(), subscribeInfo.subscribeId); - result = StartDeviceDiscovery(packageName, subscribeInfo); - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -int32_t DeviceManagerStub::StopDeviceDiscoveryInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - uint16_t subscribeId = data.ReadInt32(); - HILOGI("packageName:%{public}s, subscribeId: %{public}d", packageName.c_str(), subscribeId); - int32_t result = StopDeviceDiscovery(packageName, subscribeId); - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -int32_t DeviceManagerStub::AuthenticateDeviceInner(MessageParcel& data, MessageParcel& reply) -{ - string packageName = data.ReadString(); - DmDeviceInfo deviceInfo; - int32_t result = GetParcelableInfo(data, deviceInfo); - if (result != ERR_NONE) { - HILOGE("GetParcelableInfo fail, result: %{public}d", result); - reply.WriteInt32(result); - return result; - } - - string extra = data.ReadString(); - HILOGI("packageName:%{public}s, extra:%{public}s", packageName.c_str(), extra.c_str()); - result = AuthenticateDevice(packageName, deviceInfo, extra); - if (!reply.WriteInt32(result)) { - HILOGE("write result failed"); - return ERR_INVALID_VALUE; - } - return ERR_NONE; -} - -bool DeviceManagerStub::EnforceInterceToken(MessageParcel& data) -{ - u16string interfaceToken = data.ReadInterfaceToken(); - u16string descriptor = DeviceManagerStub::GetDescriptor(); - return interfaceToken == descriptor; -} -} // 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 15935bb99..0c5294e02 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -336,7 +336,6 @@ 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) { DMLOG(DM_LOG_INFO, "OnFaCallBack"); diff --git a/services/devicemanagerservice/src/message/msg_codec.cpp b/services/devicemanagerservice/src/message/msg_codec.cpp new file mode 100644 index 000000000..a54d63e22 --- /dev/null +++ b/services/devicemanagerservice/src/message/msg_codec.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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; +} +} +} diff --git a/interfaces/inner_kits/native_cpp/src/dm_device_info.cpp b/services/devicemanagerservice/src/message/msg_head.cpp similarity index 47% rename from interfaces/inner_kits/native_cpp/src/dm_device_info.cpp rename to services/devicemanagerservice/src/message/msg_head.cpp index b4a3bfa5e..77cc84416 100644 --- a/interfaces/inner_kits/native_cpp/src/dm_device_info.cpp +++ b/services/devicemanagerservice/src/message/msg_head.cpp @@ -1,50 +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_device_info.h" - -namespace OHOS { -namespace DistributedHardware { -bool DmDeviceInfo::ReadFromParcel(Parcel &parcel) -{ - deviceId = parcel.ReadString(); - deviceName = parcel.ReadString(); - deviceTypeId = (DMDeviceType)parcel.ReadUint8(); - return true; -} - -DmDeviceInfo *DmDeviceInfo::Unmarshalling(Parcel &parcel) -{ - DmDeviceInfo *info = new (std::nothrow) DmDeviceInfo(); - if (info == nullptr) { - return nullptr; - } - - if (!info->ReadFromParcel(parcel)) { - delete info; - info = nullptr; - } - return info; -} - -bool DmDeviceInfo::Marshalling(Parcel &parcel) const -{ - parcel.WriteString(deviceId); - parcel.WriteString(deviceName); - parcel.WriteUint8((uint8_t)deviceTypeId); - return true; -} -} // namespace DistributedHardware -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 new file mode 100644 index 000000000..9d9a727f8 --- /dev/null +++ b/services/devicemanagerservice/src/message/msg_request_auth.cpp @@ -0,0 +1,375 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "msg_request_auth.h" +#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" + +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); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + mDeviceName_ = devReqInfo.deviceName; + mDeviceId_ = localDeviceId; + mToken_ = token; + mHostPkg_ = hostPkgName; + mTargetPkg_ = targetPkgName; + mGroupVisibility_ = groupVisibility; + mAppName_ = jsonObject[APP_NAME_KEY]; + mAppDescription_ = jsonObject[APP_DESCRIPTION_KEY]; + + std::string appIconStr = ""; + GetEncodedAppInfo(imageInfo.GetAppIcon(), imageInfo.GetAppIconLen(), appIconStr); + + std::string appThumbStr = ""; + GetEncodedAppInfo(imageInfo.GetAppThumbnail(), imageInfo.GetAppThumbnailLen(), appThumbStr); + + mAppIcon_ = appIconStr; + mAppThumbnail_ = appThumbStr; + mDeviceType_ = ToHexString(devReqInfo.deviceTypeId); + DMLOG(DM_LOG_INFO, "MsgRequestAuth construction completed"); +} + +int32_t MsgRequestAuth::GetEncodedAppInfo(const uint8_t *dataSrc, size_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; + } + size_t outLen = 0; + char *tmpBuf = (char *)calloc(sizeof(char), THUMB_MAX_LEN); + if (tmpBuf == nullptr) { + DMLOG(DM_LOG_ERROR, "getEncodedAppInfoString: malloc mem error"); + return DEVICEMANAGER_MALLOC_ERROR; + } + EncryptUtils::MbedtlsBase64Encode((uint8_t *)tmpBuf, THUMB_MAX_LEN, &outLen, dataSrc, srcLen); + if (outLen > THUMB_MAX_LEN) { + DMLOG(DM_LOG_ERROR, "encode appIcon 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"); + size_t outLen = 0; + uint8_t *buffer = (uint8_t *)calloc(sizeof(char), THUMB_MAX_LEN); + if (buffer == nullptr) { + DMLOG(DM_LOG_ERROR, "GetDecodeAppInfo: malloc mem error"); + return; + } + + int32_t ret = EncryptUtils::MbedtlsBase64Decode(buffer, THUMB_MAX_LEN, &outLen, + (const uint8_t*)appString.c_str(), strlen(appString.c_str())); + if (ret != 0) { + DMLOG(DM_LOG_ERROR, "BuildAuthenticationInfo: MbedtlsBase64Decode failed"); + 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_; + jsonObj[TAG_APP_ICON] = mAppIcon_; + jsonObj[TAG_THUMBNAIL_SIZE] = mAppThumbnail_.size(); + 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]; + msg->mAppIcon_ = json[TAG_APP_ICON]; + 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 = + (mAppThumbnail_.size() / MSG_MAX_SIZE) + ((mAppThumbnail_.size() % 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] = mAppThumbnail_.size(); + jsonObj[TAG_APP_THUMBNAIL] = StringSub(mAppThumbnail_, idx * MSG_MAX_SIZE, MSG_MAX_SIZE); + 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) { + if (DecodeFirstPackageMsg(json, msg) != DEVICEMANAGER_OK) { + return nullptr; + } + } 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 src = json[TAG_APP_THUMBNAIL]; + if (msg->mAppThumbnail_.size() < src.size() + (idx - 1) * MSG_MAX_SIZE) { + auto inValidReqMsg = std::make_shared(); + inValidReqMsg->mMsgSlice_ = FAIL; + return inValidReqMsg; + } + msg->mAppThumbnail_ += StringSub(src, (idx - 1) * MSG_MAX_SIZE, MSG_MAX_SIZE); + } + msg->mMsgCnt_++; + return msg; +} + +int32_t MsgRequestAuth::DecodeFirstPackageMsg(nlohmann::json &json, std::shared_ptr msg) +{ + 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)) { + DMLOG(DM_LOG_ERROR, "err json string, second time"); + return DEVICEMANAGER_FAILED; + } + 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) { + if (!json.contains(TAG_TARGET) || !json.contains(TAG_HOST)) { + DMLOG(DM_LOG_ERROR, "err json string, third time"); + return DEVICEMANAGER_FAILED; + } + msg->mTargetPkg_ = json[TAG_TARGET]; + msg->mHostPkg_ = json[TAG_HOST]; + } + msg->mAppName_ = json[TAG_APP_NAME]; + msg->mAppDescription_ = json[TAG_APP_DESCRIPTION]; + msg->mAppIcon_ = json[TAG_APP_ICON]; + SetThumbnailSize(json, msg); + SetAuthType(json, msg); + return DEVICEMANAGER_OK; +} + +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)) { + 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, mAppIcon_ 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->mThumbnailSize_ = thumbnailSlice; + DMLOG(DM_LOG_INFO, "mThumbnailSize_ is, %d", msg->mThumbnailSize_); + msg->mAppThumbnail_ = ""; + } +} + +std::string MsgRequestAuth::StringSub(std::string &thumbStr, int32_t start, int32_t length) +{ + int32_t copyLen = start + length > (int32_t)thumbStr.size() ? (thumbStr.size() - start) : length; + std::string ret; + ret.assign(thumbStr, start, copyLen); + return ret; +} + +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 new file mode 100644 index 000000000..41f5f11ad --- /dev/null +++ b/services/devicemanagerservice/src/message/msg_response_auth.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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", 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", mGroupId_.c_str()); + DMLOG(DM_LOG_INFO, "decode mGroupName_ is %s", 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_; +} + +long long 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 new file mode 100644 index 000000000..cccb5f197 --- /dev/null +++ b/services/devicemanagerservice/src/message/msg_sync_group.cpp @@ -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. + */ + +#include "msg_sync_group.h" +#include "device_manager_log.h" +#include "constants.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_; +} +} +} \ No newline at end of file diff --git a/services/devicemanagerservice/src/requestauth/auth_manager.cpp b/services/devicemanagerservice/src/requestauth/auth_manager.cpp new file mode 100644 index 000000000..dda878297 --- /dev/null +++ b/services/devicemanagerservice/src/requestauth/auth_manager.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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" + +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; + 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 (!CanStartNewSession()) { + DMLOG(DM_LOG_ERROR, "previous session not completed yet"); + mPendingReqSessionPtr_->NotifyHostAppAuthResult(ERROR_DUPLICATE_REQUEST); + return; + } + auto curSessionPtr = std::make_shared(hostPkgName, devReqInfo, imageInfo, extrasJson); + 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::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); +} + +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, pinCode is :%s", GetAnonyInt32(pinCode).c_str()); + return PIN_CODE_CHECK_FAILED; + } + + if (pinToken < MIN_PIN_TOKEN || pinToken >= (MIN_PIN_TOKEN + MAX_PIN_TOKEN)) { + DMLOG(DM_LOG_ERROR, "pinToken err, pinToken is :%s", GetAnonyInt32(pinToken).c_str()); + 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_; +} +} +} diff --git a/services/devicemanagerservice/src/requestauth/request_session.cpp b/services/devicemanagerservice/src/requestauth/request_session.cpp new file mode 100644 index 000000000..937be386b --- /dev/null +++ b/services/devicemanagerservice/src/requestauth/request_session.cpp @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 { +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, +}; + +RequestSession::RequestSession(std::string &hostPkgName, const DmDeviceInfo &devReqInfo, + const DmAppImageInfo &imageInfo, std::string &extrasJson) +{ + DMLOG(DM_LOG_INFO, "RequestSession construction started"); + nlohmann::json jsonObject = nlohmann::json::parse(extrasJson, nullptr, false); + if (jsonObject.is_discarded()) { + DMLOG(DM_LOG_ERROR, "extrasJson error"); + } + + 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]; + mSessionType_ = SESSION_TYPE_IS_APP_AUTH; + mDevInfo_ = devReqInfo; + mImageInfo_ = imageInfo; + DMLOG(DM_LOG_ERROR, "imageinfo appIcon:%p:%p", mImageInfo_.GetAppIcon(), imageInfo.GetAppIcon()); + mHostPkgName_ = hostPkgName; + mTargetPkgName = targetPkgName; + mStatus_ = StatusType::STATUS_INIT; + 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) { + return; + } +} + +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::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) { + std::string deviceId = mDevInfo_.deviceId; + if (StartFaService() != SUCCESS) { + DMLOG(DM_LOG_INFO, "RequestSession::StartFaService failed"); + return; + } + DMLOG(DM_LOG_INFO, "RequestSession::StartFaService success"); + int32_t status = (errorCode == 0) ? 0 : -1; + IpcServerListenerAdapter::GetInstance().OnAuthResult(mHostPkgName_, deviceId, mPinToken_, status, errorCode); + DMLOG(DM_LOG_INFO, "notify host result, errorcode: %d", errorCode); + } else { + DMLOG(DM_LOG_ERROR, "wrong session type: %d", errorCode); + } +} +} +} diff --git a/services/devicemanagerservice/src/requestauth/response_session.cpp b/services/devicemanagerservice/src/requestauth/response_session.cpp new file mode 100644 index 000000000..4410243b6 --- /dev/null +++ b/services/devicemanagerservice/src/requestauth/response_session.cpp @@ -0,0 +1,291 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#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 RECEIVE_MESSAGE_TIMEOUT = 3; // 3 second +// const int32_t WAIT_NEXT_PACKAGE_TIMEOUT = 3; // 3 second +// const int32_t WAIT_ENTER_PINCODE_TIMEOUT = 3; // 3 second +} + +#define PINCODE_LEN 6 + +ResponseSession::ResponseSession() +{ + mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; + sem_init(&mSem_, 0, 0); + // need to update +} + +long long ResponseSession::GetRequestId(void) +{ + 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 ResponseSession::OnReceiveMsg(long long channelId, std::string &message) +{ + int32_t ret = DecodeReqMsg(message); + if (ret != SUCCESS) { + return; + } + + if (mMsgRequestAuthPtr_->GetMsgCnt() != mMsgRequestAuthPtr_->GetMsgSlice()) { + return; + } + + // 正常业务逻辑 + mReqDeviceId_ = mMsgRequestAuthPtr_->GetRequestDeviceId(); + mChannelId_ = channelId; + mPincode_ = GeneratePincode(); + if (StartFaService() != SUCCESS) { + // 拉起界面失败,直接回复拒绝,清理session状态 + OnUserReject(ERROR_FA_START_FAIL); + return; + } + + mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_USER_CONFIRM; +} + +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) +{ + authParam.direction = (int32_t)DmAbilityManager::GetInstance().GetAbilityRole(); + 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) { + uint8_t *appIcon = nullptr; + int32_t appIconLen = 0; + uint8_t *appThumbnail = nullptr; + int32_t appThumbnailLen = 0; + mMsgRequestAuthPtr_->GetDecodeAppInfo(mMsgRequestAuthPtr_->mAppIcon_, &appIcon, appIconLen); + mMsgRequestAuthPtr_->GetDecodeAppInfo(mMsgRequestAuthPtr_->mAppThumbnail_, &appThumbnail, appThumbnailLen); + authParam.imageinfo.Reset(appIcon, appIconLen, appThumbnail, appThumbnailLen); + if (appIcon != nullptr) { + free(appIcon); + appIcon = nullptr; + } + if (appThumbnail != nullptr) { + free(appThumbnail); + appThumbnail = nullptr; + } + } +} + +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 %d, requestId %d, 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; +} + +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() / 2); + 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"); + mRequestId_ = -1; + mGroupId_ = ""; + mGroupName_ = ""; + mReqDeviceId_ = ""; + mMsgRequestAuthPtr_ = nullptr; + mChannelId_ = -1; + mPincode_ = -1; + mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; +} + +void ResponseSession::CancelDisplay() +{ + nlohmann::json jsonObj; + jsonObj[CANCEL_DISPLAY_KEY] = 1; + std::string jsonObjTmp = jsonObj.dump(); + IpcServerListenerAdapter::GetInstance().OnFaCall(mMsgRequestAuthPtr_->mTargetPkg_, jsonObjTmp); +} + +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 index 17f72e881..3103b6a47 100644 --- a/services/devicemanagerservice/src/softbus/softbus_adapter.cpp +++ b/services/devicemanagerservice/src/softbus/softbus_adapter.cpp @@ -16,393 +16,327 @@ #include "softbus_adapter.h" #include -#include #include #include +#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 "device_manager_service.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 std::string DEVICE_MANAGER_PACKAGE_NAME = "com.huawei.devicemanager"; const int32_t CHECK_INTERVAL = 100000; // 100ms const int32_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; + } + } +} -IMPLEMENT_SINGLE_INSTANCE(SoftbusAdapter); void SoftbusAdapter::OnSoftBusDeviceOnline(NodeBasicInfo *info) { if (info == nullptr) { - HILOGE("SoftbusAdapter::OnSoftBusDeviceOnline NodeBasicInfo is nullptr"); + DMLOG(DM_LOG_ERROR, "OnSoftBusDeviceOnline NodeBasicInfo is nullptr"); return; } + DmDeviceInfo dmDeviceInfo; - std::string networkId = info->networkId; - HILOGI("device online, networkId: %{public}s", GetAnonyString(networkId).c_str()); - OnSoftBusDeviceStateChange(DmDeviceState::DEVICE_STATE_ONLINE, info); + 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 != ERR_OK) { - HILOGE("GetNodeKeyInfo failed"); + if (ret != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "GetNodeKeyInfo failed"); return; } std::string deviceId = (char *)udid; - SoftbusAdapter::GetInstance().RemoveDiscoverDeviceInfo(deviceId); + DMLOG(DM_LOG_INFO, "device online, deviceId: %s", GetAnonyString(deviceId).c_str()); + RemoveDiscoverDeviceInfo(deviceId); } void SoftbusAdapter::OnSoftbusDeviceOffline(NodeBasicInfo *info) { if (info == nullptr) { - HILOGE("SoftbusAdapter::OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); + DMLOG(DM_LOG_ERROR, "OnSoftbusDeviceOffline NodeBasicInfo is nullptr"); return; } + DmDeviceInfo dmDeviceInfo; - std::string networkId = info->networkId; - HILOGI("device offline, networkId: %{public}s", GetAnonyString(networkId).c_str()); - OnSoftBusDeviceStateChange(DmDeviceState::DEVICE_STATE_OFFLINE, info); -} - -void SoftbusAdapter::OnSoftBusDeviceStateChange(DmDeviceState state, NodeBasicInfo *info) -{ - DmDeviceInfo deviceInfo; - deviceInfo.deviceId = info->networkId; - deviceInfo.deviceName = info->deviceName; - deviceInfo.deviceTypeId = (DMDeviceType)info->deviceTypeId; - - std::map> listeners = DeviceManagerService::GetInstance().GetDmListener(); - for (auto iter : listeners) { - auto packageName = iter.first; - auto remote = iter.second; - sptr dmListener = iface_cast(remote); - if (state == DmDeviceState::DEVICE_STATE_ONLINE) { - HILOGI("SoftbusAdapter::OnSoftBusDeviceStateChange listenr handle device online."); - dmListener->OnDeviceOnline(packageName, deviceInfo); - } else { - HILOGI("SoftbusAdapter::OnSoftBusDeviceStateChange listenr handle device offline."); - dmListener->OnDeviceOffline(packageName, deviceInfo); - } - } + NodeBasicInfoCopyToDmDevice(dmDeviceInfo, *info); + IpcServerListenerAdapter::GetInstance().OnDeviceStateChange(DmDeviceState::DEVICE_STATE_OFFLINE, dmDeviceInfo); } void SoftbusAdapter::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBasicInfo *info) { - HILOGI("SoftbusAdapter::OnSoftbusDeviceInfoChanged."); + 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) { - HILOGE("deviceinfo is null"); + DMLOG(DM_LOG_ERROR, "deviceinfo is null"); return; } std::string deviceId = device->devId; - HILOGI("SoftbusAdapter::OnSoftbusDeviceFound device %{public}s found.", GetAnonyString(deviceId).c_str()); + DMLOG(DM_LOG_INFO, "SoftbusAdapter::OnSoftbusDeviceFound device %s found.", GetAnonyString(deviceId).c_str()); if (IsDeviceOnLine(deviceId)) { return; } - SoftbusAdapter::GetInstance().SaveDiscoverDeviceInfo(device); - DmDeviceInfo deviceInfo; - deviceInfo.deviceId = deviceId; - deviceInfo.deviceName = device->devName; - deviceInfo.deviceTypeId = (DMDeviceType)device->devType; - - // currently, only care ddmpCapability - if (!((device->capabilityBitmap[0] >> DDMP_CAPABILITY_BITMAP) & 0x1)) { - HILOGE("capBitmap Invalid, not contain ddmpCap"); - return; - } - - auto subscribeInfos = SoftbusAdapter::GetInstance().GetsubscribeInfos(); - for (auto iter = subscribeInfos.begin(); iter != subscribeInfos.end(); iter++) { + 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(); - HILOGI("subscribe info capability:%{public}s.", info->info.capability); - if (strcmp(DM_CAPABILITY_DDMP.c_str(), info->info.capability) != 0) { - HILOGE("subscribe info capability invalid."); + 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."); } - std::string packageName = iter->first; - sptr listener = DeviceManagerService::GetInstance().GetDmListener(packageName); - if (listener == nullptr) { - HILOGI("cannot get listener for package:%{public}s.", packageName.c_str()); - continue; - } - uint16_t originId = (uint16_t)(((uint32_t)info->info.subscribeId) & SUBSCRIBE_ID_MASK); - HILOGI("call OnDeviceFound for %{public}s, originId %{public}d, deviceId %{public}s", - packageName.c_str(), originId, GetAnonyString(deviceInfo.deviceId).c_str()); - listener->OnDeviceFound(packageName, originId, deviceInfo); - } - } -} + std::string strPkgName = iter->first; + DmDeviceInfo dmDeviceInfo; -void SoftbusAdapter::OnSoftbusDiscoverFailed(int subscribeId, DiscoveryFailReason failReason) -{ - HILOGI("In, subscribeId %{public}d, failReason %{public}d", subscribeId, (int32_t)failReason); - std::string packageName; - if (!SoftbusAdapter::GetInstance().GetPackageNameBySubscribeId(subscribeId, packageName)) { - HILOGE("OnSoftbusDiscoverFailed: packageName not found"); - return; - } - sptr listener = DeviceManagerService::GetInstance().GetDmListener(packageName); - if (listener == nullptr) { - HILOGE("OnSoftbusDiscoverFailed: listener not found for packageName %{public}s", packageName.c_str()); - return; + DeviceInfoCopyToDmDevice(dmDeviceInfo, *device); + IpcServerListenerAdapter::GetInstance().OnDeviceFound(strPkgName, originId, dmDeviceInfo); + } } - uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); - listener->OnDiscoverFailed(packageName, originId, (int32_t)failReason); } -void SoftbusAdapter::OnSoftbusDiscoverySuccess(int subscribeId) +bool SoftbusAdapter::GetpkgNameBySubscribeId(int32_t adapterId, std::string &pkgName) { - HILOGI("In, subscribeId %{public}d", subscribeId); - std::string packageName; - if (!SoftbusAdapter::GetInstance().GetPackageNameBySubscribeId(subscribeId, packageName)) { - HILOGE("OnSoftbusDiscoverySuccess: packageName not found"); - return; - } - sptr listener = DeviceManagerService::GetInstance().GetDmListener(packageName); - if (listener == nullptr) { - HILOGE("OnSoftbusDiscoverySuccess: listener not found for packageName %{public}s", packageName.c_str()); - return; + 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; + } + } } - uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); - listener->OnDiscoverySuccess(packageName, originId); + return false; } -void SoftbusAdapter::OnSoftbusJoinLNNResult(ConnectionAddr *addr, const char *networkId, int32_t retCode) +void SoftbusAdapter::OnSoftbusDiscoverFailed(int32_t subscribeId, DiscoveryFailReason failReason) { - (void)addr; - if (retCode != 0) { - HILOGE("OnSoftbusJoinLNNResult: failed, retCode %{public}d", retCode); - return; - } - - if (networkId == nullptr) { - HILOGE("OnSoftbusJoinLNNResult: success, but networkId is nullptr"); + 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; } - std::string netIdStr = networkId; - HILOGI("OnSoftbusJoinLNNResult: success, networkId %{public}s, retCode %{public}d", - GetAnonyString(netIdStr).c_str(), retCode); + uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); + IpcServerListenerAdapter::GetInstance().OnDiscoverFailed(pkgName, originId, failReason); } -void SoftbusAdapter::OnSoftbusLeaveLNNResult(const char *networkId, int32_t retCode) +void SoftbusAdapter::OnSoftbusDiscoverySuccess(int32_t subscribeId) { - if (retCode != 0) { - HILOGE("OnSoftbusLeaveLNNResult: failed, retCode %{public}d", retCode); - return; - } - - if (networkId == nullptr) { - HILOGE("OnSoftbusLeaveLNNResult: success, but networkId is nullptr"); + DMLOG(DM_LOG_INFO, "In, subscribeId %d", subscribeId); + std::string pkgName; + if (!GetpkgNameBySubscribeId(subscribeId, pkgName)) { + DMLOG(DM_LOG_ERROR, "OnSoftbusDiscoverySuccess: pkgName not found"); return; } - - std::string netIdStr = networkId; - HILOGI("OnSoftbusLeaveLNNResult: success, networkId %{public}s, retCode %{public}d", - GetAnonyString(netIdStr).c_str(), retCode); -} - -int32_t SoftbusAdapter::GetSoftbusTrustDevices(const std::string &packageName, std::string &extra, - std::vector &deviceList) -{ - // extra not used yet - (void) packageName; - (void) extra; - - HILOGI("GetSoftbusTrustDevices start, packageName: %{public}s", packageName.c_str()); - NodeBasicInfo *info = nullptr; - int32_t infoNum = 0; - int32_t ret = GetAllNodeDeviceInfo(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &info, &infoNum); - if (ret != 0) { - HILOGE("GetAllNodeDeviceInfo failed with ret %{public}d", ret); - return ret; - } - - for (int32_t i = 0; i < infoNum; i++) { - NodeBasicInfo *nodeBasicInfo = info + i; - if (nodeBasicInfo == nullptr) { - HILOGE("nodeBasicInfo is empty for index %{public}d, infoNum %{public}d.", i, infoNum); - continue; - } - DmDeviceInfo deviceInfo; - deviceInfo.deviceId = nodeBasicInfo->networkId; - deviceInfo.deviceName = nodeBasicInfo->deviceName; - deviceInfo.deviceTypeId = (DMDeviceType)nodeBasicInfo->deviceTypeId; - deviceList.push_back(deviceInfo); - } - FreeNodeInfo(info); - HILOGI("success, packageName: %{public}s, deviceCount %{public}d", packageName.c_str(), deviceList.size()); - return ERR_OK; + uint16_t originId = (uint16_t)(((uint32_t)subscribeId) & SUBSCRIBE_ID_MASK); + IpcServerListenerAdapter::GetInstance().OnDiscoverySuccess(pkgName, originId); } -bool SoftbusAdapter::IsDeviceOnLine(std::string &deviceId) +bool SoftbusAdapter::GetsubscribeIdAdapter(std::string &pkgName, int16_t originId, int32_t &adapterId) { - std::vector deviceList; - std::string extra = ""; - if (GetSoftbusTrustDevices(DEVICE_MANAGER_PACKAGE_NAME, extra, deviceList) != ERR_OK) { - HILOGE("SoftbusAdapter::IsDeviceOnLine GetSoftbusTrustDevices failed"); + 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; } - for (auto iter = deviceList.begin(); iter != deviceList.end(); ++iter) { - std::string& networkId = iter->deviceId; - if (networkId == deviceId) { - HILOGI("SoftbusAdapter::IsDeviceOnLine devccie %{public}s online", GetAnonyString(deviceId).c_str()); - return true; - } - - 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 != ERR_OK) { - HILOGE("SoftbusAdapter::IsDeviceOnLine GetNodeKeyInfo failed"); - return false; - } - - if (strcmp((char *)udid, deviceId.c_str()) == 0) { - HILOGI("SoftbusAdapter::IsDeviceOnLine devccie %{public}s online", GetAnonyString(deviceId).c_str()); + 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; } -void SoftbusAdapter::RegSoftBusDeviceStateListener() +int32_t SoftbusAdapter::Init() { int32_t ret; int32_t retryTimes = 0; do { - ret = RegNodeDeviceStateCb(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &softbusNodeStateCb); - if (ret != ERR_OK) { + ret = RegNodeDeviceStateCb(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &softbusNodeStateCb_); + if (ret != DEVICEMANAGER_OK) { ++retryTimes; - HILOGE("RegNodeDeviceStateCb failed with ret %{public}d, retryTimes %{public}d", ret, retryTimes); + DMLOG(DM_LOG_ERROR, "RegNodeDeviceStateCb failed with ret %d, retryTimes %d", ret, retryTimes); usleep(CHECK_INTERVAL); } - } while (ret != ERR_OK); - HILOGI("RegNodeDeviceStateCb success."); + } 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::StartSoftbusDiscovery(std::string &packageName, DmSubscribeInfo &info) +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(packageName) == subscribeInfos_.end()) { - subscribeInfos_[packageName] = {}; + if (subscribeInfos_.find(pkgName) == subscribeInfos_.end()) { + subscribeInfos_[pkgName] = {}; } - auto iter = subscribeInfos_.find(packageName); + 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) { + 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->subscribeIdOrigin = info->subscribeId; subinfo->subscribeIdPrefix = subscribeIdPrefix++; - subinfo->info.subscribeId = (subinfo->subscribeIdPrefix << SUBSCRIBE_ID_PREFIX_LEN) | info.subscribeId; - subinfo->info.mode = (DiscoverMode)info.mode; - subinfo->info.medium = (ExchanageMedium)info.medium; - subinfo->info.freq = (ExchangeFreq)info.freq; - subinfo->info.isSameAccount = info.isSameAccount; - subinfo->info.isWakeRemote = info.isWakeRemote; - subinfo->info.capability = info.capability.c_str(); - subinfo->info.capabilityData = nullptr; - subinfo->info.dataLen = 0; + subinfo->info = *info; + subinfo->info.subscribeId = (subinfo->subscribeIdPrefix << SUBSCRIBE_ID_PREFIX_LEN) | info->subscribeId; } - if (vectorIter == subinfoVector.end()) { subinfoVector.push_back(subinfo); } - - HILOGI("StartDiscovery, packageName: %{public}s, subscribeId %{public}d, prefix %{public}d, origin %{public}d", - packageName.c_str(), subinfo->info.subscribeId, subinfo->subscribeIdPrefix, subinfo->subscribeIdOrigin); - int ret = StartDiscovery(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &subinfo->info, &softbusDiscoverCallback); - if (ret != ERR_OK) { - HILOGE("StartDiscovery failed with ret %{public}d.", ret); - } - return ret; -} - -bool SoftbusAdapter::GetPackageNameBySubscribeId(int32_t adapterId, std::string &packageName) -{ - 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) { - packageName = iter->first; - return true; - } - } - } - return false; -} - -bool SoftbusAdapter::GetsubscribeIdAdapter(std::string packageName, int16_t originId, int32_t &adapterId) -{ - HILOGI("GetsubscribeIdAdapter in, packageName: %{public}s, originId:%{public}d", packageName.c_str(), - (int32_t)originId); - auto iter = subscribeInfos_.find(packageName); - if (iter == subscribeInfos_.end()) { - HILOGE("subscribeInfo not find for packageName: %{public}s", packageName.c_str()); - return false; - } - - std::vector> &subinfoVector = iter->second; - auto vectorIter = subinfoVector.begin(); - for (; vectorIter != subinfoVector.end(); ++vectorIter) { - if (vectorIter->get()->subscribeIdOrigin == originId) { - HILOGE("find adapterId:%{public}d for packageName: %{public}s, originId:%{public}d", - vectorIter->get()->info.subscribeId, packageName.c_str(), (int32_t)originId); - adapterId = vectorIter->get()->info.subscribeId; - return true; - } + 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; } - HILOGE("subscribe not find. packageName: %{public}s, originId:%{public}d", packageName.c_str(), (int32_t)originId); - return false; + return DEVICEMANAGER_OK; } -int32_t SoftbusAdapter::StopSoftbusDiscovery(std::string &packageName, uint16_t subscribeId) +int32_t SoftbusAdapter::StopDiscovery(std::string &pkgName, uint16_t subscribeId) { int32_t subscribeIdAdapter = -1; - if (!GetsubscribeIdAdapter(packageName, subscribeId, subscribeIdAdapter)) { - HILOGE("StopDiscovery failed, subscribeId not match"); - return ERR_INVALID_OPERATION; + if (!GetsubscribeIdAdapter(pkgName, subscribeId, subscribeIdAdapter)) { + DMLOG(DM_LOG_ERROR, "StopDiscovery failed, subscribeId not match"); + return DEVICEMANAGER_FAILED; } - HILOGI("StopDiscovery begin, packageName: %{public}s, subscribeId:%{public}d, subscribeIdAdapter:%{public}d", - packageName.c_str(), (int32_t)subscribeId, subscribeIdAdapter); - int ret = StopDiscovery(DEVICE_MANAGER_PACKAGE_NAME.c_str(), subscribeIdAdapter); - if (ret != ERR_OK) { - HILOGE("StopDiscovery failed with ret %{public}d", ret); + 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(packageName); + auto iter = subscribeInfos_.find(pkgName); auto subinfoVector = iter->second; auto vectorIter = subinfoVector.begin(); while (vectorIter != subinfoVector.end()) { @@ -414,57 +348,65 @@ int32_t SoftbusAdapter::StopSoftbusDiscovery(std::string &packageName, uint16_t } } if (subinfoVector.empty()) { - subscribeInfos_.erase(packageName); + subscribeInfos_.erase(pkgName); } - HILOGI("SoftbusAdapter::StopSoftbusDiscovery completed, packageName: %{public}s", packageName.c_str()); - return ERR_OK; + DMLOG(DM_LOG_INFO, "DM_StopSoftbusDiscovery completed, pkgName: %s", pkgName.c_str()); + return DEVICEMANAGER_OK; } -int32_t SoftbusAdapter::SoftbusJoinLnn(std::string devId) +bool SoftbusAdapter::IsDeviceOnLine(std::string &deviceId) { - auto iter = discoverDeviceInfoMap_.find(devId); - if (iter == discoverDeviceInfoMap_.end()) { - HILOGE("SoftbusAdapter::SoftbusJoinLnn deviceInfo not found: %{public}s", GetAnonyString(devId).c_str()); - return ERR_INVALID_OPERATION; - } + NodeBasicInfo *info = nullptr; + int32_t infoNum = 0; - DeviceInfo *deviceInfo = iter->second.get(); - if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { - HILOGE("deviceInfo addrNum not valid, addrNum %{public}d", deviceInfo->addrNum); - return ERR_DEVICEMANAGER_OPERATION_FAILED; + if (GetTrustDevices(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &info, &infoNum) != DEVICEMANAGER_OK) { + DMLOG(DM_LOG_ERROR, "DM_IsDeviceOnLine DM_GetSoftbusTrustDevices failed"); + return false; } - for (unsigned int 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) { + 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; + } - HILOGI("SoftbusAdapter::SoftbusJoinLnn call softbus JoinLNN."); - return JoinLNN(DEVICE_MANAGER_PACKAGE_NAME.c_str(), &deviceInfo->addr[i], OnSoftbusJoinLNNResult); + if (strcmp((char *)udid, deviceId.c_str()) == 0) { + DMLOG(DM_LOG_INFO, "DM_IsDeviceOnLine devccie %s online", GetAnonyString(deviceId).c_str()); + bDeviceOnline = true; + break; + } } - - return ERR_DEVICEMANAGER_OPERATION_FAILED; -} - -int32_t SoftbusAdapter::SoftbusLeaveLnn(std::string networkId) -{ - return LeaveLNN(networkId.c_str(), OnSoftbusLeaveLNNResult); + FreeNodeInfo(info); + return bDeviceOnline; } int32_t SoftbusAdapter::GetConnectionIpAddr(std::string deviceId, std::string &ipAddr) { auto iter = discoverDeviceInfoMap_.find(deviceId); if (iter == discoverDeviceInfoMap_.end()) { - HILOGE("deviceInfo not found by deviceId %{public}s", GetAnonyString(deviceId).c_str()); - return ERR_INVALID_OPERATION; + 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) { - HILOGE("deviceInfo addrNum not valid, addrNum %{public}d", deviceInfo->addrNum); - return ERR_DEVICEMANAGER_OPERATION_FAILED; + DMLOG(DM_LOG_ERROR, "deviceInfo addrNum not valid, addrNum %d", deviceInfo->addrNum); + return DEVICEMANAGER_FAILED; } for (unsigned int i = 0; i < deviceInfo->addrNum; ++i) { @@ -474,51 +416,98 @@ int32_t SoftbusAdapter::GetConnectionIpAddr(std::string deviceId, std::string &i continue; } ipAddr = deviceInfo->addr[i].info.ip.ip; - HILOGI("SoftbusAdapter::GetConnectionIpAddr get ip ok."); - return ERR_OK; + DMLOG(DM_LOG_INFO, "DM_GetConnectionIpAddr get ip ok."); + return DEVICEMANAGER_OK; } - HILOGE("failed to get ipAddr for deviceId %{public}s", GetAnonyString(deviceId).c_str()); - return ERR_DEVICEMANAGER_OPERATION_FAILED; + DMLOG(DM_LOG_ERROR, "failed to get ipAddr for deviceId %s", GetAnonyString(deviceId).c_str()); + return DEVICEMANAGER_FAILED; } -const std::map>>& SoftbusAdapter::GetsubscribeInfos() +// eth >> wlan >> ble >> br +ConnectionAddr *SoftbusAdapter::GetConnectAddrByType(DeviceInfo *deviceInfo, ConnectionAddrType type) { - return subscribeInfos_; + if (deviceInfo == nullptr) { + return nullptr; + } + for (unsigned int i = 0; i < deviceInfo->addrNum; ++i) { + if (deviceInfo->addr[i].type == type) { + return &deviceInfo->addr[i]; + } + } + return nullptr; } -void SoftbusAdapter::SaveDiscoverDeviceInfo(const DeviceInfo *deviceInfo) +ConnectionAddr *SoftbusAdapter::GetConnectAddr(std::string deviceId) { - std::shared_ptr info = std::make_shared(); - DeviceInfo *infoPtr = info.get(); - if (memcpy_s(infoPtr, sizeof(DeviceInfo), deviceInfo, sizeof(DeviceInfo)) != 0) { - HILOGE("SoftbusAdapter::SaveDiscoverDeviceInfo failed."); - return; + 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; } - std::string deviceId = deviceInfo->devId; - discoverDeviceInfoMap_[deviceId] = info; - discoverDeviceInfoVector_.push_back(info); + 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; + } - // 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); + 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::RemoveDiscoverDeviceInfo(const std::string deviceId) +void SoftbusAdapter::NodeBasicInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, NodeBasicInfo &nodeBasicInfo) { - 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)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + (void)memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), nodeBasicInfo.networkId, + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(nodeBasicInfo.networkId))); + (void)memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))); + dmDeviceInfo.deviceTypeId = (DMDeviceType)nodeBasicInfo.deviceTypeId; +} + +void SoftbusAdapter::DeviceInfoCopyToDmDevice(DmDeviceInfo &dmDeviceInfo, const DeviceInfo &deviceInfo) +{ + (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + (void)memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))); + (void)memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))); + 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 +} // 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 new file mode 100644 index 000000000..8a74c2e48 --- /dev/null +++ b/services/devicemanagerservice/src/softbus/softbus_session.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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) { + DMLOG(DM_LOG_INFO, "GetPeerDeviceId success for session:%d, peerDeviceId:%s", sessionId, + GetAnonyString(peerDeviceId).c_str()); + peerDevId = peerDeviceId; + return; + } + + DMLOG(DM_LOG_ERROR, "GetPeerDeviceId failed for session:%d", sessionId); + peerDevId = ""; +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/devicemanagerservice/src/util/anonymous_string.cpp b/services/devicemanagerservice/src/util/anonymous_string.cpp deleted file mode 100644 index 69ed71a76..000000000 --- a/services/devicemanagerservice/src/util/anonymous_string.cpp +++ /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. - */ - -#include "anonymous_string.h" - -#include "securec.h" - -namespace OHOS { -namespace DistributedHardware { -namespace { - const int INT32_STRING_LENGTH = 40; - const int INT32_SHORT_ID_LENGTH = 20; - const int INT32_PLAINTEXT_LENGTH = 4; - const int INT32_MIN_ID_LENGTH = 3; -} - -std::string GetAnonyString(const std::string &value) -{ - 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) -{ - 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/BUILD.gn b/utils/BUILD.gn new file mode 100644 index 000000000..97be1fa25 --- /dev/null +++ b/utils/BUILD.gn @@ -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. + +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", + ] + + cflags_cc = build_flags + + 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", + ] + + cflags_cc = build_flags + + 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" + } +} -- Gitee From fd48b21927737f8fa896e214a3811d846d85b97f Mon Sep 17 00:00:00 2001 From: yuqianyuan Date: Sat, 11 Sep 2021 22:14:14 +0800 Subject: [PATCH 04/18] add files Signed-off-by: yuqianyuan --- .../devicemanagerservice/include/requestauth/response_session.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/devicemanagerservice/include/requestauth/response_session.h b/services/devicemanagerservice/include/requestauth/response_session.h index fb547b9f3..5ad058c72 100644 --- a/services/devicemanagerservice/include/requestauth/response_session.h +++ b/services/devicemanagerservice/include/requestauth/response_session.h @@ -58,7 +58,7 @@ private: void CancelDisplay(); int32_t GeneratePincode(); -public: +private: int64_t mRequestId_; std::string mGroupId_; std::string mGroupName_; -- Gitee From 0043dfcf20d9c053690d718939f1c00ab27822e3 Mon Sep 17 00:00:00 2001 From: yuqianyuan Date: Sat, 11 Sep 2021 22:24:39 +0800 Subject: [PATCH 05/18] add files Signed-off-by: yuqianyuan --- .../devicemanagerservice/include/requestauth/request_session.h | 2 +- .../devicemanagerservice/include/requestauth/response_session.h | 2 +- services/devicemanagerservice/src/message/msg_response_auth.cpp | 2 +- .../devicemanagerservice/src/requestauth/response_session.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/devicemanagerservice/include/requestauth/request_session.h b/services/devicemanagerservice/include/requestauth/request_session.h index 2595bf6f6..4daec9e38 100644 --- a/services/devicemanagerservice/include/requestauth/request_session.h +++ b/services/devicemanagerservice/include/requestauth/request_session.h @@ -69,7 +69,7 @@ private: std::string mRemoteNetId_; std::string mRemoteGroupId_; std::string mRemoteGroupName_; - long long mRequestId_; + int64_t mRequestId_; std::shared_ptr responseMsgPtr_; }; } diff --git a/services/devicemanagerservice/include/requestauth/response_session.h b/services/devicemanagerservice/include/requestauth/response_session.h index 5ad058c72..87462daba 100644 --- a/services/devicemanagerservice/include/requestauth/response_session.h +++ b/services/devicemanagerservice/include/requestauth/response_session.h @@ -44,7 +44,7 @@ public: void OnGroupCreated(int64_t requestId, const std::string &groupId) override; void BuildAuthenticationInfo(DmAuthParam &authParam); void OnReceiveMsg(long long channelId, std::string &message); - long long GetRequestId(); + int64_t GetRequestId(); int32_t GetPinCodeByReqId(int64_t requestId); bool IsMyChannelId(long long channelId); diff --git a/services/devicemanagerservice/src/message/msg_response_auth.cpp b/services/devicemanagerservice/src/message/msg_response_auth.cpp index 41f5f11ad..59e096430 100644 --- a/services/devicemanagerservice/src/message/msg_response_auth.cpp +++ b/services/devicemanagerservice/src/message/msg_response_auth.cpp @@ -137,7 +137,7 @@ std::string MsgResponseAuth::GetGroupName() return mGroupName_; } -long long MsgResponseAuth::GetRequestId() +int64_t MsgResponseAuth::GetRequestId() { return mRequestId_; } diff --git a/services/devicemanagerservice/src/requestauth/response_session.cpp b/services/devicemanagerservice/src/requestauth/response_session.cpp index 4410243b6..d343c56db 100644 --- a/services/devicemanagerservice/src/requestauth/response_session.cpp +++ b/services/devicemanagerservice/src/requestauth/response_session.cpp @@ -51,7 +51,7 @@ ResponseSession::ResponseSession() // need to update } -long long ResponseSession::GetRequestId(void) +int64_t ResponseSession::GetRequestId(void) { return mRequestId_; } -- Gitee From ea413bf705dbe1ee647b80fad0d80ed42bdaea11 Mon Sep 17 00:00:00 2001 From: yuqianyuan Date: Sat, 11 Sep 2021 23:03:04 +0800 Subject: [PATCH 06/18] add files Signed-off-by: yuqianyuan --- devicemanager.gni | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/devicemanager.gni b/devicemanager.gni index 83db3519b..5b37dbc85 100644 --- a/devicemanager.gni +++ b/devicemanager.gni @@ -11,7 +11,6 @@ # See the License for the specific language governing permissions and # limitations under the License. - devicemanager_path = "//foundation/distributedhardware/devicemanager" common_path = "${devicemanager_path}/common" @@ -23,6 +22,6 @@ services_path = "${devicemanager_path}/services" innerkits_path = "${devicemanager_path}/interfaces/inner_kits" build_flags = [ - "-Werror", - "-Wall", - ] \ No newline at end of file + "-Werror", + "-Wall", +] -- Gitee From 744e647dfe82fe594b082ec982c2c8c22864eecd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=83=B3=E4=B8=8D=E5=87=BA=E5=88=AB=E5=90=8D?= Date: Sun, 12 Sep 2021 14:31:51 +0800 Subject: [PATCH 07/18] codestyle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 想不出别名 --- .../native_cpp/include/dm_app_image_info.h | 4 +- .../native_cpp/src/device_manager_impl.cpp | 2 +- .../src/ipc/lite/ipc_client_server_proxy.cpp | 2 +- .../src/notify/device_manager_notify.cpp | 2 +- .../kits/js/include/native_devicemanager_js.h | 8 +- .../kits/js/src/native_devicemanager_js.cpp | 79 ++++++++----------- .../include/auth/hichain_connector.h | 8 +- .../include/ipc/lite/ipc_server_listenermgr.h | 8 +- .../include/message/msg_request_auth.h | 24 +++--- .../src/auth/hichain_connector.cpp | 12 +-- .../src/ipc/lite/ipc_server_stub.cpp | 2 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 2 +- .../src/softbus/softbus_adapter.cpp | 4 +- utils/src/anonymous_string.cpp | 8 +- utils/src/cipher/encrypt_utils.cpp | 4 +- 15 files changed, 79 insertions(+), 90 deletions(-) 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 d9d18c8b3..164bd5f4c 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 @@ -54,7 +54,7 @@ public: } } - DmAppImageInfo& operator= (const DmAppImageInfo &other) + DmAppImageInfo& operator=(const DmAppImageInfo &other) { if (this != &other) { SaveData(other.GetAppIcon(), other.GetAppIconLen(), other.GetAppThumbnail(), other.GetAppThumbnailLen()); @@ -63,7 +63,7 @@ public: } DmAppImageInfo(DmAppImageInfo&&) = delete; - DmAppImageInfo& operator= (DmAppImageInfo&&) = delete; + DmAppImageInfo& operator=(DmAppImageInfo&&) = delete; int32_t GetAppIconLen() const { 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 e2a39db6c..23f7ef2c6 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -280,7 +280,7 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(std::string &packageN int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(std::string &pkgName) { - DMLOG(DM_LOG_INFO, "DeviceManager::UnRegisterDeviceManagerFaCallback start, pkgName: %s", pkgName.c_str()); + 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; 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 922844c70..bfac66bf3 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 @@ -53,7 +53,7 @@ int32_t DMDeathCallback(const IpcContext *ctx, void *ipcMsg, IpcIo *data, void * return DEVICEMANAGER_OK; } -static int32_t SendCmdResultCb(IOwner owner, int code, IpcIo *reply) +static int32_t SendCmdResultCb(IOwner owner, int32_t code, IpcIo *reply) { (void)code; int32_t cmdCode = *(int32_t *)owner; 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 bf8961b57..4144e3ac6 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 @@ -283,7 +283,7 @@ void DeviceManagerNotify::OnCheckAuthResult(std::string &pkgName, std::string &d void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) { - DMLOG(DM_LOG_INFO, "DeviceManager OnFaCallback pkgName:%s", pkgName.c_str()); + 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"); diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index c03fc4cd4..c232985c0 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -27,7 +27,7 @@ #include "nlohmann/json.hpp" #include "dm_device_info.h" -const int DM_NAPI_BUF_LENGTH = 256; +#define DM_NAPI_BUF_LENGTH (256) struct AsyncCallbackInfo { napi_env env = nullptr; @@ -149,15 +149,15 @@ public: static void ReleaseDmCallback(std::string &bundleName, std::string &eventType); static void DeviceInfoToJsArray(const napi_env &env, const std::vector& vecDevInfo, - const int idx, napi_value &arrayResult); + 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 int intValue, + static void SetValueInt32(const napi_env &env, const std::string &fieldStr, const int32_t intValue, 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 int destLen); + 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, diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 3b7c40e87..9d00ded1e 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -40,13 +40,15 @@ const std::string DM_NAPI_EVENT_DEVICE_SERVICE_DIE = "serviceDie"; const std::string DEVICE_MANAGER_NAPI_CLASS_NAME = "DeviceManager"; -const int DM_NAPI_ARGS_ONE = 1; -const int DM_NAPI_ARGS_TWO = 2; -const int DM_NAPI_ARGS_THREE = 3; -const int DM_NAPI_SUB_ID_MAX = 65535; +const int32_t DM_NAPI_ARGS_ONE = 1; +const int32_t DM_NAPI_ARGS_TWO = 2; +const int32_t DM_NAPI_ARGS_THREE = 3; +const int32_t DM_NAPI_SUB_ID_MAX = 65535; -const int DM_AUTH_TYPE_PINCODE = 1; -const int DM_AUTH_DIRECTION_CLIENT = 1; +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; std::map g_deviceManagerMap; std::map> g_initCallbackMap; @@ -57,13 +59,9 @@ std::map> g_checkAuthCallb std::map> g_dmfaCallbackMap; } -enum DmNapiSubscribeCap { - DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0 -}; - napi_ref DeviceManagerNapi::sConstructor_ = nullptr; -AuthAsyncCallbackInfo DeviceManagerNapi::authAsyncCallbackInfo_ = {0}; -AuthAsyncCallbackInfo DeviceManagerNapi::verifyAsyncCallbackInfo_ = {0}; +AuthAsyncCallbackInfo DeviceManagerNapi::authAsyncCallbackInfo_; +AuthAsyncCallbackInfo DeviceManagerNapi::verifyAsyncCallbackInfo_; void DmNapiInitCallback::OnRemoteDied() { @@ -339,7 +337,7 @@ void DeviceManagerNapi::SetValueUtf8String(const napi_env &env, const std::strin napi_set_named_property(env, result, fieldStr.c_str(), value); } -void DeviceManagerNapi::SetValueInt32(const napi_env &env, const std::string &fieldStr, const int intValue, +void DeviceManagerNapi::SetValueInt32(const napi_env &env, const std::string &fieldStr, const int32_t intValue, napi_value &result) { napi_value value; @@ -349,7 +347,7 @@ void DeviceManagerNapi::SetValueInt32(const napi_env &env, const std::string &fi void DeviceManagerNapi::DeviceInfoToJsArray(const napi_env &env, const std::vector &vecDevInfo, - const int idx, napi_value &arrayResult) + const int32_t idx, napi_value &arrayResult) { napi_value result; napi_create_object(env, &result); @@ -416,7 +414,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, } void DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_value &object, - const std::string &fieldStr, char *dest, const int destLen) + 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)); @@ -463,7 +461,7 @@ std::string DeviceManagerNapi::JsObjectToString(const napi_env &env, const napi_ } void DeviceManagerNapi::JsObjectToInt(const napi_env &env, const napi_value &object, - const std::string &fieldStr, int &fieldRef) + 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)); @@ -501,7 +499,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) { - int subscribeId = -1; + 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); @@ -510,24 +508,24 @@ int32_t DeviceManagerNapi::JsToDmSubscribeInfo(const napi_env &env, const napi_v info.subscribeId = (uint16_t)subscribeId; - int mode = -1; + int32_t mode = -1; JsObjectToInt(env, object, "mode", mode); info.mode = (DmDiscoverMode)mode; - int medium = -1; + int32_t medium = -1; JsObjectToInt(env, object, "medium", medium); info.medium = (DmExchangeMedium)medium; - int freq = -1; + int32_t freq = -1; JsObjectToInt(env, object, "freq", freq); info.freq = (DmExchangeFreq)freq; JsObjectToBool(env, object, "isSameAccount", info.isSameAccount); JsObjectToBool(env, object, "isWakeRemote", info.isWakeRemote); - int capability = -1; + int32_t capability = -1; JsObjectToInt(env, object, "capability", capability); - if (capability == DmNapiSubscribeCap::DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP) { + if (capability == DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP) { (void)strncpy_s(info.capability, sizeof(info.capability), DM_CAPABILITY_OSD, strlen(DM_CAPABILITY_OSD)); } return 0; @@ -538,7 +536,7 @@ void DeviceManagerNapi::JsToDmDeviceInfo(const napi_env &env, const napi_value & { JsObjectToString(env, object, "deviceId", info.deviceId, sizeof(info.deviceId)); JsObjectToString(env, object, "deviceName", info.deviceName, sizeof(info.deviceName)); - int deviceType = -1; + int32_t deviceType = -1; JsObjectToInt(env, object, "deviceType", deviceType); info.deviceTypeId = (DMDeviceType)deviceType; } @@ -547,7 +545,7 @@ void DeviceManagerNapi::JsToDmAppImageInfoAndDmExtra(const napi_env &env, const DmAppImageInfo& appImageInfo, std::string &extra, int32_t &authType) { DMLOG(DM_LOG_INFO, "JsToDmAppImageInfoAndDmExtra in."); - int authTypeTemp = -1; + int32_t authTypeTemp = -1; JsObjectToInt(env, object, "authType", authTypeTemp); authType = authTypeTemp; @@ -634,7 +632,6 @@ 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); napi_value jsProName = nullptr; napi_value jsProValue = nullptr; @@ -645,15 +642,12 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob napi_typeof(env, jsProValue, &jsValueType); 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()); - jsonObj[strProName] = natValue; + jsonObj[strProName] = JsObjectToString(env, jsProValue); 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); jsonObj[strProName] = elementValue; break; } @@ -663,14 +657,11 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob DMLOG(DM_LOG_ERROR, "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); } break; } - default: { - DMLOG(DM_LOG_ERROR, "Property name=%s, value type not support.", strProName.c_str()); + default: break; - } } } } @@ -678,8 +669,8 @@ 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__); - int authType = -1; - int token = -1; + int32_t authType = -1; + int32_t token = -1; JsObjectToInt(env, object, "authType", authType); JsObjectToInt(env, object, "token", token); @@ -944,6 +935,8 @@ napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_info info) { + const int32_t PARAM_INDEX_ONE = 1; + const int32_t PARAM_INDEX_TWO = 2; DMLOG(DM_LOG_INFO, "AuthenticateDevice in"); GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); napi_value result = nullptr; @@ -952,15 +945,15 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf NAPI_ASSERT(env, deviceInfoType == napi_object, "Wrong argument type. Object expected."); napi_valuetype authparamType; - napi_typeof(env, argv[1], &authparamType); + napi_typeof(env, argv[PARAM_INDEX_ONE], &authparamType); NAPI_ASSERT(env, authparamType == napi_object, "Wrong argument type. Object expected."); napi_valuetype eventHandleType = napi_undefined; - napi_typeof(env, argv[2], &eventHandleType); + napi_typeof(env, argv[PARAM_INDEX_TWO], &eventHandleType); NAPI_ASSERT(env, eventHandleType == napi_function, "Wrong argument type. Function expected."); authAsyncCallbackInfo_.env = env; - napi_create_reference(env, argv[2], 1, &authAsyncCallbackInfo_.callback); + napi_create_reference(env, argv[PARAM_INDEX_TWO], 1, &authAsyncCallbackInfo_.callback); DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); @@ -978,7 +971,7 @@ napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_inf DmAppImageInfo appImageInfo(nullptr, 0, nullptr, 0); std::string extra; - JsToDmAppImageInfoAndDmExtra(env, argv[1], appImageInfo, extra, authAsyncCallbackInfo_.authType); + JsToDmAppImageInfoAndDmExtra(env, argv[PARAM_INDEX_ONE], appImageInfo, extra, authAsyncCallbackInfo_.authType); int32_t ret = DeviceManager::GetInstance().AuthenticateDevice(deviceManagerWrapper->bundleName_, deviceInfo, appImageInfo, extra, authCallback); @@ -1167,9 +1160,7 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac DMLOG(DM_LOG_ERROR, "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); napi_get_undefined(env, &result[0]); napi_value callback = nullptr; napi_value callResult = nullptr; @@ -1177,18 +1168,16 @@ 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); napi_value message = nullptr; napi_create_object(env, &result[0]); napi_create_int32(env, asCallbackInfo->status, &message); napi_set_named_property(env, result[0], "code", message); napi_get_undefined(env, &result[1]); } + DMLOG(DM_LOG_INFO, "bunderName %s, status:%d", asCallbackInfo->bundleName, asCallbackInfo->status); napi_delete_async_work(env, asCallbackInfo->asyncWork); delete asCallbackInfo; - }, - (void *)asCallbackInfo, - &asCallbackInfo->asyncWork); + }, (void *)asCallbackInfo, &asCallbackInfo->asyncWork); napi_queue_async_work(env, asCallbackInfo->asyncWork); } diff --git a/services/devicemanagerservice/include/auth/hichain_connector.h b/services/devicemanagerservice/include/auth/hichain_connector.h index 18829cb61..61534df59 100644 --- a/services/devicemanagerservice/include/auth/hichain_connector.h +++ b/services/devicemanagerservice/include/auth/hichain_connector.h @@ -57,15 +57,15 @@ class HichainAuthenCallBack { public: static bool onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); static void onSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); - static void onFinish(int64_t requestId, int operationCode, const char *returnData); - static void onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn); - static char *onRequest(int64_t requestId, int operationCode, const char *reqParams); + static void onFinish(int64_t requestId, int32_t operationCode, const char *returnData); + static void onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn); + static char *onRequest(int64_t requestId, int32_t operationCode, const char *reqParams); }; class HichainConnector { DECLARE_SINGLE_INSTANCE(HichainConnector); public: - int Init(); + int32_t Init(); bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); int64_t GenRequestId(); void RegisterConnectorCallback(std::shared_ptr callback); diff --git a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h index 3e39f8cce..26d2ee114 100644 --- a/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h +++ b/services/devicemanagerservice/include/ipc/lite/ipc_server_listenermgr.h @@ -27,11 +27,11 @@ namespace OHOS { namespace DistributedHardware { typedef struct CommonSvcId { - unsigned int handle; - unsigned int token; - unsigned int cookie; + uint32_t handle; + uint32_t token; + uint32_t cookie; IpcContext *ipcCtx; - unsigned int cbId; + uint32_t cbId; }CommonSvcId; class IpcServerListenermgr { diff --git a/services/devicemanagerservice/include/message/msg_request_auth.h b/services/devicemanagerservice/include/message/msg_request_auth.h index c02fd17b5..f38be9b9e 100644 --- a/services/devicemanagerservice/include/message/msg_request_auth.h +++ b/services/devicemanagerservice/include/message/msg_request_auth.h @@ -44,19 +44,6 @@ public: int32_t GetMsgSlice(); int32_t GetMsgCnt(); std::string GetRequestDeviceId(); - -private: - std::string ToHexString(int32_t value); - std::string EncodeDevInfo(); - static int32_t DecodeFirstPackageMsg(nlohmann::json &json, std::shared_ptr msg); - static void DecodeDeviceInfo(nlohmann::json &json, std::shared_ptr msg); - static std::string StringSub(std::string &thumbStr, int32_t start, int32_t length); - int32_t GetEncodedAppInfo(const uint8_t *dataSrc, size_t srcLen, std::string &outString); - 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); - public: std::shared_ptr mHead_; std::string mHostPkg_; @@ -75,6 +62,17 @@ public: int32_t mMsgCnt_ = 0; int32_t mThumbnailSize_; int32_t mAppIconSize_; +private: + std::string ToHexString(int32_t value); + std::string EncodeDevInfo(); + static int32_t DecodeFirstPackageMsg(nlohmann::json &json, std::shared_ptr msg); + static void DecodeDeviceInfo(nlohmann::json &json, std::shared_ptr msg); + static std::string StringSub(std::string &thumbStr, int32_t start, int32_t length); + int32_t GetEncodedAppInfo(const uint8_t *dataSrc, size_t srcLen, std::string &outString); + 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); }; } } diff --git a/services/devicemanagerservice/src/auth/hichain_connector.cpp b/services/devicemanagerservice/src/auth/hichain_connector.cpp index fe9da1279..fcf56e54d 100644 --- a/services/devicemanagerservice/src/auth/hichain_connector.cpp +++ b/services/devicemanagerservice/src/auth/hichain_connector.cpp @@ -219,7 +219,7 @@ void HichainConnector::GetRelatedGroups(std::string deviceId, std::vectorgetRelatedGroups(DEVICE_MANAGER_APP.c_str(), deviceId.c_str(), + 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); @@ -303,7 +303,7 @@ int32_t HichainConnector::DelMemberFromGroup(std::string groupId, std::string de jsonObj[FIELD_DELETE_ID] = deviceId; std::string deleteParams = jsonObj.dump(); - int ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DEVICE_MANAGER_APP.c_str(), deleteParams.c_str()); + int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DEVICE_MANAGER_APP.c_str(), deleteParams.c_str()); if (ret != 0) { DMLOG(DM_LOG_ERROR, "HichainConnector::DelMemberFromGroup faild , ret: %d.", ret); return ret; @@ -318,13 +318,13 @@ void HichainConnector::DeleteGroup(std::string &groupId) jsonObj[FIELD_GROUP_ID] = groupId; std::string disbandParams = jsonObj.dump(); - int ret = deviceGroupManager_->deleteGroup(requestId, DEVICE_MANAGER_APP.c_str(), disbandParams.c_str()); + int32_t ret = deviceGroupManager_->deleteGroup(requestId, DEVICE_MANAGER_APP.c_str(), disbandParams.c_str()); if (ret != 0) { DMLOG(DM_LOG_ERROR, "HichainConnector::DeleteGroup faild , ret: %d.", ret); } } -void HichainAuthenCallBack::onFinish(int64_t requestId, int operationCode, const char *returnData) +void HichainAuthenCallBack::onFinish(int64_t requestId, int32_t operationCode, const char *returnData) { std::string data = ""; if (returnData != nullptr) { @@ -352,7 +352,7 @@ void HichainAuthenCallBack::onFinish(int64_t requestId, int operationCode, const } } -void HichainAuthenCallBack::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) +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.", @@ -377,7 +377,7 @@ void HichainAuthenCallBack::onError(int64_t requestId, int operationCode, int er } } -char *HichainAuthenCallBack::onRequest(int64_t requestId, int operationCode, const char *reqParams) +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); diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp index a14342da7..775245f59 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_server_stub.cpp @@ -192,7 +192,7 @@ static TaskConfig GetTaskConfig(Service *service) return config; } -static int32_t OnRemoteRequest(IServerProxy *iProxy, int funcId, void *origin, +static int32_t OnRemoteRequest(IServerProxy *iProxy, int32_t funcId, void *origin, IpcIo *req, IpcIo *reply) { DMLOG(DM_LOG_INFO, "Receive funcId:%d", funcId); diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 0c5294e02..f19028cf6 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -328,7 +328,7 @@ ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParc { std::string packageName = data.ReadString(); int32_t action = data.ReadInt32(); - int result = IpcServerAdapter::GetInstance().SetUserOperation(packageName, action); + int32_t result = IpcServerAdapter::GetInstance().SetUserOperation(packageName, action); if (!reply.WriteInt32(action)) { DMLOG(DM_LOG_ERROR, "write result failed"); diff --git a/services/devicemanagerservice/src/softbus/softbus_adapter.cpp b/services/devicemanagerservice/src/softbus/softbus_adapter.cpp index 3103b6a47..d855b7eb1 100644 --- a/services/devicemanagerservice/src/softbus/softbus_adapter.cpp +++ b/services/devicemanagerservice/src/softbus/softbus_adapter.cpp @@ -409,7 +409,7 @@ int32_t SoftbusAdapter::GetConnectionIpAddr(std::string deviceId, std::string &i return DEVICEMANAGER_FAILED; } - for (unsigned int i = 0; i < deviceInfo->addrNum; ++i) { + 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) { @@ -429,7 +429,7 @@ ConnectionAddr *SoftbusAdapter::GetConnectAddrByType(DeviceInfo *deviceInfo, Con if (deviceInfo == nullptr) { return nullptr; } - for (unsigned int i = 0; i < deviceInfo->addrNum; ++i) { + for (uint32_t i = 0; i < deviceInfo->addrNum; ++i) { if (deviceInfo->addr[i].type == type) { return &deviceInfo->addr[i]; } diff --git a/utils/src/anonymous_string.cpp b/utils/src/anonymous_string.cpp index c3fdd4f3e..f5834ee37 100644 --- a/utils/src/anonymous_string.cpp +++ b/utils/src/anonymous_string.cpp @@ -21,9 +21,9 @@ namespace OHOS { namespace DistributedHardware { std::string GetAnonyString(const std::string &value) { - const int INT32_SHORT_ID_LENGTH = 20; - const int INT32_PLAINTEXT_LENGTH = 4; - const int INT32_MIN_ID_LENGTH = 3; + 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(); @@ -46,7 +46,7 @@ std::string GetAnonyString(const std::string &value) std::string GetAnonyInt32(const int32_t value) { - const int INT32_STRING_LENGTH = 40; + 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) { diff --git a/utils/src/cipher/encrypt_utils.cpp b/utils/src/cipher/encrypt_utils.cpp index c97fc6934..67a39b9c4 100644 --- a/utils/src/cipher/encrypt_utils.cpp +++ b/utils/src/cipher/encrypt_utils.cpp @@ -97,9 +97,10 @@ int32_t EncryptUtils::GetRandomData(uint8_t *randStr, uint32_t len) return ret; } -int32_t EncryptUtils::MbedtlsEncrypt(const uint8_t *plainText, int plainTextLen, uint8_t *cipherText, +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; } @@ -110,6 +111,7 @@ int32_t EncryptUtils::MbedtlsEncrypt(const uint8_t *plainText, int plainTextLen, 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; -- Gitee From 7e21c4bcdef0f39e2c08059b90e8feae458539b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=83=B3=E4=B8=8D=E5=87=BA=E5=88=AB=E5=90=8D?= Date: Sun, 12 Sep 2021 15:21:40 +0800 Subject: [PATCH 08/18] codestyle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 想不出别名 --- interfaces/kits/js/src/native_devicemanager_js.cpp | 2 +- .../devicemanagerservice/src/auth/hichain_connector.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 9d00ded1e..1120fa805 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -718,7 +718,7 @@ 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()) { diff --git a/services/devicemanagerservice/src/auth/hichain_connector.cpp b/services/devicemanagerservice/src/auth/hichain_connector.cpp index fcf56e54d..afb7695ac 100644 --- a/services/devicemanagerservice/src/auth/hichain_connector.cpp +++ b/services/devicemanagerservice/src/auth/hichain_connector.cpp @@ -303,7 +303,8 @@ 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(), deleteParams.c_str()); + int32_t ret = deviceGroupManager_->deleteMemberFromGroup(requestId, DEVICE_MANAGER_APP.c_str(), + deleteParams.c_str()); if (ret != 0) { DMLOG(DM_LOG_ERROR, "HichainConnector::DelMemberFromGroup faild , ret: %d.", ret); return ret; @@ -352,7 +353,8 @@ void HichainAuthenCallBack::onFinish(int64_t requestId, int32_t operationCode, c } } -void HichainAuthenCallBack::onError(int64_t requestId, int32_t operationCode, int32_t errorCode, const char *errorReturn) +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.", -- Gitee From cfe8fd3de9d0cf871ca7945802b0b963eb218a5d Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Sun, 12 Sep 2021 17:33:03 +0800 Subject: [PATCH 09/18] add fa Code and buf fix Signed-off-by: pengguanqi --- BUILD.gn | 24 ++ common/include/constants.h | 4 + .../ipc/model/ipc_notify_dmfa_result_req.h | 11 - display/README_zh.md | 28 ++ display/build.gradle | 42 +++ display/entry/build.gradle | 27 ++ display/entry/src/main/config.json | 60 ++++ display/entry/src/main/js/default/app.js | 8 + .../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 + .../native_cpp/include/device_manager.h | 2 +- .../native_cpp/include/dm_device_info.h | 1 + .../native_cpp/src/device_manager.cpp | 2 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 82 +++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 9 +- .../src/notify/device_manager_notify.cpp | 10 +- interfaces/kits/js/BUILD.gn | 147 +++++--- .../kits/js/src/native_devicemanager_js.cpp | 34 +- services/devicemanagerservice/BUILD.gn | 11 +- .../include/auth/hichain_connector.h | 10 +- .../include/ipc/ipc_server_adapter.h | 3 - .../include/ipc/ipc_server_listener_adapter.h | 2 +- .../include/requestauth/auth_manager.h | 3 + .../include/requestauth/request_session.h | 2 + .../include/requestauth/response_session.h | 10 +- .../include/timer/dm_timer.h | 70 ++++ .../src/ability/dm_ability_manager.cpp | 13 +- .../src/ability/dm_ability_manager_lite.cpp | 57 +++ .../src/auth/hichain_connector.cpp | 50 +-- .../src/ipc/ipc_server_listener_adapter.cpp | 5 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 68 ++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 15 +- .../src/message/msg_response_auth.cpp | 6 +- .../src/requestauth/auth_manager.cpp | 34 +- .../src/requestauth/request_session.cpp | 38 +- .../src/requestauth/response_session.cpp | 61 +++- .../src/timer/dm_timer.cpp | 118 +++++++ 43 files changed, 1527 insertions(+), 159 deletions(-) create mode 100644 BUILD.gn create mode 100644 display/README_zh.md create mode 100644 display/build.gradle create mode 100644 display/entry/build.gradle create mode 100644 display/entry/src/main/config.json create mode 100644 display/entry/src/main/js/default/app.js create mode 100644 display/entry/src/main/js/default/i18n/en-US.json create mode 100644 display/entry/src/main/js/default/i18n/zh-CN.json create mode 100644 display/entry/src/main/js/default/pages/index/index.css create mode 100644 display/entry/src/main/js/default/pages/index/index.hml create mode 100644 display/entry/src/main/js/default/pages/index/index.js create mode 100644 display/entry/src/main/resources/base/element/string.json create mode 100644 display/entry/src/main/resources/base/media/icon.png create mode 100644 display/settings.gradle create mode 100644 services/devicemanagerservice/include/timer/dm_timer.h create mode 100644 services/devicemanagerservice/src/ability/dm_ability_manager_lite.cpp create mode 100644 services/devicemanagerservice/src/timer/dm_timer.cpp diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 index 000000000..8029a02d0 --- /dev/null +++ b/BUILD.gn @@ -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. + +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + lite_component("devicemanager_lite") { + features = [ + "utils:devicemanagerutils", + "services/devicemanagerservice:devicemanagerservice", + "interfaces/inner_kits/native_cpp:devicemanagersdk", + "interfaces/kits/js:devicemanager", + ] + } +} diff --git a/common/include/constants.h b/common/include/constants.h index d9e21679c..31e75813d 100644 --- a/common/include/constants.h +++ b/common/include/constants.h @@ -104,6 +104,7 @@ namespace DistributedHardware { 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; @@ -136,6 +137,9 @@ namespace DistributedHardware { 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; 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 b76d26ba7..e6012aa7a 100644 --- a/common/include/ipc/model/ipc_notify_dmfa_result_req.h +++ b/common/include/ipc/model/ipc_notify_dmfa_result_req.h @@ -25,16 +25,6 @@ namespace DistributedHardware { class IpcNotifyDMFAResultReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyDMFAResultReq); public: - std::string GetPkgName() const - { - return PackageName_; - } - - void SetPkgName(std::string& pkgName) - { - PackageName_ = pkgName; - } - std::string GetJsonParam() const { return JsonParam_; @@ -45,7 +35,6 @@ public: JsonParam_ = JsonParam; } private: - std::string PackageName_; std::string JsonParam_; }; } // namespace DistributedHardware diff --git a/display/README_zh.md b/display/README_zh.md new file mode 100644 index 000000000..4d2c7a6e7 --- /dev/null +++ b/display/README_zh.md @@ -0,0 +1,28 @@ +# 设备管理交互 + +- [简介](#section11660541593) + - [交互](#section78574815486) + +- [目录](#section161941989596) + +## 简介 + +为设备管理提供用户交互功能。 + +### 交互 + +主控端pin码输入、被控端授权(资源流转/FA流转)、被控端pin码展示。 + +## 目录 + +``` +/ +├── entry # 主Ability +│ └── src +│ └── main +│ ├── config.json # 全局配置文件 +│ ├── js # js代码目录 +│ └── resources # 资源配置文件存放目录 +├── interface # 接口文件 +├── signature # 证书文件目录 +``` diff --git a/display/build.gradle b/display/build.gradle new file mode 100644 index 000000000..464cc3fc5 --- /dev/null +++ b/display/build.gradle @@ -0,0 +1,42 @@ +// 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..3f35a96a6 --- /dev/null +++ b/display/entry/build.gradle @@ -0,0 +1,27 @@ +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..4afe6b107 --- /dev/null +++ b/display/entry/src/main/config.json @@ -0,0 +1,60 @@ +{ + "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" + ] + } + ], + "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..aedcefe00 --- /dev/null +++ b/display/entry/src/main/js/default/app.js @@ -0,0 +1,8 @@ +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..b8c571462 --- /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..c0dd3a09e --- /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 dmInitCallback) = 0; virtual int32_t UnInitDeviceManager(std::string &pkgName) = 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 45ccf822c..7a37e336c 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -58,6 +58,7 @@ typedef struct DmAuthParam { int32_t business; int32_t pincode; int32_t direction; + int32_t displayOwner; int32_t pinToken; DmAppImageInfo imageinfo; } DmAuthParam; diff --git a/interfaces/inner_kits/native_cpp/src/device_manager.cpp b/interfaces/inner_kits/native_cpp/src/device_manager.cpp index baececb7b..4bedc0a57 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager.cpp @@ -19,7 +19,7 @@ namespace OHOS { namespace DistributedHardware { -DeviceManager& DeviceManager::GetInstance() +DeviceManager &DeviceManager::GetInstance() { return DeviceManagerImpl::GetInstance(); } 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 79dc594be..b6eddb76b 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 @@ -16,6 +16,8 @@ #include "ipc_cmd_register.h" #include "ipc_def.h" +#include "securec.h" +#include "constants.h" #include "device_manager_errno.h" #include "device_manager_log.h" #include "device_manager_notify.h" @@ -30,6 +32,8 @@ #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" namespace OHOS { namespace DistributedHardware { @@ -283,5 +287,83 @@ ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, IpcIo &reply, const IpcContext &ctx, void * DeviceManagerNotify::GetInstance().OnCheckAuthResult(pkgName, deviceId, resultCode, flag); FreeBuffer(&ctx, ipcMsg); } + +ON_IPC_SET_REQUEST(SERVER_GET_AUTHENTCATION_INFO, std::shared_ptr pBaseReq, IpcIo& request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagename = pReq->GetPkgName(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, packagename.c_str()); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, IpcIo& reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + DmAuthParam authParam = {0}; + authParam.direction = IpcIoPopInt32(&reply); + authParam.authType = IpcIoPopInt32(&reply); + if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { + authParam.pinToken = IpcIoPopInt32(&reply); + authParam.displayOwner = IpcIoPopInt32(&reply); + pRsp->SetAuthParam(authParam); + return DEVICEMANAGER_OK; + } + size_t PackagerNamelen = 0; + authParam.packageName = strdup((const char *)IpcIoPopString(&reply, &PackagerNamelen)); + size_t appNameLen = 0; + authParam.appName = strdup((const char *)IpcIoPopString(&reply, &appNameLen)); + size_t appDesLen = 0; + authParam.appDescription = strdup((const char *)IpcIoPopString(&reply, &appDesLen)); + authParam.business = IpcIoPopInt32(&reply); + authParam.pincode = IpcIoPopInt32(&reply); + + uint32_t appIconLen = IpcIoPopInt32(&reply); + uint8_t *appIconBuffer = nullptr; + uint32_t appThumbnailLen = IpcIoPopInt32(&reply); + uint8_t *appThumbBuffer = nullptr; + + if (appIconLen > 0) { + appIconBuffer = (uint8_t *)IpcIoPopFlatObj(&reply, &appIconLen); + } + if (appThumbnailLen > 0) { + appThumbBuffer = (uint8_t *)IpcIoPopFlatObj(&reply, &appThumbnailLen); + } + + authParam.imageinfo.Reset(appIconBuffer, appIconLen, appThumbBuffer, appThumbnailLen); + pRsp->SetAuthParam(authParam); + return DEVICEMANAGER_OK; +} + +ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr pBaseReq, IpcIo& request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName= pReq->GetPkgName(); + int32_t action = pReq->GetOperation(); + + IpcIoInit(&request, buffer, buffLen, 0); + IpcIoPushString(&request, pkgName.c_str()); + IpcIoPushInt32(&request, action); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo& reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} + +ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply, const IpcContext &ctx, void *ipcMsg) +{ + 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); + IpcIoPushInt32(&reply, DEVICEMANAGER_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 88217e1bd..f668a8c18 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 @@ -303,7 +303,7 @@ ON_IPC_CMD(SERVER_CHECK_AUTH_RESULT, MessageParcel &data, MessageParcel &reply) return DEVICEMANAGER_OK; } -ON_IPC_SET_REQUEST(SERVER_GET_AUTHENTCATION_INFO, std::shared_ptr pBaseReq, MessageParcel& data) +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(); @@ -314,7 +314,7 @@ ON_IPC_SET_REQUEST(SERVER_GET_AUTHENTCATION_INFO, std::shared_ptr pBaseR return DEVICEMANAGER_OK; } -ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, MessageParcel& reply, std::shared_ptr pBaseRsp) +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; @@ -322,6 +322,7 @@ ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, MessageParcel& reply, std::s authParam.authType = reply.ReadInt32(); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { authParam.pinToken = reply.ReadInt32(); + authParam.displayOwner = reply.ReadInt32(); pRsp->SetAuthParam(authParam); return DEVICEMANAGER_OK; } @@ -347,7 +348,7 @@ ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, MessageParcel& reply, std::s return DEVICEMANAGER_OK; } -ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr pBaseReq, MessageParcel& data) +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(); @@ -365,7 +366,7 @@ ON_IPC_SET_REQUEST(SERVER_USER_AUTHORIZATION_OPERATION, std::shared_ptr return DEVICEMANAGER_OK; } -ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel& reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &reply, std::shared_ptr pBaseRsp) { pBaseRsp->SetErrCode(reply.ReadInt32()); return DEVICEMANAGER_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 4144e3ac6..c65c31a46 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 @@ -187,7 +187,7 @@ void DeviceManagerNotify::OnDeviceFound(std::string &pkgName, uint16_t subscribe DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceFound: no register discoverCallback for this package"); return; } - std::map>& discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + std::map> &discoverCallMap = deviceDiscoverCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { DMLOG(DM_LOG_ERROR, "DeviceManager OnDeviceFound: no register discoverCallback for subscribeId %d", @@ -206,7 +206,7 @@ void DeviceManagerNotify::OnDiscoverFailed(std::string &pkgName, uint16_t subscr DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverFailed: no register discoverCallback for this package"); return; } - std::map>& discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + std::map> &discoverCallMap = deviceDiscoverCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverFailed: no register discoverCallback for subscribeId %d", @@ -225,7 +225,7 @@ void DeviceManagerNotify::OnDiscoverySuccess(std::string &pkgName, uint16_t subs DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverySuccess: no register discoverCallback for this package"); return; } - std::map>& discoverCallMap = deviceDiscoverCallbacks_[pkgName]; + std::map> &discoverCallMap = deviceDiscoverCallbacks_[pkgName]; auto iter = discoverCallMap.find(subscribeId); if (iter == discoverCallMap.end()) { DMLOG(DM_LOG_ERROR, "DeviceManager OnDiscoverySuccess: no register discoverCallback for subscribeId %d", @@ -245,7 +245,7 @@ void DeviceManagerNotify::OnAuthResult(std::string &pkgName, std::string &device DMLOG(DM_LOG_ERROR, "DeviceManager OnAuthResult: no register authCallback for this package"); return; } - std::map>& authCallMap = authenticateCallback_[pkgName]; + 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 "); @@ -268,7 +268,7 @@ void DeviceManagerNotify::OnCheckAuthResult(std::string &pkgName, std::string &d DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register authCallback for this package"); return; } - std::map>& CheckAuthCallmap = checkauthcallback_[pkgName]; + std::map> &CheckAuthCallmap = checkauthcallback_[pkgName]; auto iter = CheckAuthCallmap.find(deviceId); if (iter == CheckAuthCallmap.end()) { DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register CheckAuthCallmap for deviceID"); diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 5c6777207..b82cf50ab 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -11,58 +11,115 @@ # See the License for the specific language governing permissions and # limitations under the License. -import("//build/ohos.gni") +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") +} else { + import("//build/ohos.gni") +} import("//foundation/distributedhardware/devicemanager/devicemanager.gni") -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/ipc", - "${innerkits_path}/native_cpp/include", - "${innerkits_path}/native_cpp/include/standard", - ] +if (defined(ohos_lite)) { + 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/ipc", + "${common_path}/include/ipc/model", + "${common_path}/include/ipc/lite", + "${innerkits_path}/native_cpp/include", + ] + include_dirs += [ + "//utils/native/lite/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog", + "//third_party/bounds_checking_function/include", + "//foundation/communication/ipc_lite/interfaces/kits", + "//foundation/distributedschedule/samgr_lite/interfaces/kits/samgr", + ] - sources = [ - "src/dm_native_event.cpp", - "src/native_devicemanager_js.cpp", - ] + sources = [ + "src/dm_native_event.cpp", + "src/native_devicemanager_js.cpp", + ] - deps = [ - "${utils_path}:devicemanagerutils", - "//foundation/ace/napi:ace_napi", - "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", - "//utils/native/base:utils", - ] + deps = [ + "${utils_path}:devicemanagerutils", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//foundation/communication/ipc_lite:liteipc_adapter", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//foundation/distributedschedule/samgr_lite/samgr:samgr", + "//third_party/bounds_checking_function:libsec_shared", + "//utils/native/lite:utils", + ] - cflags_cc = build_flags + cflags_cc = build_flags - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"devicemanagerkit_js\"", - "LOG_DOMAIN=0xD004100", - ] + defines = [ + "LITE_DEVICE", + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit_js\"", + "LOG_DOMAIN=0xD004100", + ] + } + group("devicemanager_native_js") { + deps = [ ":devicemanager" ] + } +} else { + 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/ipc", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/standard", + ] - external_deps = [ - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", - ] + sources = [ + "src/dm_native_event.cpp", + "src/native_devicemanager_js.cpp", + ] - subsystem_name = "distributedhardware" - relative_install_dir = "module/distributedhardware" - part_name = "device_manager_base" -} + deps = [ + "${utils_path}:devicemanagerutils", + "//foundation/ace/napi:ace_napi", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//utils/native/base:utils", + ] + + cflags_cc = build_flags + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"devicemanagerkit_js\"", + "LOG_DOMAIN=0xD004100", + ] + + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + subsystem_name = "distributedhardware" + relative_install_dir = "module/distributedhardware" + part_name = "device_manager_base" + } -group("devicemanager_native_js") { - deps = [ ":devicemanager" ] + group("devicemanager_native_js") { + deps = [ ":devicemanager" ] + } } diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 1120fa805..b63be4163 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -389,9 +389,9 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParamy(const napi_env &env, void *appIcon = nullptr; napi_value appIconBuffer = nullptr; napi_create_arraybuffer(env, appIconLen, &appIcon, &appIconBuffer); - int32_t ret = memcpy_s(appIcon, appIconLen, reinterpret_cast(authParam.imageinfo.GetAppIcon()), - appIconLen); - if (appIcon != nullptr && ret == 0) { + 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); @@ -632,6 +632,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); napi_value jsProName = nullptr; napi_value jsProValue = nullptr; @@ -642,12 +643,15 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob napi_typeof(env, jsProValue, &jsValueType); switch (jsValueType) { case napi_string: { - jsonObj[strProName] = JsObjectToString(env, jsProValue); + std::string natValue = JsObjectToString(env, jsProValue); + DMLOG(DM_LOG_INFO, "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); jsonObj[strProName] = elementValue; break; } @@ -657,11 +661,14 @@ void DeviceManagerNapi::JsToJsonObject(const napi_env &env, const napi_value &ob DMLOG(DM_LOG_ERROR, "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); } break; } - default: + default: { + DMLOG(DM_LOG_ERROR, "Property name=%s, value type not support.", strProName.c_str()); break; + } } } } @@ -1043,10 +1050,11 @@ napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen); NAPI_ASSERT(env, typeLen > 0, "typeLen == 0"); - std::unique_ptr type = std::make_unique(typeLen + 1); - napi_get_value_string_utf8(env, argv[0], type.get(), typeLen + 1, &typeLen); + 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); - std::string eventType = type.get(); + std::string eventType = type; DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); @@ -1081,10 +1089,11 @@ napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) napi_get_value_string_utf8(env, argv[0], nullptr, 0, &typeLen); NAPI_ASSERT(env, typeLen > 0, "typeLen == 0"); - std::unique_ptr type = std::make_unique(typeLen + 1); - napi_get_value_string_utf8(env, argv[0], type.get(), typeLen + 1, &typeLen); + 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); - std::string eventType = type.get(); + std::string eventType = type; DeviceManagerNapi *deviceManagerWrapper = nullptr; napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); @@ -1161,6 +1170,7 @@ void DeviceManagerNapi::HandleCreateDmCallBack(const napi_env &env, AsyncCallbac asCallbackInfo->status = -1; } if (asCallbackInfo->status == 0) { + DMLOG(DM_LOG_INFO, "InitDeviceManager for bunderName %s success", asCallbackInfo->bundleName); napi_get_undefined(env, &result[0]); napi_value callback = nullptr; napi_value callResult = nullptr; @@ -1168,13 +1178,13 @@ 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); napi_value message = nullptr; napi_create_object(env, &result[0]); napi_create_int32(env, asCallbackInfo->status, &message); napi_set_named_property(env, result[0], "code", message); napi_get_undefined(env, &result[1]); } - DMLOG(DM_LOG_INFO, "bunderName %s, status:%d", asCallbackInfo->bundleName, asCallbackInfo->status); napi_delete_async_work(env, asCallbackInfo->asyncWork); delete asCallbackInfo; }, (void *)asCallbackInfo, &asCallbackInfo->asyncWork); diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index a4aeac7b8..7aafb8dc1 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -28,6 +28,7 @@ if (defined(ohos_lite)) { "include/requestauth", "include/auth", "include/ipc", + "include/timer", "include/message", "include/ipc/lite", "${utils_path}/include/cipher", @@ -59,7 +60,7 @@ if (defined(ohos_lite)) { ] sources = [ - "src/ability/dm_ability_manager.cpp", + "src/ability/dm_ability_manager_lite.cpp", "src/auth/hichain_connector.cpp", "src/ipc/ipc_server_adapter.cpp", "src/ipc/ipc_server_listener_adapter.cpp", @@ -78,6 +79,7 @@ if (defined(ohos_lite)) { "src/requestauth/response_session.cpp", "src/softbus/softbus_adapter.cpp", "src/softbus/softbus_session.cpp", + "src/timer/dm_timer.cpp", ] defines = [ @@ -90,13 +92,11 @@ if (defined(ohos_lite)) { cflags_cc = build_flags deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", "${utils_path}:devicemanagerutils", "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", "//base/security/deviceauth/services:deviceauth_sdk", "//base/startup/syspara_lite/frameworks/parameter/src:sysparam", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/communication/dsoftbus/sdk:softbus_client", "//foundation/communication/ipc_lite:liteipc_adapter", "//foundation/distributedschedule/samgr_lite/samgr:samgr", @@ -117,6 +117,7 @@ if (defined(ohos_lite)) { "include/auth", "include/ipc", "include/message", + "include/timer", "include/ipc/standard", "${utils_path}/include/cipher", "${utils_path}/include/log", @@ -151,9 +152,11 @@ if (defined(ohos_lite)) { "src/requestauth/response_session.cpp", "src/softbus/softbus_adapter.cpp", "src/softbus/softbus_session.cpp", + "src/timer/dm_timer.cpp", ] deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", "${utils_path}:devicemanagerutils", "//base/security/deviceauth/services:deviceauth_sdk", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", diff --git a/services/devicemanagerservice/include/auth/hichain_connector.h b/services/devicemanagerservice/include/auth/hichain_connector.h index 61534df59..b1cec9bd5 100644 --- a/services/devicemanagerservice/include/auth/hichain_connector.h +++ b/services/devicemanagerservice/include/auth/hichain_connector.h @@ -48,9 +48,10 @@ struct GroupInfo { void from_json(const nlohmann::json& jsonObject, GroupInfo& groupInfo); -class GroupCreateCallback { +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 { @@ -68,24 +69,23 @@ public: int32_t Init(); bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); int64_t GenRequestId(); - void RegisterConnectorCallback(std::shared_ptr callback); + void RegisterConnectorCallback(std::shared_ptr callback); int32_t CreateGroup(int64_t requestId, const std::string &groupName); int32_t AddMemeber(std::string deviceId, std::shared_ptr msgResponseAuth); - void NotifyHostOnCheckAuthResult(int errorCode); 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); private: std::string GetConnectPara(std::string deviceId, std::shared_ptr msgResponseAuth); bool IsGroupInfoInvalid(GroupInfo &group); private: std::atomic requestIdIndex_ {0}; - std::shared_ptr groupCreateCallback_ = nullptr; + std::shared_ptr hichainConnectorCallback_ = nullptr; const DeviceGroupManager *deviceGroupManager_ = nullptr; DeviceAuthCallback deviceAuthCallback_ = { .onTransmit = nullptr, diff --git a/services/devicemanagerservice/include/ipc/ipc_server_adapter.h b/services/devicemanagerservice/include/ipc/ipc_server_adapter.h index b371e03a4..deec8bfee 100644 --- a/services/devicemanagerservice/include/ipc/ipc_server_adapter.h +++ b/services/devicemanagerservice/include/ipc/ipc_server_adapter.h @@ -26,9 +26,6 @@ #include "single_instance.h" #include "softbus_adapter.h" -#include "ability_manager_interface.h" -#include "want.h" -#include "ipc_server_adapter.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h b/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h index e4b3e357d..b812eca27 100644 --- a/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h +++ b/services/devicemanagerservice/include/ipc/ipc_server_listener_adapter.h @@ -33,7 +33,7 @@ public: 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 &pkgName, std::string &deviceId, int32_t resultCode, int32_t flag); + void OnCheckAuthResult(std::string &deviceId, int32_t resultCode, int32_t flag); void OnFaCall(std::string &pkgName, std::string ¶mJson); private: IpcServerListener ipcServerListener_; diff --git a/services/devicemanagerservice/include/requestauth/auth_manager.h b/services/devicemanagerservice/include/requestauth/auth_manager.h index 8778a44bc..0fb99a70f 100644 --- a/services/devicemanagerservice/include/requestauth/auth_manager.h +++ b/services/devicemanagerservice/include/requestauth/auth_manager.h @@ -40,6 +40,8 @@ public: 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); @@ -53,6 +55,7 @@ private: private: std::string authParam_ = ""; + int32_t displayOwner_ = 0; std::shared_ptr mPendingReqSessionPtr_ {nullptr}; std::shared_ptr mPendingRespSessionPtr {}; std::map> mWaitScanReqSessionMap_ = {}; diff --git a/services/devicemanagerservice/include/requestauth/request_session.h b/services/devicemanagerservice/include/requestauth/request_session.h index 4daec9e38..22bbbf451 100644 --- a/services/devicemanagerservice/include/requestauth/request_session.h +++ b/services/devicemanagerservice/include/requestauth/request_session.h @@ -44,6 +44,8 @@ public: 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(); diff --git a/services/devicemanagerservice/include/requestauth/response_session.h b/services/devicemanagerservice/include/requestauth/response_session.h index 87462daba..b8aa38eb5 100644 --- a/services/devicemanagerservice/include/requestauth/response_session.h +++ b/services/devicemanagerservice/include/requestauth/response_session.h @@ -25,6 +25,7 @@ #include "msg_response_auth.h" #include "msg_request_auth.h" #include "hichain_connector.h" +#include "dm_timer.h" namespace OHOS { namespace DistributedHardware { @@ -35,27 +36,28 @@ enum ResponseSessionStatus : int32_t { SESSION_WAITTING_PIN_CODE = 3 }; -class ResponseSession : public GroupCreateCallback, public std::enable_shared_from_this { +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(); private: - void Release(); int32_t DecodeReqMsg(std::string &message); int32_t StartFaService(); std::string GenerateGroupName(); void OnUserConfirm(); void OnUserReject(int32_t errorCode); - void CancelDisplay(); int32_t GeneratePincode(); private: @@ -68,6 +70,8 @@ private: int64_t mChannelId_; int32_t mPincode_; int32_t mSessionStatus_; + std::shared_ptr mReceiveTimerPtr_; + std::shared_ptr mMemberJoinTimerPtr_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/timer/dm_timer.h b/services/devicemanagerservice/include/timer/dm_timer.h new file mode 100644 index 000000000..10d312c2f --- /dev/null +++ b/services/devicemanagerservice/include/timer/dm_timer.h @@ -0,0 +1,70 @@ +/* + ** Copyright (c) 2021 Huawei Device Co., Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** + ** http://www.apache.org/licenses/LICENSE-2.0 + ** + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT WARRANTIES 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(); + DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data); + void Stop(int32_t code); + void WiteforTimeout(); + void Release(); + +private: + int32_t CreateTimeFd(); + +private: + DmTimerStatus mStatus; + uint32_t mTimeOutS; + TimeoutHandle mHandle; + void* mHandleData; + int32_t mTimeFd[2]; + struct epoll_event mEv; + struct epoll_event mEvents[MAXEVENTS]; + int32_t mEpFd; + std::thread mThread; +}; +} +} +#endif + diff --git a/services/devicemanagerservice/src/ability/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/dm_ability_manager.cpp index b9d310e3a..645b47051 100644 --- a/services/devicemanagerservice/src/ability/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/dm_ability_manager.cpp @@ -15,7 +15,7 @@ #include "dm_ability_manager.h" - +#include "auth_manager.h" #include "ability_manager_client.h" #include "ability_record.h" #include "ability_manager_service.h" @@ -57,22 +57,25 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) 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"); + DMLOG(DM_LOG_INFO,"Start Ability succeed"); } else { - DMLOG(DM_LOG_INFO, "Start Ability faild"); + DMLOG(DM_LOG_INFO,"Start Ability faild"); mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; return mStatus_; } - waitForTimeout(ABILITY_START_TIMEOUT); return mStatus_; } diff --git a/services/devicemanagerservice/src/ability/dm_ability_manager_lite.cpp b/services/devicemanagerservice/src/ability/dm_ability_manager_lite.cpp new file mode 100644 index 000000000..f4d9e40a1 --- /dev/null +++ b/services/devicemanagerservice/src/ability/dm_ability_manager_lite.cpp @@ -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. + */ + +#include "dm_ability_manager.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) +{ + // 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/auth/hichain_connector.cpp b/services/devicemanagerservice/src/auth/hichain_connector.cpp index afb7695ac..a023019fa 100644 --- a/services/devicemanagerservice/src/auth/hichain_connector.cpp +++ b/services/devicemanagerservice/src/auth/hichain_connector.cpp @@ -33,6 +33,8 @@ #include "ipc_check_authenticate_req.h" #include "softbus_session.h" #include "auth_manager.h" +#include "ipc_server_stub.h" +#include "dm_ability_manager.h" namespace OHOS { namespace DistributedHardware { @@ -125,34 +127,51 @@ int32_t HichainConnector::CreateGroup(int64_t requestId, const std::string &grou return SUCCESS; } -void HichainConnector::RegisterConnectorCallback(std::shared_ptr callback) +void HichainConnector::RegisterConnectorCallback(std::shared_ptr callback) { - groupCreateCallback_ = callback; + hichainConnectorCallback_ = callback; } void HichainConnector::OnGroupCreated(int64_t requestId, const std::string &returnData) { - if (groupCreateCallback_ == nullptr) { - DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated groupCreateCallback_ not registe."); + 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."); - groupCreateCallback_->OnGroupCreated(requestId, ""); + hichainConnectorCallback_->OnGroupCreated(requestId, ""); return; } if (jsonObject.find(FIELD_GROUP_ID) == jsonObject.end()) { DMLOG(DM_LOG_ERROR, "HichainConnector::OnGroupCreated failed to get groupId."); - groupCreateCallback_->OnGroupCreated(requestId, ""); + 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()); - groupCreateCallback_->OnGroupCreated(requestId, groupId); + 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) @@ -335,7 +354,7 @@ 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().NotifyHostOnCheckAuthResult(SUCCESS); + HichainConnector::GetInstance().OnMemberJoin(requestId, SUCCESS); } if (operationCode == GroupOperationCode::GROUP_CREATE) { @@ -362,12 +381,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().NotifyHostOnCheckAuthResult(FAIL); + HichainConnector::GetInstance().OnMemberJoin(requestId, FAIL); } if (operationCode == GroupOperationCode::GROUP_CREATE) { DMLOG(DM_LOG_ERROR, "Create group failed"); - HichainConnector::GetInstance().NotifyHostOnCheckAuthResult(FAIL); + HichainConnector::GetInstance().OnGroupCreated(requestId, "{}"); } if (operationCode == GroupOperationCode::MEMBER_DELETE) { @@ -402,16 +421,5 @@ char *HichainAuthenCallBack::onRequest(int64_t requestId, int32_t operationCode, char *buffer = strdup(jsonStr.c_str()); return buffer; } - -void HichainConnector::NotifyHostOnCheckAuthResult(int errorCode) -{ - DMLOG(DM_LOG_INFO, "notify host result, errorcode: %d", errorCode); - std::string hostPkgName = "com.ohos.devicemanagerui"; - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - - std::string authParam = AuthManager::GetInstance().GetAuthPara(); - IpcServerListenerAdapter::GetInstance().OnCheckAuthResult(hostPkgName, authParam, errorCode, 0); -} } } diff --git a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp b/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp index fe29635d2..90c9c3683 100644 --- a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp +++ b/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp @@ -100,7 +100,7 @@ void IpcServerListenerAdapter::OnAuthResult(std::string &pkgName, std::string &d ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); } -void IpcServerListenerAdapter::OnCheckAuthResult(std::string &pkgName, std::string &authParam, int32_t resultCode, +void IpcServerListenerAdapter::OnCheckAuthResult(std::string &authParam, int32_t resultCode, int32_t flag) { DMLOG(DM_LOG_INFO, "OnCheckResult, authParam: %s, errorCode: %d", @@ -108,11 +108,10 @@ void IpcServerListenerAdapter::OnCheckAuthResult(std::string &pkgName, std::stri std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); pReq->SetDeviceId(authParam); pReq->SetResult(resultCode); pReq->SetFlag(flag); - ipcServerListener_.SendRequest(SERVER_CHECK_AUTH_RESULT, pReq, pRsp); + ipcServerListener_.SendAll(SERVER_CHECK_AUTH_RESULT, pReq, pRsp); } void IpcServerListenerAdapter::OnFaCall(std::string &pkgName, std::string ¶mJson) diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index b4e185050..96c666775 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include "constants.h" #include "ipc_cmd_register.h" #include "device_manager_errno.h" @@ -24,6 +25,7 @@ #include "ipc_notify_device_found_req.h" #include "ipc_notify_device_state_req.h" #include "ipc_notify_discover_result_req.h" +#include "ipc_notify_dmfa_result_req.h" #include "ipc_server_adapter.h" #include "ipc_server_stub.h" @@ -211,5 +213,71 @@ ON_IPC_SERVER_CMD(CHECK_AUTHENTICATION, IpcIo &req, IpcIo &reply) int32_t ret = IpcServerAdapter::GetInstance().CheckAuthentication(authPara); IpcIoPushInt32(&reply, ret); } + +ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) +{ + size_t len = 0; + std::string packName = (const char *)IpcIoPopString(&req, &len); + DmAuthParam authParam = {0}; + DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); + IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); + if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { + IpcIoPushInt32(&reply, authParam.direction); + IpcIoPushInt32(&reply, authParam.authType); + IpcIoPushInt32(&reply, authParam.pinToken); + IpcIoPushInt32(&reply, authParam.displayOwner); + DMLOG(DM_LOG_DEBUG,"DeviceManagerStub::is Client so just return direction"); + return; + } + + int32_t appIconLen = authParam.imageinfo.GetAppIconLen(); + int32_t appThumbnailLen = authParam.imageinfo.GetAppThumbnailLen(); + + IpcIoPushInt32(&reply, authParam.direction); + IpcIoPushInt32(&reply, authParam.authType); + IpcIoPushString(&reply, authParam.packageName.c_str()); + IpcIoPushString(&reply, authParam.appName.c_str()); + IpcIoPushString(&reply, authParam.appDescription.c_str()); + IpcIoPushInt32(&reply, authParam.business); + IpcIoPushInt32(&reply, authParam.pincode); + IpcIoPushInt32(&reply, appIconLen); + IpcIoPushInt32(&reply, appThumbnailLen); + + if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { + IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppIcon(),appIconLen); + } + + if ( appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { + IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppThumbnail(), appThumbnailLen); + } + +} + +ON_IPC_SERVER_CMD(SERVER_USER_AUTHORIZATION_OPERATION, IpcIo &req, IpcIo &reply) +{ + size_t len = 0; + std::string packName = (const char *)IpcIoPopString(&req, &len); + int32_t action = IpcIoPopInt32(&reply); + IpcServerAdapter::GetInstance().SetUserOperation(packName, action); + + IpcIoPushInt32(&reply, action); +} + +ON_IPC_SET_REQUEST(SERVER_DEVICEMANAGER_FA_NOTIFY, std::shared_ptr pBaseReq, IpcIo& request, + uint8_t *buffer, size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string packagname = pReq->GetPkgName(); + std::string paramJson = pReq->GetJsonParam(); + IpcIoPushString(&request, packagname.c_str()); + IpcIoPushString(&request, paramJson.c_str()); + return DEVICEMANAGER_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo& reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(IpcIoPopInt32(&reply)); + return DEVICEMANAGER_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index f19028cf6..9039fd858 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -285,14 +285,13 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re std::string packName = data.ReadString(); DmAuthParam authParam; int32_t ret = DEVICEMANAGER_OK; - DMLOG(DM_LOG_ERROR, "GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); + DMLOG(DM_LOG_ERROR, "DeviceManagerStub:: GET_AUTHENTCATION_INFO:pkgName:%s", packName.c_str()); IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { - if (!reply.WriteInt32(authParam.direction) || - !reply.WriteInt32(authParam.authType) || - !reply.WriteInt32(authParam.pinToken)) { - DMLOG(DM_LOG_ERROR, "wirte client fail"); - ret = DEVICEMANAGER_WRITE_FAILED; + if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || + !reply.WriteInt32(authParam.pinToken) || !reply.WriteInt32(authParam.displayOwner)) { + DMLOG(DM_LOG_ERROR,"DeviceManagerStub::wirte client fail"); + ret = DEVICEMANAGER_WRITE_FAILED; } return ret; } @@ -321,6 +320,7 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re return DEVICEMANAGER_WRITE_FAILED; } } + return DEVICEMANAGER_OK; } @@ -328,7 +328,7 @@ ON_IPC_CMD(SERVER_USER_AUTHORIZATION_OPERATION, MessageParcel &data, MessageParc { std::string packageName = data.ReadString(); int32_t action = data.ReadInt32(); - int32_t result = IpcServerAdapter::GetInstance().SetUserOperation(packageName, action); + int result = IpcServerAdapter::GetInstance().SetUserOperation(packageName, action); if (!reply.WriteInt32(action)) { DMLOG(DM_LOG_ERROR, "write result failed"); @@ -336,6 +336,7 @@ 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) { DMLOG(DM_LOG_INFO, "OnFaCallBack"); diff --git a/services/devicemanagerservice/src/message/msg_response_auth.cpp b/services/devicemanagerservice/src/message/msg_response_auth.cpp index 59e096430..b1b18492b 100644 --- a/services/devicemanagerservice/src/message/msg_response_auth.cpp +++ b/services/devicemanagerservice/src/message/msg_response_auth.cpp @@ -69,7 +69,7 @@ void MsgResponseAuth::Encode(nlohmann::json &jsonObj) 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", mGroupId_.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_); } @@ -103,8 +103,8 @@ int32_t MsgResponseAuth::Decode(nlohmann::json &jsonObj) mRequestId_ = jsonObj[TAG_REQUEST_ID]; } DMLOG(DM_LOG_INFO, "decode mReply_ is : %d", mReply_); - DMLOG(DM_LOG_INFO, "decode mGroupId_ is %s", mGroupId_.c_str()); - DMLOG(DM_LOG_INFO, "decode mGroupName_ is %s", mGroupName_.c_str()); + 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_); diff --git a/services/devicemanagerservice/src/requestauth/auth_manager.cpp b/services/devicemanagerservice/src/requestauth/auth_manager.cpp index dda878297..2a01cd060 100644 --- a/services/devicemanagerservice/src/requestauth/auth_manager.cpp +++ b/services/devicemanagerservice/src/requestauth/auth_manager.cpp @@ -23,6 +23,7 @@ #include "device_manager_errno.h" #include "softbus_session.h" #include "encrypt_utils.h" +#include "ipc_server_listener_adapter.h" namespace OHOS { namespace DistributedHardware { @@ -64,6 +65,13 @@ void AuthManager::AuthAppGroup(std::string &hostPkgName, const DmDeviceInfo &dev return; } + 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); @@ -165,17 +173,34 @@ int32_t AuthManager::CheckAuthentication(std::string &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, pinCode is :%s", GetAnonyInt32(pinCode).c_str()); + 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, pinToken is :%s", GetAnonyInt32(pinToken).c_str()); + DMLOG(DM_LOG_ERROR, "pinToken err, please check pinToken."); return PIN_TOKEN_CHECK_FAILED; } OnPinInputResult(pinCode, pinToken); @@ -234,5 +259,10 @@ 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 index 937be386b..20fa069f8 100644 --- a/services/devicemanagerservice/src/requestauth/request_session.cpp +++ b/services/devicemanagerservice/src/requestauth/request_session.cpp @@ -113,10 +113,21 @@ void RequestSession::OnReceivePinCode(int32_t pinCode) 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"); @@ -237,19 +248,24 @@ void RequestSession::SyncDmPrivateGroup(std::vector &remoteGroupLis void RequestSession::NotifyHostAppAuthResult(int32_t errorCode) { - if (mSessionType_ == SESSION_TYPE_IS_APP_AUTH) { - std::string deviceId = mDevInfo_.deviceId; - if (StartFaService() != SUCCESS) { - DMLOG(DM_LOG_INFO, "RequestSession::StartFaService failed"); - return; - } - DMLOG(DM_LOG_INFO, "RequestSession::StartFaService success"); - int32_t status = (errorCode == 0) ? 0 : -1; - IpcServerListenerAdapter::GetInstance().OnAuthResult(mHostPkgName_, deviceId, mPinToken_, status, 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); - } else { - DMLOG(DM_LOG_ERROR, "wrong session type: %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 index d343c56db..519a0dcbb 100644 --- a/services/devicemanagerservice/src/requestauth/response_session.cpp +++ b/services/devicemanagerservice/src/requestauth/response_session.cpp @@ -37,21 +37,19 @@ namespace OHOS { namespace DistributedHardware { namespace { -// const int32_t RECEIVE_MESSAGE_TIMEOUT = 3; // 3 second -// const int32_t WAIT_NEXT_PACKAGE_TIMEOUT = 3; // 3 second -// const int32_t WAIT_ENTER_PINCODE_TIMEOUT = 3; // 3 second +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; } -#define PINCODE_LEN 6 - ResponseSession::ResponseSession() { mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; sem_init(&mSem_, 0, 0); - // need to update } -int64_t ResponseSession::GetRequestId(void) +int64_t ResponseSession::GetRequestId() { return mRequestId_; } @@ -128,28 +126,54 @@ bool ResponseSession::IsMyChannelId(long long channelId) return channelId == mChannelId_ && mChannelId_ > 0; } +void OnReceiveTimeOut(void *data) +{ + DMLOG(DM_LOG_ERROR, "Receive TimeOut"); + ResponseSession *respSess = (ResponseSession*)data; + respSess->Release(); +} + +void OnMemberJoinTimeOut(void *data) +{ + DMLOG(DM_LOG_ERROR, "Receive TimeOut"); + ResponseSession *respSess = (ResponseSession*)data; + 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_) { + mReceiveTimerPtr_ = std::make_shared(); + } + + 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) { - // 拉起界面失败,直接回复拒绝,清理session状态 OnUserReject(ERROR_FA_START_FAIL); return; } mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_USER_CONFIRM; + if (!mMemberJoinTimerPtr_) { + mMemberJoinTimerPtr_ = std::make_shared(); + } + + mMemberJoinTimerPtr_->Start(SESSION_WAIT_MEMBER_JOIN_TIMEOUT, OnMemberJoinTimeOut, this); } int32_t ResponseSession::GetPinCodeByReqId(int64_t requestId) @@ -228,6 +252,15 @@ void ResponseSession::OnGroupCreated(int64_t requestId, const std::string &group 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); + mMemberJoinTimerPtr_->Release(); + Release(); +} + std::string ResponseSession::GenerateGroupName() { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; @@ -273,14 +306,18 @@ void ResponseSession::Release() mChannelId_ = -1; mPincode_ = -1; mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; + mReceiveTimerPtr_ = nullptr; + mMemberJoinTimerPtr_ = nullptr; } void ResponseSession::CancelDisplay() { nlohmann::json jsonObj; - jsonObj[CANCEL_DISPLAY_KEY] = 1; - std::string jsonObjTmp = jsonObj.dump(); - IpcServerListenerAdapter::GetInstance().OnFaCall(mMsgRequestAuthPtr_->mTargetPkg_, jsonObjTmp); + 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, "CancelDisplay close pin code window %s", mMsgRequestAuthPtr_->mTargetPkg_.c_str()); } int32_t ResponseSession::GeneratePincode() diff --git a/services/devicemanagerservice/src/timer/dm_timer.cpp b/services/devicemanagerservice/src/timer/dm_timer.cpp new file mode 100644 index 000000000..c957f23db --- /dev/null +++ b/services/devicemanagerservice/src/timer/dm_timer.cpp @@ -0,0 +1,118 @@ +/* + ** Copyright (C) 2021 Huawei Device Co., Ltd. + ** Licensed under the Apache License, Version 2.0 (the "License"); + ** you may not use this file except in compliance with the License. + ** You may obtain a copy of the License at + ** + ** http://www.apache.org/licenses/LICENSE-2.0 + ** + ** Unless required by applicable law or agreed to in writing, software + ** distributed under the License is distributed on an "AS IS" BASIS, + ** WITHOUT 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 + +namespace OHOS { +namespace DistributedHardware { +DmTimer::DmTimer() { + mStatus = DmTimerStatus::DM_STATUS_INIT; +} + +DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) +{ + DMLOG(DM_LOG_ERROR, "DmTimer start timeout(%d)\n", timeOut); + if (mStatus != DmTimerStatus::DM_STATUS_INIT) { + return DmTimerStatus::DM_STATUS_BUSY; + } + + mTimeOutS = 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) { + char event; + event = 'S'; + if (mTimeFd[1]) { + if (write(mTimeFd[1], &event, 1) < 0) { + DMLOG(DM_LOG_ERROR, "DmTimer Stop timer failed %d \n", errno); + } + } + + return; +} + +void DmTimer::WiteforTimeout() { + DMLOG(DM_LOG_ERROR, "DmTimer start timer at (%d)s" ,mTimeOutS); + + int32_t nfds = epoll_wait(mEpFd, mEvents, MAXEVENTS, mTimeOutS * 1000); + if (nfds < 0) { + DMLOG(DM_LOG_ERROR, "epoll_wait returned n=%d, error: %d", 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 exit with event %d", event); + } else { + DMLOG(DM_LOG_ERROR, "DmTimer exit with errno %d", errno); + } + } + } + + mHandle(mHandleData); + Release(); + + DMLOG(DM_LOG_ERROR, "DmTimer end timer at (%d)s" ,mTimeOutS); + return; +} + +int32_t DmTimer::CreateTimeFd(){ + DMLOG(DM_LOG_ERROR, "DmTimer creatTimeFd" ); + int ret = 0; + + ret = pipe(mTimeFd); + if ( ret < 0) { + DMLOG(DM_LOG_ERROR, "DmTimer CreateTimeFd fail:(%d) errno(%d)" ,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() +{ + mStatus = DmTimerStatus::DM_STATUS_INIT; + close(mTimeFd[0]); + close(mTimeFd[1]); + close(mEpFd); + mTimeFd[0] = 0; + mTimeFd[1] = 0; + mEpFd = 0; +} +} +} -- Gitee From bd8b0c1562e093b8839f38560f114c9316376859 Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Sun, 12 Sep 2021 17:44:44 +0800 Subject: [PATCH 10/18] add fa Code and buf fix Signed-off-by: pengguanqi --- display/build.gradle | 17 ++++++++++++++++- display/entry/build.gradle | 17 ++++++++++++++++- display/entry/src/main/js/default/app.js | 15 +++++++++++++++ services/devicemanagerservice/BUILD.gn | 4 ++-- .../dm_ability_manager.cpp} | 0 .../{ => standard}/dm_ability_manager.cpp | 0 6 files changed, 49 insertions(+), 4 deletions(-) rename services/devicemanagerservice/src/ability/{dm_ability_manager_lite.cpp => lite/dm_ability_manager.cpp} (100%) rename services/devicemanagerservice/src/ability/{ => standard}/dm_ability_manager.cpp (100%) diff --git a/display/build.gradle b/display/build.gradle index 464cc3fc5..12771702e 100644 --- a/display/build.gradle +++ b/display/build.gradle @@ -1,4 +1,19 @@ -// Top-level build file where you can add configuration options common to all sub-projects/modules. +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 { diff --git a/display/entry/build.gradle b/display/entry/build.gradle index 3f35a96a6..498918b6f 100644 --- a/display/entry/build.gradle +++ b/display/entry/build.gradle @@ -1,4 +1,19 @@ -apply plugin: 'com.huawei.ohos.hap' +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 { diff --git a/display/entry/src/main/js/default/app.js b/display/entry/src/main/js/default/app.js index aedcefe00..8e47afff1 100644 --- a/display/entry/src/main/js/default/app.js +++ b/display/entry/src/main/js/default/app.js @@ -1,3 +1,18 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + export default { onCreate() { console.info('AceApplication onCreate'); diff --git a/services/devicemanagerservice/BUILD.gn b/services/devicemanagerservice/BUILD.gn index 7aafb8dc1..cdc51d983 100644 --- a/services/devicemanagerservice/BUILD.gn +++ b/services/devicemanagerservice/BUILD.gn @@ -60,7 +60,7 @@ if (defined(ohos_lite)) { ] sources = [ - "src/ability/dm_ability_manager_lite.cpp", + "src/ability/lite/dm_ability_manager.cpp", "src/auth/hichain_connector.cpp", "src/ipc/ipc_server_adapter.cpp", "src/ipc/ipc_server_listener_adapter.cpp", @@ -134,7 +134,7 @@ if (defined(ohos_lite)) { ] sources = [ - "src/ability/dm_ability_manager.cpp", + "src/ability/standard/dm_ability_manager.cpp", "src/auth/hichain_connector.cpp", "src/ipc/ipc_server_adapter.cpp", "src/ipc/ipc_server_listener_adapter.cpp", diff --git a/services/devicemanagerservice/src/ability/dm_ability_manager_lite.cpp b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp similarity index 100% rename from services/devicemanagerservice/src/ability/dm_ability_manager_lite.cpp rename to services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp diff --git a/services/devicemanagerservice/src/ability/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp similarity index 100% rename from services/devicemanagerservice/src/ability/dm_ability_manager.cpp rename to services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp -- Gitee From 9265cc603d128cf3859a5db36ea29b250e197e59 Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Sun, 12 Sep 2021 17:49:42 +0800 Subject: [PATCH 11/18] add fa Code and buf fix Signed-off-by: pengguanqi --- .../src/ability/lite/dm_ability_manager.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp index f4d9e40a1..3b5885159 100644 --- a/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/lite/dm_ability_manager.cpp @@ -22,9 +22,6 @@ namespace OHOS { namespace DistributedHardware { -namespace { -const int32_t ABILITY_START_TIMEOUT = 3; // 3 second -} IMPLEMENT_SINGLE_INSTANCE(DmAbilityManager); AbilityRole DmAbilityManager::GetAbilityRole() -- Gitee From ca6d06887a818850d968f45e508f16960969f18b Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Sun, 12 Sep 2021 18:38:33 +0800 Subject: [PATCH 12/18] add fa Code and buf fix Signed-off-by: pengguanqi --- .../src/main/js/default/pages/index/index.js | 2 +- .../include/device_manager_callback.h | 2 +- .../native_cpp/include/dm_device_info.h | 1 - .../src/ipc/lite/ipc_cmd_parser.cpp | 1 - .../src/ipc/standard/ipc_cmd_parser.cpp | 1 - .../include/timer/dm_timer.h | 26 ++++++------ .../ability/standard/dm_ability_manager.cpp | 4 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 1 - .../src/ipc/standard/ipc_cmd_parser.cpp | 4 +- .../src/requestauth/request_session.cpp | 14 +++---- .../src/requestauth/response_session.cpp | 6 +++ .../src/timer/dm_timer.cpp | 42 +++++++++++-------- 12 files changed, 56 insertions(+), 48 deletions(-) diff --git a/display/entry/src/main/js/default/pages/index/index.js b/display/entry/src/main/js/default/pages/index/index.js index b8c571462..0304a8d52 100644 --- a/display/entry/src/main/js/default/pages/index/index.js +++ b/display/entry/src/main/js/default/pages/index/index.js @@ -27,7 +27,7 @@ function uint8ArrayToBase64(array) { if (lastByte === 1) { const lastNum1 = array[i]; base64Str += table[lastNum1 >>> 2] + table[((lastNum1 & 0b11) << 4)] + '=='; - } else if (lastByte === 2){ + } 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] + '='; 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 a8ea7fb6a..786e8ca85 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 ~DeviceManagerFaCallback() {} virtual void OnCall(std::string ¶mJson) = 0; }; } // namespace DistributedHardware 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 7a37e336c..45ccf822c 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -58,7 +58,6 @@ typedef struct DmAuthParam { int32_t business; int32_t pincode; int32_t direction; - int32_t displayOwner; int32_t pinToken; DmAppImageInfo imageinfo; } DmAuthParam; 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 b6eddb76b..8112ba8af 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 @@ -307,7 +307,6 @@ ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, IpcIo& reply, std::shared_pt authParam.authType = IpcIoPopInt32(&reply); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { authParam.pinToken = IpcIoPopInt32(&reply); - authParam.displayOwner = IpcIoPopInt32(&reply); pRsp->SetAuthParam(authParam); return DEVICEMANAGER_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 f668a8c18..df3cd9f02 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 @@ -322,7 +322,6 @@ ON_IPC_READ_RESPONSE(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &reply, std::s authParam.authType = reply.ReadInt32(); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { authParam.pinToken = reply.ReadInt32(); - authParam.displayOwner = reply.ReadInt32(); pRsp->SetAuthParam(authParam); return DEVICEMANAGER_OK; } diff --git a/services/devicemanagerservice/include/timer/dm_timer.h b/services/devicemanagerservice/include/timer/dm_timer.h index 10d312c2f..bb660a9cd 100644 --- a/services/devicemanagerservice/include/timer/dm_timer.h +++ b/services/devicemanagerservice/include/timer/dm_timer.h @@ -1,17 +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. - **/ + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES 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 diff --git a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp index 645b47051..8cf00eccc 100644 --- a/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp +++ b/services/devicemanagerservice/src/ability/standard/dm_ability_manager.cpp @@ -70,9 +70,9 @@ AbilityStatus DmAbilityManager::StartAbility(AbilityRole role) AAFwk::AbilityManagerClient::GetInstance()->Connect(); ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); if (result == OHOS::ERR_OK) { - DMLOG(DM_LOG_INFO,"Start Ability succeed"); + DMLOG(DM_LOG_INFO, "Start Ability succeed"); } else { - DMLOG(DM_LOG_INFO,"Start Ability faild"); + DMLOG(DM_LOG_INFO, "Start Ability faild"); mStatus_ = AbilityStatus::ABILITY_STATUS_FAILED; return mStatus_; } diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 96c666775..9e85ebaac 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -225,7 +225,6 @@ ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, authParam.direction); IpcIoPushInt32(&reply, authParam.authType); IpcIoPushInt32(&reply, authParam.pinToken); - IpcIoPushInt32(&reply, authParam.displayOwner); DMLOG(DM_LOG_DEBUG,"DeviceManagerStub::is Client so just return direction"); return; } diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 9039fd858..ea3f6a432 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -289,7 +289,7 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re IpcServerAdapter::GetInstance().GetAuthenticationParam(packName, authParam); if (authParam.direction == AUTH_SESSION_SIDE_CLIENT) { if (!reply.WriteInt32(authParam.direction) || !reply.WriteInt32(authParam.authType) || - !reply.WriteInt32(authParam.pinToken) || !reply.WriteInt32(authParam.displayOwner)) { + !reply.WriteInt32(authParam.pinToken)) { DMLOG(DM_LOG_ERROR,"DeviceManagerStub::wirte client fail"); ret = DEVICEMANAGER_WRITE_FAILED; } @@ -308,7 +308,7 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re } if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { - if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)){ + if (!reply.WriteRawData(authParam.imageinfo.GetAppIcon(), appIconLen)) { DMLOG(DM_LOG_ERROR, "write appIcon failed"); return DEVICEMANAGER_WRITE_FAILED; } diff --git a/services/devicemanagerservice/src/requestauth/request_session.cpp b/services/devicemanagerservice/src/requestauth/request_session.cpp index 20fa069f8..bd8ab35d7 100644 --- a/services/devicemanagerservice/src/requestauth/request_session.cpp +++ b/services/devicemanagerservice/src/requestauth/request_session.cpp @@ -118,15 +118,15 @@ void RequestSession::OnUserOperate(int32_t action) } } - int64_t RequestSession::GetRequestId() - { - return mRequestId_; - } +int64_t RequestSession::GetRequestId() +{ + return mRequestId_; +} std::string RequestSession::GetRequestDeviceId() - { - return mRemoteDeviceId_; - } +{ + return mRemoteDeviceId_; +} int32_t RequestSession::StartFaService() { diff --git a/services/devicemanagerservice/src/requestauth/response_session.cpp b/services/devicemanagerservice/src/requestauth/response_session.cpp index 519a0dcbb..1bffdf58b 100644 --- a/services/devicemanagerservice/src/requestauth/response_session.cpp +++ b/services/devicemanagerservice/src/requestauth/response_session.cpp @@ -187,7 +187,13 @@ int32_t ResponseSession::GetPinCodeByReqId(int64_t requestId) 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_; diff --git a/services/devicemanagerservice/src/timer/dm_timer.cpp b/services/devicemanagerservice/src/timer/dm_timer.cpp index c957f23db..bd152d5c2 100644 --- a/services/devicemanagerservice/src/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/timer/dm_timer.cpp @@ -1,17 +1,18 @@ /* - ** Copyright (C) 2021 Huawei Device Co., Ltd. - ** Licensed under the Apache License, Version 2.0 (the "License"); - ** you may not use this file except in compliance with the License. - ** You may obtain a copy of the License at - ** - ** http://www.apache.org/licenses/LICENSE-2.0 - ** - ** Unless required by applicable law or agreed to in writing, software - ** distributed under the License is distributed on an "AS IS" BASIS, - ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - ** See the License for the specific language governing permissions and - ** limitations under the License. - **/ + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 @@ -44,7 +45,9 @@ DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) return mStatus; } -void DmTimer::Stop(int32_t code) { +void DmTimer::Stop(int32_t code) +{ + DMLOG(DM_LOG_ERROR, "DmTimer Stop code (%d)\n", code); char event; event = 'S'; if (mTimeFd[1]) { @@ -56,7 +59,8 @@ void DmTimer::Stop(int32_t code) { return; } -void DmTimer::WiteforTimeout() { +void DmTimer::WiteforTimeout() +{ DMLOG(DM_LOG_ERROR, "DmTimer start timer at (%d)s" ,mTimeOutS); int32_t nfds = epoll_wait(mEpFd, mEvents, MAXEVENTS, mTimeOutS * 1000); @@ -67,13 +71,14 @@ void DmTimer::WiteforTimeout() { char event = 0; if (nfds > 0) { if (mEvents[0].events & EPOLLIN) { - int num=read(mTimeFd[0], &event, 1); + int num= read(mTimeFd[0], &event, 1); if (num > 0) { DMLOG(DM_LOG_INFO, "DmTimer exit with event %d", event); } else { DMLOG(DM_LOG_ERROR, "DmTimer exit with errno %d", errno); } } + return; } mHandle(mHandleData); @@ -83,7 +88,8 @@ void DmTimer::WiteforTimeout() { return; } -int32_t DmTimer::CreateTimeFd(){ +int32_t DmTimer::CreateTimeFd() +{ DMLOG(DM_LOG_ERROR, "DmTimer creatTimeFd" ); int ret = 0; @@ -94,7 +100,7 @@ int32_t DmTimer::CreateTimeFd(){ } mEv.data.fd = mTimeFd[0]; - mEv.events = EPOLLIN|EPOLLET; + mEv.events = EPOLLIN | EPOLLET; mEpFd = epoll_create(MAXEVENTS); ret = epoll_ctl(mEpFd, EPOLL_CTL_ADD, mTimeFd[0], &mEv); if (ret != 0) { -- Gitee From 948ca7ceabc10d26cbbefb23b4667639f2dc7240 Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Sun, 12 Sep 2021 20:03:58 +0800 Subject: [PATCH 13/18] add fa Code and buf fix Signed-off-by: pengguanqi --- .../src/ipc/lite/ipc_cmd_parser.cpp | 3 +- .../include/requestauth/response_session.h | 1 + .../include/timer/dm_timer.h | 21 ++--- .../src/ipc/lite/ipc_cmd_parser.cpp | 5 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 2 +- .../src/requestauth/response_session.cpp | 32 ++++--- .../src/timer/dm_timer.cpp | 84 ++++++++++--------- 7 files changed, 84 insertions(+), 64 deletions(-) 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 8112ba8af..2178b0644 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 @@ -361,8 +361,9 @@ ON_IPC_CMD(SERVER_DEVICEMANAGER_FA_NOTIFY, IpcIo &reply, const IpcContext &ctx, 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); IpcIoPushInt32(&reply, DEVICEMANAGER_OK); + FreeBuffer(&ctx, ipcMsg); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/devicemanagerservice/include/requestauth/response_session.h b/services/devicemanagerservice/include/requestauth/response_session.h index b8aa38eb5..ee80835b2 100644 --- a/services/devicemanagerservice/include/requestauth/response_session.h +++ b/services/devicemanagerservice/include/requestauth/response_session.h @@ -51,6 +51,7 @@ public: bool IsMyChannelId(long long channelId); void Release(); void CancelDisplay(); + int32_t GetStatus(); private: int32_t DecodeReqMsg(std::string &message); diff --git a/services/devicemanagerservice/include/timer/dm_timer.h b/services/devicemanagerservice/include/timer/dm_timer.h index bb660a9cd..2be5e0001 100644 --- a/services/devicemanagerservice/include/timer/dm_timer.h +++ b/services/devicemanagerservice/include/timer/dm_timer.h @@ -48,21 +48,22 @@ public: DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data); void Stop(int32_t code); void WiteforTimeout(); - void Release(); private: int32_t CreateTimeFd(); + void Release(); private: - DmTimerStatus mStatus; - uint32_t mTimeOutS; - TimeoutHandle mHandle; - void* mHandleData; - int32_t mTimeFd[2]; - struct epoll_event mEv; - struct epoll_event mEvents[MAXEVENTS]; - int32_t mEpFd; - std::thread mThread; + 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_; }; } } diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 9e85ebaac..2b10a0e43 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -225,7 +225,7 @@ ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, authParam.direction); IpcIoPushInt32(&reply, authParam.authType); IpcIoPushInt32(&reply, authParam.pinToken); - DMLOG(DM_LOG_DEBUG,"DeviceManagerStub::is Client so just return direction"); + DMLOG(DM_LOG_DEBUG, "DeviceManagerStub::is Client so just return direction"); return; } @@ -246,10 +246,9 @@ ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppIcon(),appIconLen); } - if ( appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { + 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) diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index ea3f6a432..580c4100b 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -290,7 +290,7 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re 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"); + DMLOG(DM_LOG_ERROR, "DeviceManagerStub::wirte client fail"); ret = DEVICEMANAGER_WRITE_FAILED; } return ret; diff --git a/services/devicemanagerservice/src/requestauth/response_session.cpp b/services/devicemanagerservice/src/requestauth/response_session.cpp index 1bffdf58b..422e5ea8d 100644 --- a/services/devicemanagerservice/src/requestauth/response_session.cpp +++ b/services/devicemanagerservice/src/requestauth/response_session.cpp @@ -128,15 +128,25 @@ bool ResponseSession::IsMyChannelId(long long channelId) void OnReceiveTimeOut(void *data) { - DMLOG(DM_LOG_ERROR, "Receive TimeOut"); + 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, "Receive TimeOut"); + 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(); @@ -151,7 +161,7 @@ void ResponseSession::OnReceiveMsg(long long channelId, std::string &message) } if (!mReceiveTimerPtr_) { - mReceiveTimerPtr_ = std::make_shared(); + mReceiveTimerPtr_ = std::make_shared("mReceiveTimer"); } mReceiveTimerPtr_->Start(SESSION_MSG_RECEIVE_TIMEOUT, OnReceiveTimeOut, this); @@ -170,7 +180,7 @@ void ResponseSession::OnReceiveMsg(long long channelId, std::string &message) mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_USER_CONFIRM; if (!mMemberJoinTimerPtr_) { - mMemberJoinTimerPtr_ = std::make_shared(); + mMemberJoinTimerPtr_ = std::make_shared("mMemberJoinTimer"); } mMemberJoinTimerPtr_->Start(SESSION_WAIT_MEMBER_JOIN_TIMEOUT, OnMemberJoinTimeOut, this); @@ -236,7 +246,7 @@ void ResponseSession::OnGroupCreated(int64_t requestId, const std::string &group 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 %d, requestId %d, groupId %s", + 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(); @@ -263,7 +273,6 @@ void ResponseSession::OnMemberJoin(int64_t requestId, int32_t status) DMLOG(DM_LOG_INFO, "ResponseSession::OnMemberJoin, result: %d", status); CancelDisplay(); mMemberJoinTimerPtr_->Stop(SESSION_CANCEL_TIMEOUT); - mMemberJoinTimerPtr_->Release(); Release(); } @@ -304,6 +313,7 @@ void ResponseSession::OnUserReject(int32_t errorCode) void ResponseSession::Release() { DMLOG(DM_LOG_INFO, "ResponseSession::Release in"); + mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; mRequestId_ = -1; mGroupId_ = ""; mGroupName_ = ""; @@ -311,9 +321,6 @@ void ResponseSession::Release() mMsgRequestAuthPtr_ = nullptr; mChannelId_ = -1; mPincode_ = -1; - mSessionStatus_ = ResponseSessionStatus::SESSION_INIT; - mReceiveTimerPtr_ = nullptr; - mMemberJoinTimerPtr_ = nullptr; } void ResponseSession::CancelDisplay() @@ -323,7 +330,12 @@ void ResponseSession::CancelDisplay() std::string paramJson = jsonObj.dump(); std::string pkgName = "com.ohos.devicemanagerui"; IpcServerListenerAdapter::GetInstance().OnFaCall(pkgName, paramJson); - DMLOG(DM_LOG_INFO, "CancelDisplay close pin code window %s", mMsgRequestAuthPtr_->mTargetPkg_.c_str()); + DMLOG(DM_LOG_INFO, "CancelDisplay close pin code window"); +} + +int32_t ResponseSession::GetStatus() +{ + return mSessionStatus_; } int32_t ResponseSession::GeneratePincode() diff --git a/services/devicemanagerservice/src/timer/dm_timer.cpp b/services/devicemanagerservice/src/timer/dm_timer.cpp index bd152d5c2..427b51ec5 100644 --- a/services/devicemanagerservice/src/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/timer/dm_timer.cpp @@ -19,41 +19,45 @@ namespace OHOS { namespace DistributedHardware { -DmTimer::DmTimer() { - mStatus = DmTimerStatus::DM_STATUS_INIT; +DmTimer::DmTimer(std::string &name) +{ + mStatus_ = DmTimerStatus::DM_STATUS_INIT; + mTimerName_ = name; } DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) { - DMLOG(DM_LOG_ERROR, "DmTimer start timeout(%d)\n", timeOut); - if (mStatus != DmTimerStatus::DM_STATUS_INIT) { + DMLOG(DM_LOG_INFO, "DmTimer %s start timeout(%d)", mTimerName_.c_str(), timeOut); + if (mStatus_ != DmTimerStatus::DM_STATUS_INIT) { return DmTimerStatus::DM_STATUS_BUSY; } - mTimeOutS = timeOut; - mHandle = handle; - mHandleData = data; + 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(); + mStatus_ = DmTimerStatus::DM_STATUS_RUNNING; + mThread_ = std::thread(&DmTimer::WiteforTimeout, this); + mThread_.detach(); - return mStatus; + return mStatus_; } void DmTimer::Stop(int32_t code) { - DMLOG(DM_LOG_ERROR, "DmTimer Stop code (%d)\n", code); + DMLOG(DM_LOG_INFO, "DmTimer %s Stop code (%d)", mTimerName_.c_str(), code); char event; event = 'S'; - if (mTimeFd[1]) { - if (write(mTimeFd[1], &event, 1) < 0) { - DMLOG(DM_LOG_ERROR, "DmTimer Stop timer failed %d \n", errno); + if (mTimeFd_[1]) { + 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; @@ -61,48 +65,49 @@ void DmTimer::Stop(int32_t code) void DmTimer::WiteforTimeout() { - DMLOG(DM_LOG_ERROR, "DmTimer start timer at (%d)s" ,mTimeOutS); + DMLOG(DM_LOG_INFO, "DmTimer %s start timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); - int32_t nfds = epoll_wait(mEpFd, mEvents, MAXEVENTS, mTimeOutS * 1000); + int32_t nfds = epoll_wait(mEpFd_, mEvents_, MAXEVENTS, mTimeOutSec_ * 1000); if (nfds < 0) { - DMLOG(DM_LOG_ERROR, "epoll_wait returned n=%d, error: %d", nfds, errno); + 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 (mEvents_[0].events & EPOLLIN) { + int num= read(mTimeFd_[0], &event, 1); if (num > 0) { - DMLOG(DM_LOG_INFO, "DmTimer exit with event %d", event); + DMLOG(DM_LOG_INFO, "DmTimer %s exit with event %d", mTimerName_.c_str(), event); } else { - DMLOG(DM_LOG_ERROR, "DmTimer exit with errno %d", errno); + DMLOG(DM_LOG_ERROR, "DmTimer %s exit with errno %d", mTimerName_.c_str(), errno); } } + Release(); return; } - mHandle(mHandleData); + mHandle_(mHandleData_); Release(); - DMLOG(DM_LOG_ERROR, "DmTimer end timer at (%d)s" ,mTimeOutS); + DMLOG(DM_LOG_ERROR, "DmTimer %s end timer at (%d)s", mTimerName_.c_str(), mTimeOutSec_); return; } int32_t DmTimer::CreateTimeFd() { - DMLOG(DM_LOG_ERROR, "DmTimer creatTimeFd" ); + DMLOG(DM_LOG_INFO, "DmTimer %s creatTimeFd", mTimerName_.c_str()); int ret = 0; - ret = pipe(mTimeFd); - if ( ret < 0) { - DMLOG(DM_LOG_ERROR, "DmTimer CreateTimeFd fail:(%d) errno(%d)" ,ret, errno); + 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); + 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(); } @@ -112,13 +117,14 @@ int32_t DmTimer::CreateTimeFd() void DmTimer::Release() { - mStatus = DmTimerStatus::DM_STATUS_INIT; - close(mTimeFd[0]); - close(mTimeFd[1]); - close(mEpFd); - mTimeFd[0] = 0; - mTimeFd[1] = 0; - mEpFd = 0; + DMLOG(DM_LOG_INFO, "DmTimer %s Release in", mTimerName_.c_str()); + mStatus_ = DmTimerStatus::DM_STATUS_INIT; + close(mTimeFd_[0]); + close(mTimeFd_[1]); + close(mEpFd_); + mTimeFd_[0] = 0; + mTimeFd_[1] = 0; + mEpFd_ = 0; } } } -- Gitee From bbe8b2365fd7ac03134b56c662f91531a4fa9cbe Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Sun, 12 Sep 2021 22:48:38 +0800 Subject: [PATCH 14/18] add fa Code and buf fix Signed-off-by: pengguanqi --- .../include/notify/device_manager_notify.h | 2 +- .../src/notify/device_manager_notify.cpp | 23 ++++--------------- .../include/timer/dm_timer.h | 5 ++-- .../src/ipc/ipc_server_listener_adapter.cpp | 2 +- .../src/ipc/lite/ipc_cmd_parser.cpp | 2 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 4 ++-- .../src/requestauth/response_session.cpp | 9 +++++--- .../src/timer/dm_timer.cpp | 15 +++++++++--- 8 files changed, 30 insertions(+), 32 deletions(-) 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 d49118a88..a22cae427 100644 --- a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h +++ b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -65,7 +65,7 @@ private: std::map> deviceStateCallback_; std::map>> deviceDiscoverCallbacks_; std::map>> authenticateCallback_; - std::map>> checkauthcallback_; + std::map> checkauthcallback_; std::map> dmInitCallback_; std::map> dmFaCallback_; }; 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 c65c31a46..94f03d156 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 @@ -106,19 +106,12 @@ void DeviceManagerNotify::RegisterCheckAuthenticationCallback(std::string &pkgNa std::shared_ptr callback) { std::lock_guard autoLock(lock_); - if (checkauthcallback_.count(pkgName) == 0) { - checkauthcallback_[pkgName] = std::map>(); - } - checkauthcallback_[pkgName][authPara] = callback; + checkauthcallback_[pkgName] = callback; } void DeviceManagerNotify::UnRegisterCheckAuthenticationCallback(std::string &pkgName) { std::lock_guard autoLock(lock_); - deviceStateCallback_.erase(pkgName); - deviceDiscoverCallbacks_.erase(pkgName); - authenticateCallback_.erase(pkgName); - dmInitCallback_.erase(pkgName); checkauthcallback_.erase(pkgName); } @@ -268,17 +261,9 @@ void DeviceManagerNotify::OnCheckAuthResult(std::string &pkgName, std::string &d DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register authCallback for this package"); return; } - std::map> &CheckAuthCallmap = checkauthcallback_[pkgName]; - auto iter = CheckAuthCallmap.find(deviceId); - if (iter == CheckAuthCallmap.end()) { - DMLOG(DM_LOG_ERROR, "DeviceManager OnCheckAuthResult: no register CheckAuthCallmap for deviceID"); - return; - } - iter->second->OnCheckAuthResult(deviceId, resultCode, flag); - checkauthcallback_[pkgName].erase(deviceId); - if (checkauthcallback_[pkgName].empty()) { - checkauthcallback_.erase(pkgName); - } + + checkauthcallback_[pkgName]->OnCheckAuthResult(deviceId, resultCode, flag); + checkauthcallback_.erase(pkgName); } void DeviceManagerNotify::OnFaCall(std::string &pkgName, std::string ¶mJson) diff --git a/services/devicemanagerservice/include/timer/dm_timer.h b/services/devicemanagerservice/include/timer/dm_timer.h index 2be5e0001..f0deba4a7 100644 --- a/services/devicemanagerservice/include/timer/dm_timer.h +++ b/services/devicemanagerservice/include/timer/dm_timer.h @@ -44,7 +44,8 @@ enum DmTimerStatus : int32_t { class DmTimer { public: - DmTimer(); + DmTimer(std::string &name); + ~DmTimer(); DmTimerStatus Start(uint32_t timeOut, TimeoutHandle handle, void *data); void Stop(int32_t code); void WiteforTimeout(); @@ -57,7 +58,7 @@ private: DmTimerStatus mStatus_; uint32_t mTimeOutSec_; TimeoutHandle mHandle_; - void* mHandleData_; + void *mHandleData_; int32_t mTimeFd_[2]; struct epoll_event mEv_; struct epoll_event mEvents_[MAXEVENTS]; diff --git a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp b/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp index 90c9c3683..2fd07e261 100644 --- a/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp +++ b/services/devicemanagerservice/src/ipc/ipc_server_listener_adapter.cpp @@ -116,7 +116,7 @@ void IpcServerListenerAdapter::OnCheckAuthResult(std::string &authParam, int32_t void IpcServerListenerAdapter::OnFaCall(std::string &pkgName, std::string ¶mJson) { - DMLOG(DM_LOG_INFO, "OnFaCallSuccess"); + DMLOG(DM_LOG_INFO, "OnFaCall in"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); diff --git a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp index 2b10a0e43..45dc5a862 100644 --- a/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/lite/ipc_cmd_parser.cpp @@ -243,7 +243,7 @@ ON_IPC_SERVER_CMD(SERVER_GET_AUTHENTCATION_INFO, IpcIo &req, IpcIo &reply) IpcIoPushInt32(&reply, appThumbnailLen); if (appIconLen > 0 && authParam.imageinfo.GetAppIcon() != nullptr) { - IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppIcon(),appIconLen); + IpcIoPushFlatObj(&reply, authParam.imageinfo.GetAppIcon(), appIconLen); } if (appThumbnailLen > 0 && authParam.imageinfo.GetAppThumbnail() != nullptr) { diff --git a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp index 580c4100b..9df2dadcd 100644 --- a/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/devicemanagerservice/src/ipc/standard/ipc_cmd_parser.cpp @@ -290,8 +290,8 @@ ON_IPC_CMD(SERVER_GET_AUTHENTCATION_INFO, MessageParcel &data, MessageParcel &re 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; + DMLOG(DM_LOG_ERROR, "DeviceManagerStub::wirte client fail"); + ret = DEVICEMANAGER_WRITE_FAILED; } return ret; } diff --git a/services/devicemanagerservice/src/requestauth/response_session.cpp b/services/devicemanagerservice/src/requestauth/response_session.cpp index 422e5ea8d..83e32e311 100644 --- a/services/devicemanagerservice/src/requestauth/response_session.cpp +++ b/services/devicemanagerservice/src/requestauth/response_session.cpp @@ -161,7 +161,8 @@ void ResponseSession::OnReceiveMsg(long long channelId, std::string &message) } if (!mReceiveTimerPtr_) { - mReceiveTimerPtr_ = std::make_shared("mReceiveTimer"); + std::string mReceiveTimerName = "mReceiveTimer"; + mReceiveTimerPtr_ = std::make_shared(mReceiveTimerName); } mReceiveTimerPtr_->Start(SESSION_MSG_RECEIVE_TIMEOUT, OnReceiveTimeOut, this); @@ -180,7 +181,8 @@ void ResponseSession::OnReceiveMsg(long long channelId, std::string &message) mSessionStatus_ = ResponseSessionStatus::SESSION_WAITTING_USER_CONFIRM; if (!mMemberJoinTimerPtr_) { - mMemberJoinTimerPtr_ = std::make_shared("mMemberJoinTimer"); + std::string mMemberJoinTimerName = "mMemberJoinTimer"; + mMemberJoinTimerPtr_ = std::make_shared(mMemberJoinTimerName); } mMemberJoinTimerPtr_->Start(SESSION_WAIT_MEMBER_JOIN_TIMEOUT, OnMemberJoinTimeOut, this); @@ -325,12 +327,13 @@ void ResponseSession::Release() 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, "CancelDisplay close pin code window"); + DMLOG(DM_LOG_INFO, "Cancel PinCode Display success"); } int32_t ResponseSession::GetStatus() diff --git a/services/devicemanagerservice/src/timer/dm_timer.cpp b/services/devicemanagerservice/src/timer/dm_timer.cpp index 427b51ec5..d35747df6 100644 --- a/services/devicemanagerservice/src/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/timer/dm_timer.cpp @@ -25,6 +25,12 @@ DmTimer::DmTimer(std::string &name) 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); @@ -50,9 +56,8 @@ DmTimerStatus DmTimer::Start(uint32_t timeOut, TimeoutHandle handle, void *data) void DmTimer::Stop(int32_t code) { DMLOG(DM_LOG_INFO, "DmTimer %s Stop code (%d)", mTimerName_.c_str(), code); - char event; - event = 'S'; 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; @@ -75,7 +80,7 @@ void DmTimer::WiteforTimeout() char event = 0; if (nfds > 0) { if (mEvents_[0].events & EPOLLIN) { - int num= read(mTimeFd_[0], &event, 1); + 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 { @@ -118,6 +123,10 @@ int32_t DmTimer::CreateTimeFd() 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]); -- Gitee From c510df73bc25fbaa7dfa4f811b64a928932db1d5 Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Sun, 12 Sep 2021 23:41:35 +0800 Subject: [PATCH 15/18] add fa Code and buf fix Signed-off-by: pengguanqi --- OAT.xml | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 OAT.xml diff --git a/OAT.xml b/OAT.xml new file mode 100644 index 000000000..bf986c17e --- /dev/null +++ b/OAT.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + -- Gitee From 589e3304d9f565b2af552f28864f11654e0c04cd Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Mon, 13 Sep 2021 09:36:10 +0800 Subject: [PATCH 16/18] add fa Code and buf fix Signed-off-by: pengguanqi --- OAT.xml | 65 --------------------------------------------------------- 1 file changed, 65 deletions(-) delete mode 100644 OAT.xml diff --git a/OAT.xml b/OAT.xml deleted file mode 100644 index bf986c17e..000000000 --- a/OAT.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - -- Gitee From 73ef4c719ba7c6281926933aefd6d2434c176246 Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Mon, 13 Sep 2021 10:15:43 +0800 Subject: [PATCH 17/18] add fa Code and buf fix Signed-off-by: pengguanqi --- .../src/requestauth/response_session.cpp | 3 ++- services/devicemanagerservice/src/timer/dm_timer.cpp | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/services/devicemanagerservice/src/requestauth/response_session.cpp b/services/devicemanagerservice/src/requestauth/response_session.cpp index 83e32e311..ff71485c3 100644 --- a/services/devicemanagerservice/src/requestauth/response_session.cpp +++ b/services/devicemanagerservice/src/requestauth/response_session.cpp @@ -41,6 +41,7 @@ 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() @@ -284,7 +285,7 @@ std::string ResponseSession::GenerateGroupName() GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string sLocalDeviceID = localDeviceId; std::string groupName = mMsgRequestAuthPtr_->mTargetPkg_ + mMsgRequestAuthPtr_->mHostPkg_ + - sLocalDeviceID.substr(0, sLocalDeviceID.size() / 2); + sLocalDeviceID.substr(0, sLocalDeviceID.size() / DEVICE_ID_HALF); return groupName; } diff --git a/services/devicemanagerservice/src/timer/dm_timer.cpp b/services/devicemanagerservice/src/timer/dm_timer.cpp index d35747df6..8dcd7a703 100644 --- a/services/devicemanagerservice/src/timer/dm_timer.cpp +++ b/services/devicemanagerservice/src/timer/dm_timer.cpp @@ -19,6 +19,9 @@ namespace OHOS { namespace DistributedHardware { +namespace { +const int32_t MILL_SECONDS_PER_SECOND = 1000; +} DmTimer::DmTimer(std::string &name) { mStatus_ = DmTimerStatus::DM_STATUS_INIT; @@ -72,7 +75,7 @@ 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_ * 1000); + 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); } -- Gitee From f121255c574e03db21aa2520430a98ad2d4e6e45 Mon Sep 17 00:00:00 2001 From: pengguanqi Date: Mon, 13 Sep 2021 16:00:15 +0800 Subject: [PATCH 18/18] suport OSD capability from JS param Signed-off-by: pengguanqi --- interfaces/kits/js/src/native_devicemanager_js.cpp | 3 ++- ohos.build | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index b63be4163..a555fc582 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -49,6 +49,7 @@ const int32_t DM_AUTH_TYPE_PINCODE = 1; const int32_t DM_AUTH_DIRECTION_CLIENT = 1; const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0; +const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_OSD = 1; std::map g_deviceManagerMap; std::map> g_initCallbackMap; @@ -525,7 +526,7 @@ 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) { + 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; diff --git a/ohos.build b/ohos.build index a5ba6d594..eeead16d4 100644 --- a/ohos.build +++ b/ohos.build @@ -19,7 +19,7 @@ } ], "module_list": [ - "//foundation/distributedhardware/devicemanager/utils:devicemanagerutils", + "//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", -- Gitee