From b3e6ad34305b195ac2ffe9b7e48ac243233b5fc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 22 Jul 2024 22:46:43 +0800 Subject: [PATCH 001/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0softbusconnector=20fu?= =?UTF-8?q?zz=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/softbusfuzztest/BUILD.gn | 3 + .../softbusconnectorcommon_fuzzer/BUILD.gn | 67 +++++++++++++++++++ .../softbusconnectorcommon_fuzzer/corpus/init | 13 ++++ .../softbusconnectorcommon_fuzzer/project.xml | 25 +++++++ .../softbus_connector_common_fuzzer.cpp | 58 ++++++++++++++++ .../softbus_connector_common_fuzzer.h | 21 ++++++ 6 files changed, 187 insertions(+) create mode 100644 test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn create mode 100644 test/softbusfuzztest/softbusconnectorcommon_fuzzer/corpus/init create mode 100644 test/softbusfuzztest/softbusconnectorcommon_fuzzer/project.xml create mode 100644 test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp create mode 100644 test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h diff --git a/test/softbusfuzztest/BUILD.gn b/test/softbusfuzztest/BUILD.gn index 3196b53dd..66b55a3aa 100644 --- a/test/softbusfuzztest/BUILD.gn +++ b/test/softbusfuzztest/BUILD.gn @@ -26,6 +26,9 @@ group("fuzztest") { "refreshsoftbuslnn_fuzzer:fuzztest", "softbusadapterobject_fuzzer:fuzztest", "softbusconnector_fuzzer:fuzztest", + "softbusconnectorcommon_fuzzer:fuzztest", + "softbusconnectorpublish_fuzzer:fuzztest", + "softbusconnectorregister_fuzzer:fuzztest", "softbusconnectorstatic_fuzzer:fuzztest", "softbuslistenergetlocaldeviceinfo_fuzzer:fuzztest", "softbussession_fuzzer:fuzztest", diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn new file mode 100644 index 000000000..812059e7b --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2022-2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("SoftbusConnectorCommonFuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/softbusfuzztest/softbusconnectorcommon_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${utils_path}/include/ipc/standard", + "${servicesimpl_path}/include", + "${servicesimpl_path}/include/dependency/commonevent", + "${servicesimpl_path}/include/dependency/softbus", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "softbus_connector_common_fuzzer.cpp" ] + + deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", + "${servicesimpl_path}:devicemanagerserviceimpl", + ] + + external_deps = [ "safwk:system_ability_fwk" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"SoftbusConnectorCommonFuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":SoftbusConnectorCommonFuzzTest" ] +} +############################################################################### diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/corpus/init b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/corpus/init new file mode 100644 index 000000000..1b910144f --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +FUZZ \ No newline at end of file diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/project.xml b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/project.xml new file mode 100644 index 000000000..27c26d11b --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp new file mode 100644 index 000000000..7d2988fd8 --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_connector.h" +#include "softbus_bus_center.h" +#include "dm_device_info.h" +#include "dm_publish_info.h" +#include "dm_subscribe_info.h" +#include "softbus_discovery_callback.h" +#include "softbus_publish_callback.h" +#include "softbus_session.h" +#include "softbus_connector_common_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { + +void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + + std::string str(reinterpret_cast(data), size); + int32_t authForm = *(reinterpret_cast(data)); + std::shared_ptr softbusConnector = std::make_shared(); + + softbusConnector->GetDeviceUdidHashByUdid(str); + softbusConnector->EraseUdidFromMap(str); + softbusConnector->GetNetworkIdByDeviceId(str); + softbusConnector->SetPkgName(str); + softbusConnector->HandleDeviceOnline(str, authForm); + softbusConnector->HandleDeviceOffline(str); + softbusConnector->CheckIsOnline(str); + softbusConnector->GetDeviceInfoByDeviceId(str); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::SoftBusConnectorCommonFuzzTest(data, size); + + return 0; +} diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h new file mode 100644 index 000000000..18f35c4ec --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFTBUS_CONNECTOR_COMMON_FUZZER_H +#define SOFTBUS_CONNECTOR_COMMON_FUZZER_H + +#define FUZZ_PROJECT_NAME "softbusconnectorcommon_fuzzer" + +#endif // SOFTBUS_CONNECTOR_COMMON_FUZZER_H \ No newline at end of file -- Gitee From 2dfab940bb62de39cb2dc3991336deca98dd497c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 22 Jul 2024 23:32:55 +0800 Subject: [PATCH 002/520] =?UTF-8?q?=E8=A1=A5=E5=85=85fuzz?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/softbusfuzztest/BUILD.gn | 1 + .../softbus_connector_common_fuzzer.cpp | 4 +- .../softbusconnectorstate_fuzzer/BUILD.gn | 67 +++++++++++++++++++ .../softbusconnectorstate_fuzzer/corpus/init | 13 ++++ .../softbusconnectorstate_fuzzer/project.xml | 25 +++++++ .../softbus_connector_state_fuzzer.cpp | 60 +++++++++++++++++ .../softbus_connector_state_fuzzer.h | 21 ++++++ 7 files changed, 188 insertions(+), 3 deletions(-) create mode 100644 test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn create mode 100644 test/softbusfuzztest/softbusconnectorstate_fuzzer/corpus/init create mode 100644 test/softbusfuzztest/softbusconnectorstate_fuzzer/project.xml create mode 100644 test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp create mode 100644 test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h diff --git a/test/softbusfuzztest/BUILD.gn b/test/softbusfuzztest/BUILD.gn index 66b55a3aa..1771786ef 100644 --- a/test/softbusfuzztest/BUILD.gn +++ b/test/softbusfuzztest/BUILD.gn @@ -29,6 +29,7 @@ group("fuzztest") { "softbusconnectorcommon_fuzzer:fuzztest", "softbusconnectorpublish_fuzzer:fuzztest", "softbusconnectorregister_fuzzer:fuzztest", + "softbusconnectorstate_fuzzer:fuzztest", "softbusconnectorstatic_fuzzer:fuzztest", "softbuslistenergetlocaldeviceinfo_fuzzer:fuzztest", "softbussession_fuzzer:fuzztest", diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp index 7d2988fd8..7bb0d2426 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp @@ -28,7 +28,7 @@ namespace DistributedHardware { void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size == 0)) { + if ((data == nullptr) || (size < sizeof(int32_t))) { return; } @@ -40,8 +40,6 @@ void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) softbusConnector->EraseUdidFromMap(str); softbusConnector->GetNetworkIdByDeviceId(str); softbusConnector->SetPkgName(str); - softbusConnector->HandleDeviceOnline(str, authForm); - softbusConnector->HandleDeviceOffline(str); softbusConnector->CheckIsOnline(str); softbusConnector->GetDeviceInfoByDeviceId(str); } diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn new file mode 100644 index 000000000..f6e4bf81a --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2022-2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("SoftbusConnectorStateFuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/softbusfuzztest/softbusconnectorstate_fuzzer" + + include_dirs = [ + "${utils_path}/include", + "${common_path}/include", + "${common_path}/include/ipc", + "${common_path}/include/ipc/model", + "${utils_path}/include/ipc/standard", + "${servicesimpl_path}/include", + "${servicesimpl_path}/include/dependency/commonevent", + "${servicesimpl_path}/include/dependency/softbus", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "softbus_connector_state_fuzzer.cpp" ] + + deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", + "${servicesimpl_path}:devicemanagerserviceimpl", + ] + + external_deps = [ "safwk:system_ability_fwk" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"SoftbusConnectorStateFuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":SoftbusConnectorStateFuzzTest" ] +} +############################################################################### diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/corpus/init b/test/softbusfuzztest/softbusconnectorstate_fuzzer/corpus/init new file mode 100644 index 000000000..1b910144f --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +FUZZ \ No newline at end of file diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/project.xml b/test/softbusfuzztest/softbusconnectorstate_fuzzer/project.xml new file mode 100644 index 000000000..27c26d11b --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp new file mode 100644 index 000000000..450ad6246 --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_connector.h" +#include "softbus_bus_center.h" +#include "dm_device_info.h" +#include "dm_publish_info.h" +#include "dm_subscribe_info.h" +#include "softbus_discovery_callback.h" +#include "softbus_publish_callback.h" +#include "softbus_session.h" +#include "softbus_state_callback.h" +#include "softbus_connector_state_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { +class SoftbusStateCallbackFuzzTest : public ISoftbusStateCallback{ +public: + void OnDeviceOnline(std::string deviceId, int32_t authForm) {} + void OnDeviceOffline(std::string deviceId) {} +}; + +void SoftBusConnectorStateFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::string str(reinterpret_cast(data), size); + int32_t authForm = *(reinterpret_cast(data)); + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr callback = std::make_shared(); + + softbusConnector->RegisterSoftbusStateCallback(callback); + softbusConnector->HandleDeviceOnline(str, authForm); + softbusConnector->HandleDeviceOffline(str); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::SoftBusConnectorStateFuzzTest(data, size); + + return 0; +} diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h new file mode 100644 index 000000000..2574d7aec --- /dev/null +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SOFTBUS_CONNECTOR_STATE_FUZZER_H +#define SOFTBUS_CONNECTOR_STATE_FUZZER_H + +#define FUZZ_PROJECT_NAME "softbusconnectorstate_fuzzer" + +#endif // SOFTBUS_CONNECTOR_STATE_FUZZER_H \ No newline at end of file -- Gitee From 95a64ecff72d9b67500a055a4587405fdf82843a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 23 Jul 2024 10:32:04 +0800 Subject: [PATCH 003/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../softbus_connector_common_fuzzer.cpp | 5 ++--- .../softbus_connector_common_fuzzer.h | 2 +- .../softbus_connector_state_fuzzer.cpp | 8 +++++--- .../softbus_connector_state_fuzzer.h | 2 +- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp index 7bb0d2426..2d666504d 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -28,12 +28,11 @@ namespace DistributedHardware { void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(int32_t))) { + if ((data == nullptr) || (size == 0)) { return; } std::string str(reinterpret_cast(data), size); - int32_t authForm = *(reinterpret_cast(data)); std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->GetDeviceUdidHashByUdid(str); diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h index 18f35c4ec..8957c14e0 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp index 450ad6246..13182fd05 100644 --- a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -28,8 +28,10 @@ namespace OHOS { namespace DistributedHardware { class SoftbusStateCallbackFuzzTest : public ISoftbusStateCallback{ public: - void OnDeviceOnline(std::string deviceId, int32_t authForm) {} - void OnDeviceOffline(std::string deviceId) {} + virtual ~SoftbusStateCallbackFuzzTest() {} + + void OnDeviceOnline(std::string deviceId, int32_t authForm) override {} + void OnDeviceOffline(std::string deviceId) override {} }; void SoftBusConnectorStateFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h index 2574d7aec..9e9ec63ab 100644 --- a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From cf58896166a2fb6cd79a58116ad27675ac95e3ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 23 Jul 2024 16:56:29 +0800 Subject: [PATCH 004/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9codecheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../softbus_connector_state_fuzzer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp index 13182fd05..1365cb4fb 100644 --- a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp @@ -26,7 +26,7 @@ namespace OHOS { namespace DistributedHardware { -class SoftbusStateCallbackFuzzTest : public ISoftbusStateCallback{ +class SoftbusStateCallbackFuzzTest : public ISoftbusStateCallback { public: virtual ~SoftbusStateCallbackFuzzTest() {} -- Gitee From 10ede24da57f0179ec1f370bb8ccd775ce3e8ff4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 1 Aug 2024 11:35:29 +0800 Subject: [PATCH 005/520] =?UTF-8?q?dlopen=E7=BB=9D=E5=AF=B9=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E6=94=B9=E4=B8=BA=E7=9B=B8=E5=AF=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/config/dm_config_manager.cpp | 34 +++++++------------ .../service/src/device_manager_service.cpp | 32 +++++++---------- .../src/discovery/discovery_manager.cpp | 9 +++-- .../service/src/softbus/softbus_listener.cpp | 9 +++-- 4 files changed, 34 insertions(+), 50 deletions(-) diff --git a/services/implementation/src/config/dm_config_manager.cpp b/services/implementation/src/config/dm_config_manager.cpp index 578cb7d44..4f680c68d 100644 --- a/services/implementation/src/config/dm_config_manager.cpp +++ b/services/implementation/src/config/dm_config_manager.cpp @@ -139,28 +139,24 @@ DmConfigManager::~DmConfigManager() { void *so_handle = nullptr; for (auto iter = soAdapterLoadInfo_.begin(); iter != soAdapterLoadInfo_.end(); iter++) { - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = (iter->second).soPath + (iter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (iter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); continue; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("DmConfigManager so_handle is not nullptr first."); dlclose(so_handle); } } for (auto iter = soAuthLoadInfo_.begin(); iter != soAuthLoadInfo_.end(); iter++) { - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = (iter->second).soPath + (iter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (iter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); continue; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("DmConfigManager so_handle is not nullptr second."); dlclose(so_handle); @@ -189,16 +185,14 @@ std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::str } void *so_handle = nullptr; - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = (soInfoIter->second).soPath + (soInfoIter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (soInfoIter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); return nullptr; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { - LOGE("load crypto so %{public}s failed", soName.c_str()); + LOGE("load crypto so failed."); return nullptr; } @@ -224,14 +218,12 @@ void DmConfigManager::GetAuthAdapter(std::mapsecond).soPath + (iter->second).soName; - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = (iter->second).soName; + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); continue; } - so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { LOGE("load auth so %{public}s failed", (iter->second).soName.c_str()); continue; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 6cfec1869..67db3e107 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -829,15 +829,14 @@ bool DeviceManagerService::IsDMServiceImplReady() if (isImplsoLoaded_ && (dmServiceImpl_ != nullptr)) { return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_IMPL_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { + std::string soName = std::string(LIB_IMPL_NAME); + if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soName.c_str()); return false; } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); + void *so_handle = dlopen(soName.c_str(), RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { - LOGE("load libdevicemanagerserviceimpl so %{public}s failed, errMsg: %{public}s.", soName.c_str(), dlerror()); + LOGE("load libdevicemanagerserviceimpl so failed, errMsg: %{public}s.", dlerror()); return false; } dlerror(); @@ -1063,14 +1062,12 @@ void DeviceManagerService::UnloadDMServiceImplSo() if (dmServiceImpl_ != nullptr) { dmServiceImpl_->Release(); } - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_IMPL_NAME); - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = std::string(LIB_IMPL_NAME); + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); return; } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + void *so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("DeviceManagerService so_handle is not nullptr."); dlclose(so_handle); @@ -1085,13 +1082,12 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_DM_ADAPTER_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { + std::string soName = std::string(LIB_DM_ADAPTER_NAME); + if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soName.c_str()); return false; } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NODELETE); + void *so_handle = dlopen(soName.c_str(), RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { LOGE("load dm service adapter so %{public}s failed.", soName.c_str()); return false; @@ -1126,14 +1122,12 @@ void DeviceManagerService::UnloadDMServiceAdapter() } dmServiceImplExt_ = nullptr; - char path[PATH_MAX + 1] = {0x00}; - std::string soPathName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_DM_ADAPTER_NAME); - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX) || - (realpath(soPathName.c_str(), path) == nullptr)) { + std::string soPathName = std::string(LIB_DM_ADAPTER_NAME); + if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); return; } - void *so_handle = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + void *so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("dm service adapter so_handle is not nullptr."); dlclose(so_handle); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index c283cccaf..8aea8f8d1 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -532,15 +532,14 @@ bool DiscoveryManager::IsCommonDependencyReady() if (isSoLoaded_ && dpConnector_ != nullptr && dpConnectorHandle_ != nullptr) { return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_DM_COMDENPENDENCY_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { + std::string soName = std::string(LIB_DM_COMDENPENDENCY_NAME); + if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soName.c_str()); return false; } - dpConnectorHandle_ = dlopen(path, RTLD_NOW | RTLD_NODELETE); + dpConnectorHandle_ = dlopen(soName.c_str(), RTLD_NOW | RTLD_NODELETE); if (dpConnectorHandle_ == nullptr) { - LOGE("load libdevicemanagerdependency so %{public}s failed, errMsg: %{public}s.", soName.c_str(), dlerror()); + LOGE("load libdevicemanagerdependency so failed, errMsg: %{public}s.", dlerror()); return false; } dlerror(); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 878f5596e..533bb24ab 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -808,15 +808,14 @@ bool SoftbusListener::IsDmRadarHelperReady() LOGI("IsDmRadarHelperReady alReady."); return true; } - char path[PATH_MAX + 1] = {0x00}; - std::string soName = std::string(DM_LIB_LOAD_PATH) + std::string(LIB_RADAR_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX) || (realpath(soName.c_str(), path) == nullptr)) { + std::string soName = std::string(LIB_RADAR_NAME); + if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { LOGE("File %{public}s canonicalization failed.", soName.c_str()); return false; } - radarHandle_ = dlopen(path, RTLD_NOW); + radarHandle_ = dlopen(soName.c_str(), RTLD_NOW); if (radarHandle_ == nullptr) { - LOGE("load libdevicemanagerradar so %{public}s failed.", soName.c_str()); + LOGE("load libdevicemanagerradar so failed."); return false; } dlerror(); -- Gitee From 0124465b99101ab6a90142c53b6d2c58b6937e83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 1 Aug 2024 20:34:32 +0800 Subject: [PATCH 006/520] =?UTF-8?q?=E8=A1=A5=E5=85=85ut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_softbus_listener.cpp | 17 ++ test/unittest/BUILD.gn | 5 +- .../UTTest_device_manager_notify_three.cpp | 2 + ...UTTest_device_manager_service_listener.cpp | 47 ++++ .../UTTest_device_manager_service_two.cpp | 252 ++++++++++++++++++ 5 files changed, 322 insertions(+), 1 deletion(-) create mode 100644 test/unittest/UTTest_device_manager_service_two.cpp diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index e24d744cd..91aa49fd9 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -102,6 +102,23 @@ HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_001, testing::ext::TestSize. EXPECT_EQ(softbusListener->isRadarSoLoad_, true); } +/** + * @tc.name: OnSoftbusDeviceOnline_001 + * @tc.desc: return true + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_002, testing::ext::TestSize.Level0) +{ + NodeBasicInfo *info = nullptr; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->OnSoftbusDeviceOnline(info); + softbusListener->OnSoftbusDeviceOffline(info); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + /** * @tc.name: ShiftLNNGear_001 * @tc.desc: return DM_OK diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 2e2170508..9bad1ad69 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -282,7 +282,10 @@ ohos_unittest("UTTest_dm_credential_manager") { ohos_unittest("UTTest_device_manager_service") { module_out_path = module_out_path - sources = [ "UTTest_device_manager_service.cpp" ] + sources = [ + "UTTest_device_manager_service.cpp", + "UTTest_device_manager_service_two.cpp", + ] deps = [ ":device_manager_test_common" ] diff --git a/test/unittest/UTTest_device_manager_notify_three.cpp b/test/unittest/UTTest_device_manager_notify_three.cpp index e268761a4..50e23fa60 100644 --- a/test/unittest/UTTest_device_manager_notify_three.cpp +++ b/test/unittest/UTTest_device_manager_notify_three.cpp @@ -938,6 +938,8 @@ HWTEST_F(DeviceManagerNotifyTest, OnDeviceFound7, testing::ext::TestSize.Level0) auto map = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName]; EXPECT_EQ(map.empty(), false); } + + } // namespace DmInitCallbackTest::DmInitCallbackTest(int &count) : DmInitCallback() diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 441b74dce..55d494013 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -544,6 +544,53 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::T listener_->OnPinHolderEvent(pkgName, event, result, content); EXPECT_EQ(listener_->dmListenerMap_.empty(), true); } + +/** + * @tc.name: ComposeOnlineKey_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, ComposeOnlineKey_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string str1 = "hello"; + std::string str2 = "world"; + std::string str = listener_->ComposeOnlineKey(str1, str2); + EXPECT_EQ(str, str1 + "_" + str2); +} + +/** + * @tc.name: GetDeviceId_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + std::string udidHash = "123445676788908"; + std::string deviceId = "123"; + listener_->udidHashMap_[pkgName][deviceId] = udidHash; + std::string str = listener_->GetDeviceId(udidHash, pkgName); + EXPECT_EQ(str, deviceId); +} + +/** + * @tc.name: GetDeviceId_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + std::string udidHash = "123445676788908"; + std::string udidHash2 = "123445676788909"; + std::string deviceId = "123"; + listener_->udidHashMap_[pkgName][deviceId] = udidHash; + std::string str = listener_->GetDeviceId(udidHash2, pkgName); + EXPECT_EQ(str, ""); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp new file mode 100644 index 000000000..1fe96e1dc --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_device_manager_service.h" + +#include "accesstoken_kit.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "softbus_common.h" +#include "softbus_error_code.h" + +using namespace OHOS::Security::AccessToken; +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); + +void DeviceManagerServiceTest::SetUp() +{ + const int32_t permsNum = 4; + const int32_t indexZero = 0; + const int32_t indexOne = 1; + const int32_t indexTwo = 2; + const int32_t indexThree = 3; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.DISTRIBUTED_SOFTBUS_CENTER"; + perms[indexOne] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[indexTwo] = "ohos.permission.ACCESS_SERVICE_DM"; + perms[indexThree] = "ohos.permission.MONITOR_DEVICE_NETWORK_STATE"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "dsoftbus_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +void DeviceManagerServiceTest::TearDown() +{ +} + +void DeviceManagerServiceTest::SetUpTestCase() +{ +} + +void DeviceManagerServiceTest::TearDownTestCase() +{ +} + +void DeletePermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "DeviceManagerServiceTest", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +namespace { +/** + * @tc.name: Init_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, Init_001, testing::ext::TestSize.Level0) +{ + int ret = DeviceManagerService::GetInstance().Init(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: InitSoftbusListener_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, InitSoftbusListener_001, testing::ext::TestSize.Level0) +{ + int ret = DeviceManagerService::GetInstance().InitSoftbusListener(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SubscribePublishCommonEvent_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, SubscribePublishCommonEvent_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().SubscribePublishCommonEvent(); + EXPECT_NE(DeviceManagerService::GetInstance().publshCommonEventManager_, nullptr); +} + +/** + * @tc.name: RegisterDeviceManagerListener_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().listener_ = std::make_shared(); + int ret = DeviceManagerService::GetInstance().RegisterDeviceManagerListener(); + EXPECT_NE(DeviceManagerService::GetInstance().listener_ , nullptr); +} + +/** + * @tc.name: RegisterUiStateCallback_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_001, testing::ext::TestSize.Level0) +{ + DeletePermission(); + std::string pkgName = "pkgName"; + int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +/** + * @tc.name: UnRegisterUiStateCallback_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_001, testing::ext::TestSize.Level0) +{ + DeletePermission(); + std::string pkgName = "pkgName"; + int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +/** + * @tc.name: IsDMImplSoLoaded_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize.Level0) +{ + bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: GetEncryptedUuidByNetworkId_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string networkId = "123"; + std::string uuid; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: CheckAccessControl_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: CheckIsSameAccount_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_EQ(ret, true); +} + +/** + * @tc.name: InitAccountInfo_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_001, testing::ext::TestSize.Level0) +{ + int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: InitScreenLockEvent_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, InitScreenLockEvent_001, testing::ext::TestSize.Level0) +{ + int32_t ret = DeviceManagerService::GetInstance().InitScreenLockEvent(); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: SubscribeAccountCommonEvent_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_001, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().SubscribeAccountCommonEvent(); + EXPECT_NE(DeviceManagerService::GetInstance().accountCommonEventManager_, nullptr); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From 6a354571f2a93ebbae396436a75fed96a3f68345 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 3 Aug 2024 15:14:48 +0800 Subject: [PATCH 007/520] =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=B6=85=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- commondependency/BUILD.gn | 2 +- interfaces/inner_kits/native_cpp/BUILD.gn | 4 ++-- services/softbuscache/BUILD.gn | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/commondependency/BUILD.gn b/commondependency/BUILD.gn index 162437022..f08ca00d4 100644 --- a/commondependency/BUILD.gn +++ b/commondependency/BUILD.gn @@ -40,7 +40,7 @@ ohos_shared_library("devicemanagerdependency") { defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"devicemanagerdependency\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004112", ] deps = [ diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index a28a57043..d2ed0b1f4 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -107,7 +107,7 @@ if (defined(ohos_lite)) { "LITE_DEVICE", "HI_LOG_ENABLE", "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004111", ] deps = [ @@ -170,7 +170,7 @@ if (defined(ohos_lite)) { defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"devicemanagerkit\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004111", ] external_deps = [ diff --git a/services/softbuscache/BUILD.gn b/services/softbuscache/BUILD.gn index 4cdcad1db..e33a288ed 100644 --- a/services/softbuscache/BUILD.gn +++ b/services/softbuscache/BUILD.gn @@ -36,7 +36,7 @@ if (defined(ohos_lite)) { defines = [ "LITE_DEVICE", "DH_LOG_TAG=\"dmdevicecache\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004113", ] deps = [ @@ -72,7 +72,7 @@ if (defined(ohos_lite)) { defines = [ "HI_LOG_ENABLE", "DH_LOG_TAG=\"dmdevicecache\"", - "LOG_DOMAIN=0xD004110", + "LOG_DOMAIN=0xD004113", ] deps = [ "${utils_path}:devicemanagerutils" ] -- Gitee From 57fcb1652908b0d272406fbe2ca2f79d96848dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 15:19:13 +0800 Subject: [PATCH 008/520] =?UTF-8?q?=E8=A1=A5=E5=85=85UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_notify_three.cpp | 2 - .../UTTest_device_manager_service.cpp | 2 +- ...UTTest_device_manager_service_listener.cpp | 66 ++-- .../UTTest_device_manager_service_two.cpp | 285 +++++++++++++----- 4 files changed, 251 insertions(+), 104 deletions(-) diff --git a/test/unittest/UTTest_device_manager_notify_three.cpp b/test/unittest/UTTest_device_manager_notify_three.cpp index 50e23fa60..e268761a4 100644 --- a/test/unittest/UTTest_device_manager_notify_three.cpp +++ b/test/unittest/UTTest_device_manager_notify_three.cpp @@ -938,8 +938,6 @@ HWTEST_F(DeviceManagerNotifyTest, OnDeviceFound7, testing::ext::TestSize.Level0) auto map = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName]; EXPECT_EQ(map.empty(), false); } - - } // namespace DmInitCallbackTest::DmInitCallbackTest(int &count) : DmInitCallback() diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 4576eae89..45f12c768 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -69,6 +69,7 @@ void DeviceManagerServiceTest::TearDownTestCase() { } +namespace { void DeletePermission() { const int32_t permsNum = 1; @@ -91,7 +92,6 @@ void DeletePermission() OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } -namespace { /** * @tc.name: InitDMServiceListener_001 * @tc.desc: Init device manager listener and return DM_OK diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 55d494013..f944ea80b 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -442,6 +442,39 @@ HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSi EXPECT_EQ(str.empty(), true); } +/** + * @tc.name: GetDeviceId_002 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_002, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + std::string udidHash = "123445676788908"; + std::string deviceId = "123"; + listener_->udidHashMap_[pkgName][deviceId] = udidHash; + std::string str = listener_->GetDeviceId(udidHash, pkgName); + EXPECT_EQ(str, deviceId); +} + +/** + * @tc.name: GetDeviceId_003 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + std::string udidHash = "123445676788908"; + std::string udidHash2 = "123445676788909"; + std::string deviceId = "123"; + listener_->udidHashMap_[pkgName][deviceId] = udidHash; + std::string str = listener_->GetDeviceId(udidHash2, pkgName); + EXPECT_EQ(str, ""); +} + /** * @tc.name: GetUdidHash_001 * @tc.desc: GetUdidHash, construct a dummy listener, pass in deviceId @@ -558,39 +591,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, ComposeOnlineKey_001, testing::ext::T std::string str = listener_->ComposeOnlineKey(str1, str2); EXPECT_EQ(str, str1 + "_" + str2); } - -/** - * @tc.name: GetDeviceId_001 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string udidHash = "123445676788908"; - std::string deviceId = "123"; - listener_->udidHashMap_[pkgName][deviceId] = udidHash; - std::string str = listener_->GetDeviceId(udidHash, pkgName); - EXPECT_EQ(str, deviceId); -} - -/** - * @tc.name: GetDeviceId_001 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string udidHash = "123445676788908"; - std::string udidHash2 = "123445676788909"; - std::string deviceId = "123"; - listener_->udidHashMap_[pkgName][deviceId] = udidHash; - std::string str = listener_->GetDeviceId(udidHash2, pkgName); - EXPECT_EQ(str, ""); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 1fe96e1dc..dbf939db4 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -28,20 +28,14 @@ using namespace OHOS::Security::AccessToken; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); - -void DeviceManagerServiceTest::SetUp() +namespace { +void DeletePermission() { - const int32_t permsNum = 4; + const int32_t permsNum = 1; const int32_t indexZero = 0; - const int32_t indexOne = 1; - const int32_t indexTwo = 2; - const int32_t indexThree = 3; uint64_t tokenId; const char *perms[permsNum]; - perms[indexZero] = "ohos.permission.DISTRIBUTED_SOFTBUS_CENTER"; - perms[indexOne] = "ohos.permission.DISTRIBUTED_DATASYNC"; - perms[indexTwo] = "ohos.permission.ACCESS_SERVICE_DM"; - perms[indexThree] = "ohos.permission.MONITOR_DEVICE_NETWORK_STATE"; + perms[indexZero] = "ohos.permission"; NativeTokenInfoParams infoInstance = { .dcapsNum = 0, .permsNum = permsNum, @@ -49,7 +43,7 @@ void DeviceManagerServiceTest::SetUp() .dcaps = NULL, .perms = perms, .acls = NULL, - .processName = "dsoftbus_service", + .processName = "DeviceManagerServiceTest", .aplStr = "system_core", }; tokenId = GetAccessTokenId(&infoInstance); @@ -57,84 +51,86 @@ void DeviceManagerServiceTest::SetUp() OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } -void DeviceManagerServiceTest::TearDown() -{ -} - -void DeviceManagerServiceTest::SetUpTestCase() -{ -} -void DeviceManagerServiceTest::TearDownTestCase() +/** + * @tc.name: InitSoftbusListener_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, InitSoftbusListener_201, testing::ext::TestSize.Level0) { + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + int32_t ret = DeviceManagerService::GetInstance().InitSoftbusListener(); + EXPECT_EQ(ret, DM_OK); } -void DeletePermission() +/** + * @tc.name: RegisterDeviceManagerListener_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_201, testing::ext::TestSize.Level0) { - const int32_t permsNum = 1; - const int32_t indexZero = 0; - uint64_t tokenId; - const char *perms[permsNum]; - perms[indexZero] = "ohos.permission"; - NativeTokenInfoParams infoInstance = { - .dcapsNum = 0, - .permsNum = permsNum, - .aclsNum = 0, - .dcaps = NULL, - .perms = perms, - .acls = NULL, - .processName = "DeviceManagerServiceTest", - .aplStr = "system_core", - }; - tokenId = GetAccessTokenId(&infoInstance); - SetSelfTokenID(tokenId); - OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); + std::string pkgName = "pkgName"; + DeviceManagerService::GetInstance().listener_ = std::make_shared(); + DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_ != nullptr, true); } -namespace { /** - * @tc.name: Init_001 + * @tc.name: GetTrustedDeviceList_201 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, Init_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestSize.Level0) { - int ret = DeviceManagerService::GetInstance().Init(); - EXPECT_EQ(ret, DM_OK); + DeletePermission(); + std::string pkgName = "pkgName"; + const std::string extra; + std::vector deviceList; + int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } /** - * @tc.name: InitSoftbusListener_001 + * @tc.name: GetDeviceInfo_201 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, InitSoftbusListener_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Level0) { - int ret = DeviceManagerService::GetInstance().InitSoftbusListener(); - EXPECT_EQ(ret, DM_OK); + DeletePermission(); + std::string networkId = "123"; + DmDeviceInfo deviceIndo; + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, deviceIndo); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } /** - * @tc.name: SubscribePublishCommonEvent_001 + * @tc.name: GetLocalDeviceInfo_201 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, SubscribePublishCommonEvent_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_201, testing::ext::TestSize.Level0) { - DeviceManagerService::GetInstance().SubscribePublishCommonEvent(); - EXPECT_NE(DeviceManagerService::GetInstance().publshCommonEventManager_, nullptr); + DeletePermission(); + DmDeviceInfo deviceIndo; + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(deviceIndo); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } /** - * @tc.name: RegisterDeviceManagerListener_001 + * @tc.name: GetLocalDeviceInfo_201 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_201, testing::ext::TestSize.Level0) { - DeviceManagerService::GetInstance().listener_ = std::make_shared(); - int ret = DeviceManagerService::GetInstance().RegisterDeviceManagerListener(); - EXPECT_NE(DeviceManagerService::GetInstance().listener_ , nullptr); + DeletePermission(); + std::string pkgName = "pkgName"; + uint16_t subscribeId = 111; + int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } /** @@ -142,7 +138,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_001, testing::e * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_201, testing::ext::TestSize.Level0) { DeletePermission(); std::string pkgName = "pkgName"; @@ -155,7 +151,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_001, testing::ext::Te * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_201, testing::ext::TestSize.Level0) { DeletePermission(); std::string pkgName = "pkgName"; @@ -168,8 +164,9 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_001, testing::ext:: * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize.Level0) { + DeviceManagerService::GetInstance().IsDMServiceImplReady(); bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); EXPECT_EQ(ret, true); } @@ -179,13 +176,129 @@ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize. * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; std::string networkId = "123"; std::string uuid; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: StopAdvertising_201 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StopAdvertising_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map advertiseParam; + advertiseParam[PARAM_KEY_META_TYPE] = "1"; + int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: StopAdvertising_202 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StopAdvertising_202, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map advertiseParam; + advertiseParam[PARAM_KEY_PUBLISH_ID] = "12"; + int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: BindTarget_201 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + targetId.deviceId = "123"; + std::map bindParam; + bindParam[PARAM_KEY_META_TYPE] = "1"; + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: BindTarget_202 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, BindTarget_202, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + targetId.wifiIp = "192.168.1.1"; + targetId.deviceId = "123"; + std::map bindParam; + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: UnbindTarget_201 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnbindTarget_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + targetId.wifiIp = "192.168.1.1"; + targetId.deviceId = "123"; + std::map unbindParam; + unbindParam[PARAM_KEY_META_TYPE] = "1"; + int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: RegisterPinHolderCallback_201 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "CollaborationFwk"; + int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: CreatePinHolder_201 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "CollaborationFwk"; + int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetDeviceSecurityLevel_201 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string networkId = "123"; + int32_t securityLevel; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, networkId, securityLevel); EXPECT_EQ(ret, DM_OK); } @@ -194,7 +307,7 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSize.Level0) { DmAccessCaller caller; DmAccessCallee callee; @@ -203,11 +316,25 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSiz } /** - * @tc.name: CheckIsSameAccount_001 + * @tc.name: CheckAccessControl_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSize.Level0) +{ + DeletePermission(); + DmAccessCaller caller; + DmAccessCallee callee; + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: CheckIsSameAccount_201 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSize.Level0) { DmAccessCaller caller; DmAccessCallee callee; @@ -216,12 +343,31 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSiz } /** - * @tc.name: InitAccountInfo_001 + * @tc.name: CheckIsSameAccount_202 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSize.Level0) +{ + DeletePermission(); + DmAccessCaller caller; + DmAccessCallee callee; + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_EQ(ret, false); +} + +/** + * @tc.name: InitAccountInfo_201 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.Level0) { + int32_t userId = 100; + std::string commonEventType = CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; + DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); EXPECT_EQ(ret, DM_OK); } @@ -231,20 +377,23 @@ HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_001, testing::ext::TestSize.L * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, InitScreenLockEvent_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, InitScreenLockEvent_201, testing::ext::TestSize.Level0) { int32_t ret = DeviceManagerService::GetInstance().InitScreenLockEvent(); EXPECT_EQ(ret, DM_OK); } /** - * @tc.name: SubscribeAccountCommonEvent_001 + * @tc.name: SubscribeAccountCommonEvent_201 * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_201, testing::ext::TestSize.Level0) { DeviceManagerService::GetInstance().SubscribeAccountCommonEvent(); + DeviceManagerService::GetInstance().SubscribeScreenLockEvent(); + std::string commonEventType = CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + DeviceManagerService::GetInstance().ScreenCommonEventCallback(commonEventType); EXPECT_NE(DeviceManagerService::GetInstance().accountCommonEventManager_, nullptr); } } // namespace -- Gitee From 446bf9d595bc20006211120e1a2df82a2529cc81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 16:00:03 +0800 Subject: [PATCH 009/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_softbus_listener.cpp | 3 +- .../unittest/UTTest_device_manager_notify.cpp | 85 +++++++++++++++++++ test/unittest/UTTest_device_manager_notify.h | 14 +++ 3 files changed, 101 insertions(+), 1 deletion(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 91aa49fd9..342c3cfc1 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -103,7 +103,7 @@ HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_001, testing::ext::TestSize. } /** - * @tc.name: OnSoftbusDeviceOnline_001 + * @tc.name: OnSoftbusDeviceOnline_002 * @tc.desc: return true * @tc.type: FUNC * @tc.require: AR000GHSJK @@ -116,6 +116,7 @@ HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_002, testing::ext::TestSize. } softbusListener->OnSoftbusDeviceOnline(info); softbusListener->OnSoftbusDeviceOffline(info); + softbusListener->OnLocalDevInfoChange(); EXPECT_EQ(softbusListener->isRadarSoLoad_, true); } diff --git a/test/unittest/UTTest_device_manager_notify.cpp b/test/unittest/UTTest_device_manager_notify.cpp index 61d242b4e..45961b2c7 100644 --- a/test/unittest/UTTest_device_manager_notify.cpp +++ b/test/unittest/UTTest_device_manager_notify.cpp @@ -1995,6 +1995,91 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterPackageCallback_006, testing::ext::T ASSERT_EQ(checkMap3, nullptr); ASSERT_EQ(checkMap4, nullptr); } + +/** + * @tc.name: RegisterCredentialCallback_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().UnRegisterCredentialCallback(pkgName); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterCredentialCallback_002 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterCredentialCallback_003 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_001 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_002 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_003 + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_notify.h b/test/unittest/UTTest_device_manager_notify.h index f78f9dfd6..5260f112d 100644 --- a/test/unittest/UTTest_device_manager_notify.h +++ b/test/unittest/UTTest_device_manager_notify.h @@ -110,6 +110,20 @@ public: void OnDeviceChanged(const DmDeviceBasicInfo &deviceBasicInfo) override {} void OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) override {} }; + +class CredentialCallbackTest : public CredentialCallback { +public: + void CredentialCallbackTest(int32_t &action, const std::string &credentialResult) override {} +}; + +class PinHolderCallbackTest: public PinHolderCallback { +public: + void OnPinHolderCreate(const std::string &deviceId, DmPinType pinType, const std::string &payload) {} + void OnPinHolderDestroy(DmPinType pinType, const std::string &payload) {} + void OnCreateResult(int32_t result) {} + void OnDestroyResult(int32_t result) {} + void OnPinHolderEvent(DmPinHolderEvent event, int32_t result, const std::string &content) {} +}; } // namespace DistributedHardware } // namespace OHOS -- Gitee From d8b292608cb98b831ab2735fcecadd4a20f7232a Mon Sep 17 00:00:00 2001 From: w30042960 Date: Sat, 3 Aug 2024 16:01:22 +0800 Subject: [PATCH 010/520] add UT Signed-off-by: w30042960 --- test/unittest/UTTest_device_manager_impl.cpp | 502 ++++++++++++++++++- 1 file changed, 498 insertions(+), 4 deletions(-) diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index aa8c42032..d4b983251 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -417,7 +417,7 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceName_104, testing::ext::TestSize.Level0 std::shared_ptr callback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); ret = DeviceManager::GetInstance().GetDeviceName(packName, networkId, deviceName); - ASSERT_EQ(ret, DM_OK); + ASSERT_EQ(ret, ERR_DM_NO_PERMISSION); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -497,7 +497,7 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceType_104, testing::ext::TestSize.Level0 std::shared_ptr callback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); ret = DeviceManager::GetInstance().GetDeviceType(packName, networkId, deviceType); - ASSERT_EQ(ret, DM_OK); + ASSERT_EQ(ret, ERR_DM_NO_PERMISSION); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1085,7 +1085,7 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_101, testing::ext::TestSize.Lev // 3. call DeviceManagerImpl::SetUserOperation with parameter ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 4. check ret is DM_OK - ASSERT_EQ(ret, DM_OK); + ASSERT_EQ(ret, ERR_DM_NO_PERMISSION); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1495,6 +1495,314 @@ HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList_007, testing::ext::TestSize ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); } +/** + * @tc.name: GetTrustedDeviceList_008 + * @tc.desc: 1. set packName not null + * set extra null + * set deviceList null + * set isRefresh true + * 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter + * 3. check ret is DM_OK + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GetTrustedDeviceList_008, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::map filterOptions; + bool isRefresh = false; + std::vector deviceList; + int32_t ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, filterOptions, isRefresh, deviceList); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + packName = "packNameTest"; + ret = DeviceManager::GetInstance().GetTrustedDeviceList(packName, filterOptions, isRefresh, deviceList); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); +} + +/** + * @tc.name: ImportCredential_001 + * @tc.desc: 1. set pkgName not null + * set reqJsonStr null + * set returnJsonStr null + * 2. call DeviceManagerImpl::ImportCredential with parameter + * 3. check ret is DM_OK + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, ImportCredential_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string reqJsonStr = ""; + std::string returnJsonStr = ""; + int32_t ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + reqJsonStr = "reqJsonStrTest"; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: RequestCredential_001 + * @tc.desc: 1. set pkgName not null + * set reqJsonStr null + * set returnJsonStr null + * 2. call DeviceManagerImpl::RequestCredential with parameter + * 3. check ret is DM_OK + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, RequestCredential_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string reqJsonStr = ""; + std::string returnJsonStr = ""; + int32_t ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + reqJsonStr = "reqJsonStrTest"; + ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RequestCredential(pkgName, returnJsonStr); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GenerateEncryptedUuid_001 + * @tc.desc: 1. set packName null + * set extra null + * set deviceList null + * 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GenerateEncryptedUuid_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string uuid = ""; + std::string appId = ""; + std::string encryptedUuid = ""; + int32_t ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + uuid = "uuidTest"; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().GenerateEncryptedUuid(pkgName, uuid, appId, encryptedUuid); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetNetworkTypeByNetworkId_001 + * @tc.desc: 1. set pkgName null + * set networkId null + * set networkType null + * 2. call DeviceManagerImpl::GetTrustedDeviceList with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GetNetworkTypeByNetworkId_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string networkId = ""; + int32_t netWorkType = 0; + int32_t ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + networkId = "networkIdTest"; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().GetNetworkTypeByNetworkId(pkgName, networkId, netWorkType); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: ImportAuthCode_001 + * @tc.desc: 1. set packName null + * set authCode null + * 2. call DeviceManagerImpl::ImportAuthCode with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, ImportAuthCode_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string authCode = ""; + int32_t ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = ""; + authCode = "authCodeTest"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + authCode = "authoCo"; + ret = DeviceManager::GetInstance().ImportAuthCode(pkgName, authCode); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: RegisterDiscoveryCallback_001 + * @tc.desc: 1. set packName null + * set discoverParam null + * set filterOptions null + * set callback null + * 2. call DeviceManagerImpl::RegisterDiscoveryCallback with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, RegisterDiscoveryCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::map discoverParam; + std::map filterOptions; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterDiscoveryCallback(pkgName, + discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().UnRegisterDiscoveryCallback(pkgName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, discoverParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RegisterDiscoveryCallback(pkgName, discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + callback = std::make_shared(); + ret = DeviceManager::GetInstance().UnRegisterDiscoveryCallback(pkgName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, discoverParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: StartAdvertising_001 + * @tc.desc: 1. set packName null + * set discoverParam null + * set filterOptions null + * set callback null + * 2. call DeviceManagerImpl::StartAdvertising with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, StartAdvertising_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::map advertiseParam; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().StartAdvertising(pkgName, advertiseParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, advertiseParam); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().StartAdvertising(pkgName, advertiseParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().StopDiscovering(pkgName, advertiseParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + callback = std::make_shared(); + ret = DeviceManager::GetInstance().StartAdvertising(pkgName, advertiseParam, callback); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: BindTarget_001 + * @tc.desc: 1. set packName null + * set targetId null + * set unbindParam null + * set callback null + * 2. call DeviceManagerImpl::BindTarget with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, BindTarget_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + std::map unbindParam; + std::shared_ptr callback = nullptr; + std::shared_ptr uncallback = nullptr; + int32_t ret = DeviceManager::GetInstance().BindTarget(pkgName, targetId, unbindParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().UnbindTarget(pkgName, targetId, unbindParam, uncallback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + targetId.deviceId = "deviceIdTest"; + targetId.brMac = "brMacTest"; + targetId.bleMac = "bleMacTest"; + targetId.wifiIp = "wifiIpTest"; + ret = DeviceManager::GetInstance().BindTarget(pkgName, targetId, unbindParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ret = DeviceManager::GetInstance().UnbindTarget(pkgName, targetId, unbindParam, uncallback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().BindTarget(pkgName, targetId, unbindParam, callback); + ASSERT_EQ(ret, DM_OK); + ret = DeviceManager::GetInstance().UnbindTarget(pkgName, targetId, unbindParam, uncallback); + ASSERT_EQ(ret, DM_OK); +} + /** * @tc.name: GetLocalDeviceInfo_001 * @tc.desc: 1. set packName null @@ -1765,6 +2073,35 @@ HWTEST_F(DeviceManagerImplTest, RegisterDevStateCallback_005, testing::ext::Test ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } +/** + * @tc.name: RegisterDevStateCallback_006 + * @tc.desc: 1. set packName not null + * set extra not null + * set callback null + * 2. call DeviceManagerImpl::RegisterDevStateCallback with parameter + * 3. check ret is ERR_DM_INPUT_PARA_INVALID + * deviceTypeId + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerImplTest, RegisterDevStateCallback_006, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::map extraParam; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + callback = std::make_shared(); + ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, DM_OK); + pkgName = ""; + ret = DeviceManager::GetInstance().RegisterDevStateCallback(pkgName, extraParam, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + /** * @tc.name: UnRegisterDevStateCallback_001 * @tc.desc: 1. set packName null @@ -2040,7 +2377,164 @@ HWTEST_F(DeviceManagerImplTest, IsSameAccount_002, testing::ext::TestSize.Level0 std::shared_ptr initCallback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(pkgName, initCallback); bool ret = DeviceManager::GetInstance().IsSameAccount(udid); - ASSERT_EQ(ret, false); + ASSERT_EQ(ret, true); +} + +/** + * @tc.name: AddPublishCallback_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::AddPublishCallback with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, AddPublishcCllback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int32_t ret = DeviceManagerImpl::GetInstance().AddPublishCallback(pkgName); + ASSERT_NE(ret, 0); + ret = DeviceManagerImpl::GetInstance().RemovePublishCallback(pkgName); + ASSERT_NE(ret, 0); +} + +/** + * @tc.name: RegisterPinHolderCallback_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::RegisterPinHolderCallback with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, RegisterPinHolderCallback_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterPinHolderCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "pkgNameTest"; + ret = DeviceManager::GetInstance().RegisterPinHolderCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: CreatePinHolder_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::CreatePinHolder with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, CreatePinHolder_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload = "payload"; + int32_t ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "com.ohos.test"; + targetId.deviceId = "deviceIdTest"; + targetId.brMac = "brMacTest"; + targetId.bleMac = "bleMacTest"; + targetId.wifiIp = "wifiIpTest"; + pinType = static_cast(6); + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pinType = DmPinType::QR_CODE; + payload.resize(DM_STRING_LENGTH_MAX * 2); + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + payload.resize(10); + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DestroyPinHolder_001 + * @tc.desc: 1. set udid and bundleName not null + * 2. call DeviceManagerImpl::DestroyPinHolder with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, DestoryPinHolder_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload = "payload"; + int32_t ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "com.ohos.test"; + targetId.deviceId = "deviceIdTest"; + targetId.brMac = "brMacTest"; + targetId.bleMac = "bleMacTest"; + targetId.wifiIp = "wifiIpTest"; + pinType = static_cast(6); + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pinType = DmPinType::QR_CODE; + payload.resize(DM_STRING_LENGTH_MAX * 2); + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + payload.resize(10); + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: DpAclAdd_001 + * @tc.desc: 1. set DpAclAdd and Udid not null + * 2. call DeviceManagerImpl::DpAclAdd with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, DpAclAdd_001, testing::ext::TestSize.Level0) +{ + int64_t accessControlId = 0; + std::string udid = "udidTest"; + int32_t bindType = PEER_TO_PEER; + int32_t ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); + ASSERT_EQ(ret, DM_OK); + bindType = IDENTICAL_ACCOUNT; + ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); + ASSERT_EQ(ret, DM_OK); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + ret = DeviceManager::GetInstance().DpAclAdd(accessControlId, udid, bindType); + ASSERT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetDeviceSecurityLevel_001 + * @tc.desc: 1. set DpAclAdd and Udid not null + * 2. call DeviceManagerImpl::GetDeviceSecurityLevel with parameter + * 3. check ret is true + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerImplTest, GetDeviceSecurityLevel_001, testing::ext::TestSize.Level0) +{ + int32_t securityLevel = 3; + std::string pkgName = ""; + std::string netWorkId = ""; + int32_t ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + pkgName = "com.ohos.test"; + ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + netWorkId = "netWorkIdTest"; + ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, DM_OK); + pkgName = ""; + ret = DeviceManager::GetInstance().GetDeviceSecurityLevel(pkgName, netWorkId, securityLevel); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } } // namespace } // namespace DistributedHardware -- Gitee From 45397524ce33ca78494b7d252613986a5bc18a44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 17:16:06 +0800 Subject: [PATCH 011/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../unittest/UTTest_device_manager_notify.cpp | 85 ------------------- test/unittest/UTTest_device_manager_notify.h | 5 -- .../UTTest_device_manager_notify_three.cpp | 79 +++++++++++++++++ .../UTTest_device_manager_service_two.cpp | 26 ------ 4 files changed, 79 insertions(+), 116 deletions(-) diff --git a/test/unittest/UTTest_device_manager_notify.cpp b/test/unittest/UTTest_device_manager_notify.cpp index 45961b2c7..61d242b4e 100644 --- a/test/unittest/UTTest_device_manager_notify.cpp +++ b/test/unittest/UTTest_device_manager_notify.cpp @@ -1995,91 +1995,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterPackageCallback_006, testing::ext::T ASSERT_EQ(checkMap3, nullptr); ASSERT_EQ(checkMap4, nullptr); } - -/** - * @tc.name: RegisterCredentialCallback_001 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::shared_ptr callback = std::make_shared(); - DeviceManagerNotify::GetInstance().credentialCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); - DeviceManagerNotify::GetInstance().UnRegisterCredentialCallback(pkgName); - EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); -} - -/** - * @tc.name: RegisterCredentialCallback_002 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::shared_ptr callback = nullptr; - DeviceManagerNotify::GetInstance().credentialCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); - EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); -} - -/** - * @tc.name: RegisterCredentialCallback_003 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_003, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::shared_ptr callback = nullptr; - DeviceManagerNotify::GetInstance().credentialCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); - EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); -} - -/** - * @tc.name: RegisterPinHolderCallback_001 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::shared_ptr callback = nullptr; - DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); - EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); -} - -/** - * @tc.name: RegisterPinHolderCallback_002 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::shared_ptr callback = nullptr; - DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); - EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); -} - -/** - * @tc.name: RegisterPinHolderCallback_003 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_003, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::shared_ptr callback = std::make_shared(); - DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); - EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); -} } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_notify.h b/test/unittest/UTTest_device_manager_notify.h index 5260f112d..0db841585 100644 --- a/test/unittest/UTTest_device_manager_notify.h +++ b/test/unittest/UTTest_device_manager_notify.h @@ -111,11 +111,6 @@ public: void OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) override {} }; -class CredentialCallbackTest : public CredentialCallback { -public: - void CredentialCallbackTest(int32_t &action, const std::string &credentialResult) override {} -}; - class PinHolderCallbackTest: public PinHolderCallback { public: void OnPinHolderCreate(const std::string &deviceId, DmPinType pinType, const std::string &payload) {} diff --git a/test/unittest/UTTest_device_manager_notify_three.cpp b/test/unittest/UTTest_device_manager_notify_three.cpp index e268761a4..fab5cb1f7 100644 --- a/test/unittest/UTTest_device_manager_notify_three.cpp +++ b/test/unittest/UTTest_device_manager_notify_three.cpp @@ -938,6 +938,85 @@ HWTEST_F(DeviceManagerNotifyTest, OnDeviceFound7, testing::ext::TestSize.Level0) auto map = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName]; EXPECT_EQ(map.empty(), false); } + +/** + * @tc.name: RegisterCredentialCallback_301 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().UnRegisterCredentialCallback(pkgName); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterCredentialCallback_302 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_302, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterCredentialCallback_303 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_303, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().credentialCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_301 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_302 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_302, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} + +/** + * @tc.name: RegisterPinHolderCallback_303 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_303, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); + int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); +} } // namespace DmInitCallbackTest::DmInitCallbackTest(int &count) : DmInitCallback() diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index dbf939db4..12100fbe0 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -51,11 +51,9 @@ void DeletePermission() OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } - /** * @tc.name: InitSoftbusListener_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, InitSoftbusListener_201, testing::ext::TestSize.Level0) { @@ -67,7 +65,6 @@ HWTEST_F(DeviceManagerServiceTest, InitSoftbusListener_201, testing::ext::TestSi /** * @tc.name: RegisterDeviceManagerListener_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_201, testing::ext::TestSize.Level0) { @@ -80,7 +77,6 @@ HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_201, testing::e /** * @tc.name: GetTrustedDeviceList_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestSize.Level0) { @@ -95,7 +91,6 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestS /** * @tc.name: GetDeviceInfo_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Level0) { @@ -109,7 +104,6 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Lev /** * @tc.name: GetLocalDeviceInfo_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_201, testing::ext::TestSize.Level0) { @@ -122,7 +116,6 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_201, testing::ext::TestSiz /** * @tc.name: GetLocalDeviceInfo_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_201, testing::ext::TestSize.Level0) { @@ -136,7 +129,6 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_201, testing::ext::TestSi /** * @tc.name: RegisterUiStateCallback_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_201, testing::ext::TestSize.Level0) { @@ -149,7 +141,6 @@ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_201, testing::ext::Te /** * @tc.name: UnRegisterUiStateCallback_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_201, testing::ext::TestSize.Level0) { @@ -162,7 +153,6 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_201, testing::ext:: /** * @tc.name: IsDMImplSoLoaded_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize.Level0) { @@ -174,7 +164,6 @@ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize. /** * @tc.name: GetEncryptedUuidByNetworkId_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_201, testing::ext::TestSize.Level0) { @@ -189,7 +178,6 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_201, testing::ext /** * @tc.name: StopAdvertising_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_201, testing::ext::TestSize.Level0) { @@ -203,7 +191,6 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_201, testing::ext::TestSize.L /** * @tc.name: StopAdvertising_202 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_202, testing::ext::TestSize.Level0) { @@ -217,7 +204,6 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_202, testing::ext::TestSize.L /** * @tc.name: BindTarget_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0) { @@ -233,7 +219,6 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 /** * @tc.name: BindTarget_202 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, BindTarget_202, testing::ext::TestSize.Level0) { @@ -249,7 +234,6 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_202, testing::ext::TestSize.Level0 /** * @tc.name: UnbindTarget_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, UnbindTarget_201, testing::ext::TestSize.Level0) { @@ -266,7 +250,6 @@ HWTEST_F(DeviceManagerServiceTest, UnbindTarget_201, testing::ext::TestSize.Leve /** * @tc.name: RegisterPinHolderCallback_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext::TestSize.Level0) { @@ -278,7 +261,6 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext:: /** * @tc.name: CreatePinHolder_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.Level0) { @@ -290,7 +272,6 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.L /** * @tc.name: GetDeviceSecurityLevel_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_201, testing::ext::TestSize.Level0) { @@ -305,7 +286,6 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_201, testing::ext::Tes /** * @tc.name: CheckAccessControl_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSize.Level0) { @@ -318,7 +298,6 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz /** * @tc.name: CheckAccessControl_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSize.Level0) { @@ -332,7 +311,6 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSiz /** * @tc.name: CheckIsSameAccount_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSize.Level0) { @@ -345,7 +323,6 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz /** * @tc.name: CheckIsSameAccount_202 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSize.Level0) { @@ -359,7 +336,6 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSiz /** * @tc.name: InitAccountInfo_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.Level0) { @@ -375,7 +351,6 @@ HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.L /** * @tc.name: InitScreenLockEvent_001 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, InitScreenLockEvent_201, testing::ext::TestSize.Level0) { @@ -386,7 +361,6 @@ HWTEST_F(DeviceManagerServiceTest, InitScreenLockEvent_201, testing::ext::TestSi /** * @tc.name: SubscribeAccountCommonEvent_201 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_201, testing::ext::TestSize.Level0) { -- Gitee From 30f2696bf560b648839b99426d66bd5542264d42 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 3 Aug 2024 17:16:07 +0800 Subject: [PATCH 012/520] =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=B6=85=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../native_cpp/src/ipc/standard/ipc_client_manager.cpp | 3 +-- services/service/src/device_manager_service.cpp | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 111132e2a..0d9b7264a 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -145,9 +145,8 @@ int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr r if (req == nullptr || rsp == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } - LOGI("IpcClientManager::SendRequest in"); if (dmInterface_ != nullptr) { - LOGI("IpcClientManager::SendRequest cmdCode: %{public}d", cmdCode); + LOGD("IpcClientManager::SendRequest cmdCode: %{public}d", cmdCode); return dmInterface_->SendCmd(cmdCode, req, rsp); } else { LOGE("dmInterface_ is not init."); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 6cfec1869..4863e48a9 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -278,7 +278,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std::string &callerId, bool isRefresh, bool isWakeUp) { - LOGI("DeviceManagerService::ShiftLNNGear begin for pkgName = %{public}s, callerId = %{public}s, isRefresh =" + LOGD("DeviceManagerService::ShiftLNNGear begin for pkgName = %{public}s, callerId = %{public}s, isRefresh =" "%{public}d, isWakeUp = %{public}d", pkgName.c_str(), GetAnonyString(callerId).c_str(), isRefresh, isWakeUp); if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call ShiftLNNGear, pkgName = %{public}s", pkgName.c_str()); -- Gitee From 2d7048286b5f5f8989338128f0a08ec495e2ff21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 17:23:48 +0800 Subject: [PATCH 013/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/softbusunittest/UTTest_softbus_listener.cpp | 2 -- test/unittest/UTTest_device_manager_service_listener.cpp | 2 -- test/unittest/UTTest_device_manager_service_two.cpp | 2 +- 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 342c3cfc1..978b6ad4d 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -104,9 +104,7 @@ HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_001, testing::ext::TestSize. /** * @tc.name: OnSoftbusDeviceOnline_002 - * @tc.desc: return true * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_002, testing::ext::TestSize.Level0) { diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index f944ea80b..fd0236720 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -445,7 +445,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSi /** * @tc.name: GetDeviceId_002 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_002, testing::ext::TestSize.Level0) { @@ -461,7 +460,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_002, testing::ext::TestSi /** * @tc.name: GetDeviceId_003 * @tc.type: FUNC - * @tc.require: AR000GHSJK */ HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_003, testing::ext::TestSize.Level0) { diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 12100fbe0..0998987e7 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From b4eb0c2cbc49a9522dbf5b5490e749bcc8c96864 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 17:32:59 +0800 Subject: [PATCH 014/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_service_two.cpp | 77 ++----------------- 1 file changed, 8 insertions(+), 69 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 0998987e7..15daf90cd 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -51,17 +51,6 @@ void DeletePermission() OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } -/** - * @tc.name: InitSoftbusListener_001 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, InitSoftbusListener_201, testing::ext::TestSize.Level0) -{ - DeviceManagerService::GetInstance().softbusListener_ = nullptr; - int32_t ret = DeviceManagerService::GetInstance().InitSoftbusListener(); - EXPECT_EQ(ret, DM_OK); -} - /** * @tc.name: RegisterDeviceManagerListener_001 * @tc.type: FUNC @@ -99,17 +88,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Lev DmDeviceInfo deviceIndo; int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, deviceIndo); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - -/** - * @tc.name: GetLocalDeviceInfo_201 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_201, testing::ext::TestSize.Level0) -{ - DeletePermission(); - DmDeviceInfo deviceIndo; - int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(deviceIndo); + ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(deviceIndo); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } @@ -186,18 +165,9 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_201, testing::ext::TestSize.L advertiseParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: StopAdvertising_202 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, StopAdvertising_202, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::map advertiseParam; + std::map advertiseParam2; advertiseParam[PARAM_KEY_PUBLISH_ID] = "12"; - int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam2); EXPECT_EQ(ret, DM_OK); } @@ -214,20 +184,9 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 bindParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: BindTarget_202 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, BindTarget_202, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - PeerTargetId targetId; targetId.wifiIp = "192.168.1.1"; - targetId.deviceId = "123"; - std::map bindParam; - int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + std::map bindParam2; + ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam2); EXPECT_EQ(ret, DM_OK); } @@ -243,7 +202,7 @@ HWTEST_F(DeviceManagerServiceTest, UnbindTarget_201, testing::ext::TestSize.Leve targetId.deviceId = "123"; std::map unbindParam; unbindParam[PARAM_KEY_META_TYPE] = "1"; - int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, bindParam); + int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); EXPECT_EQ(ret, DM_OK); } @@ -293,18 +252,8 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_EQ(ret, true); -} - -/** - * @tc.name: CheckAccessControl_001 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSize.Level0) -{ DeletePermission(); - DmAccessCaller caller; - DmAccessCallee callee; - bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_EQ(ret, false); } @@ -318,18 +267,8 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); EXPECT_EQ(ret, true); -} - -/** - * @tc.name: CheckIsSameAccount_202 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSize.Level0) -{ DeletePermission(); - DmAccessCaller caller; - DmAccessCallee callee; - bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); EXPECT_EQ(ret, false); } -- Gitee From e6ecebb8d52b51f9dd50402e050d00e0256d1cae Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 3 Aug 2024 17:33:43 +0800 Subject: [PATCH 015/520] =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=B6=85=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../native_cpp/src/ipc/standard/ipc_client_manager.cpp | 2 +- services/service/src/softbus/softbus_listener.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 0d9b7264a..0cfc31c04 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -57,7 +57,7 @@ int32_t IpcClientManager::ClientInit() return ERR_DM_INIT_FAILED; } - if (dmRecipient_ == nullptr) { + if (dmRecipient_ == nullptr) { dmRecipient_ = sptr(new DmDeathRecipient()); } if (!object->AddDeathRecipient(dmRecipient_)) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 937e8b832..37c5e27a4 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -805,7 +805,7 @@ bool SoftbusListener::IsDmRadarHelperReady() { std::lock_guard lock(g_radarLoadLock); if (isRadarSoLoad_ && (dmRadarHelper_ != nullptr) && (radarHandle_ != nullptr)) { - LOGI("IsDmRadarHelperReady alReady."); + LOGD("IsDmRadarHelperReady alReady."); return true; } char path[PATH_MAX + 1] = {0x00}; -- Gitee From d3ec11ffd72c1faf35f24ee887d4d3b18d4b91f2 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 3 Aug 2024 17:38:07 +0800 Subject: [PATCH 016/520] =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=B6=85=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../native_cpp/src/ipc/standard/ipc_client_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 0cfc31c04..0d9b7264a 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -57,7 +57,7 @@ int32_t IpcClientManager::ClientInit() return ERR_DM_INIT_FAILED; } - if (dmRecipient_ == nullptr) { + if (dmRecipient_ == nullptr) { dmRecipient_ = sptr(new DmDeathRecipient()); } if (!object->AddDeathRecipient(dmRecipient_)) { -- Gitee From 7059a078481a2071f8151cab78472a6062caa7e8 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Sat, 3 Aug 2024 15:11:09 +0800 Subject: [PATCH 017/520] =?UTF-8?q?kill=20softbus=20=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E6=B3=A8=E5=86=8C=E6=80=BB=E7=BA=BF?= =?UTF-8?q?=E7=9A=84callback?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../native_cpp/src/device_manager_impl.cpp | 2 +- .../include/ipc/standard/ipc_server_stub.h | 2 -- .../service/src/device_manager_service.cpp | 20 +++++------ .../src/ipc/standard/ipc_server_stub.cpp | 36 +++++-------------- 4 files changed, 18 insertions(+), 42 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 422717894..d2cbff68d 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -126,7 +126,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh int32_t retryNum = 0; while (retryNum < SERVICE_INIT_TRY_MAX_NUM) { ret = ipcClientProxy_->Init(pkgName); - if (ret != ERR_DM_NOT_INIT) { + if (ret == DM_OK) { break; } usleep(SLEEP_TIME_MS); diff --git a/services/service/include/ipc/standard/ipc_server_stub.h b/services/service/include/ipc/standard/ipc_server_stub.h index d5390706f..77a83b211 100644 --- a/services/service/include/ipc/standard/ipc_server_stub.h +++ b/services/service/include/ipc/standard/ipc_server_stub.h @@ -160,8 +160,6 @@ private: mutable std::mutex listenerLock_; std::map> appRecipient_; std::map> dmListener_; - std::mutex dependsSASetLock_; - std::unordered_set dependsSASet_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 6cfec1869..a01419d6d 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -128,15 +128,9 @@ void DeviceManagerService::QueryDependsSwitchState() { LOGI("DeviceManagerService::QueryDependsSwitchState start."); std::shared_ptr publishSubScriber = publshCommonEventManager_->GetSubscriber(); - if (publishSubScriber == nullptr) { - LOGE("publishSubScriber is nullptr."); - return; - } + CHECK_NULL_VOID(publishSubScriber); auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr == nullptr) { - LOGE("Get SystemAbilityManager Failed"); - return; - } + CHECK_NULL_VOID(samgr); #ifdef SUPPORT_BLUETOOTH if (samgr->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID) == nullptr) { publishSubScriber->SetBluetoothState(static_cast(Bluetooth::BTStateID::STATE_TURN_OFF)); @@ -164,10 +158,14 @@ void DeviceManagerService::QueryDependsSwitchState() #endif // SUPPORT_WIFI #ifdef SUPPORT_POWER_MANAGER - if (OHOS::PowerMgr::PowerMgrClient::GetInstance().IsScreenOn()) { - publishSubScriber->SetScreenState(DM_SCREEN_ON); - } else { + if (samgr->CheckSystemAbility(POWER_MANAGER_SERVICE_ID) == nullptr) { publishSubScriber->SetScreenState(DM_SCREEN_OFF); + } else { + if (OHOS::PowerMgr::PowerMgrClient::GetInstance().IsScreenOn()) { + publishSubScriber->SetScreenState(DM_SCREEN_ON); + } else { + publishSubScriber->SetScreenState(DM_SCREEN_OFF); + } } #else publishSubScriber->SetScreenState(DM_SCREEN_ON); diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 548ca3dc9..95c8d13d3 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -57,42 +57,22 @@ void IpcServerStub::OnStart() AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN); AddSystemAbilityListener(SCREENLOCK_SERVICE_ID); - - { - std::lock_guard lock(dependsSASetLock_); - dependsSASet_.emplace(SOFTBUS_SERVER_SA_ID); -#ifdef SUPPORT_POWER_MANAGER - dependsSASet_.emplace(POWER_MANAGER_SERVICE_ID); // power -#endif // SUPPORT_POWER_MANAGER - } - AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID); -#ifdef SUPPORT_POWER_MANAGER - AddSystemAbilityListener(POWER_MANAGER_SERVICE_ID); // power -#endif // SUPPORT_POWER_MANAGER LOGI("called:AddAbilityListener end!"); } void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) { LOGI("OnAddSystemAbility systemAbilityId:%{public}d added!", systemAbilityId); - { - std::lock_guard lock(dependsSASetLock_); - if (dependsSASet_.find(systemAbilityId) != dependsSASet_.end()) { - dependsSASet_.erase(systemAbilityId); - if (dependsSASet_.empty()) { - DeviceManagerService::GetInstance().InitSoftbusListener(); - if (!Init()) { - LOGE("failed to init IpcServerStub"); - state_ = ServiceRunningState::STATE_NOT_START; - return; - } - state_ = ServiceRunningState::STATE_RUNNING; - } + if (systemAbilityId == SOFTBUS_SERVER_SA_ID) { + DeviceManagerService::GetInstance().InitSoftbusListener(); + if (!Init()) { + LOGE("failed to init IpcServerStub"); + state_ = ServiceRunningState::STATE_NOT_START; + return; } - } - - if (systemAbilityId == MEMORY_MANAGER_SA_ID) { + state_ = ServiceRunningState::STATE_RUNNING; + } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) { int pid = getpid(); Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 1, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); } else if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { -- Gitee From 888ccd86e5c2b2aa588514924072fc88f1949fef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 18:53:41 +0800 Subject: [PATCH 018/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_notify_three.cpp | 24 +++++++++---------- .../UTTest_device_manager_service_two.cpp | 11 +++++---- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/test/unittest/UTTest_device_manager_notify_three.cpp b/test/unittest/UTTest_device_manager_notify_three.cpp index fab5cb1f7..820700d7b 100644 --- a/test/unittest/UTTest_device_manager_notify_three.cpp +++ b/test/unittest/UTTest_device_manager_notify_three.cpp @@ -943,12 +943,12 @@ HWTEST_F(DeviceManagerNotifyTest, OnDeviceFound7, testing::ext::TestSize.Level0) * @tc.name: RegisterCredentialCallback_301 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_301, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerNotifyTest, RegisterCredentialCallback_301, testing::ext::TestSize.Level0) { std::string pkgName; std::shared_ptr callback = std::make_shared(); DeviceManagerNotify::GetInstance().credentialCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); DeviceManagerNotify::GetInstance().UnRegisterCredentialCallback(pkgName); EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); } @@ -957,12 +957,12 @@ HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_301, testing::ext: * @tc.name: RegisterCredentialCallback_302 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_302, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerNotifyTest, RegisterCredentialCallback_302, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; std::shared_ptr callback = nullptr; DeviceManagerNotify::GetInstance().credentialCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); } @@ -970,12 +970,12 @@ HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_302, testing::ext: * @tc.name: RegisterCredentialCallback_303 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_303, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerNotifyTest, RegisterCredentialCallback_303, testing::ext::TestSize.Level0) { std::string pkgName; std::shared_ptr callback = nullptr; DeviceManagerNotify::GetInstance().credentialCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); EXPECT_EQ(DeviceManagerNotify::GetInstance().credentialCallback_.empty(), true); } @@ -983,12 +983,12 @@ HWTEST_F(DeviceManagerServiceTest, RegisterCredentialCallback_303, testing::ext: * @tc.name: RegisterPinHolderCallback_301 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_301, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerNotifyTest, RegisterPinHolderCallback_301, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; std::shared_ptr callback = nullptr; DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); } @@ -996,12 +996,12 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_301, testing::ext:: * @tc.name: RegisterPinHolderCallback_302 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_302, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerNotifyTest, RegisterPinHolderCallback_302, testing::ext::TestSize.Level0) { std::string pkgName; std::shared_ptr callback = nullptr; DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); } @@ -1009,12 +1009,12 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_302, testing::ext:: * @tc.name: RegisterPinHolderCallback_303 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_303, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerNotifyTest, RegisterPinHolderCallback_303, testing::ext::TestSize.Level0) { std::string pkgName; std::shared_ptr callback = std::make_shared(); DeviceManagerNotify::GetInstance().pinHolderCallback_.clear(); - int32_t ret = DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterPinHolderCallback(pkgName, callback); EXPECT_EQ(DeviceManagerNotify::GetInstance().pinHolderCallback_.empty(), true); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 15daf90cd..9d1df7b71 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -224,7 +224,10 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext:: HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.Level0) { std::string pkgName = "CollaborationFwk"; - int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName); + PeerTargetId targetId; + DmPinType pinType; + std::string payload; + int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, DM_OK); } @@ -279,9 +282,9 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.Level0) { int32_t userId = 100; - std::string commonEventType = CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + std::string commonEventType = "usual.event.USER_SWITCHED"; DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); - std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; + commonEventType = "common.event.HWID_LOGIN"; DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); EXPECT_EQ(ret, DM_OK); @@ -305,7 +308,7 @@ HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_201, testing::ext { DeviceManagerService::GetInstance().SubscribeAccountCommonEvent(); DeviceManagerService::GetInstance().SubscribeScreenLockEvent(); - std::string commonEventType = CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + std::string commonEventType = "usual.event.USER_SWITCHED"; DeviceManagerService::GetInstance().ScreenCommonEventCallback(commonEventType); EXPECT_NE(DeviceManagerService::GetInstance().accountCommonEventManager_, nullptr); } -- Gitee From 19395410f4b619aa5374cabd8f08d5708a4921ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 19:44:23 +0800 Subject: [PATCH 019/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_service_two.cpp | 47 +++++++++++++------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 9d1df7b71..f2de2586d 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -27,7 +27,6 @@ using namespace OHOS::Security::AccessToken; namespace OHOS { namespace DistributedHardware { -DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); namespace { void DeletePermission() { @@ -74,7 +73,7 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestS const std::string extra; std::vector deviceList; int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } /** @@ -89,7 +88,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Lev int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, deviceIndo); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(deviceIndo); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } /** @@ -164,11 +163,11 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_201, testing::ext::TestSize.L std::map advertiseParam; advertiseParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); std::map advertiseParam2; advertiseParam[PARAM_KEY_PUBLISH_ID] = "12"; ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam2); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } /** @@ -183,11 +182,11 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 std::map bindParam; bindParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_START_ADVERTISING_FAILED); targetId.wifiIp = "192.168.1.1"; std::map bindParam2; ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam2); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_START_ADVERTISING_FAILED); } /** @@ -203,7 +202,7 @@ HWTEST_F(DeviceManagerServiceTest, UnbindTarget_201, testing::ext::TestSize.Leve std::map unbindParam; unbindParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_START_ADVERTISING_FAILED); } /** @@ -214,7 +213,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext:: { std::string pkgName = "CollaborationFwk"; int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** @@ -225,10 +224,10 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.L { std::string pkgName = "CollaborationFwk"; PeerTargetId targetId; - DmPinType pinType; + DmPinType pinType = NUMBER_PIN_CODE; std::string payload; int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** @@ -242,7 +241,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_201, testing::ext::Tes int32_t securityLevel; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, networkId, securityLevel); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); } /** @@ -255,8 +254,18 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_EQ(ret, true); +} + +/** + * @tc.name: CheckAccessControl_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; DeletePermission(); - ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_EQ(ret, false); } @@ -270,8 +279,18 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); EXPECT_EQ(ret, true); +} + +/** + * @tc.name: CheckIsSameAccount_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; DeletePermission(); - ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); EXPECT_EQ(ret, false); } -- Gitee From 3c728c1da6d70747e726b18930e41ace65bb8ad5 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 3 Aug 2024 18:37:32 +0800 Subject: [PATCH 020/520] add ffrt Signed-off-by: gaoqiang_strong --- services/implementation/BUILD.gn | 1 + .../ability/standard/dm_dialog_manager.cpp | 11 +++++ services/service/BUILD.gn | 1 + .../dm_account_common_event.cpp | 7 ++++ .../dm_publish_common_event.cpp | 7 ++++ .../dm_screen_common_event.cpp | 7 ++++ .../service/src/softbus/softbus_listener.cpp | 19 +++++++++ test/unittest/BUILD.gn | 3 ++ utils/BUILD.gn | 3 ++ .../include/threadManager/dm_thread_manager.h | 34 +++++++++++++++ utils/src/threadManager/dm_thread_manager.cpp | 41 +++++++++++++++++++ 11 files changed, 134 insertions(+) create mode 100644 utils/include/threadManager/dm_thread_manager.h create mode 100644 utils/src/threadManager/dm_thread_manager.cpp diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 7fde85621..1cc59a5c7 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -212,6 +212,7 @@ if (defined(ohos_lite)) { "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_core", diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 54fdd0d0b..80750f4a2 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -26,6 +26,9 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "dm_single_instance.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_thread_manager.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -111,12 +114,20 @@ void DmDialogManager::ShowPinDialog(const std::string param) bundleName_ = DM_UI_BUNDLE_NAME; abilityName_ = PIN_ABILITY_NAME; pinCode_ = param; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::task_handle handle = ThreadManager::GetInstance().Submit( + CONNECT_PIN_DIALOG.c_str(), []() { ConnectExtension(); }); + if (handle != nullptr) { + ThreadManager::GetInstance().Wait(handle); + } +#else std::thread pinDilog([]() { ConnectExtension(); }); int32_t ret = pthread_setname_np(pinDilog.native_handle(), CONNECT_PIN_DIALOG.c_str()); if (ret != DM_OK) { LOGE("pinDilog setname failed."); } pinDilog.detach(); +#endif } void DmDialogManager::ShowInputDialog(const std::string param) diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index f05823c4c..da48237a9 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -199,6 +199,7 @@ if (defined(ohos_lite)) { "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "eventhandler:libeventhandler", + "ffrt:libffrt", "hicollie:libhicollie", "hilog:libhilog", "init:libbeget_proxy", diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 3e97a5c24..92d6a317b 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -22,6 +22,9 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_thread_manager.h" +#endif #include "iservice_registry.h" #include "multiple_user_connector.h" #include "system_ability_definition.h" @@ -144,12 +147,16 @@ void DmAccountEventSubscriber::OnReceiveEvent(const CommonEventData &data) LOGE("userId is less zero"); return; } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(userId, receiveEvent); }); +#else std::thread dealThread([=]() { callback_(userId, receiveEvent); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); } dealThread.detach(); +#endif } void DmAccountCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( diff --git a/services/service/src/publishcommonevent/dm_publish_common_event.cpp b/services/service/src/publishcommonevent/dm_publish_common_event.cpp index 85e6009a2..859f53a7c 100644 --- a/services/service/src/publishcommonevent/dm_publish_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_publish_common_event.cpp @@ -27,6 +27,9 @@ #include "wifi_msg.h" #endif // SUPPORT_WIFI #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_thread_manager.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -232,12 +235,16 @@ void DmPublishEventSubscriber::OnReceiveEvent(const CommonEventData &data) } #endif // SUPPORT_WIFI +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(bluetoothState_, wifiState_, screenState_); }); +#else std::thread dealThread([=]() { callback_(bluetoothState_, wifiState_, screenState_); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); } dealThread.detach(); +#endif } void DmPublishCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( diff --git a/services/service/src/publishcommonevent/dm_screen_common_event.cpp b/services/service/src/publishcommonevent/dm_screen_common_event.cpp index d683d8761..fa7867242 100644 --- a/services/service/src/publishcommonevent/dm_screen_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_screen_common_event.cpp @@ -22,6 +22,9 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_thread_manager.h" +#endif #include "iservice_registry.h" #include "multiple_user_connector.h" #include "system_ability_definition.h" @@ -135,12 +138,16 @@ void DmScreenEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { return; } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(receiveEvent); }); +#else std::thread dealThread(callback_, receiveEvent); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); } dealThread.detach(); +#endif } void DmScreenCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 937e8b832..2995530cf 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -29,6 +29,9 @@ #include "dm_device_info.h" #include "dm_log.h" #include "dm_softbus_cache.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_thread_manager.h" +#endif #include "parameter.h" #include "system_ability_definition.h" #include "softbus_adapter.cpp" @@ -168,12 +171,16 @@ void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) std::lock_guard lock(g_onlineDeviceNumLock); g_onlinDeviceNum++; } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEVICE_ONLINE, [=]() { DeviceOnLine(dmDeviceInfo); }); +#else std::thread deviceOnLine([=]() { DeviceOnLine(dmDeviceInfo); }); int32_t ret = pthread_setname_np(deviceOnLine.native_handle(), DEVICE_ONLINE); if (ret != DM_OK) { LOGE("deviceOnLine setname failed."); } deviceOnLine.detach(); +#endif { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); @@ -215,12 +222,16 @@ void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info) } } LOGI("device offline networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str()); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEVICE_OFFLINE, [=]() { DeviceOffLine(dmDeviceInfo); }); +#else std::thread deviceOffLine([=]() { DeviceOffLine(dmDeviceInfo); }); int32_t ret = pthread_setname_np(deviceOffLine.native_handle(), DEVICE_OFFLINE); if (ret != DM_OK) { LOGE("deviceOffLine setname failed."); } deviceOffLine.detach(); +#endif { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); @@ -265,11 +276,15 @@ void SoftbusListener::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBas LOGI("device changed networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str()); dmDeviceInfo.networkType = networkType; SoftbusCache::GetInstance().ChangeDeviceInfo(dmDeviceInfo); + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEVICE_NAME_CHANGE, [=]() { DeviceNameChange(dmDeviceInfo); }); + #else std::thread deviceInfoChange([=]() { DeviceNameChange(dmDeviceInfo); }); if (pthread_setname_np(deviceInfoChange.native_handle(), DEVICE_NAME_CHANGE) != DM_OK) { LOGE("DeviceNameChange setname failed."); } deviceInfoChange.detach(); + #endif } } @@ -288,12 +303,16 @@ void SoftbusListener::OnDeviceNotTrusted(const char *msg) return; } std::string softbusMsg = std::string(msg); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEVICE_NOT_TRUST, [=]() { DeviceNotTrust(softbusMsg); }); +#else std::thread deviceNotTrust([=]() { DeviceNotTrust(softbusMsg); }); int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); if (ret != DM_OK) { LOGE("deviceNotTrust setname failed."); } deviceNotTrust.detach(); +#endif } void SoftbusListener::OnSoftbusDeviceFound(const DeviceInfo *device) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 2e2170508..0967feabe 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -455,6 +455,7 @@ ohos_unittest("UTTest_softbus_listener") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -1101,6 +1102,7 @@ ohos_unittest("UTTest_dm_publish_manager") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "hitrace:hitrace_meter", ] @@ -1212,6 +1214,7 @@ ohos_static_library("device_manager_test_common") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", + "ffrt:libffrt", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 433c613c5..da08bdd68 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -73,6 +73,7 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "include/crypto", + "include/threadManager", "include/fwkload/standard", "include/appInfo/standard", "include/timer", @@ -97,6 +98,7 @@ if (defined(ohos_lite)) { "src/appInfo/standard/app_manager.cpp", "src/crypto/dm_crypto.cpp", "src/dm_random.cpp", + "src/threadManager/dm_thread_manager.cpp", "src/timer/dm_timer.cpp", ] @@ -118,6 +120,7 @@ if (defined(ohos_lite)) { "bundle_framework:appexecfwk_core", "c_utils:utils", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "ipc:ipc_core", "ipc:ipc_single", diff --git a/utils/include/threadManager/dm_thread_manager.h b/utils/include/threadManager/dm_thread_manager.h new file mode 100644 index 000000000..a99f2b284 --- /dev/null +++ b/utils/include/threadManager/dm_thread_manager.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_THREAD_MANAGER_H +#define OHOS_DM_THREAD_MANAGER_H + +#include "dm_single_instance.h" +#include "ffrt.h" + +namespace OHOS { +namespace DistributedHardware { +class ThreadManager { + DM_DECLARE_SINGLE_INSTANCE(ThreadManager); +public: + ffrt::task_handle Submit(const char* threadName, const std::function& threadFunc); + void Wait(const ffrt::task_handle& handle); +private: + std::shared_ptr ffrtQueue_ = nullptr; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_THREAD_MANAGER_H diff --git a/utils/src/threadManager/dm_thread_manager.cpp b/utils/src/threadManager/dm_thread_manager.cpp new file mode 100644 index 000000000..08036592b --- /dev/null +++ b/utils/src/threadManager/dm_thread_manager.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_thread_manager.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(ThreadManager); +constexpr const char* DEVICE_MANAGER_THREAD_QUEUE = "device_manager_thread_queue"; +ffrt::task_handle ThreadManager::Submit(const char* threadName, const std::function& threadFunc) +{ + if (ffrtQueue_ == nullptr) { + ffrtQueue_ = std::make_shared(DEVICE_MANAGER_THREAD_QUEUE, + ffrt::queue_attr().qos(ffrt::qos_default)); + } + return ffrtQueue_->submit_h(threadFunc, ffrt::task_attr().name(threadName)); +} + +void ThreadManager::Wait(const ffrt::task_handle& handle) +{ + if (ffrtQueue_ != nullptr) { + LOGE("ThreadManager Wait, ffrtQueue is null."); + return; + } + ffrtQueue_->wait(handle); +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From 2095885f91fcffe5390d0bbd28f14f28e7641a5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 19:58:50 +0800 Subject: [PATCH 021/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_service_two.cpp | 28 +++++-------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index f2de2586d..2f179581a 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -139,20 +139,6 @@ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize. EXPECT_EQ(ret, true); } -/** - * @tc.name: GetEncryptedUuidByNetworkId_001 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_201, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::string networkId = "123"; - std::string uuid; - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); - EXPECT_EQ(ret, ERR_DM_FAILED); -} - /** * @tc.name: StopAdvertising_201 * @tc.type: FUNC @@ -182,11 +168,11 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 std::map bindParam; bindParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); - EXPECT_EQ(ret, ERR_DM_START_ADVERTISING_FAILED); + EXPECT_EQ(ret, ERR_DM_LOAD_CUSTOM_META_NODE); targetId.wifiIp = "192.168.1.1"; std::map bindParam2; ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam2); - EXPECT_EQ(ret, ERR_DM_START_ADVERTISING_FAILED); + EXPECT_EQ(ret, ERR_DM_LOAD_CUSTOM_META_NODE); } /** @@ -202,7 +188,7 @@ HWTEST_F(DeviceManagerServiceTest, UnbindTarget_201, testing::ext::TestSize.Leve std::map unbindParam; unbindParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); - EXPECT_EQ(ret, ERR_DM_START_ADVERTISING_FAILED); + EXPECT_EQ(ret, ERR_DM_LOAD_CUSTOM_META_NODE); } /** @@ -266,7 +252,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSiz DmAccessCallee callee; DeletePermission(); bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); - EXPECT_EQ(ret, false); + EXPECT_EQ(ret, true); } /** @@ -282,16 +268,16 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz } /** - * @tc.name: CheckIsSameAccount_201 + * @tc.name: CheckIsSameAccount_202 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSize.Level0) { DmAccessCaller caller; DmAccessCallee callee; DeletePermission(); bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); - EXPECT_EQ(ret, false); + EXPECT_EQ(ret, true); } /** -- Gitee From fe2be09269b67566c55e98dbd4c66baef9c94804 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 3 Aug 2024 20:15:01 +0800 Subject: [PATCH 022/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_service_two.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 2f179581a..73f059e6d 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -172,7 +172,7 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 targetId.wifiIp = "192.168.1.1"; std::map bindParam2; ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam2); - EXPECT_EQ(ret, ERR_DM_LOAD_CUSTOM_META_NODE); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** -- Gitee From fda34790f92ff31ba862cd54ac29ab4c22c8126d Mon Sep 17 00:00:00 2001 From: q30043944 Date: Sun, 4 Aug 2024 09:09:46 +0800 Subject: [PATCH 023/520] =?UTF-8?q?ut=E5=A4=B1=E8=B4=A5=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- test/commonunittest/UTTest_dm_publish_manager.cpp | 2 +- test/unittest/UTTest_device_manager_impl.cpp | 7 +++---- test/unittest/UTTest_ipc_server_stub.cpp | 3 ++- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/commonunittest/UTTest_dm_publish_manager.cpp b/test/commonunittest/UTTest_dm_publish_manager.cpp index 1eef1fff1..fb1ba8042 100644 --- a/test/commonunittest/UTTest_dm_publish_manager.cpp +++ b/test/commonunittest/UTTest_dm_publish_manager.cpp @@ -111,7 +111,7 @@ HWTEST_F(DmPublishManagerTest, PublishDeviceDiscovery_002, testing::ext::TestSiz publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); pkgName = "com.ohos.helloworld.new"; int32_t ret = publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); - ASSERT_EQ(ret, SOFTBUS_INVALID_PARAM); + ASSERT_EQ(ret, SOFTBUS_IPC_ERR); publishMgr_->UnPublishDeviceDiscovery(pkgName, publishInfo.publishId); } diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index aa8c42032..f94115f1c 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -1150,11 +1150,10 @@ HWTEST_F(DeviceManagerImplTest, InitDeviceManager_003, testing::ext::TestSize.Le std::shared_ptr mockInstance = std::make_shared(); std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, Init(testing::_)).Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::InitDeviceManager with parameter int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); - // 4. check ret is ERR_DM_INIT_FAILED - ASSERT_EQ(ret, ERR_DM_INIT_FAILED); + // 4. check ret is DM_OK + ASSERT_EQ(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -2036,7 +2035,7 @@ HWTEST_F(DeviceManagerImplTest, IsSameAccount_001, testing::ext::TestSize.Level0 HWTEST_F(DeviceManagerImplTest, IsSameAccount_002, testing::ext::TestSize.Level0) { std::string udid = "udidTest"; - std::string pkgName = "com.ohos.test"; + std::string pkgName = "com.ohos.sameaccounttest"; std::shared_ptr initCallback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(pkgName, initCallback); bool ret = DeviceManager::GetInstance().IsSameAccount(udid); diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp index 587d3dc85..d33ce8f8a 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -569,7 +569,8 @@ HWTEST_F(IpcServerStubTest, OnAddSystemAbility_001, testing::ext::TestSize.Level int32_t systemAbilityId = SOFTBUS_SERVER_SA_ID; std::string deviceId; IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); - ASSERT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + ASSERT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + IpcServerStub::GetInstance().OnRemoveSystemAbility(systemAbilityId, deviceId); } /** -- Gitee From 9697318341593505bca788e0a20139d0bcb41e51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 5 Aug 2024 09:06:33 +0800 Subject: [PATCH 024/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9codecheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_notify.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_notify.h b/test/unittest/UTTest_device_manager_notify.h index 0db841585..ed1413bee 100644 --- a/test/unittest/UTTest_device_manager_notify.h +++ b/test/unittest/UTTest_device_manager_notify.h @@ -111,7 +111,7 @@ public: void OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) override {} }; -class PinHolderCallbackTest: public PinHolderCallback { +class PinHolderCallbackTest : public PinHolderCallback { public: void OnPinHolderCreate(const std::string &deviceId, DmPinType pinType, const std::string &payload) {} void OnPinHolderDestroy(DmPinType pinType, const std::string &payload) {} -- Gitee From 6a864658880d53e5475a96a21a7c1ef3f4af0354 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=98=BF=E5=AE=85?= Date: Mon, 5 Aug 2024 04:04:06 +0000 Subject: [PATCH 025/520] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9EtokenID?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E6=9D=83=E9=99=90=20=E6=96=B0=E5=A2=9EtokenI?= =?UTF-8?q?D=E8=AE=BE=E7=BD=AE=E6=9D=83=E9=99=90=EF=BC=8C=E4=BC=A0?= =?UTF-8?q?=E9=80=92tokenID=E7=BB=99=E6=80=BB=E7=BA=BF=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 小阿宅 --- sa_profile/device_manager.cfg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sa_profile/device_manager.cfg b/sa_profile/device_manager.cfg index d69548366..ef994d6c8 100644 --- a/sa_profile/device_manager.cfg +++ b/sa_profile/device_manager.cfg @@ -3,7 +3,7 @@ "name" : "device_manager", "path" : ["/system/bin/sa_main", "/system/profile/device_manager.json"], "uid" : "device_manager", - "gid" : ["device_manager"], + "gid" : ["device_manager", "access_token"], "start-mode" : "boot", "apl" : "system_basic", "permission" : [ -- Gitee From 642c032a529f469d2e0e2ba3ffef955e48022c60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 5 Aug 2024 15:40:37 +0800 Subject: [PATCH 026/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../service/src/device_manager_service.cpp | 30 ++++--------------- .../src/discovery/discovery_manager.cpp | 7 +---- .../service/src/softbus/softbus_listener.cpp | 7 +---- 3 files changed, 7 insertions(+), 37 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 67db3e107..587ce5805 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -829,12 +829,7 @@ bool DeviceManagerService::IsDMServiceImplReady() if (isImplsoLoaded_ && (dmServiceImpl_ != nullptr)) { return true; } - std::string soName = std::string(LIB_IMPL_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; - } - void *so_handle = dlopen(soName.c_str(), RTLD_NOW | RTLD_NODELETE); + void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { LOGE("load libdevicemanagerserviceimpl so failed, errMsg: %{public}s.", dlerror()); return false; @@ -1062,12 +1057,7 @@ void DeviceManagerService::UnloadDMServiceImplSo() if (dmServiceImpl_ != nullptr) { dmServiceImpl_->Release(); } - std::string soPathName = std::string(LIB_IMPL_NAME); - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { - LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); - return; - } - void *so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("DeviceManagerService so_handle is not nullptr."); dlclose(so_handle); @@ -1082,14 +1072,9 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() return true; } - std::string soName = std::string(LIB_DM_ADAPTER_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; - } - void *so_handle = dlopen(soName.c_str(), RTLD_NOW | RTLD_NODELETE); + void *so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NODELETE); if (so_handle == nullptr) { - LOGE("load dm service adapter so %{public}s failed.", soName.c_str()); + LOGE("load dm service adapter so failed."); return false; } dlerror(); @@ -1122,12 +1107,7 @@ void DeviceManagerService::UnloadDMServiceAdapter() } dmServiceImplExt_ = nullptr; - std::string soPathName = std::string(LIB_DM_ADAPTER_NAME); - if ((soPathName.length() == 0) || (soPathName.length() > PATH_MAX)) { - LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); - return; - } - void *so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NOLOAD); + void *so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NOLOAD); if (so_handle != nullptr) { LOGI("dm service adapter so_handle is not nullptr."); dlclose(so_handle); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 8aea8f8d1..1d7094d39 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -532,12 +532,7 @@ bool DiscoveryManager::IsCommonDependencyReady() if (isSoLoaded_ && dpConnector_ != nullptr && dpConnectorHandle_ != nullptr) { return true; } - std::string soName = std::string(LIB_DM_COMDENPENDENCY_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; - } - dpConnectorHandle_ = dlopen(soName.c_str(), RTLD_NOW | RTLD_NODELETE); + dpConnectorHandle_ = dlopen(LIB_DM_COMDENPENDENCY_NAME, RTLD_NOW | RTLD_NODELETE); if (dpConnectorHandle_ == nullptr) { LOGE("load libdevicemanagerdependency so failed, errMsg: %{public}s.", dlerror()); return false; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 533bb24ab..a73290347 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -808,12 +808,7 @@ bool SoftbusListener::IsDmRadarHelperReady() LOGI("IsDmRadarHelperReady alReady."); return true; } - std::string soName = std::string(LIB_RADAR_NAME); - if ((soName.length() == 0) || (soName.length() > PATH_MAX)) { - LOGE("File %{public}s canonicalization failed.", soName.c_str()); - return false; - } - radarHandle_ = dlopen(soName.c_str(), RTLD_NOW); + radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW); if (radarHandle_ == nullptr) { LOGE("load libdevicemanagerradar so failed."); return false; -- Gitee From 5b9f6208fe88cb9bdde4e57633df1bd0998169c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 5 Aug 2024 17:30:54 +0800 Subject: [PATCH 027/520] ui_crash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../entry/src/main/ets/pages/ConfirmDialog.ets | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/display/entry/src/main/ets/pages/ConfirmDialog.ets b/display/entry/src/main/ets/pages/ConfirmDialog.ets index 2e320c6a2..871ad2f51 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialog.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialog.ets @@ -369,17 +369,22 @@ struct dialogPlusPage { } destruction() { + let session = AppStorage.get('ConfirmSession'); + if (session) { + session.terminateSelf(); + } + } + + aboutToDisappear() { + console.log(TAG + 'aboutToDisappear aboutToDisappear') if (dmClass != null) { try { + dmClass.off('uiStateChange'); dmClass.release(); - dmClass = null; } catch (error) { - console.log('dmClass release failed') + console.log('dmClass release failed'); } - } - let session = AppStorage.get('ConfirmSession'); - if (session) { - session.terminateSelf(); + dmClass = null } } -- Gitee From b6375c753fc5dba0505c8b078c801ad3bee44500 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 5 Aug 2024 17:44:54 +0800 Subject: [PATCH 028/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9ui=20destruction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- display/entry/src/main/ets/pages/ConfirmDialog.ets | 8 -------- 1 file changed, 8 deletions(-) diff --git a/display/entry/src/main/ets/pages/ConfirmDialog.ets b/display/entry/src/main/ets/pages/ConfirmDialog.ets index 871ad2f51..f41867c45 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialog.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialog.ets @@ -139,14 +139,6 @@ struct ConfirmCustomDialog { } destruction() { - if (dmClass != null) { - try { - dmClass.release(); - dmClass = null; - } catch (error) { - console.log('dmClass release failed') - } - } let session = AppStorage.get('ConfirmSession'); if (session) { session.terminateSelf(); -- Gitee From 06a51754a4cdd6a271944cfbd8de7c9cc051d5d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 5 Aug 2024 20:01:47 +0800 Subject: [PATCH 029/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=AC=A6=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- display/entry/src/main/ets/pages/ConfirmDialog.ets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/display/entry/src/main/ets/pages/ConfirmDialog.ets b/display/entry/src/main/ets/pages/ConfirmDialog.ets index f41867c45..796a246d4 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialog.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialog.ets @@ -374,7 +374,7 @@ struct dialogPlusPage { dmClass.off('uiStateChange'); dmClass.release(); } catch (error) { - console.log('dmClass release failed'); + console.log('dmClass release failed') } dmClass = null } -- Gitee From ca6f43724c23e89109faff6d1ec49017bc3c89dd Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 5 Aug 2024 09:15:24 +0800 Subject: [PATCH 030/520] =?UTF-8?q?memmgr=E6=94=B9=E4=B8=BA=E5=BC=B1?= =?UTF-8?q?=E8=80=A6=E5=90=88=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- device_manager.gni | 13 +++++++--- .../src/ipc/standard/ipc_client_manager.cpp | 4 ++-- services/service/BUILD.gn | 6 ++++- .../src/ipc/standard/ipc_server_stub.cpp | 24 ++++++++++++++++--- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/device_manager.gni b/device_manager.gni index f07ffdfda..d4c31fbb5 100644 --- a/device_manager.gni +++ b/device_manager.gni @@ -36,21 +36,21 @@ declare_args() { device_manager_no_interaction_auth = false device_manager_feature_product = "default" - if (!defined(global_parts_info) || + if (defined(global_parts_info) && defined(global_parts_info.account_os_account)) { os_account_part_exists = true } else { os_account_part_exists = false } - if (!defined(global_parts_info) || + if (defined(global_parts_info) && defined(global_parts_info.communication_bluetooth)) { support_bluetooth = true } else { support_bluetooth = false } - if (!defined(global_parts_info) || + if (defined(global_parts_info) && defined(global_parts_info.communication_wifi)) { support_wifi = true } else { @@ -70,4 +70,11 @@ declare_args() { } else { support_screenlock = false } + + if (defined(global_parts_info) && + defined(global_parts_info.resourceschedule_memmgr_override)) { + support_memmgr = true + } else { + support_memmgr = false + } } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 0d9b7264a..61b9f45f5 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -213,8 +213,8 @@ void IpcClientManager::SystemAbilityListener::OnAddSystemAbility(int32_t systemA { LOGI("sa %{public}d is added.", systemAbilityId); if (systemAbilityId == DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID) { - std::map> dmInitCallback - = DeviceManagerNotify::GetInstance().GetDmInitCallback(); + std::map> dmInitCallback = + DeviceManagerNotify::GetInstance().GetDmInitCallback(); if (dmInitCallback.size() == 0) { LOGI("dmInitCallback is empty when ReInit"); return; diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index f05823c4c..731d713a3 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -205,7 +205,6 @@ if (defined(ohos_lite)) { "init:libbegetutil", "ipc:ipc_core", "ipc:ipc_single", - "memmgr:memmgrclient", "openssl:libcrypto_shared", "os_account:libaccountkits", "safwk:system_ability_fwk", @@ -234,6 +233,11 @@ if (defined(ohos_lite)) { external_deps += [ "power_manager:powermgr_client" ] } + if (support_memmgr) { + defines += [ "SUPPORT_MEMMGR" ] + external_deps += [ "memmgr:memmgrclient" ] + } + public_external_deps = [ "json:nlohmann_json_static" ] subsystem_name = "distributedhardware" diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 95c8d13d3..58061195a 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -24,8 +24,10 @@ #include "ipc_skeleton.h" #include "ipc_types.h" #include "iservice_registry.h" +#ifdef SUPPORT_MEMMGR #include "mem_mgr_client.h" #include "mem_mgr_proxy.h" +#endif // SUPPORT_MEMMGR #include "string_ex.h" #include "system_ability_definition.h" @@ -54,7 +56,9 @@ void IpcServerStub::OnStart() LOGI("called:AddAbilityListener begin!"); AddSystemAbilityListener(DISTRIBUTED_HARDWARE_SA_ID); +#ifdef SUPPORT_MEMMGR AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); +#endif // SUPPORT_MEMMGR AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN); AddSystemAbilityListener(SCREENLOCK_SERVICE_ID); AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID); @@ -72,13 +76,25 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; - } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) { + return; + } + +#ifdef SUPPORT_MEMMGR + if (systemAbilityId == MEMORY_MANAGER_SA_ID) { int pid = getpid(); Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 1, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); - } else if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + return; + } +#endif // SUPPORT_MEMMGR + + if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { DeviceManagerService::GetInstance().InitAccountInfo(); - } else if (systemAbilityId == SCREENLOCK_SERVICE_ID) { + return; + } + + if (systemAbilityId == SCREENLOCK_SERVICE_ID) { DeviceManagerService::GetInstance().InitScreenLockEvent(); + return; } } @@ -113,8 +129,10 @@ void IpcServerStub::OnStop() DeviceManagerService::GetInstance().UninitDMServiceListener(); state_ = ServiceRunningState::STATE_NOT_START; registerToService_ = false; +#ifdef SUPPORT_MEMMGR int pid = getpid(); Memory::MemMgrClient::GetInstance().NotifyProcessStatus(pid, 1, 0, DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); +#endif // SUPPORT_MEMMGR LOGI("IpcServerStub::OnStop end."); } -- Gitee From 2d3a96d0a1b17a99b8e674f0b23ddd055cf27086 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 5 Aug 2024 10:54:15 +0800 Subject: [PATCH 031/520] =?UTF-8?q?=E8=BE=93=E5=85=A5=E5=BC=B9=E7=AA=97?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=AF=86=E7=A0=81=E6=A8=A1=E5=BC=8F=20Signed?= =?UTF-8?q?-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- display/AppScope/app.json | 4 ++-- .../main/ets/UIExtAbility/InputUIExtAbility.ets | 3 +++ .../entry/src/main/ets/pages/InputPinDialog.ets | 15 +++++++++++++-- .../src/main/resources/base/element/string.json | 4 ++++ .../src/main/resources/bo_CN/element/string.json | 4 ++++ .../src/main/resources/ug/element/string.json | 4 ++++ .../src/main/resources/zh_CN/element/string.json | 4 ++++ .../src/main/resources/zh_HK/element/string.json | 4 ++++ .../src/main/resources/zh_TW/element/string.json | 4 ++++ 9 files changed, 42 insertions(+), 4 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index e2743b68d..e7217c340 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -4,8 +4,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000016, - "versionName": "1.0.16", + "versionCode": 1000017, + "versionName": "1.0.17", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets index 4c24158c3..15a8081dc 100644 --- a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets @@ -24,6 +24,9 @@ export default class InputUIExtAbility extends UIExtensionAbility { if (want.parameters && want.parameters.targetDeviceName) { AppStorage.setOrCreate('targetDeviceName', want.parameters.targetDeviceName); } + if (want.parameters && want.parameters.model) { + AppStorage.setOrCreate('model', want.parameters.model); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index d261d732a..32e505220 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -26,6 +26,8 @@ const ACTION_DONE_PINCODE_INPUT: number = 5 const MSG_PIN_CODE_ERROR: number = 0 const MSG_CANCEL_PIN_CODE_INPUT: number = 3 const MSG_DOING_AUTH: number = 4 +const MODEL_PIN: string = 'pin'; +const MODEL_PASSWORD: string = 'password'; @CustomDialog struct InputCustomDialog { @@ -36,6 +38,7 @@ struct InputCustomDialog { @State errorTipsVisible: Visibility = Visibility.None; @State heightNum: number = 600; @State targetDeviceName: string = ''; + @State model: string = MODEL_PIN; @State isPC: boolean = false; @State btnColor: ResourceColor = Color.Transparent; listener: mediaquery.MediaQueryListener = mediaquery.matchMediaSync('(orientation: landscape)'); @@ -67,6 +70,10 @@ struct InputCustomDialog { this.targetDeviceName = AppStorage.get('targetDeviceName') as string; console.log('targetDeviceName is ' + this.targetDeviceName); } + if (AppStorage.get('model') != null) { + this.model = AppStorage.get('model') as string; + console.log('model is ' + this.model); + } deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', (err: Error, dm: deviceManager.DeviceManager) => { if (err) { @@ -88,8 +95,12 @@ struct InputCustomDialog { return; } if (msg === MSG_PIN_CODE_ERROR) { - this.isTimes--; - this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); + if (this.model == MODEL_PASSWORD) { + this.errorTips = $r('app.string.dm_password_error'); + } else { + this.isTimes--; + this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); + } this.password = ''; this.errorTipsVisible = Visibility.Visible; this.passwordCircle = ['', '', '', '', '', '']; diff --git a/display/entry/src/main/resources/base/element/string.json b/display/entry/src/main/resources/base/element/string.json index fdcc8bdf1..2aaa625a4 100644 --- a/display/entry/src/main/resources/base/element/string.json +++ b/display/entry/src/main/resources/base/element/string.json @@ -79,6 +79,10 @@ { "name":"dm_enter_peer_connect_code", "value":"Enter the peer connection code" + }, + { + "name":"dm_password_error", + "value":"Incorrect password. Connection failed." } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/bo_CN/element/string.json b/display/entry/src/main/resources/bo_CN/element/string.json index 172322a68..56d4566e0 100644 --- a/display/entry/src/main/resources/bo_CN/element/string.json +++ b/display/entry/src/main/resources/bo_CN/element/string.json @@ -55,6 +55,10 @@ { "name":"dm_bluetooth_dialog_content", "value":"སྒྲིག་ཆས་སྦྲེལ་མཐུད་བྱ་བར་སོ་སྔོན་ཁ་འབྱེད་དགོས། ཁ་ཕྱེ་ནས་ཡང་བསྐྱར་ཚོད་ལྟ་གནང་རོགས།" + }, + { + "name":"dm_password_error", + "value":"གསང་གྲངས་ནོར་འཁྲུལ་བྱུང་། སྦྲེལ་མཐུད་བྱེད་མ་ཐུབ།" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/ug/element/string.json b/display/entry/src/main/resources/ug/element/string.json index bef55b20e..9ad7fa3fa 100644 --- a/display/entry/src/main/resources/ug/element/string.json +++ b/display/entry/src/main/resources/ug/element/string.json @@ -55,6 +55,10 @@ { "name":"dm_bluetooth_dialog_content", "value":"ئۈسكۈنە ئۇلاش ئۈچۈن كۆكچىشنى ئېچىش كېرەك، ئېچىپ قايتا سىناڭ." + }, + { + "name":"dm_password_error", + "value":"مەخپىي نومۇر خاتا، ئۇلانمىدى." } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_CN/element/string.json b/display/entry/src/main/resources/zh_CN/element/string.json index cde7f2102..e4e630fb1 100644 --- a/display/entry/src/main/resources/zh_CN/element/string.json +++ b/display/entry/src/main/resources/zh_CN/element/string.json @@ -79,6 +79,10 @@ { "name":"dm_enter_peer_connect_code", "value":"输入对端连接码" + }, + { + "name":"dm_password_error", + "value":"密码错误,连接失败。" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_HK/element/string.json b/display/entry/src/main/resources/zh_HK/element/string.json index 52c71bd58..a2e76aadf 100644 --- a/display/entry/src/main/resources/zh_HK/element/string.json +++ b/display/entry/src/main/resources/zh_HK/element/string.json @@ -55,6 +55,10 @@ { "name":"dm_bluetooth_dialog_content", "value":"裝置連接需要啟用藍牙。請先啟用,然後重試。" + }, + { + "name":"dm_password_error", + "value":"密碼錯誤,連接失敗。" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_TW/element/string.json b/display/entry/src/main/resources/zh_TW/element/string.json index a5e5c5eca..f6935899d 100644 --- a/display/entry/src/main/resources/zh_TW/element/string.json +++ b/display/entry/src/main/resources/zh_TW/element/string.json @@ -55,6 +55,10 @@ { "name":"dm_bluetooth_dialog_content", "value":"裝置連線需要啟用藍牙,請啟用後重試。" + }, + { + "name":"dm_password_error", + "value":"密碼錯誤,連線失敗。" } ] } \ No newline at end of file -- Gitee From 423796f45f2e7ee2cd09b0b0c2f7a0ca92ebeb58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 6 Aug 2024 14:23:35 +0800 Subject: [PATCH 032/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- display/AppScope/app.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index e2743b68d..e7217c340 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -4,8 +4,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000016, - "versionName": "1.0.16", + "versionCode": 1000017, + "versionName": "1.0.17", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, -- Gitee From 1ebab0eb53cef01edaa8396ad24db25fddb0620e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Tue, 6 Aug 2024 17:27:37 +0800 Subject: [PATCH 033/520] add unit tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../UTTest_permission_manager.cpp | 73 ++++++++++++++++++- .../UTTest_device_manager_service_impl.cpp | 66 +++++++++++++++++ 2 files changed, 137 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 202417e4a..15769b2fe 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -98,7 +98,7 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_001, testing::ex /** * @tc.name: PinAuthUi::CheckProcessNameValidOnAuthCode_002 - * @tc.desc: the return value is true + * @tc.desc: the return value is false * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -109,6 +109,25 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ex ASSERT_EQ(ret, false); } +/** + * @tc.name: PinAuthUi::CheckProcessNameValidOnAuthCode_003 + * @tc.desc: the return value is true + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ext::TestSize.Level0) +{ + std::string processName = "com.huawei.msdp.hmringgenerator"; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + ASSERT_EQ(ret, true); + processName = "com.huawei.msdp.hmringdiscriminator"; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + ASSERT_EQ(ret, true); + processName = "CollaborationFwk"; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + ASSERT_EQ(ret, true); +} + /** * @tc.name: PinAuthUi::CheckProcessNameValidOnPinHolder_001 * @tc.desc: the return value is false @@ -124,7 +143,7 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_001, testing::e /** * @tc.name: PinAuthUi::CheckProcessNameValidOnPinHolder_002 - * @tc.desc: the return value is true + * @tc.desc: the return value is false * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -134,6 +153,56 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::e bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); ASSERT_EQ(ret, false); } + +/** + * @tc.name: PinAuthUi::CheckProcessNameValidOnPinHolder_003 + * @tc.desc: the return value is true + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::ext::TestSize.Level0) +{ + std::string processName = "CollaborationFwk"; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + ASSERT_EQ(ret, true); +} + +/** + * @tc.name: PinAuthUi::CheckSystemSA_001 + * @tc.desc: the return value is false + * @tc.type:FUNC + * @tc.require: AR000GHSJK +*/ +HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.level0) +{ + std::string pkgName; + bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_EQ(ret, false); + pkgName = "pkgName"; + ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_EQ(ret, false); +} + +/** + * @tc.name: PinAuthUi::CheckSystemSA_002 + * @tc.desc: the return value is true + * @tc.type:FUNC + * @tc.require: AR000GHSJK +*/ +HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.level0) +{ + std::string pkgName = "Samgr_Networking"; + bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_EQ(ret, true); + pkgName = "ohos.distributeddata.service"; + ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_EQ(ret, true); + pkgName = "ohos.dslm"; + ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_EQ(ret, true); + pkgName = "ohos.deviceprofile"; + ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_EQ(ret, true); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 3c7c927ef..90bdca12e 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -709,6 +709,22 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_001, testing::ext::TestSize EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); } +/** + * @tc.name: HandleOffline_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + devInfo.networkId = "111111"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + /** * @tc.name: HandleOnline_001 * @tc.type: FUNC @@ -724,6 +740,22 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_001, testing::ext::TestSize. EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); } +/** + * @tc.name: HandleOnline_002 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + devInfo.networkId = "111111"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + /** * @tc.name: HandleDeviceStatusChange_001 * @tc.type: FUNC @@ -1549,6 +1581,40 @@ HWTEST_F(DeviceManagerServiceImplTest, LoadHardwareFwkService_001, testing::ext: deviceManagerServiceImpl_->LoadHardwareFwkService(); EXPECT_NE(deviceManagerServiceImpl_->hiChainConnector_, nullptr); } + +/** + * tc.name: AccountCommonEventCallback_001 + * tc.type: FUNC +*/ +HWTEST_F(DeviceManagerServiceImplTest, AccountCommonEventCallback_001, testing::ext::TestSize.level0) +{ + int32_t userId = "111111"; + std::string commonEventType = "usual.event.USER_SWITCHED"; + deviceManagerServiceImpl_->AccountCommonEventCallback(userId, commonEventType); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + +/** + * tc.name: ScreenCommonEventCallback_001 + * tc.type: FUNC +*/ +HWTEST_F(DeviceManagerServiceImplTest, ScreenCommonEventCallback_001, testing::ext::TestSize.level0) +{ + std::string commonEventType = "usual.event.SCREEN_LOCKED"; + deviceManagerServiceImpl_->ScreenCommonEventCallback(commonEventType); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); +} + +/** + * tc.name: HandleDeviceNotTrust_001 + * tc.type: FUNC +*/ +HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::TestSize.level0) +{ + std::string udid = "111111"; + deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr) +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From f23f5924b7af90a9db740e3eb9d849fd8181ea52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Tue, 6 Aug 2024 18:04:39 +0800 Subject: [PATCH 034/520] add unit tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../UTTest_permission_manager.cpp | 36 ++++++++++++++----- .../UTTest_device_manager_service_impl.cpp | 9 ++--- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 15769b2fe..716a4db2f 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -43,6 +43,20 @@ void PremissionManagerTest::SetUp() SetSelfTokenID(tokenId); OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } +#define AUTH_CODE_WHITE_LIST_NUM (3) +#define SYSTEM_SA_WHITE_LIST_NUM (4) +constexpr int32_t PKG_NAME_SIZE_MAX = 256; +constexpr const static char g_authCodeWhiteList_test[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "com.huawei.msdp.hmringgenerator", + "com.huawei.msdp.hmringdiscriminator", + "CollaborationFwk", +}; +constexpr const static char systemSaWhiteList_test[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "Samgr_Networking", + "ohos.distributeddata.service", + "ohos.dslm", + "ohos.deviceprofile", +}; void PremissionManagerTest::TearDown() { @@ -117,13 +131,13 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ex */ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ext::TestSize.Level0) { - std::string processName = "com.huawei.msdp.hmringgenerator"; + std::string processName = g_authCodeWhiteList_test[0] bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); ASSERT_EQ(ret, true); - processName = "com.huawei.msdp.hmringdiscriminator"; + processName = g_authCodeWhiteList_test[1]; ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); ASSERT_EQ(ret, true); - processName = "CollaborationFwk"; + processName = g_authCodeWhiteList_test[2]; ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); ASSERT_EQ(ret, true); } @@ -162,9 +176,15 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::e */ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::ext::TestSize.Level0) { - std::string processName = "CollaborationFwk"; + std::string processName = g_authCodeWhiteList_test[0]; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); ASSERT_EQ(ret, true); + processName = g_authCodeWhiteList_test[1]; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + ASSERT_EQ(ret, true); + processName = g_authCodeWhiteList_test[2]; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + ASSERT_EQ(ret, true); } /** @@ -191,16 +211,16 @@ HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.level0 */ HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.level0) { - std::string pkgName = "Samgr_Networking"; + std::string pkgName = systemSaWhiteList_test[0]; bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); ASSERT_EQ(ret, true); - pkgName = "ohos.distributeddata.service"; + pkgName = systemSaWhiteList_test[1]; ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); ASSERT_EQ(ret, true); - pkgName = "ohos.dslm"; + pkgName = systemSaWhiteList_test[2]; ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); ASSERT_EQ(ret, true); - pkgName = "ohos.deviceprofile"; + pkgName = systemSaWhiteList_test[3]; ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); ASSERT_EQ(ret, true); } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 90bdca12e..309dad5dc 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -25,6 +25,7 @@ void DeviceManagerServiceImplTest::SetUp() } deviceManagerServiceImpl_->Initialize(listener_); } +constexpr std::string testID = "111111"; void DeviceManagerServiceImplTest::TearDown() { @@ -717,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - devInfo.networkId = "111111"; + devInfo.networkId = testID; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -748,7 +749,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - devInfo.networkId = "111111"; + devInfo.networkId = testID; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -1588,7 +1589,7 @@ HWTEST_F(DeviceManagerServiceImplTest, LoadHardwareFwkService_001, testing::ext: */ HWTEST_F(DeviceManagerServiceImplTest, AccountCommonEventCallback_001, testing::ext::TestSize.level0) { - int32_t userId = "111111"; + int32_t userId = testID; std::string commonEventType = "usual.event.USER_SWITCHED"; deviceManagerServiceImpl_->AccountCommonEventCallback(userId, commonEventType); EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); @@ -1611,7 +1612,7 @@ HWTEST_F(DeviceManagerServiceImplTest, ScreenCommonEventCallback_001, testing::e */ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::TestSize.level0) { - std::string udid = "111111"; + std::string udid = testID; deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr) } -- Gitee From d561f5307d59e2e57913ed2f56766e64367f6b91 Mon Sep 17 00:00:00 2001 From: pwx1285814 Date: Tue, 6 Aug 2024 18:39:37 +0800 Subject: [PATCH 035/520] =?UTF-8?q?=E8=A1=A5=E5=85=85services/implementati?= =?UTF-8?q?on/src/dependency/hichain=20UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: pwx1285814 --- .../UTTest_hichain_auth_connector.cpp | 250 +++++++++++++++++- .../UTTest_hichain_auth_connector.h | 16 ++ .../UTTest_hichain_connector.cpp | 231 ++++++++++++++-- .../commonunittest/UTTest_hichain_connector.h | 11 + 4 files changed, 481 insertions(+), 27 deletions(-) diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 2a9142c63..1c6626c11 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -12,16 +12,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include "UTTest_hichain_auth_connector.h" - #include "dm_constants.h" #include "hichain_auth_connector.h" +static int32_t g_processCredentialResultCode = -1; +static std::string g_processCredentialReturnDataStr = ""; + namespace OHOS { namespace DistributedHardware { void HiChainAuthConnectorTest::SetUp() { + g_processCredentialResultCode = -1; + g_processCredentialReturnDataStr = ""; } void HiChainAuthConnectorTest::TearDown() @@ -157,6 +161,20 @@ HWTEST_F(HiChainAuthConnectorTest, onRequest_003, testing::ext::TestSize.Level0) EXPECT_NE(hiChain_->dmDeviceAuthCallback_, nullptr); } +HWTEST_F(HiChainAuthConnectorTest, onRequest_004, testing::ext::TestSize.Level0) +{ + int64_t requestId = 0; + int operationCode = 0; + char *reqParams = nullptr; + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr mockCallback = std::make_shared(); + hiChainAuthConnector->dmDeviceAuthCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) + .Times(1) + .WillOnce(testing::Return(ERR_DM_FAILED)); + EXPECT_NE(hiChainAuthConnector->onRequest(requestId, operationCode, reqParams), nullptr); +} + HWTEST_F(HiChainAuthConnectorTest, onFinish_001, testing::ext::TestSize.Level0) { int64_t requestId = 0; @@ -228,6 +246,61 @@ HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_001, testing::ext::TestSiz EXPECT_NE(ret, DM_OK); } +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_002, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}";; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_003, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_004, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 1)"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_005, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "key"})"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(HiChainAuthConnectorTest, GenerateCredential_006, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t osAccountId = 0; + std::string publicKey; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 0, "publicKey": "key"})"; + int32_t ret = hiChain_->GenerateCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(HiChainAuthConnectorTest, QueryCredential_001, testing::ext::TestSize.Level0) { std::string localUdid = "2131351352"; @@ -247,6 +320,84 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L EXPECT_EQ(ret, false); } +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = jsonObject.dump(); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = jsonObject.dump(); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = jsonObject.dump(); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = jsonObject.dump(); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = jsonObject.dump(); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + jsonObject["result"] = 15; + jsonObject["publicKey"] = 0; + std::string localUdid = jsonObject.dump(); + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; + int32_t osAccountId = 1245; + bool ret = hiChain_->QueryCredential(localUdid, osAccountId); + EXPECT_TRUE(ret); +} + HWTEST_F(HiChainAuthConnectorTest, GetCredential_001, testing::ext::TestSize.Level0) { std::string localUdid; @@ -283,6 +434,50 @@ HWTEST_F(HiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestSize. EXPECT_NE(ret, DM_OK); } +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_003, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_004, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_005, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": -1})"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, ImportCredential_006, testing::ext::TestSize.Level0) +{ + int32_t localUdid = 0; + std::string deviceId = "test"; + std::string publicKey = "test"; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 0})"; + int32_t ret = hiChain_->ImportCredential(localUdid, deviceId, publicKey); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_001, testing::ext::TestSize.Level0) { std::string deviceId; @@ -298,5 +493,56 @@ HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_002, testing::ext::TestSize. int32_t ret = hiChain_->DeleteCredential(deviceId, userId); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_003, testing::ext::TestSize.Level0) +{ + std::string deviceId = "test"; + int32_t userId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_004, testing::ext::TestSize.Level0) +{ + std::string deviceId = "test"; + int32_t userId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int"})"; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, DeleteCredential_005, testing::ext::TestSize.Level0) +{ + std::string deviceId = "test"; + int32_t userId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 100})"; + int32_t ret = hiChain_->DeleteCredential(deviceId, userId); + EXPECT_EQ(ret, 100); +} } // namespace DistributedHardware } // namespace OHOS + +extern "C" __attribute__((constructor)) DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, + const char *requestParams, char **returnData) +{ + if (requestParams == nullptr || returnData == nullptr) { + return -1; + } + + if (g_processCredentialReturnDataStr.empty()) { + *returnData = nullptr; + return -1; + } + + char *charArray = strdup(g_processCredentialReturnDataStr.c_str()); + if (charArray == nullptr) { + return -1; + } + + *returnData = charArray; + return g_processCredentialResultCode; +} diff --git a/test/commonunittest/UTTest_hichain_auth_connector.h b/test/commonunittest/UTTest_hichain_auth_connector.h index 6709fd41e..3c708b598 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.h +++ b/test/commonunittest/UTTest_hichain_auth_connector.h @@ -17,9 +17,11 @@ #define OHOS_UTTEST_HICHAIN_AUTH_CONNECTOR_H #include +#include #include #include "hichain_auth_connector.h" +#include "hichain_connector_callback.h" namespace OHOS { namespace DistributedHardware { @@ -31,6 +33,20 @@ public: void TearDown(); std::shared_ptr hiChain_ = std::make_shared(); }; + +class MockIDmDeviceAuthCallback : public IDmDeviceAuthCallback { +public: + MockIDmDeviceAuthCallback() = default; + virtual ~MockIDmDeviceAuthCallback() = default; + + MOCK_METHOD(bool, AuthDeviceTransmit, (int64_t requestId, const uint8_t *data, uint32_t dataLen), (override)); + MOCK_METHOD(void, AuthDeviceFinish, (int64_t requestId), (override)); + MOCK_METHOD(void, AuthDeviceError, (int64_t requestId, int32_t errorCode), (override)); + MOCK_METHOD(void, AuthDeviceSessionKey, + (int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen), (override)); + MOCK_METHOD(void, GetRemoteDeviceId, (std::string &deviceId), (override)); + MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_UTTEST_HICHAIN_AUTH_CONNECTOR_H diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index 23acd3771..e28fe09d1 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,13 +20,13 @@ #include #include -#include "parameter.h" +#include "device_manager_service_listener.h" #include "dm_anonymous.h" -#include "dm_log.h" #include "dm_constants.h" +#include "dm_credential_manager.h" +#include "dm_log.h" #include "dm_random.h" -#include "hichain_connector.h" -#include "device_manager_service_listener.h" +#include "parameter.h" namespace OHOS { namespace DistributedHardware { @@ -231,6 +231,37 @@ HWTEST_F(HichainConnectorTest, from_json_001, testing::ext::TestSize.Level0) EXPECT_EQ(groupInfo.groupVisibility, 5); } +/** + * @tc.name: from_json_002 + * @tc.desc: Pass in arguments to the from_JSON function and convert it to the correct value + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, from_json_002, testing::ext::TestSize.Level0) +{ + GroupInfo groupInfo; + groupInfo.userId = "test"; + groupInfo.groupName = "test"; + nlohmann::json jsonObject; + jsonObject[FIELD_GROUP_NAME] = 0; + jsonObject[FIELD_GROUP_ID] = 0; + jsonObject[FIELD_GROUP_OWNER] = 0; + jsonObject[FIELD_GROUP_TYPE] = "test"; + jsonObject[FIELD_GROUP_VISIBILITY] = "test"; + jsonObject[FIELD_USER_ID] = "userId"; + from_json(jsonObject, groupInfo); + EXPECT_EQ(groupInfo.userId, "userId"); + + jsonObject[FIELD_USER_ID] = "0"; + jsonObject.erase(FIELD_GROUP_NAME); + jsonObject.erase(FIELD_GROUP_ID); + jsonObject.erase(FIELD_GROUP_OWNER); + jsonObject.erase(FIELD_GROUP_TYPE); + jsonObject.erase(FIELD_GROUP_VISIBILITY); + from_json(jsonObject, groupInfo); + EXPECT_EQ(groupInfo.groupName, "test"); +} + /** * @tc.name: HiChainConnector_001 * @tc.desc: Returns a new pointer to the HiChainConnector constructor new @@ -369,53 +400,88 @@ HWTEST_F(HichainConnectorTest, onRequest_002, testing::ext::TestSize.Level0) EXPECT_EQ(ret, nullptr); } +/** + * @tc.name: onRequest_003 + * @tc.desc: Test the onRequest method of HiChainConnector to ensure it handles different + * return values from GetPinCode correctly. + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, onRequest_003, testing::ext::TestSize.Level0) +{ + int64_t requestId = 2; + int32_t operationCode = 3; + char *reqParams = nullptr; + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr mockCallback = std::make_shared(); + hiChainConnector->hiChainConnectorCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) + .Times(1) + .WillOnce(testing::Return(ERR_DM_FAILED)); + EXPECT_NE(hiChainConnector->onRequest(requestId, operationCode, reqParams), nullptr); + + EXPECT_CALL(*mockCallback, GetPinCode(testing::_)) + .Times(1) + .WillOnce(testing::Return(DM_OK)); + EXPECT_NE(hiChainConnector->onRequest(requestId, operationCode, reqParams), nullptr); +} + /** * @tc.name: GetConnectPara_001 - * @tc.desc: set para not null and go to the second branch + * @tc.desc: Test GetConnectPara method when hiChainConnectorCallback_ is set to nullptr, + * ensuring it returns an empty string. * @tc.type: FUNC * @tc.require: AR000GHSJK */ HWTEST_F(HichainConnectorTest, GetConnectPara_001, testing::ext::TestSize.Level0) { std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->RegisterHiChainCallback(std::make_shared()); - std::string deviceId = "23445"; - std::string reqDeviceId = "234566"; - std::string p; + hiChainConnector->hiChainConnectorCallback_ = nullptr; + std::string deviceId = "12345"; + std::string reqDeviceId = "12345"; std::string ret = hiChainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, p); + EXPECT_EQ(ret, ""); } /** * @tc.name: GetConnectPara_002 - * @tc.desc:Empty deviceId so that jsonObject.is_discarded is null and the value of connectAddr is returned + * @tc.desc: Test GetConnectPara method with an empty deviceId to ensure JSON parsing fails + * and returns an empty string. * @tc.type: FUNC * @tc.require: AR000GHSJK */ HWTEST_F(HichainConnectorTest, GetConnectPara_002, testing::ext::TestSize.Level0) { std::string deviceId; - std::string reqDeviceId = "234566"; + std::string reqDeviceId = "12345"; + std::shared_ptr mockCallback = std::make_shared(); std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->RegisterHiChainCallback(std::make_shared()); + hiChainConnector->hiChainConnectorCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetConnectAddr(testing::_)) + .Times(1) + .WillOnce(testing::Return(R"({"key": "value"})")); std::string ret = hiChainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, ""); + EXPECT_NE(ret, ""); } /** * @tc.name: GetConnectPara_003 - * @tc.desc: hiChainConnectorCallback_ is nullptr return "" + * @tc.desc: Test GetConnectPara method with invalid JSON returned by hiChainConnectorCallback_ + * to ensure it returns an empty string. * @tc.type: FUNC * @tc.require: AR000GHSJK */ HWTEST_F(HichainConnectorTest, GetConnectPara_003, testing::ext::TestSize.Level0) { - std::string deviceId = "deviceIdTest"; - std::string reqDeviceId = "11369"; + std::string deviceId; + std::string reqDeviceId = "12345"; + std::shared_ptr mockCallback = std::make_shared(); std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->hiChainConnectorCallback_ = nullptr; + hiChainConnector->hiChainConnectorCallback_ = mockCallback; + EXPECT_CALL(*mockCallback, GetConnectAddr(testing::_)) + .Times(1) + .WillOnce(testing::Return("invalid json")); std::string ret = hiChainConnector->GetConnectPara(deviceId, reqDeviceId); - EXPECT_EQ(ret, ""); + EXPECT_EQ(ret, "invalid json"); } /** @@ -502,12 +568,19 @@ HWTEST_F(HichainConnectorTest, GetSyncGroupList_002, testing::ext::TestSize.Leve { std::vector groupList; GroupInfo groupList1; - groupList1.groupName = "hichainconnector"; - groupList1.groupId = "123456"; - groupList1.groupOwner = "doftbus"; - groupList1.groupType = 1; - groupList1.groupVisibility = 2; + groupList1.groupName = "groupName"; + groupList1.groupId = 1; + groupList1.groupOwner = "ohos.distributedhardware.devicemanager"; + groupList1.groupType = 7; + groupList1.groupVisibility = 1; groupList.push_back(groupList1); + GroupInfo groupList2; + groupList2.groupName = "hichainconnector"; + groupList2.groupId = "123456"; + groupList2.groupOwner = "doftbus"; + groupList2.groupType = 1; + groupList2.groupVisibility = 2; + groupList.push_back(groupList2); std::vector syncGroupList; std::shared_ptr hiChainConnector = std::make_shared(); int ret = hiChainConnector->GetSyncGroupList(groupList, syncGroupList); @@ -572,6 +645,46 @@ HWTEST_F(HichainConnectorTest, onFinish_001, testing::ext::TestSize.Level0) EXPECT_EQ(ret, DM_OK); } +/** + * @tc.name: onFinish_002 + * @tc.desc: return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, onFinish_002, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + int operationCode = GroupOperationCode::MEMBER_JOIN; + const char *returnData = "returnDataTest"; + std::shared_ptr hiChainConnector = std::make_shared(); + int32_t ret = hiChainConnector->RegisterHiChainCallback(std::make_shared()); + EXPECT_EQ(ret, DM_OK); + ret = hiChainConnector->UnRegisterHiChainCallback(); + EXPECT_EQ(ret, DM_OK); + + hiChainConnector->onFinish(requestId, operationCode, returnData); + + operationCode = GroupOperationCode::GROUP_CREATE; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + hiChainConnector->networkStyle_ = 1; + hiChainConnector->hiChainResCallback_ = nullptr; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConn = std::make_shared(); + hiChainConnector->hiChainResCallback_ = std::make_shared(hiChainConn, listener); + hiChainConnector->onFinish(requestId, operationCode, returnData); + + operationCode = GroupOperationCode::GROUP_DISBAND; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + hiChainConnector->hiChainResCallback_ = nullptr; + hiChainConnector->onFinish(requestId, operationCode, returnData); + + EXPECT_EQ(hiChainConnector->hiChainConnectorCallback_, nullptr); +} + /** * @tc.name: onError_001 * @tc.desc: return DM_OK @@ -599,6 +712,45 @@ HWTEST_F(HichainConnectorTest, onError_001, testing::ext::TestSize.Level0) EXPECT_EQ(ret, DM_OK); } +/** + * @tc.name: onError_002 + * @tc.desc: return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, onError_002, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + int operationCode = GroupOperationCode::MEMBER_JOIN; + int errorCode = 1; + const char *errorReturn = "errorReturnTest"; + std::shared_ptr hiChainConnector = std::make_shared(); + int32_t ret = hiChainConnector->RegisterHiChainCallback(std::make_shared()); + EXPECT_EQ(ret, DM_OK); + ret = hiChainConnector->UnRegisterHiChainCallback(); + EXPECT_EQ(ret, DM_OK); + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + operationCode = GroupOperationCode::GROUP_CREATE; + hiChainConnector->networkStyle_ = 0; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + hiChainConnector->networkStyle_ = 1; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConn = std::make_shared(); + hiChainConnector->hiChainResCallback_ = std::make_shared(hiChainConn, listener); + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + operationCode = GroupOperationCode::GROUP_DISBAND; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + + hiChainConnector->hiChainResCallback_ = nullptr; + hiChainConnector->onError(requestId, operationCode, errorCode, errorReturn); + EXPECT_EQ(hiChainConnector->hiChainConnectorCallback_, nullptr); +} + /** * @tc.name: DeleteGroup_002 * @tc.desc: return ERR_DM_FAILED @@ -1169,6 +1321,35 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); } +/** + * @tc.name: GetTrustedDevicesUdid_003 + * @tc.desc: Verify that the function returns DM_OK and correctly populates the udidList. + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_003, testing::ext::TestSize.Level0) +{ + const char* jsonStr = R"({ + "device1": { + "authId": "valid_udid_1" + }, + "device2": { + "authId": 12345 + }, + "device3": { + "authId": "valid_udid_2" + } + })"; + + std::vector udidList; + std::shared_ptr hiChainConnector = std::make_shared(); + int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr, udidList); + EXPECT_EQ(ret, DM_OK); + + std::vector expectedUdidList = {"valid_udid_1", "valid_udid_2"}; + EXPECT_EQ(udidList, expectedUdidList); +} + /** * @tc.name: DeleteAllGroup_001 * @tc.type: FUNC diff --git a/test/commonunittest/UTTest_hichain_connector.h b/test/commonunittest/UTTest_hichain_connector.h index 1040a0846..a641b0d89 100644 --- a/test/commonunittest/UTTest_hichain_connector.h +++ b/test/commonunittest/UTTest_hichain_connector.h @@ -16,6 +16,7 @@ #define OHOS_UTTEST_HICHAIN_CONNECTOR_H #include +#include #include #include #include @@ -41,6 +42,16 @@ public: void SetUp(); void TearDown(); }; + +class MockIHiChainConnectorCallback : public IHiChainConnectorCallback { +public: + MockIHiChainConnectorCallback() = default; + virtual ~MockIHiChainConnectorCallback() = default; + MOCK_METHOD(void, OnGroupCreated, (int64_t requestId, const std::string &groupId), (override)); + MOCK_METHOD(void, OnMemberJoin, (int64_t requestId, int32_t status), (override)); + MOCK_METHOD(std::string, GetConnectAddr, (std::string deviceId), (override)); + MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_HICHAIN_CONNECTOR_H -- Gitee From 2086031cdf471e1d013602bebad6ffc972e59148 Mon Sep 17 00:00:00 2001 From: w30042960 Date: Tue, 6 Aug 2024 19:08:54 +0800 Subject: [PATCH 036/520] add UT Signed-off-by: w30042960 --- test/commonunittest/UTTest_dm_anonymous.cpp | 40 +++++++++ .../UTTest_dm_deviceprofile_connector.cpp | 63 ++++++++++++++ .../UTTest_softbus_session.cpp | 3 + .../UTTest_auth_message_processor.cpp | 83 +++++++++++++++++++ test/unittest/UTTest_device_manager_impl.cpp | 6 +- test/unittest/UTTest_ipc_client_proxy.cpp | 7 ++ 6 files changed, 199 insertions(+), 3 deletions(-) diff --git a/test/commonunittest/UTTest_dm_anonymous.cpp b/test/commonunittest/UTTest_dm_anonymous.cpp index d26792a0e..547b4d927 100644 --- a/test/commonunittest/UTTest_dm_anonymous.cpp +++ b/test/commonunittest/UTTest_dm_anonymous.cpp @@ -241,6 +241,24 @@ HWTEST_F(DmAnonymousTest, IsInt32_002, testing::ext::TestSize.Level0) EXPECT_EQ(ret, false); } +/** + * @tc.name: IsUint32_001 + * @tc.desc: Return false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAnonymousTest, IsUint32_001, testing::ext::TestSize.Level0) +{ + std::string str = R"( + { + "AUTHTYPE" : "authtypeTest" + } + )"; + nlohmann::json jsonObj = nlohmann::json::parse(str, nullptr, false); + bool ret = IsUint32(jsonObj, TAG_AUTH_TYPE); + EXPECT_EQ(ret, false); +} + /** * @tc.name: IsInt64_001 * @tc.desc: Return true @@ -367,6 +385,28 @@ HWTEST_F(DmAnonymousTest, IsBool_002, testing::ext::TestSize.Level0) bool ret = IsBool(jsonObj, TAG_CRYPTO_SUPPORT); EXPECT_EQ(ret, false); } + +/** + * @tc.name: ConvertCharArray2String_001 + * @tc.desc: Return false + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmAnonymousTest, ConvertCharArray2String_001, testing::ext::TestSize.Level0) +{ + char *srcData = nullptr; + uint32_t srcLen = 0; + std::string ret = ConvertCharArray2String(srcData, srcLen); + EXPECT_EQ(ret, ""); + srcLen = 40 * 1024 * 1024 * 2; + char *srcData1 = new char[srcLen](); + if (srcData1 == nullptr) { + return; + } + ret = ConvertCharArray2String(srcData1, srcLen); + EXPECT_EQ(ret, ""); + delete[] srcData1; +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index ecf3f49c2..295f3caae 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -739,5 +739,68 @@ HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_002, testing::ext::TestSize.L int32_t ret = DeviceProfileConnector::GetInstance().IsSameAccount(udid); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DeviceProfileConnectorTest, GetAuthForm_001, testing::ext::TestSize.Level0) +{ + DistributedDeviceProfile::AccessControlProfile profile; + std::string trustDev = ""; + std::string reqDev = ""; + int32_t ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, INVALIED_TYPE); + profile.SetBindType(DM_IDENTICAL_ACCOUNT); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); + profile.SetBindType(DM_POINT_TO_POINT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, DEVICE_PEER_TO_PEER_TYPE); + profile.SetBindType(DM_ACROSS_ACCOUNT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, DEVICE_ACROSS_ACCOUNT_TYPE); + profile.SetBindLevel(APP); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, APP_ACROSS_ACCOUNT_TYPE); + profile.SetBindType(INVALIED_TYPE); + ret = DeviceProfileConnector::GetInstance().GetAuthForm(profile, trustDev, reqDev); + EXPECT_EQ(ret, INVALIED_TYPE); +} + +HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSize.Level0) +{ + DistributedDeviceProfile::AccessControlProfile profile; + DmAccessCaller caller; + DmAccessCallee callee; + int32_t ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, false); + profile.SetBindType(DM_IDENTICAL_ACCOUNT); + profile.accessee_.SetAccesseeBundleName("pkgName"); + profile.accessee_.SetAccesseeDeviceId("localDeviceId"); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindType(DM_POINT_TO_POINT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindLevel(APP); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindLevel(SERVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindType(DM_ACROSS_ACCOUNT); + profile.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindLevel(APP); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindLevel(SERVICE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, true); + profile.SetBindType(INVALIED_TYPE); + ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); + EXPECT_EQ(ret, false); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index 08f2b0df3..84ff8726a 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -259,6 +259,9 @@ HWTEST_F(SoftbusSessionTest, OnSessionOpened_001, testing::ext::TestSize.Level0) void *data = nullptr; unsigned int dataLen = 1; softbusSession->OnBytesReceived(sessionId, data, dataLen); + softbusSession->OnBytesReceived(sessionId, data, -1); + sessionId = -1; + softbusSession->OnBytesReceived(sessionId, data, dataLen); int ret = softbusSession->OnSessionOpened(sessionId, result); softbusSession->OnSessionClosed(sessionId); EXPECT_EQ(ret, DM_OK); diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index 1bed5dffe..cf84dcb08 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -133,6 +133,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes authMessageProcessor->cryptoAdapter_ = nullptr; authMessageProcessor->CreateNegotiateMessage(jsonObj); std::string str1 = jsonObj.dump(); + authMessageProcessor->cryptoAdapter_ = std::make_shared(); + authMessageProcessor->CreateNegotiateMessage(jsonObj); nlohmann::json jsonObject; jsonObject[TAG_ACCOUNT_GROUPID] = ""; @@ -274,6 +276,7 @@ HWTEST_F(AuthMessageProcessorTest, ParseResponseFinishMessage_002, testing::ext: authMessageProcessor->authResponseContext_ = std::make_shared(); nlohmann::json jsonObj; jsonObj[TAG_REPLY] = 22; + jsonObj[TAG_AUTH_FINISH] = true; authMessageProcessor->ParseResponseFinishMessage(jsonObj); ASSERT_EQ(authMessageProcessor->authResponseContext_->reply, jsonObj[TAG_REPLY]); } @@ -607,6 +610,22 @@ HWTEST_F(AuthMessageProcessorTest, ParseAuthRequestMessage_002, testing::ext::Te jsonThumbnail[TAG_DEVICE_TYPE] = 1; int32_t ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_INDEX] = 1; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_SLICE_NUM] = 10; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_SLICE_NUM] = 1; + jsonThumbnail[TAG_IS_SHOW_DIALOG] = true; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); + jsonThumbnail[TAG_BIND_TYPE_SIZE] = 10001; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, ERR_DM_FAILED); + jsonThumbnail[TAG_BIND_TYPE_SIZE] = 1; + ret = authMessageProcessor->ParseAuthRequestMessage(jsonThumbnail); + ASSERT_EQ(ret, DM_OK); } /** @@ -807,6 +826,42 @@ HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_005, testing::ext::Test ASSERT_EQ(authMessageProcessor->authResponseContext_, authResponseContext); } +/** + * @tc.name: AuthMessageProcessor::ParseNegotiateMessage_006 + * @tc.desc: Compare authResponseContext before and after assignment + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(AuthMessageProcessorTest, ParseNegotiateMessage_006, testing::ext::TestSize.Level0) +{ + std::shared_ptr hiChainConnector_ = std::make_shared(); + std::shared_ptr data = + std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); + std::shared_ptr authMessageProcessor = std::make_shared(data); + std::shared_ptr authResponseContext = std::make_shared(); + authMessageProcessor->authResponseContext_ = std::make_shared(); + nlohmann::json jsonObj; + authResponseContext->localDeviceId = "22"; + authResponseContext->authType = 1; + authResponseContext->reply = 33; + jsonObj[TAG_LOCAL_DEVICE_ID] = "LOCALDEVICEID"; + jsonObj[TAG_LOCAL_DEVICE_ID] = authResponseContext->localDeviceId; + jsonObj[TAG_AUTH_TYPE] = authResponseContext->authType; + jsonObj[TAG_LOCAL_DEVICE_ID] = authResponseContext->localDeviceId; + jsonObj[TAG_REPLY] = authResponseContext->reply; + jsonObj[TAG_CRYPTO_SUPPORT] = true; + jsonObj[TAG_CRYPTO_NAME] = "NAMETEST"; + jsonObj[TAG_CRYPTO_VERSION] = "1.0"; + jsonObj[TAG_ACCOUNT_GROUPID] = "GROUPID"; + authMessageProcessor->ParseNegotiateMessage(jsonObj); + jsonObj[TAG_ACCOUNT_GROUPID] = 12; + jsonObj[TAG_HOST] = "12"; + jsonObj[TAG_AUTH_TYPE] = "12"; + authMessageProcessor->SetResponseContext(authResponseContext); + authMessageProcessor->ParseNegotiateMessage(jsonObj); + ASSERT_EQ(authMessageProcessor->authResponseContext_, authResponseContext); +} + /** * @tc.name: AuthMessageProcessor::ParseRespNegotiateMessage_001 * @tc.desc: return true @@ -869,6 +924,7 @@ HWTEST_F(AuthMessageProcessorTest, ParseRespNegotiateMessage_003, testing::ext:: jsonObj[TAG_NET_ID] = "1212"; jsonObj[TAG_TOKENID] = "1212"; jsonObj[TAG_TARGET_DEVICE_NAME] = "1212"; + jsonObj[TAG_IMPORT_AUTH_CODE] = "1212"; authMessageProcessor->ParseRespNegotiateMessage(jsonObj); ASSERT_EQ(authMessageProcessor->authResponseContext_->isIdenticalAccount, true); } @@ -1038,6 +1094,9 @@ HWTEST_F(AuthMessageProcessorTest, CreateSimpleMessage_001, testing::ext::TestSi msgType = MSG_TYPE_RESP_NEGOTIATE; ret = authMessageProcessor->CreateSimpleMessage(msgType); ASSERT_NE(ret.size(), 0); + msgType = MSG_TYPE_UNKNOWN; + ret = authMessageProcessor->CreateSimpleMessage(msgType); + ASSERT_NE(ret.size(), 0); } /** @@ -1272,6 +1331,27 @@ HWTEST_F(AuthMessageProcessorTest, ParseMessage_008, testing::ext::TestSize.Leve } )"; int32_t ret = authMessageProcessor->ParseMessage(message); + std::string message1 = R"( + { + "publicKey": "publicKey_test", + "MSG_TYPE": "503", + } + )"; + ret = authMessageProcessor->ParseMessage(message); + std::string message2 = R"( + { + "publicKey": "publicKey_test", + "MSG_TYPE": "504", + } + )"; + ret = authMessageProcessor->ParseMessage(message2); + std::string message3 = R"( + { + "publicKey": "publicKey_test", + "MSG_TYPE": "600", + } + )"; + ret = authMessageProcessor->ParseMessage(message3); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -1591,6 +1671,9 @@ HWTEST_F(AuthMessageProcessorTest, ParsePkgNegotiateMessage_002, testing::ext::T jsonObj[TAG_HAVECREDENTIAL] = "1212"; jsonObj[TAG_BIND_TYPE_SIZE] = "1212"; authMessageProcessor->ParsePkgNegotiateMessage(jsonObj); + jsonObj[TAG_BIND_TYPE_SIZE] = 1212; + jsonObj[TAG_HOST_PKGLABEL] = "1212"; + authMessageProcessor->ParsePkgNegotiateMessage(jsonObj); ASSERT_NE(authMessageProcessor->authResponseContext_->authType, 21); } diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index f7fab0b17..80904a61e 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -417,7 +417,7 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceName_104, testing::ext::TestSize.Level0 std::shared_ptr callback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); ret = DeviceManager::GetInstance().GetDeviceName(packName, networkId, deviceName); - ASSERT_EQ(ret, ERR_DM_NO_PERMISSION); + ASSERT_EQ(ret, DM_OK); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -497,7 +497,7 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceType_104, testing::ext::TestSize.Level0 std::shared_ptr callback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); ret = DeviceManager::GetInstance().GetDeviceType(packName, networkId, deviceType); - ASSERT_EQ(ret, ERR_DM_NO_PERMISSION); + ASSERT_EQ(ret, DM_OK); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1085,7 +1085,7 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_101, testing::ext::TestSize.Lev // 3. call DeviceManagerImpl::SetUserOperation with parameter ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 4. check ret is DM_OK - ASSERT_EQ(ret, ERR_DM_NO_PERMISSION); + ASSERT_EQ(ret, DM_OK); DeviceManager::GetInstance().UnInitDeviceManager(packName); } diff --git a/test/unittest/UTTest_ipc_client_proxy.cpp b/test/unittest/UTTest_ipc_client_proxy.cpp index a39e3a58e..666f5f940 100644 --- a/test/unittest/UTTest_ipc_client_proxy.cpp +++ b/test/unittest/UTTest_ipc_client_proxy.cpp @@ -409,6 +409,10 @@ HWTEST_F(IpcClientProxyTest, SendRequest5, testing::ext::TestSize.Level0) int32_t ret = ipcClientProxy->SendRequest(0, req, rsp); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); + ret = ipcClientProxy->SendRequest(-1, req, rsp); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); + ret = ipcClientProxy->SendRequest(IPC_MSG_SEV, req, rsp); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); } /** @@ -461,6 +465,9 @@ HWTEST_F(IpcClientProxyTest, OnDmServiceDied_002, testing::ext::TestSize.Level0) int32_t ret = ipcClientProxy->OnDmServiceDied(); // 4. check ret is DM_OK ASSERT_EQ(ret, DM_OK); + ipcClientProxy->ipcClientManager_ = nullptr; + ret = ipcClientProxy->OnDmServiceDied(); + ASSERT_EQ(ret, ERR_DM_POINT_NULL); } } // namespace } // namespace DistributedHardware -- Gitee From c3525bd2f494cb6ebeb4b47bf7c67025b09bdf21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 09:17:22 +0800 Subject: [PATCH 037/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../UTTest_permission_manager.cpp | 37 ++++++++++--------- .../UTTest_permission_manager.h | 3 +- .../UTTest_device_manager_service_impl.cpp | 2 +- 3 files changed, 22 insertions(+), 20 deletions(-) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 716a4db2f..4785dbddf 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -20,7 +20,7 @@ namespace OHOS { namespace DistributedHardware { -void PremissionManagerTest::SetUp() +void PermissionManagerTest::SetUp() { const int32_t permsNum = 2; const int32_t indexZero = 0; @@ -45,28 +45,29 @@ void PremissionManagerTest::SetUp() } #define AUTH_CODE_WHITE_LIST_NUM (3) #define SYSTEM_SA_WHITE_LIST_NUM (4) -constexpr int32_t PKG_NAME_SIZE_MAX = 256; -constexpr const static char g_authCodeWhiteList_test[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { +std::array g_authCodeWhiteList_test = { "com.huawei.msdp.hmringgenerator", "com.huawei.msdp.hmringdiscriminator", "CollaborationFwk", }; -constexpr const static char systemSaWhiteList_test[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + +std::array systemSaWhiteList_test = { "Samgr_Networking", "ohos.distributeddata.service", "ohos.dslm", "ohos.deviceprofile", }; -void PremissionManagerTest::TearDown() + +void PermissionManagerTest::TearDown() { } -void PremissionManagerTest::SetUpTestCase() +void PermissionManagerTest::SetUpTestCase() { } -void PremissionManagerTest::TearDownTestCase() +void PermissionManagerTest::TearDownTestCase() { } @@ -78,7 +79,7 @@ namespace { * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckPermission_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckPermission_001, testing::ext::TestSize.Level0) { bool ret = PermissionManager::GetInstance().CheckPermission(); ASSERT_EQ(ret, true); @@ -90,7 +91,7 @@ HWTEST_F(PremissionManagerTest, CheckPermission_001, testing::ext::TestSize.Leve * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, GetCallerProcessName_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, GetCallerProcessName_001, testing::ext::TestSize.Level0) { std::string processName; int32_t ret = PermissionManager::GetInstance().GetCallerProcessName(processName); @@ -103,7 +104,7 @@ HWTEST_F(PremissionManagerTest, GetCallerProcessName_001, testing::ext::TestSize * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_001, testing::ext::TestSize.Level0) { std::string processName; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); @@ -116,7 +117,7 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_001, testing::ex * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ext::TestSize.Level0) { std::string processName = "processName"; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); @@ -129,9 +130,9 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ex * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ext::TestSize.Level0) { - std::string processName = g_authCodeWhiteList_test[0] + std::string processName = g_authCodeWhiteList_test[0]; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); ASSERT_EQ(ret, true); processName = g_authCodeWhiteList_test[1]; @@ -148,7 +149,7 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ex * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_001, testing::ext::TestSize.Level0) { std::string processName; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); @@ -161,7 +162,7 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_001, testing::e * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::ext::TestSize.Level0) { std::string processName = "processName"; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); @@ -174,7 +175,7 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::e * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::ext::TestSize.Level0) { std::string processName = g_authCodeWhiteList_test[0]; bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); @@ -193,7 +194,7 @@ HWTEST_F(PremissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::e * @tc.type:FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.level0) +HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.Level0) { std::string pkgName; bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); @@ -209,7 +210,7 @@ HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.level0 * @tc.type:FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.level0) +HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.Level0) { std::string pkgName = systemSaWhiteList_test[0]; bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); diff --git a/test/commonunittest/UTTest_permission_manager.h b/test/commonunittest/UTTest_permission_manager.h index b66d7c0b7..e591b4746 100644 --- a/test/commonunittest/UTTest_permission_manager.h +++ b/test/commonunittest/UTTest_permission_manager.h @@ -19,13 +19,14 @@ #include #include +#include #include "dm_constants.h" #include "permission_manager.h" namespace OHOS { namespace DistributedHardware { -class PremissionManagerTest : public testing::Test { +class PermissionManagerTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 309dad5dc..8bd97b7e1 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -25,7 +25,7 @@ void DeviceManagerServiceImplTest::SetUp() } deviceManagerServiceImpl_->Initialize(listener_); } -constexpr std::string testID = "111111"; +const std::string testID("111111"); void DeviceManagerServiceImplTest::TearDown() { -- Gitee From 8fb5ceb3cf08e55abe2c846ce6c2bcca7e092418 Mon Sep 17 00:00:00 2001 From: wangxuanxuan Date: Wed, 7 Aug 2024 09:44:21 +0800 Subject: [PATCH 038/520] wearable trans Signed-off-by: wangxuanxuan --- display/AppScope/app.json | 4 ++-- .../src/main/resources/base/element/plural.json | 4 ++-- .../src/main/resources/base/element/string.json | 2 +- .../src/main/resources/bo_CN/element/string.json | 4 ++++ .../entry/src/main/resources/ug/element/string.json | 4 ++++ .../src/main/resources/zh_CN/element/plural.json | 2 +- .../src/main/resources/zh_HK/element/string.json | 4 ++++ .../src/main/resources/zh_TW/element/string.json | 4 ++++ .../src/main/resources/zz_ZX/element/plural.json | 12 ++++++------ .../src/main/resources/zz_ZX/element/string.json | 4 ++++ 10 files changed, 32 insertions(+), 12 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index e7217c340..60a7a4125 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -4,8 +4,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000017, - "versionName": "1.0.17", + "versionCode": 1000018, + "versionName": "1.0.18", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/resources/base/element/plural.json b/display/entry/src/main/resources/base/element/plural.json index e19eb94d6..f103d249c 100644 --- a/display/entry/src/main/resources/base/element/plural.json +++ b/display/entry/src/main/resources/base/element/plural.json @@ -18,11 +18,11 @@ "value":[ { "quantity":"one", - "value":"Incorrect connection code. %d attempt remaining." + "value":"Incorrect. %d attempt remaining." }, { "quantity":"other", - "value":"Incorrect connection code. %d attempts remaining." + "value":"Incorrect. %d attempts remaining." } ] } diff --git a/display/entry/src/main/resources/base/element/string.json b/display/entry/src/main/resources/base/element/string.json index 2aaa625a4..ad22f14fe 100644 --- a/display/entry/src/main/resources/base/element/string.json +++ b/display/entry/src/main/resources/base/element/string.json @@ -78,7 +78,7 @@ }, { "name":"dm_enter_peer_connect_code", - "value":"Enter the peer connection code" + "value":"Enter connection code" }, { "name":"dm_password_error", diff --git a/display/entry/src/main/resources/bo_CN/element/string.json b/display/entry/src/main/resources/bo_CN/element/string.json index 56d4566e0..3b5e8dd45 100644 --- a/display/entry/src/main/resources/bo_CN/element/string.json +++ b/display/entry/src/main/resources/bo_CN/element/string.json @@ -59,6 +59,10 @@ { "name":"dm_password_error", "value":"གསང་གྲངས་ནོར་འཁྲུལ་བྱུང་། སྦྲེལ་མཐུད་བྱེད་མ་ཐུབ།" + }, + { + "name":"dm_enter_peer_connect_code", + "value":"ཕ་རོལ་སྣེའི་སྦྲེལ་མཐུད་ཨང་རྟགས་འཇུག་རོགས།" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/ug/element/string.json b/display/entry/src/main/resources/ug/element/string.json index 9ad7fa3fa..88d86cb8a 100644 --- a/display/entry/src/main/resources/ug/element/string.json +++ b/display/entry/src/main/resources/ug/element/string.json @@ -59,6 +59,10 @@ { "name":"dm_password_error", "value":"مەخپىي نومۇر خاتا، ئۇلانمىدى." + }, + { + "name":"dm_enter_peer_connect_code", + "value":"ئۇلاش كودى كىرگۈزۈڭ" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_CN/element/plural.json b/display/entry/src/main/resources/zh_CN/element/plural.json index cc627408d..47e018471 100644 --- a/display/entry/src/main/resources/zh_CN/element/plural.json +++ b/display/entry/src/main/resources/zh_CN/element/plural.json @@ -22,7 +22,7 @@ }, { "quantity":"other", - "value":"连接码错误,还可尝试 %d 次" + "value":"连接码错误,还可以尝试 %d 次" } ] } diff --git a/display/entry/src/main/resources/zh_HK/element/string.json b/display/entry/src/main/resources/zh_HK/element/string.json index a2e76aadf..0cac2b3e9 100644 --- a/display/entry/src/main/resources/zh_HK/element/string.json +++ b/display/entry/src/main/resources/zh_HK/element/string.json @@ -59,6 +59,10 @@ { "name":"dm_password_error", "value":"密碼錯誤,連接失敗。" + }, + { + "name":"dm_enter_peer_connect_code", + "value":"輸入對端連接碼" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zh_TW/element/string.json b/display/entry/src/main/resources/zh_TW/element/string.json index f6935899d..adebbc904 100644 --- a/display/entry/src/main/resources/zh_TW/element/string.json +++ b/display/entry/src/main/resources/zh_TW/element/string.json @@ -59,6 +59,10 @@ { "name":"dm_password_error", "value":"密碼錯誤,連線失敗。" + }, + { + "name":"dm_enter_peer_connect_code", + "value":"輸入對端連線碼" } ] } \ No newline at end of file diff --git a/display/entry/src/main/resources/zz_ZX/element/plural.json b/display/entry/src/main/resources/zz_ZX/element/plural.json index f015807ed..45ea14644 100644 --- a/display/entry/src/main/resources/zz_ZX/element/plural.json +++ b/display/entry/src/main/resources/zz_ZX/element/plural.json @@ -5,27 +5,27 @@ "value":[ { "quantity":"one", - "value":"[TS_922746]_Incorrect connection code. %d attempt remaining." + "value":"[TS_922746]_Incorrect. %d attempt remaining." }, { "quantity":"other", - "value":"[TS_922743]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922743]_Incorrect. %d attempts remaining." }, { "quantity":"zero", - "value":"[TS_922738]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922738]_Incorrect. %d attempts remaining." }, { "quantity":"few", - "value":"[TS_922740]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922740]_Incorrect. %d attempts remaining." }, { "quantity":"many", - "value":"[TS_922747]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922747]_Incorrect. %d attempts remaining." }, { "quantity":"two", - "value":"[TS_922736]_Incorrect connection code. %d attempts remaining." + "value":"[TS_922736]_Incorrect. %d attempts remaining." } ] }, diff --git a/display/entry/src/main/resources/zz_ZX/element/string.json b/display/entry/src/main/resources/zz_ZX/element/string.json index 7404e663b..868ace1ac 100644 --- a/display/entry/src/main/resources/zz_ZX/element/string.json +++ b/display/entry/src/main/resources/zz_ZX/element/string.json @@ -75,6 +75,10 @@ { "name":"dm_confirm_intention", "value":"[TS_931360]_This is required for cross-device data syncing and collaboration." + }, + { + "name":"dm_enter_peer_connect_code", + "value":"[TS_949559]_Enter connection code" } ] } \ No newline at end of file -- Gitee From c1124d78dd4d07ebe2fbdca445f2a71ba5719ed0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 09:50:52 +0800 Subject: [PATCH 039/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../permission/standard/permission_manager.h | 19 +++++++ .../standard/permission_manager.cpp | 19 ------- .../UTTest_permission_manager.cpp | 56 +++++++------------ 3 files changed, 39 insertions(+), 55 deletions(-) diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index b62f81ea5..0c62cd70d 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -36,6 +36,25 @@ public: bool CheckSystemSA(const std::string &pkgName); std::unordered_set GetSystemSA(); }; +#define AUTH_CODE_WHITE_LIST_NUM (3) +constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "com.huawei.msdp.hmringgenerator", + "com.huawei.msdp.hmringdiscriminator", + "CollaborationFwk", +}; + +#define PIN_HOLDER_WHITE_LIST_NUM (1) +constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "CollaborationFwk", +}; + +#define SYSTEM_SA_WHITE_LIST_NUM (4) +constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "Samgr_Networking", + "ohos.distributeddata.service", + "ohos.dslm", + "ohos.deviceprofile", +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_PERMISSION_STANDARD_PERMISSION_MANAGER_H diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 914ddf819..f58ff87fe 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -37,25 +37,6 @@ constexpr const char* DM_MONITOR_DEVICE_NETWORK_STATE_PERMISSION = "ohos.permiss constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; constexpr int32_t PKG_NAME_SIZE_MAX = 256; -#define AUTH_CODE_WHITE_LIST_NUM (3) -constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { - "com.huawei.msdp.hmringgenerator", - "com.huawei.msdp.hmringdiscriminator", - "CollaborationFwk", -}; - -#define PIN_HOLDER_WHITE_LIST_NUM (1) -constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { - "CollaborationFwk", -}; - -#define SYSTEM_SA_WHITE_LIST_NUM (4) -constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { - "Samgr_Networking", - "ohos.distributeddata.service", - "ohos.dslm", - "ohos.deviceprofile", -}; } bool PermissionManager::CheckPermission(void) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 4785dbddf..285ee6160 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -43,22 +43,6 @@ void PermissionManagerTest::SetUp() SetSelfTokenID(tokenId); OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } -#define AUTH_CODE_WHITE_LIST_NUM (3) -#define SYSTEM_SA_WHITE_LIST_NUM (4) -std::array g_authCodeWhiteList_test = { - "com.huawei.msdp.hmringgenerator", - "com.huawei.msdp.hmringdiscriminator", - "CollaborationFwk", -}; - -std::array systemSaWhiteList_test = { - "Samgr_Networking", - "ohos.distributeddata.service", - "ohos.dslm", - "ohos.deviceprofile", -}; - - void PermissionManagerTest::TearDown() { } @@ -132,14 +116,14 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_002, testing::ex */ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ext::TestSize.Level0) { - std::string processName = g_authCodeWhiteList_test[0]; - bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + std::string processName1(g_authCodeWhiteList[0]); + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName1); ASSERT_EQ(ret, true); - processName = g_authCodeWhiteList_test[1]; - ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + std::string processName2(g_authCodeWhiteList[1]); + ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName2); ASSERT_EQ(ret, true); - processName = g_authCodeWhiteList_test[2]; - ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + std::string processName3(g_authCodeWhiteList[2]); + ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName3); ASSERT_EQ(ret, true); } @@ -177,14 +161,14 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::e */ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::ext::TestSize.Level0) { - std::string processName = g_authCodeWhiteList_test[0]; - bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + std::string processName1(g_authCodeWhiteList[0]); + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName1); ASSERT_EQ(ret, true); - processName = g_authCodeWhiteList_test[1]; - ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + std::string processName2(g_authCodeWhiteList[1]); + ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName2); ASSERT_EQ(ret, true); - processName = g_authCodeWhiteList_test[2]; - ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + std::string processName3(g_authCodeWhiteList[2]); + ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName3); ASSERT_EQ(ret, true); } @@ -212,17 +196,17 @@ HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.Level0 */ HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.Level0) { - std::string pkgName = systemSaWhiteList_test[0]; - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + std::string pkgName1(systemSaWhiteList[0]); + bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName1); ASSERT_EQ(ret, true); - pkgName = systemSaWhiteList_test[1]; - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + std::string pkgName2(systemSaWhiteList[1]); + ret = PermissionManager::GetInstance().CheckSystemSA(pkgName2); ASSERT_EQ(ret, true); - pkgName = systemSaWhiteList_test[2]; - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + std::string pkgName3(systemSaWhiteList[2]); + ret = PermissionManager::GetInstance().CheckSystemSA(pkgName3); ASSERT_EQ(ret, true); - pkgName = systemSaWhiteList_test[3]; - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + std::string pkgName4(systemSaWhiteList[3]); + ret = PermissionManager::GetInstance().CheckSystemSA(pkgName4); ASSERT_EQ(ret, true); } } // namespace DistributedHardware -- Gitee From 99c721b09b7d838b56c6ae6c319336ab5c4edb88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 10:06:44 +0800 Subject: [PATCH 040/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../service/include/permission/standard/permission_manager.h | 1 + services/service/src/permission/standard/permission_manager.cpp | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index 0c62cd70d..82f72e9e6 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -36,6 +36,7 @@ public: bool CheckSystemSA(const std::string &pkgName); std::unordered_set GetSystemSA(); }; +constexpr int32_t PKG_NAME_SIZE_MAX = 256; #define AUTH_CODE_WHITE_LIST_NUM (3) constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "com.huawei.msdp.hmringgenerator", diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index f58ff87fe..e42f60830 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -36,7 +36,6 @@ constexpr const char* DM_SERVICE_ACCESS_NEWPERMISSION = "ohos.permission.DISTRIB constexpr const char* DM_MONITOR_DEVICE_NETWORK_STATE_PERMISSION = "ohos.permission.MONITOR_DEVICE_NETWORK_STATE"; constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; -constexpr int32_t PKG_NAME_SIZE_MAX = 256; } bool PermissionManager::CheckPermission(void) -- Gitee From 6a4333c135cc121eadf4dae5aeb5e9ac024efeac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 10:26:02 +0800 Subject: [PATCH 041/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../include/permission/standard/permission_manager.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index 82f72e9e6..3135d826a 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -36,21 +36,21 @@ public: bool CheckSystemSA(const std::string &pkgName); std::unordered_set GetSystemSA(); }; -constexpr int32_t PKG_NAME_SIZE_MAX = 256; +constexpr int32_t PAKAGE_NAME_SIZE_MAX = 256; #define AUTH_CODE_WHITE_LIST_NUM (3) -constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { +constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { "com.huawei.msdp.hmringgenerator", "com.huawei.msdp.hmringdiscriminator", "CollaborationFwk", }; #define PIN_HOLDER_WHITE_LIST_NUM (1) -constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { +constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { "CollaborationFwk", }; #define SYSTEM_SA_WHITE_LIST_NUM (4) -constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { +constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", "ohos.dslm", -- Gitee From 5a240a8e7f5059d641a28878f13c1b6f0f76d4ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 10:53:20 +0800 Subject: [PATCH 042/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/commonunittest/UTTest_permission_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 285ee6160..6d63585fe 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -209,5 +209,6 @@ HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.Level0 ret = PermissionManager::GetInstance().CheckSystemSA(pkgName4); ASSERT_EQ(ret, true); } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 0417819363b84beb7fe286dc73e139f08d37c0ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 11:39:22 +0800 Subject: [PATCH 043/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 8bd97b7e1..b16434ee5 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - devInfo.networkId = testID; + strcpy(devInfo.networkId, testID); if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -749,7 +749,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - devInfo.networkId = testID; + strcpy(devInfo.networkId, testID); if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -1587,7 +1587,7 @@ HWTEST_F(DeviceManagerServiceImplTest, LoadHardwareFwkService_001, testing::ext: * tc.name: AccountCommonEventCallback_001 * tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceImplTest, AccountCommonEventCallback_001, testing::ext::TestSize.level0) +HWTEST_F(DeviceManagerServiceImplTest, AccountCommonEventCallback_001, testing::ext::TestSize.Level0) { int32_t userId = testID; std::string commonEventType = "usual.event.USER_SWITCHED"; @@ -1599,7 +1599,7 @@ HWTEST_F(DeviceManagerServiceImplTest, AccountCommonEventCallback_001, testing:: * tc.name: ScreenCommonEventCallback_001 * tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceImplTest, ScreenCommonEventCallback_001, testing::ext::TestSize.level0) +HWTEST_F(DeviceManagerServiceImplTest, ScreenCommonEventCallback_001, testing::ext::TestSize.Level0) { std::string commonEventType = "usual.event.SCREEN_LOCKED"; deviceManagerServiceImpl_->ScreenCommonEventCallback(commonEventType); @@ -1610,7 +1610,7 @@ HWTEST_F(DeviceManagerServiceImplTest, ScreenCommonEventCallback_001, testing::e * tc.name: HandleDeviceNotTrust_001 * tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::TestSize.level0) +HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::TestSize.Level0) { std::string udid = testID; deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); -- Gitee From 837b0f03d89e062e3fa7fdeedf88e464e987d4c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 12:13:54 +0800 Subject: [PATCH 044/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index b16434ee5..21a57378d 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - strcpy(devInfo.networkId, testID); + strcpy(devInfo.networkId, testID.c_str()); if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -749,7 +749,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - strcpy(devInfo.networkId, testID); + strcpy(devInfo.networkId, testID.c_str()); if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } -- Gitee From 6e7428b0e70d8aba0a60587ae1e62270ed668d21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Wed, 7 Aug 2024 14:45:25 +0800 Subject: [PATCH 045/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 21a57378d..1db58bad5 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1589,7 +1589,7 @@ HWTEST_F(DeviceManagerServiceImplTest, LoadHardwareFwkService_001, testing::ext: */ HWTEST_F(DeviceManagerServiceImplTest, AccountCommonEventCallback_001, testing::ext::TestSize.Level0) { - int32_t userId = testID; + int32_t userId = 111111; std::string commonEventType = "usual.event.USER_SWITCHED"; deviceManagerServiceImpl_->AccountCommonEventCallback(userId, commonEventType); EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); @@ -1614,7 +1614,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::T { std::string udid = testID; deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); - EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr) + EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); } } // namespace } // namespace DistributedHardware -- Gitee From 8876b4f1b5e0ea43f2996deb26d4bdaf67e3de6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Thu, 8 Aug 2024 09:05:49 +0800 Subject: [PATCH 046/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../permission/standard/permission_manager.h | 20 ------------------- .../standard/permission_manager.cpp | 20 +++++++++++++++++++ .../UTTest_permission_manager.cpp | 20 +++++++++++++++++++ 3 files changed, 40 insertions(+), 20 deletions(-) diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index 3135d826a..b62f81ea5 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -36,26 +36,6 @@ public: bool CheckSystemSA(const std::string &pkgName); std::unordered_set GetSystemSA(); }; -constexpr int32_t PAKAGE_NAME_SIZE_MAX = 256; -#define AUTH_CODE_WHITE_LIST_NUM (3) -constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { - "com.huawei.msdp.hmringgenerator", - "com.huawei.msdp.hmringdiscriminator", - "CollaborationFwk", -}; - -#define PIN_HOLDER_WHITE_LIST_NUM (1) -constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { - "CollaborationFwk", -}; - -#define SYSTEM_SA_WHITE_LIST_NUM (4) -constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { - "Samgr_Networking", - "ohos.distributeddata.service", - "ohos.dslm", - "ohos.deviceprofile", -}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_PERMISSION_STANDARD_PERMISSION_MANAGER_H diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index e42f60830..441e185da 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -36,6 +36,26 @@ constexpr const char* DM_SERVICE_ACCESS_NEWPERMISSION = "ohos.permission.DISTRIB constexpr const char* DM_MONITOR_DEVICE_NETWORK_STATE_PERMISSION = "ohos.permission.MONITOR_DEVICE_NETWORK_STATE"; constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; +constexpr int32_t PKG_NAME_SIZE_MAX = 256; +#define AUTH_CODE_WHITE_LIST_NUM (3) +constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "com.huawei.msdp.hmringgenerator", + "com.huawei.msdp.hmringdiscriminator", + "CollaborationFwk", +}; + +#define PIN_HOLDER_WHITE_LIST_NUM (1) +constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "CollaborationFwk", +}; + +#define SYSTEM_SA_WHITE_LIST_NUM (4) +constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "Samgr_Networking", + "ohos.distributeddata.service", + "ohos.dslm", + "ohos.deviceprofile", +}; } bool PermissionManager::CheckPermission(void) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 6d63585fe..e9045360a 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -43,6 +43,26 @@ void PermissionManagerTest::SetUp() SetSelfTokenID(tokenId); OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } +constexpr int32_t PAKAGE_NAME_SIZE_MAX = 256; +#define AUTH_CODE_WHITE_LIST_NUM (3) +constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "com.huawei.msdp.hmringgenerator", + "com.huawei.msdp.hmringdiscriminator", + "CollaborationFwk", +}; + +#define PIN_HOLDER_WHITE_LIST_NUM (1) +constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "CollaborationFwk", +}; + +#define SYSTEM_SA_WHITE_LIST_NUM (4) +constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { + "Samgr_Networking", + "ohos.distributeddata.service", + "ohos.dslm", + "ohos.deviceprofile", +}; void PermissionManagerTest::TearDown() { } -- Gitee From 7275cd9ebfe426ab95eaa0a77fd1fbfb887654ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Thu, 8 Aug 2024 09:16:28 +0800 Subject: [PATCH 047/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- .../service/src/permission/standard/permission_manager.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 441e185da..914ddf819 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -38,19 +38,19 @@ constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; constexpr int32_t PKG_NAME_SIZE_MAX = 256; #define AUTH_CODE_WHITE_LIST_NUM (3) -constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { +constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "com.huawei.msdp.hmringgenerator", "com.huawei.msdp.hmringdiscriminator", "CollaborationFwk", }; #define PIN_HOLDER_WHITE_LIST_NUM (1) -constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { +constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "CollaborationFwk", }; #define SYSTEM_SA_WHITE_LIST_NUM (4) -constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { +constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", "ohos.dslm", -- Gitee From 3d25cb34a9b750982d1d5415de28f51b24930c5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Thu, 8 Aug 2024 09:37:30 +0800 Subject: [PATCH 048/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/commonunittest/UTTest_permission_manager.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index e9045360a..e28e9ed68 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -50,12 +50,6 @@ constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE "com.huawei.msdp.hmringdiscriminator", "CollaborationFwk", }; - -#define PIN_HOLDER_WHITE_LIST_NUM (1) -constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { - "CollaborationFwk", -}; - #define SYSTEM_SA_WHITE_LIST_NUM (4) constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { "Samgr_Networking", -- Gitee From 6287067f23393ddb40a431ddc46fcee758420862 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Thu, 8 Aug 2024 09:59:01 +0800 Subject: [PATCH 049/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 1db58bad5..6f0f68c06 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,8 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - strcpy(devInfo.networkId, testID.c_str()); + std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.network) - 1); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } @@ -749,7 +750,8 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - strcpy(devInfo.networkId, testID.c_str()); + std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.network) - 1); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } -- Gitee From 19df8ae6ecf09760c0c313f19fba9b27a2a1bf16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Thu, 8 Aug 2024 10:21:10 +0800 Subject: [PATCH 050/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 6f0f68c06..38af57afb 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.network) - 1); + std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.networkId) - 1); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); @@ -750,7 +750,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.network) - 1); + std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.networkId) - 1); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); -- Gitee From a3408a0ea89fb0944558a212495a9930a2438d87 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 8 Aug 2024 11:32:02 +0800 Subject: [PATCH 051/520] fix bug Signed-off-by: gaoqiang_strong --- .../src/ability/standard/dm_dialog_manager.cpp | 6 +----- utils/src/threadManager/dm_thread_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 80750f4a2..1953e5de9 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -115,11 +115,7 @@ void DmDialogManager::ShowPinDialog(const std::string param) abilityName_ = PIN_ABILITY_NAME; pinCode_ = param; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::task_handle handle = ThreadManager::GetInstance().Submit( - CONNECT_PIN_DIALOG.c_str(), []() { ConnectExtension(); }); - if (handle != nullptr) { - ThreadManager::GetInstance().Wait(handle); - } + ThreadManager::GetInstance().Submit(CONNECT_PIN_DIALOG.c_str(), []() { ConnectExtension(); }); #else std::thread pinDilog([]() { ConnectExtension(); }); int32_t ret = pthread_setname_np(pinDilog.native_handle(), CONNECT_PIN_DIALOG.c_str()); diff --git a/utils/src/threadManager/dm_thread_manager.cpp b/utils/src/threadManager/dm_thread_manager.cpp index 08036592b..2e60152f4 100644 --- a/utils/src/threadManager/dm_thread_manager.cpp +++ b/utils/src/threadManager/dm_thread_manager.cpp @@ -31,7 +31,7 @@ ffrt::task_handle ThreadManager::Submit(const char* threadName, const std::funct void ThreadManager::Wait(const ffrt::task_handle& handle) { - if (ffrtQueue_ != nullptr) { + if (ffrtQueue_ == nullptr) { LOGE("ThreadManager Wait, ffrtQueue is null."); return; } -- Gitee From 025e52bfef04142f933ea515f8255f08065328fa Mon Sep 17 00:00:00 2001 From: q30043944 Date: Fri, 9 Aug 2024 08:47:44 +0800 Subject: [PATCH 052/520] =?UTF-8?q?=E5=8A=A0=E9=94=81=E7=AE=A1=E6=8E=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../service/src/softbus/softbus_listener.cpp | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index cc8414783..e11c68472 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -61,6 +61,7 @@ static std::mutex g_lockDeviceNotTrust; static std::mutex g_lockDeviceOnLine; static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; +static std::mutex g_lockDeviceIdSet; static std::map>>> discoveredDeviceMap; static std::map> lnnOpsCbkMap; @@ -323,17 +324,20 @@ void SoftbusListener::OnSoftbusDeviceFound(const DeviceInfo *device) } DmDeviceInfo dmDevInfo; ConvertDeviceInfoToDmDevice(*device, dmDevInfo); - if (deviceIdSet.find(std::string(dmDevInfo.deviceId)) == deviceIdSet.end()) { - deviceIdSet.insert(std::string(dmDevInfo.deviceId)); - struct RadarInfo info = { - .funcName = "OnSoftbusDeviceFound", - .stageRes = static_cast(StageRes::STAGE_SUCC), - .peerNetId = "", - .peerUdid = std::string(dmDevInfo.deviceId), - }; - if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { - if (!GetDmRadarHelperObj()->ReportDiscoverResCallback(info)) { - LOGE("ReportDiscoverResCallback failed"); + { + std::lock_guard lock(g_lockDeviceIdSet); + if (deviceIdSet.find(std::string(dmDevInfo.deviceId)) == deviceIdSet.end()) { + deviceIdSet.insert(std::string(dmDevInfo.deviceId)); + struct RadarInfo info = { + .funcName = "OnSoftbusDeviceFound", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .peerNetId = "", + .peerUdid = std::string(dmDevInfo.deviceId), + }; + if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { + if (!GetDmRadarHelperObj()->ReportDiscoverResCallback(info)) { + LOGE("ReportDiscoverResCallback failed"); + } } } } @@ -490,7 +494,10 @@ int32_t SoftbusListener::RefreshSoftbusLNN(const char *pkgName, const DmSubscrib int32_t SoftbusListener::StopRefreshSoftbusLNN(uint16_t subscribeId) { LOGI("StopRefreshSoftbusLNN begin, subscribeId: %{public}d.", (int32_t)subscribeId); - deviceIdSet.clear(); + { + std::lock_guard lock(g_lockDeviceIdSet); + deviceIdSet.clear(); + } int32_t ret = ::StopRefreshLNN(DM_PKG_NAME, subscribeId); struct RadarInfo info = { .funcName = "StopRefreshSoftbusLNN", -- Gitee From 68eda4a21b0993fc4a87527c03cb31d48ef6247b Mon Sep 17 00:00:00 2001 From: unknown_yangzhou Date: Sat, 10 Aug 2024 12:05:54 +0000 Subject: [PATCH 053/520] Add touch discovery type and freq Signed-off-by: unknown_yangzhou --- common/include/dm_anonymous.h | 1 + common/include/dm_constants.h | 1 + common/src/dm_anonymous.cpp | 15 +++++++++++++++ .../include/discovery/discovery_manager.h | 1 + .../service/src/advertise/advertise_manager.cpp | 2 +- .../service/src/discovery/discovery_manager.cpp | 16 +++++++++++++++- 6 files changed, 34 insertions(+), 2 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 94993cc7c..e95a8fcff 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -38,6 +38,7 @@ std::string ConvertMapToJsonString(const std::map &par void ParseMapFromJsonString(const std::string &jsonStr, std::map ¶mMap); bool IsInvalidPeerTargetId(const PeerTargetId &targetId); std::string ConvertCharArray2String(const char *srcData, uint32_t srcLen); +int32_t StringToInt(const std::string &str, int32_t base); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 00927bc59..8bc56951d 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -131,6 +131,7 @@ constexpr const char* DM_PIN_HOLDER_SESSION_NAME = "ohos.distributedhardware.dev constexpr const char* DM_UNBIND_SESSION_NAME = "ohos.distributedhardware.devicemanager.unbind"; constexpr const char* DM_CAPABILITY_OSD = "osdCapability"; constexpr const char* DM_CAPABILITY_APPROACH = "approach"; +constexpr const char* DM_CAPABILITY_TOUCH = "touch"; constexpr const char* DM_CAPABILITY_CASTPLUS = "castPlus"; constexpr const char* DM_CAPABILITY_VIRTUAL_LINK = "virtualLink"; constexpr const char* DM_CAPABILITY_SHARE = "share"; diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 3ede31124..fea9bde51 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -189,5 +189,20 @@ std::string ConvertCharArray2String(const char *srcData, uint32_t srcLen) delete[] dstData; return temp; } + +int32_t StringToInt(const std::string &str, int32_t base) +{ + if (str.empty()) { + LOGE("Str is empty."); + return 0; + } + char *nextPtr = nullptr; + long result = strtol(str.c_str(), &nextPtr, base); + if (errno == ERANGE || *nextPtr != '\0') { + LOGE("parse int error"); + return 0; + } + return static_cast(result); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index 07a725ff6..fd204234e 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -88,6 +88,7 @@ private: bool CompareCapability(uint32_t capabilityType, const std::string &capabilityStr); void OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara); + void UpdateInfoFreq(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); private: std::mutex locks_; diff --git a/services/service/src/advertise/advertise_manager.cpp b/services/service/src/advertise/advertise_manager.cpp index 3e4490281..263203e85 100644 --- a/services/service/src/advertise/advertise_manager.cpp +++ b/services/service/src/advertise/advertise_manager.cpp @@ -48,7 +48,7 @@ int32_t AdvertiseManager::StartAdvertising(const std::string &pkgName, if (advertiseParam.find(PARAM_KEY_DISC_CAPABILITY) != advertiseParam.end()) { capability = advertiseParam.find(PARAM_KEY_DISC_CAPABILITY)->second; } - if (capability == DM_CAPABILITY_APPROACH) { + if (capability == DM_CAPABILITY_APPROACH || capability == DM_CAPABILITY_TOUCH) { dmPubInfo.mode = DmDiscoverMode::DM_DISCOVER_MODE_ACTIVE; } std::string customData = ""; diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 1d7094d39..94177b459 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -30,6 +30,7 @@ const int32_t DISCOVERY_TIMEOUT = 120; const uint16_t DM_INVALID_FLAG_ID = 0; constexpr const char* LNN_DISC_CAPABILITY = "capability"; const std::string TYPE_MINE = "findDeviceMode"; +const int32_t DECIMALISM = 10; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) static std::mutex comDependencyLoadLock; @@ -72,7 +73,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGE("capability copy err."); return ERR_DM_ENABLE_DISCOVERY_LISTENER_FAILED; } - + UpdateInfoFreq(discoverParam, dmSubInfo); if (discoverParam.find(PARAM_KEY_META_TYPE) != discoverParam.end()) { std::string metaType = discoverParam.find(PARAM_KEY_META_TYPE)->second; LOGI("EnableDiscoveryListener, input MetaType = %{public}s in discoverParam map.", metaType.c_str()); @@ -499,6 +500,19 @@ void DiscoveryManager::HandleDiscoveryTimeout(const std::string &pkgName) StopDiscovering(pkgName, subscribeId); } +void DiscoveryManager::UpdateInfoFreq( + const std::map &discoverParam, DmSubscribeInfo &dmSubInfo) +{ + if (auto it = discoverParam.find(PARAM_KEY_DISC_FREQ); it != discoverParam.end()) { + int32_t freq = StringToInt(it->second, DECIMALISM); + if (freq < DmExchangeFreq::DM_LOW || freq > DmExchangeFreq::DM_FREQ_BUTT) { + LOGE("Invalid freq value."); + return; + } + dmSubInfo.freq = static_cast(freq); + } +} + int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, std::string deviceId, bool &isOnline, int32_t &authForm) { -- Gitee From 129c1a1b23e498f50da68e47c33cfed291f46ed4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Mon, 12 Aug 2024 10:05:14 +0800 Subject: [PATCH 054/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/commonunittest/UTTest_permission_manager.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index e28e9ed68..e3c48e8d2 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -50,6 +50,12 @@ constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PAKAGE "com.huawei.msdp.hmringdiscriminator", "CollaborationFwk", }; + +#define PIN_HOLDER_WHITE_LIST_NUM (1) +constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { + "CollaborationFwk", +}; + #define SYSTEM_SA_WHITE_LIST_NUM (4) constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PAKAGE_NAME_SIZE_MAX] = { "Samgr_Networking", @@ -175,15 +181,9 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_002, testing::e */ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::ext::TestSize.Level0) { - std::string processName1(g_authCodeWhiteList[0]); + std::string processName1(g_pinHolderWhiteList[0]); bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName1); ASSERT_EQ(ret, true); - std::string processName2(g_authCodeWhiteList[1]); - ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName2); - ASSERT_EQ(ret, true); - std::string processName3(g_authCodeWhiteList[2]); - ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName3); - ASSERT_EQ(ret, true); } /** -- Gitee From dc2ed0711f17b944b5ed8fbeb6de83c1225ede98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 12 Aug 2024 11:54:29 +0800 Subject: [PATCH 055/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- display/entry/src/main/ets/pages/ConfirmDialog.ets | 1 + 1 file changed, 1 insertion(+) diff --git a/display/entry/src/main/ets/pages/ConfirmDialog.ets b/display/entry/src/main/ets/pages/ConfirmDialog.ets index 796a246d4..598b966e3 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialog.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialog.ets @@ -348,6 +348,7 @@ struct dialogPlusPage { let tmpStr: Record = JSON.parse(data.param) let msg: number = tmpStr.uiStateMsg as number if (msg === MSG_CANCEL_CONFIRM_SHOW) { + console.log('cancel confirm show.') this.destruction() return } -- Gitee From f6fd467e656d3c3a2f59349cce43a37571fcfae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Mon, 12 Aug 2024 14:30:22 +0800 Subject: [PATCH 056/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 38af57afb..4fb7f14e0 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.networkId) - 1); + std::strcpy(devInfo.networkId, testID.c_str()); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); @@ -750,7 +750,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfo.networkId) - 1); + std::strcpy(devInfo.networkId, testID.c_str()); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); -- Gitee From 32e579dcb61913836e49ced6ce775d21a8769a3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Mon, 12 Aug 2024 14:44:34 +0800 Subject: [PATCH 057/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 4fb7f14e0..1133f5f9b 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -750,7 +750,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strcpy(devInfo.networkId, testID.c_str()); + std::strncpy(devInfo.networkId, testID.c_str()); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); -- Gitee From 1e84cbbb6bb3f294d42870f28e58fca003260aed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Mon, 12 Aug 2024 15:08:58 +0800 Subject: [PATCH 058/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 1133f5f9b..94ea71cb0 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strcpy(devInfo.networkId, testID.c_str()); + std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfoId.networkId) - 1); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); @@ -750,7 +750,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strncpy(devInfo.networkId, testID.c_str()); + std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfoId.networkId) - 1); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); -- Gitee From bdcc87a77527b467d7c43bca101bb9eed8325a15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Mon, 12 Aug 2024 15:20:02 +0800 Subject: [PATCH 059/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 94ea71cb0..14c42d393 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfoId.networkId) - 1); + std::strcpy_s(devInfo.networkId, sizeof(devInfoId.networkId) - 1, testID.c_str()); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); @@ -750,7 +750,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strncpy(devInfo.networkId, testID.c_str(), sizeof(devInfoId.networkId) - 1); + std::strcpy_s(devInfo.networkId, sizeof(devInfoId.networkId) - 1, testID.c_str()); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); -- Gitee From ae5c09283d957ee3103898d6eed354371f189af3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A1=8C=E5=A2=9E?= Date: Mon, 12 Aug 2024 15:51:26 +0800 Subject: [PATCH 060/520] add UTs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 行增 --- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 14c42d393..b40fa2128 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -718,7 +718,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_002, testing::ext::TestSize { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strcpy_s(devInfo.networkId, sizeof(devInfoId.networkId) - 1, testID.c_str()); + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); @@ -750,7 +750,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_002, testing::ext::TestSize. { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; - std::strcpy_s(devInfo.networkId, sizeof(devInfoId.networkId) - 1, testID.c_str()); + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); -- Gitee From dd0a510ed06433a807f7a90fca4bce5db2d78563 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 12 Aug 2024 18:12:03 +0800 Subject: [PATCH 061/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=AB=98=E9=A2=91?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../inner_kits/native_cpp/src/device_manager_impl.cpp | 2 +- .../native_cpp/src/notify/device_manager_notify.cpp | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index d2cbff68d..496e85d2a 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -768,7 +768,7 @@ int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(netWorkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetUdidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGD("GetUdidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); 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 997e277c5..72d72c9e3 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 @@ -577,8 +577,8 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGI("DeviceManagerNotify::OnDeviceFound complete with DmDeviceInfo, pkgName:%{public}s, subscribeId:%{public}d.", - pkgName.c_str(), (int32_t)subscribeId); + LOGI("Complete with devInfo, pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceInfo); } @@ -611,8 +611,8 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGI("DeviceManagerNotify::OnDeviceFound complete with DmDeviceBasicInfo, pkgName:%{public}s," - "subscribeId:%{public}d.", pkgName.c_str(), (int32_t)subscribeId); + LOGD("Complete with DmDeviceBasicInfo, pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceBasicInfo); } @@ -654,8 +654,7 @@ void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_ LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDiscoverySuccess in, pkgName:%{public}s, subscribeId:%{public}d.", pkgName.c_str(), - subscribeId); + LOGI("PkgName:%{public}s, subscribeId:%{public}d.", GetAnonyString(pkgName).c_str(), subscribeId); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); -- Gitee From 646a311e5eecb998b409d52fb1ba7590e41ed091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 13 Aug 2024 10:33:03 +0800 Subject: [PATCH 062/520] =?UTF-8?q?=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_service_two.cpp | 39 ++++--------------- 1 file changed, 8 insertions(+), 31 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 73f059e6d..e1ddbdaf9 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -133,27 +133,17 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_201, testing::ext:: * @tc.type: FUNC */ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize.Level0) -{ - DeviceManagerService::GetInstance().IsDMServiceImplReady(); - bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); - EXPECT_EQ(ret, true); -} - -/** - * @tc.name: StopAdvertising_201 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, StopAdvertising_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; std::map advertiseParam; advertiseParam[PARAM_KEY_META_TYPE] = "1"; - int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); - EXPECT_EQ(ret, ERR_DM_POINT_NULL); + DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); std::map advertiseParam2; advertiseParam[PARAM_KEY_PUBLISH_ID] = "12"; - ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam2); - EXPECT_EQ(ret, ERR_DM_POINT_NULL); + DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam2); + DeviceManagerService::GetInstance().IsDMServiceImplReady(); + bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); + EXPECT_EQ(ret, true); } /** @@ -167,28 +157,15 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 targetId.deviceId = "123"; std::map bindParam; bindParam[PARAM_KEY_META_TYPE] = "1"; - int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); - EXPECT_EQ(ret, ERR_DM_LOAD_CUSTOM_META_NODE); + DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); targetId.wifiIp = "192.168.1.1"; std::map bindParam2; - ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam2); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnbindTarget_201 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, UnbindTarget_201, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - PeerTargetId targetId; - targetId.wifiIp = "192.168.1.1"; + DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam2); targetId.deviceId = "123"; std::map unbindParam; unbindParam[PARAM_KEY_META_TYPE] = "1"; int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); - EXPECT_EQ(ret, ERR_DM_LOAD_CUSTOM_META_NODE); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** -- Gitee From be4d135d2921939fd6fa008c0bd2947d9ebb38f6 Mon Sep 17 00:00:00 2001 From: dwx1032708 Date: Mon, 12 Aug 2024 18:47:07 +0800 Subject: [PATCH 063/520] =?UTF-8?q?=E8=A1=A5=E5=85=85DM=20UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: dwx1032708 --- .../UTTest_hichain_auth_connector.cpp | 66 ++++ .../UTTest_ipc_cmd_parser_service.cpp | 286 ++++++++++++++++-- test/unittest/UTTest_ipc_server_stub.cpp | 99 +++++- 3 files changed, 425 insertions(+), 26 deletions(-) diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 1c6626c11..6469f5222 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -416,6 +416,72 @@ HWTEST_F(HiChainAuthConnectorTest, GetCredential_002, testing::ext::TestSize.Lev EXPECT_EQ(ret, ERR_DM_FAILED); } +HWTEST_F(HiChainAuthConnectorTest, GetCredential_003, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = "{invalid_json}"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_004, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_005, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_006, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_007, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(HiChainAuthConnectorTest, GetCredential_008, testing::ext::TestSize.Level0) +{ + std::string publicKey = "test"; + std::string localUdid = "test"; + int32_t osAccountId = 0; + g_processCredentialResultCode = HC_SUCCESS; + g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; + int32_t ret = hiChain_->GetCredential(localUdid, osAccountId, publicKey); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(HiChainAuthConnectorTest, ImportCredential_001, testing::ext::TestSize.Level0) { int32_t localUdid = 0; diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 323b4fd43..9a2b7683a 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -18,32 +18,33 @@ #include #include "device_manager_ipc_interface_code.h" +#include "device_manager_notify.h" +#include "dm_constants.h" +#include "dm_device_info.h" #include "ipc_client_manager.h" #include "ipc_cmd_register.h" -#include "ipc_register_listener_req.h" -#include "ipc_get_trustdevice_rsp.h" -#include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" -#include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_publish_req.h" -#include "ipc_unpublish_req.h" -#include "ipc_set_useroperation_req.h" -#include "ipc_unauthenticate_device_req.h" -#include "ipc_authenticate_device_req.h" +#include "ipc_get_info_by_network_rsp.h" #include "ipc_get_local_device_info_rsp.h" -#include "ipc_set_credential_req.h" -#include "ipc_set_credential_rsp.h" +#include "ipc_get_trustdevice_req.h" +#include "ipc_get_trustdevice_rsp.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" #include "ipc_notify_device_discovery_req.h" +#include "ipc_notify_device_discovery_req.h" #include "ipc_notify_dmfa_result_req.h" #include "ipc_notify_event_req.h" -#include "device_manager_notify.h" +#include "ipc_publish_req.h" +#include "ipc_register_listener_req.h" #include "ipc_req.h" -#include "dm_device_info.h" -#include "dm_constants.h" +#include "ipc_set_credential_req.h" +#include "ipc_set_credential_rsp.h" +#include "ipc_set_useroperation_req.h" +#include "ipc_start_discovery_req.h" +#include "ipc_stop_discovery_req.h" +#include "ipc_unauthenticate_device_req.h" +#include "ipc_unpublish_req.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { @@ -270,7 +271,20 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_014, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_008, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_CREDENTIAL_RESULT; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_015, testing::ext::TestSize.Level0) @@ -324,7 +338,26 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_020, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_011, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_CREATE_PIN_HOLDER; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 100; + DmDeviceBasicInfo deviceBasicInfo; + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + req->SetDeviceBasicInfo(deviceBasicInfo); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_021, testing::ext::TestSize.Level0) @@ -342,7 +375,26 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_022, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_012, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DESTROY_PIN_HOLDER; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 100; + DmDeviceBasicInfo deviceBasicInfo; + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + req->SetDeviceBasicInfo(deviceBasicInfo); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_023, testing::ext::TestSize.Level0) @@ -360,7 +412,26 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_024, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_013, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_CREATE_PIN_HOLDER_RESULT; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 100; + DmDeviceBasicInfo deviceBasicInfo; + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + req->SetDeviceBasicInfo(deviceBasicInfo); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_025, testing::ext::TestSize.Level0) @@ -378,7 +449,26 @@ HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_026, testing::ext::TestSize.L HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_014, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DESTROY_PIN_HOLDER_RESULT; - ASSERT_EQ(ERR_DM_FAILED, TestIpcRequestFuncReqNull(cmdCode)); + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 100; + DmDeviceBasicInfo deviceBasicInfo; + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + req->SetDeviceBasicInfo(deviceBasicInfo); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_027, testing::ext::TestSize.Level0) @@ -791,13 +881,31 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_025, testing::ext::TestSize.Level int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; MessageParcel data; MessageParcel reply; - std::string pkgName = "ohos.dm.test"; + std::string pkgName = "pkgName"; data.WriteString(pkgName); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); if (ptr) { ret = ptr(data, reply); } ASSERT_EQ(ret, ERR_DM_POINT_NULL); + + data.WriteString(pkgName); + sptr remoteObject = nullptr; + data.WriteRemoteObject(remoteObject); + + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, ERR_DM_POINT_NULL); + + data.WriteString(pkgName); + remoteObject = sptr(new IpcClientStub()); + data.WriteRemoteObject(remoteObject); + + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); } HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_026, testing::ext::TestSize.Level0) @@ -1200,6 +1308,82 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_052, testing::ext::TestSize.Level ASSERT_EQ(ret, DM_OK); } +HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_053, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = IMPORT_CREDENTIAL; + int32_t ret = DM_OK; + MessageParcel data; + MessageParcel reply; + std::string pkgName = "ohos.dm.test"; + nlohmann::json jsonObject; + jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_OH; + jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; + std::string credentialInfo = jsonObject.dump(); + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = DELETE_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr1 = GetIpcCmdFunc(cmdCode); + if (ptr1) { + ret = ptr1(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = REQUEST_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr2 = GetIpcCmdFunc(cmdCode); + if (ptr2) { + ret = ptr2(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_054, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = IMPORT_CREDENTIAL; + int32_t ret = DM_OK; + MessageParcel data; + MessageParcel reply; + std::string pkgName = "ohos.dm.test"; + nlohmann::json jsonObject; + jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_MINE; + jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; + std::string credentialInfo = jsonObject.dump(); + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = DELETE_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr1 = GetIpcCmdFunc(cmdCode); + if (ptr1) { + ret = ptr1(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = REQUEST_CREDENTIAL; + data.WriteString(pkgName); + data.WriteString(credentialInfo); + OnIpcCmdFunc ptr2 = GetIpcCmdFunc(cmdCode); + if (ptr2) { + ret = ptr2(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} + HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_016, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DEVICE_DISCOVERY; @@ -1302,6 +1486,64 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_020, testing::ext::TestSize. } ASSERT_EQ(DM_OK, ret); } + +HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_021, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVER_ON_PIN_HOLDER_EVENT; + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + uint16_t subscribeId = 100; + DmDeviceBasicInfo deviceBasicInfo; + req->SetPkgName(pkgName); + req->SetSubscribeId(subscribeId); + req->SetDeviceBasicInfo(deviceBasicInfo); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_029, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVER_ON_PIN_HOLDER_EVENT; + ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); +} + +HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_055, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_ACCESS_CONTROL; + int32_t ret = DM_OK; + MessageParcel data; + MessageParcel reply; + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = CHECK_SAME_ACCOUNT; + OnIpcCmdFunc ptr1 = GetIpcCmdFunc(cmdCode); + if (ptr1) { + ret = ptr1(data, reply); + } + ASSERT_EQ(ret, DM_OK); + + cmdCode = SHIFT_LNN_GEAR; + OnIpcCmdFunc ptr2 = GetIpcCmdFunc(cmdCode); + if (ptr2) { + ret = ptr2(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp index d33ce8f8a..2bbbecb96 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -87,6 +87,23 @@ HWTEST_F(IpcServerStubTest, OnStart_001, testing::ext::TestSize.Level0) ASSERT_EQ(ServiceRunningState::STATE_RUNNING, IpcServerStub::GetInstance().state_); } +/** + * @tc.name: OnStart_002 + * @tc.desc: 1. Set initial state to STATE_NOT_START + * 2. Call OnStart to start the service + * 3. Call OnStop to stop the service + * 4. Check the final state is STATE_NOT_START + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, OnStart_002, testing::ext::TestSize.Level0) +{ + IpcServerStub::GetInstance().state_ = ServiceRunningState::STATE_NOT_START; + IpcServerStub::GetInstance().OnStart(); + IpcServerStub::GetInstance().OnStop(); + ASSERT_EQ(ServiceRunningState::STATE_NOT_START, IpcServerStub::GetInstance().state_); +} + /** * @tc.name: Init_001 * @tc.desc: 1. Call IpcServerStub OnStart @@ -275,6 +292,8 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_004, testing::ext::Tes * 3. check ret is DM_OK * 4. Call IpcServerStub RegisterDeviceManagerListener with same pkgName another listener * 5. check result is DM_OK + * 6. earse pkgName for appRecipient_ + * 7. check result is DM_OK * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -294,6 +313,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener2); // 5. check result is DM_OK ASSERT_EQ(result, DM_OK); + sptr listener3 = sptr(new IpcClientStub()); + // 6. earse pkgName for appRecipient_ + IpcServerStub::GetInstance().appRecipient_.erase(pkgName); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener3); + // 7. check result is DM_OK + ASSERT_EQ(result, DM_OK); } /** @@ -393,6 +418,8 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_004, testing::ext::T * 3. check ret is DM_OK * 4. Call IpcServerStub UnRegisterDeviceManagerListener * 5. check ret is DM_OK + * 6. Call IpcServerStub UnRegisterDeviceManagerListener + * 7. check ret is DM_OK * @tc.type: FUNC * @tc.require: AR000GHSJK */ @@ -412,8 +439,58 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_005, testing::ext::T result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(testPkgName); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); - sptr dmListener = IpcServerStub::GetInstance().dmListener_[pkgName]; - ASSERT_NE(dmListener, nullptr); + IpcServerStub::GetInstance().appRecipient_.erase(pkgName); + // 6. Call IpcServerStub UnRegisterDeviceManagerListener + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + // 7. check ret is DM_OK + ASSERT_EQ(result, DM_OK); +} + +/** + * @tc.name: SendALL_001 + * @tc.desc: 1. Set PkgName1 is com.ohos.SendALL_001 + * 2. Set PkgName2 is com.ohos.SendALL_002 + * 3. Add listener1 (nullptr) to dmListener_ with key pkgName1 + * 4. Add listener2 to dmListener_ with key listener2 + * 5. Call IpcServerStub::SendALL with cmdCode, req, rsp + * 6. Check result is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, SendALL_001, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = -1; + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + std::string pkgName1 = "com.ohos.SendALL_001"; + std::string pkgName2 = "com.ohos.SendALL_002"; + sptr listener1 = nullptr; + sptr listener2 = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().dmListener_[pkgName1] = listener1; + IpcServerStub::GetInstance().dmListener_[pkgName2] = listener2; + int32_t result = IpcServerStub::GetInstance().SendALL(cmdCode, req, rsp); + ASSERT_EQ(result, DM_OK); + IpcServerStub::GetInstance().dmListener_.clear(); +} + +/** + * @tc.name: GetDmListenerPkgName_001 + * @tc.desc: 1. Set pkgName is com.ohos.GetDmListenerPkgName_001 + * 2. Create listener and add it to dmListener_ with key pkgName + * 3. Call IpcServerStub::GetDmListenerPkgName with remote object + * 4. Check the result is not empty + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(IpcServerStubTest, GetDmListenerPkgName_001, testing::ext::TestSize.Level0) +{ + sptr remote(new IpcClientStub()); + std::string pkgName = "com.ohos.GetDmListenerPkgName_001"; + sptr listener = sptr(new IpcClientStub()); + IpcServerStub::GetInstance().dmListener_[pkgName] = listener; + std::string ret = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); + EXPECT_TRUE(ret.empty() || (ret == pkgName)); + IpcServerStub::GetInstance().dmListener_.clear(); } /** @@ -554,7 +631,7 @@ HWTEST_F(IpcServerStubTest, OnRemoveSystemAbility_001, testing::ext::TestSize.Le */ HWTEST_F(IpcServerStubTest, OnRemoveSystemAbility_002, testing::ext::TestSize.Level0) { - int32_t systemAbilityId = 9999; + int32_t systemAbilityId = DISTRIBUTED_HARDWARE_SA_ID; std::string deviceId; IpcServerStub::GetInstance().OnRemoveSystemAbility(systemAbilityId, deviceId); ASSERT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); @@ -582,7 +659,21 @@ HWTEST_F(IpcServerStubTest, OnAddSystemAbility_002, testing::ext::TestSize.Level int32_t systemAbilityId = 9999; std::string deviceId; IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); - ASSERT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + + systemAbilityId = SOFTBUS_SERVER_SA_ID; + IpcServerStub::GetInstance().registerToService_ = false; + IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + systemAbilityId = SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN; + IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + + systemAbilityId = SCREENLOCK_SERVICE_ID; + IpcServerStub::GetInstance().OnAddSystemAbility(systemAbilityId, deviceId); + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } /** -- Gitee From 649d504e3a30e265efe01684baaf275a028da4fd Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Tue, 13 Aug 2024 14:05:20 +0800 Subject: [PATCH 064/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=E4=B8=8D=E4=B8=80=E8=87=B4=20Signed-off-by:=20liuzhon?= =?UTF-8?q?gming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- display/AppScope/app.json | 4 ++-- display/entry/src/main/resources/zh_HK/element/string.json | 2 +- display/entry/src/main/resources/zz_ZX/element/string.json | 4 ++++ 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 60a7a4125..346650e60 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -4,8 +4,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000018, - "versionName": "1.0.18", + "versionCode": 1000019, + "versionName": "1.0.19", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/resources/zh_HK/element/string.json b/display/entry/src/main/resources/zh_HK/element/string.json index 0cac2b3e9..86d184a73 100644 --- a/display/entry/src/main/resources/zh_HK/element/string.json +++ b/display/entry/src/main/resources/zh_HK/element/string.json @@ -34,7 +34,7 @@ }, { "name":"dm_is_trust_device", - "value":"%s 信任此裝置?" + "value":"%s信任此裝置?" }, { "name":"dm_confirm_title_hap", diff --git a/display/entry/src/main/resources/zz_ZX/element/string.json b/display/entry/src/main/resources/zz_ZX/element/string.json index 868ace1ac..1fdf6a26c 100644 --- a/display/entry/src/main/resources/zz_ZX/element/string.json +++ b/display/entry/src/main/resources/zz_ZX/element/string.json @@ -79,6 +79,10 @@ { "name":"dm_enter_peer_connect_code", "value":"[TS_949559]_Enter connection code" + }, + { + "name":"dm_password_error", + "value":"[TS_958913]_Incorrect password. Connection failed." } ] } \ No newline at end of file -- Gitee From e6940c422e5648e69be96de016fcebc19f03679e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 13 Aug 2024 15:17:54 +0800 Subject: [PATCH 065/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_service_two.cpp | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index e1ddbdaf9..3a5d354c5 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -141,18 +141,6 @@ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize. std::map advertiseParam2; advertiseParam[PARAM_KEY_PUBLISH_ID] = "12"; DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam2); - DeviceManagerService::GetInstance().IsDMServiceImplReady(); - bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); - EXPECT_EQ(ret, true); -} - -/** - * @tc.name: BindTarget_201 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; PeerTargetId targetId; targetId.deviceId = "123"; std::map bindParam; @@ -164,8 +152,10 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 targetId.deviceId = "123"; std::map unbindParam; unbindParam[PARAM_KEY_META_TYPE] = "1"; - int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); + DeviceManagerService::GetInstance().IsDMServiceImplReady(); + bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); + EXPECT_EQ(ret, true); } /** -- Gitee From 153fc81b54a54375646a3f177789e04b61d554b4 Mon Sep 17 00:00:00 2001 From: w30042960 Date: Mon, 12 Aug 2024 14:55:32 +0800 Subject: [PATCH 066/520] add UT Signed-off-by: w30042960 --- .../UTTest_dm_auth_manager_first.cpp | 44 ++++++- .../UTTest_dm_auth_manager_second.cpp | 107 +++++++++++++++++- 2 files changed, 149 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 86619a9ca..19481affc 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -134,11 +134,23 @@ HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_002, testing::ext::TestSiz ASSERT_TRUE(authManager_->authRequestState_ != nullptr); } +HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_003, testing::ext::TestSize.Level0) +{ + std::string name = "test"; + std::shared_ptr authRequestState = std::make_shared(); + authManager_->SetAuthRequestState(authRequestState); + authManager_->HandleAuthenticateTimeout(name); + std::shared_ptr authResponseState = std::make_shared(); + authManager_->SetAuthResponseState(authResponseState); + ASSERT_TRUE(authManager_->authRequestState_ != nullptr); +} + HWTEST_F(DmAuthManagerTest, EstablishAuthChannel_001, testing::ext::TestSize.Level0) { std::shared_ptr sessionSession = std::shared_ptr(); std::shared_ptr authRequestContext = std::make_shared(); std::string deviceId1; + authManager_->AbilityNegotiate(); int32_t ret = authManager_->EstablishAuthChannel(deviceId1); ASSERT_EQ(ret, DM_OK); } @@ -214,6 +226,9 @@ HWTEST_F(DmAuthManagerTest, AddMember_002, testing::ext::TestSize.Level0) authManager_->authResponseContext_ = nullptr; int32_t ret = authManager_->AddMember(pinCode); ASSERT_EQ(ret, ERR_DM_FAILED); + authManager_->isAddingMember_ = true; + ret = authManager_->AddMember(pinCode); + ASSERT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, JoinNetwork_001, testing::ext::TestSize.Level0) @@ -295,8 +310,15 @@ HWTEST_F(DmAuthManagerTest, SetPageId_002, testing::ext::TestSize.Level0) int32_t status = 2; authManager_->OnMemberJoin(requestId, status); authManager_->OnDataReceived(sessionId, message); + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->OnDataReceived(sessionId, message); + authManager_->authRequestState_ = nullptr; + authManager_->authResponseState_ = std::make_shared(); + authManager_->OnDataReceived(sessionId, message); int32_t ret = authManager_->SetPageId(pageId); - ASSERT_EQ(ret, ERR_DM_AUTH_NOT_START); + ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, SetReasonAndFinish_001, testing::ext::TestSize.Level0) @@ -597,6 +619,20 @@ HWTEST_F(DmAuthManagerTest, UnBindDevice_004, testing::ext::TestSize.Level0) ASSERT_EQ(ret, ERR_DM_FAILED); } +HWTEST_F(DmAuthManagerTest, UnBindDevice_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos_test"; + std::string udidHash = "networkId"; + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseContext_ = std::make_shared(); + authManager_->isAuthenticateDevice_ = false; + int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); + ASSERT_EQ(ret, ERR_DM_FAILED); + authManager_->isAuthenticateDevice_ = true; + ret = authManager_->UnBindDevice(pkgName, udidHash); + ASSERT_EQ(ret, DM_OK); +} + HWTEST_F(DmAuthManagerTest, RequestCredential001, testing::ext::TestSize.Level0) { authManager_->hiChainAuthConnector_ = std::make_shared(); @@ -1074,6 +1110,12 @@ HWTEST_F(DmAuthManagerTest, PutAccessControlList001, testing::ext::TestSize.Leve { authManager_->PutAccessControlList(); ASSERT_EQ(authManager_->isAuthDevice_, false); + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->PutAccessControlList(); + ASSERT_EQ(authManager_->isAuthDevice_, false); + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->PutAccessControlList(); + ASSERT_EQ(authManager_->isAuthDevice_, false); } HWTEST_F(DmAuthManagerTest, BindSocketFail_001, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 3fec91f62..5fbfd788d 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -18,6 +18,7 @@ #include "nlohmann/json.hpp" #include "dm_log.h" +#include "dm_crypto.h" #include "dm_constants.h" #include "dm_auth_manager.h" #include "auth_message_processor.h" @@ -260,6 +261,15 @@ HWTEST_F(DmAuthManagerTest, HandleMemberJoinImportAuthCode_003, testing::ext::Te ASSERT_EQ(authManager_->isFinishOfLocal_, true); } +HWTEST_F(DmAuthManagerTest, HandleMemberJoinImportAuthCode_004, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + int32_t status = 0; + authManager_->authResponseContext_->requestId = 0; + authManager_->HandleMemberJoinImportAuthCode(requestId, status); + ASSERT_EQ(authManager_->isFinishOfLocal_, true); +} + HWTEST_F(DmAuthManagerTest, RespNegotiate_001, testing::ext::TestSize.Level0) { int64_t requestId = 1; @@ -295,6 +305,19 @@ HWTEST_F(DmAuthManagerTest, RespNegotiate_004, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } +HWTEST_F(DmAuthManagerTest, RespNegotiate_005, testing::ext::TestSize.Level0) +{ + int64_t requestId = 1; + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseContext_->dmVersion = "4.1.5.1"; + authManager_->authResponseContext_->bindLevel = 0; + authManager_->RespNegotiate(requestId); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->RespNegotiate(requestId); + ASSERT_EQ(authManager_->isFinishOfLocal_, true); +} + HWTEST_F(DmAuthManagerTest, SendAuthRequest_001, testing::ext::TestSize.Level0) { int64_t sessionId = 1; @@ -329,6 +352,15 @@ HWTEST_F(DmAuthManagerTest, SendAuthRequest_003, testing::ext::TestSize.Level0) authManager_->authResponseContext_->deviceId = "deviceId"; authManager_->authResponseContext_->reply = -20018; authManager_->SendAuthRequest(sessionId); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 0; + authManager_->SendAuthRequest(sessionId); + authManager_->authResponseContext_->dmVersion = ""; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->SendAuthRequest(sessionId); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->SendAuthRequest(sessionId); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } @@ -341,6 +373,11 @@ HWTEST_F(DmAuthManagerTest, GetAuthRequestContext_001, testing::ext::TestSize.Le authManager_->authRequestContext_->localAccountId = "123456789"; authManager_->authResponseContext_->localUserId = 123456789; authManager_->GetAuthRequestContext(); + authManager_->authResponseContext_->isOnline = false; + authManager_->GetAuthRequestContext(); + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->haveCredential = true; + authManager_->GetAuthRequestContext(); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } @@ -371,6 +408,19 @@ HWTEST_F(DmAuthManagerTest, ProcessAuthRequestExt_004, testing::ext::TestSize.Le authManager_->authResponseContext_->isIdenticalAccount = false; authManager_->authResponseContext_->isAuthCodeReady = false; authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authed = true; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->authed = false; + authManager_->authResponseContext_->isOnline = false; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->authed = true; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->isOnline = true; + authManager_->ProcessAuthRequestExt(sessionId); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } @@ -677,7 +727,16 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_004, testing::ext::TestSize.Leve authManager_->authResponseContext_->dmVersion = ""; authManager_->authResponseContext_->bindLevel = 0; authManager_->ShowStartAuthDialog(); - ASSERT_EQ(authManager_->authResponseContext_->bindLevel, 0); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 0; + authManager_->ShowStartAuthDialog(); + authManager_->authResponseContext_->dmVersion = ""; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->ShowStartAuthDialog(); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 1; + authManager_->ShowStartAuthDialog(); + ASSERT_EQ(authManager_->authResponseContext_->bindLevel, 1); } HWTEST_F(DmAuthManagerTest, ProcessPincode_001, testing::ext::TestSize.Level0) @@ -706,6 +765,18 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level0) authManager_->authUiStateMgr_ = nullptr; int32_t ret = authManager_->ProcessPincode(pinCode); ASSERT_EQ(ret, ERR_DM_FAILED); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 0; + ret = authManager_->ProcessPincode(pinCode); + ASSERT_EQ(ret, ERR_DM_FAILED); + authManager_->authResponseContext_->dmVersion = ""; + authManager_->authResponseContext_->bindLevel = 1; + ret = authManager_->ProcessPincode(pinCode); + ASSERT_EQ(ret, ERR_DM_FAILED); + authManager_->authResponseContext_->dmVersion = "5.0.1"; + authManager_->authResponseContext_->bindLevel = 1; + ret = authManager_->ProcessPincode(pinCode); + ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level0) @@ -1320,6 +1391,9 @@ HWTEST_F(DmAuthManagerTest, InitAuthState_001, testing::ext::TestSize.Level0) authManager_->timer_ = nullptr; authManager_->InitAuthState(pkgName, authType, deviceId, extra); ASSERT_EQ(authManager_->isFinishOfLocal_, true); + authManager_->timer_ = std::make_shared(); + authManager_->InitAuthState(pkgName, authType, deviceId, extra); + ASSERT_EQ(authManager_->isFinishOfLocal_, true); } HWTEST_F(DmAuthManagerTest, HandleSessionHeartbeat_001, testing::ext::TestSize.Level0) @@ -1390,6 +1464,37 @@ HWTEST_F(DmAuthManagerTest, CheckTrustState_005, testing::ext::TestSize.Level0) int32_t ret = authManager_->CheckTrustState(); ASSERT_EQ(ret, DM_OK); } + +HWTEST_F(DmAuthManagerTest, CheckTrustState_006, testing::ext::TestSize.Level0) +{ + std::string udid = ""; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->authType = 6; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->importAuthCode_ = "importAuthCode_"; + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->reply = 1; + authManager_->authResponseContext_->authType = 1; + authManager_->authResponseContext_->isAuthCodeReady = true; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, DM_OK); + authManager_->importAuthCode_ = Crypto::Sha256("importAuthCode_"); + ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, DM_OK); + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, DM_OK); + authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + ret = authManager_->CheckTrustState(); + authManager_->OnScreenLocked(); + authManager_->HandleDeviceNotTrust(udid); + udid = "udidTest"; + authManager_->HandleDeviceNotTrust(udid); + authManager_->authRequestState_ = nullptr; + authManager_->OnScreenLocked(); + ASSERT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From 4e657b7254d8b02ad5c8c7c8a6993aca1af40371 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 13 Aug 2024 17:18:36 +0800 Subject: [PATCH 067/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/src/device_manager_impl.cpp | 240 +++++++++--------- .../src/ipc/standard/ipc_client_manager.cpp | 4 +- .../src/notify/device_manager_notify.cpp | 16 +- .../js4.0/src/native_devicemanager_js.cpp | 10 +- .../service/src/device_manager_service.cpp | 86 +++---- .../src/device_manager_service_listener.cpp | 6 +- .../src/discovery/discovery_manager.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 12 +- .../service/src/softbus/softbus_listener.cpp | 12 +- .../service/src/softbus/softbus_publish.cpp | 6 +- 10 files changed, 189 insertions(+), 205 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 496e85d2a..8dcf42f79 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -120,7 +120,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh return ERR_DM_INPUT_PARA_INVALID; } DmTraceStart(std::string(DM_HITRACE_INIT)); - LOGI("InitDeviceManager start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); int32_t ret = DM_OK; int32_t retryNum = 0; @@ -145,7 +145,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); DmTraceEnd(); - LOGI("InitDeviceManager success"); + LOGI("Success"); SysEventWrite(std::string(DM_INIT_DEVICE_MANAGER_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(DM_INIT_DEVICE_MANAGER_SUCCESS_MSG)); return DM_OK; @@ -157,7 +157,7 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) LOGE("UnInitDeviceManager Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnInitDeviceManager start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); int32_t ret = ipcClientProxy_->UnInit(pkgName); if (ret != DM_OK) { @@ -166,7 +166,7 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) } DeviceManagerNotify::GetInstance().UnRegisterPackageCallback(pkgName); - LOGI("UnInitDeviceManager success"); + LOGI("Success"); return DM_OK; } @@ -196,7 +196,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetTrustedDeviceList start, pkgName: %{public}s, extra: %{public}s", pkgName.c_str(), extra.c_str()); + LOGI("Start, pkgName: %{public}s, extra: %{public}s", GetAnonyString(pkgName).c_str(), extra.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -215,8 +215,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons } deviceList = rsp->GetDeviceVec(); - LOGI("DeviceManagerImpl::GetTrustedDeviceList completed, pkgName: %{public}s, device size %{public}zu", - pkgName.c_str(), deviceList.size()); + LOGI("Completed, device size %{public}zu", deviceList.size()); return DM_OK; } @@ -227,8 +226,8 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetTrustedDeviceList start, pkgName: %{public}s, extra: %{public}s, isRefresh: %{public}d", pkgName.c_str(), - extra.c_str(), isRefresh); + LOGI("Start, pkgName: %{public}s, extra: %{public}s, isRefresh: %{public}d", GetAnonyString(pkgName).c_str(), + extra.c_str(), isRefresh); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -247,15 +246,14 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons return ret; } deviceList = rsp->GetDeviceVec(); - LOGI("DeviceManagerImpl::GetTrustedDeviceList completed, pkgName: %{public}s, device size %{public}zu", - pkgName.c_str(), deviceList.size()); + LOGI("Completed, device size %{public}zu", deviceList.size()); return DM_OK; } int32_t DeviceManagerImpl::GetAvailableDeviceList(const std::string &pkgName, std::vector &deviceList) { - LOGI("GetAvailableDeviceList start, pkgName: %{public}s.", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s.", GetAnonyString(pkgName).c_str()); std::vector deviceListTemp; std::string extra = ""; int32_t ret = GetTrustedDeviceList(pkgName, extra, false, deviceListTemp); @@ -268,8 +266,7 @@ int32_t DeviceManagerImpl::GetAvailableDeviceList(const std::string &pkgName, ConvertDeviceInfoToDeviceBasicInfo(item, deviceBasicInfo); deviceList.push_back(deviceBasicInfo); } - LOGI("DeviceManagerImpl::GetAvailableDeviceList completed, pkgName: %{public}s, device size %{public}zu", - pkgName.c_str(), deviceList.size()); + LOGI("Completed, device size %{public}zu", deviceList.size()); return DM_OK; } @@ -281,7 +278,7 @@ int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, const std:: GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::GetDeviceInfo start, pkgName: %{public}s networKId : %{public}s", pkgName.c_str(), + LOGI("Start, pkgName: %{public}s networKId : %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -300,16 +297,14 @@ int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, const std:: } deviceInfo = rsp->GetDeviceInfo(); - LOGI("DeviceManagerImpl::GetDeviceInfo completed, pkgname = %{public}s networKId = %{public}s deviceName" - " = %{public}s", - req->GetPkgName().c_str(), GetAnonyString(req->GetNetWorkId()).c_str(), + LOGI("Completed, networKId = %{public}s deviceName = %{public}s", GetAnonyString(req->GetNetWorkId()).c_str(), GetAnonyString(deviceInfo.deviceName).c_str()); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDeviceInfo &info) { - LOGI("DeviceManagerImpl::GetLocalDeviceInfo start, pkgName: %{public}s", pkgName.c_str()); + LOGD("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); DmTraceStart(std::string(DM_HITRACE_GET_LOCAL_DEVICE_INFO)); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -330,7 +325,7 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDevi info = rsp->GetLocalDeviceInfo(); DmTraceEnd(); - LOGI("DeviceManagerImpl::GetLocalDeviceInfo completed, pkgname = %{public}s", req->GetPkgName().c_str()); + LOGI("Completed"); SysEventWrite(std::string(GET_LOCAL_DEVICE_INFO_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(GET_LOCAL_DEVICE_INFO_SUCCESS_MSG)); return DM_OK; @@ -343,7 +338,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, LOGE("RegisterDevStateCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::RegisterDevStateCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { @@ -361,7 +356,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, } #endif DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); - LOGI("RegisterDevStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -372,9 +367,9 @@ int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, LOGE("RegisterDevStatusCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::RegisterDevStatusCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterDeviceStatusCallback(pkgName, callback); - LOGI("RegisterDevStatusCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } @@ -384,9 +379,9 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName LOGE("UnRegisterDevStateCallback Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDevStateCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); - LOGI("UnRegisterDevStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -396,9 +391,9 @@ int32_t DeviceManagerImpl::UnRegisterDevStatusCallback(const std::string &pkgNam LOGE("UnRegisterDevStatusCallback Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDevStatusCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterDeviceStatusCallback(pkgName); - LOGI("UnRegisterDevStatusCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -411,7 +406,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StartDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeInfo.subscribeId, callback); @@ -435,7 +430,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons } DmTraceEnd(); - LOGI("StartDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); return DM_OK; @@ -449,7 +444,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StartDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); uint16_t subscribeId = 0; { std::lock_guard autoLock(subscribIdLock); @@ -481,7 +476,7 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint } DmTraceEnd(); - LOGI("StartDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); return DM_OK; @@ -493,7 +488,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint1 LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StopDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -511,7 +506,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint1 } DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); - LOGI("StopDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -521,7 +516,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::stri LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StopDeviceDiscovery start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); uint16_t subscribeId = 0; { std::lock_guard autoLock(subscribIdLock); @@ -548,7 +543,7 @@ int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::stri } DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); - LOGI("StopDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -560,7 +555,7 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co return ERR_DM_INPUT_PARA_INVALID; } - LOGI("PublishDeviceDiscovery start, pkgName %{public}s", pkgName.c_str()); + LOGI("Start, pkgName %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterPublishCallback(pkgName, publishInfo.publishId, callback); std::shared_ptr req = std::make_shared(); @@ -580,7 +575,7 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co return ret; } - LOGI("PublishDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -591,7 +586,7 @@ int32_t DeviceManagerImpl::UnPublishDeviceDiscovery(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnPublishDeviceDiscovery start, pkgName %{public}s", pkgName.c_str()); + LOGI("Start, pkgName %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -609,7 +604,7 @@ int32_t DeviceManagerImpl::UnPublishDeviceDiscovery(const std::string &pkgName, } DeviceManagerNotify::GetInstance().UnRegisterPublishCallback(pkgName, publishId); - LOGI("UnPublishDeviceDiscovery completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -621,7 +616,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("AuthenticateDevice start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmTraceStart(std::string(DM_HITRACE_AUTH_TO_CONSULT)); std::string strDeviceId = deviceInfo.deviceId; @@ -648,7 +643,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ return ret; } DmTraceEnd(); - LOGI("AuthenticateDevice completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -658,7 +653,7 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons LOGE("UnAuthenticateDevice error: Invalid para. pkgName %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnAuthenticateDevice start, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), + LOGI("Start, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(std::string(deviceInfo.networkId)).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -679,7 +674,7 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons SysEventWrite(std::string(UNAUTHENTICATE_DEVICE_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(UNAUTHENTICATE_DEVICE_SUCCESS_MSG)); - LOGI("UnAuthenticateDevice completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -691,10 +686,10 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pk return ERR_DM_INPUT_PARA_INVALID; } - LOGI("dRegisterDeviceManagerFaCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); RegisterUiStateCallback(pkgName); - LOGI("DeviceManagerImpl::RegisterDeviceManagerFaCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -705,10 +700,10 @@ int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string & return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDeviceManagerFaCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); UnRegisterUiStateCallback(pkgName); - LOGI("UnRegisterDevStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -737,7 +732,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t params.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("SetUserOperation start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -756,7 +751,7 @@ int32_t DeviceManagerImpl::SetUserOperation(const std::string &pkgName, int32_t LOGE("CheckAuthentication Failed with ret %{public}d", ret); return ret; } - LOGI("SetUserOperation completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -768,7 +763,7 @@ int32_t DeviceManagerImpl::GetUdidByNetworkId(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(netWorkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGD("GetUdidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGD("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -798,7 +793,7 @@ int32_t DeviceManagerImpl::GetUuidByNetworkId(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(netWorkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetUuidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -842,7 +837,7 @@ int32_t DeviceManagerImpl::RegisterUiStateCallback(const std::string &pkgName) LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("RegisterUiStateCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -993,7 +988,7 @@ int32_t DeviceManagerImpl::RegisterCredentialCallback(const std::string &pkgName return ERR_DM_INPUT_PARA_INVALID; } - LOGI("RegisterCredentialCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterCredentialCallback(pkgName, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1010,7 +1005,7 @@ int32_t DeviceManagerImpl::RegisterCredentialCallback(const std::string &pkgName LOGE("RegisterCredentialCallback error: Failed with ret %{public}d", ret); return ret; } - LOGI("RegisterCredentialCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } @@ -1020,7 +1015,7 @@ int32_t DeviceManagerImpl::UnRegisterCredentialCallback(const std::string &pkgNa LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterCredentialCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterCredentialCallback(pkgName); std::shared_ptr req = std::make_shared(); @@ -1038,7 +1033,7 @@ int32_t DeviceManagerImpl::UnRegisterCredentialCallback(const std::string &pkgNa LOGE("UnRegisterCredentialCallback Failed with ret %{public}d", ret); return ret; } - LOGI("UnRegisterCredentialCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1052,7 +1047,7 @@ int32_t DeviceManagerImpl::NotifyEvent(const std::string &pkgName, const int32_t LOGE("NotifyEvent eventId invalid"); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("NotifyEvent start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -1070,7 +1065,7 @@ int32_t DeviceManagerImpl::NotifyEvent(const std::string &pkgName, const int32_t LOGE("NotifyEvent failed with ret %{public}d", ret); return ret; } - LOGI("NotifyEvent completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1080,8 +1075,7 @@ int32_t DeviceManagerImpl::RequestCredential(const std::string &pkgName, std::st LOGE("RequestCredential failed, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::RequestCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("Request credential start."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::map requestParam; requestParam.emplace(DM_CREDENTIAL_TYPE, DM_TYPE_MINE); std::string reqParaStr = ConvertMapToJsonString(requestParam); @@ -1100,7 +1094,7 @@ int32_t DeviceManagerImpl::RequestCredential(const std::string &pkgName, std::st return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("request device credential completed."); + LOGI("Completed."); return DM_OK; } @@ -1111,8 +1105,7 @@ int32_t DeviceManagerImpl::CheckCredential(const std::string &pkgName, const std LOGE("Check the credential is invalid para."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::CheckCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("start to CheckCredential."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -1130,7 +1123,7 @@ int32_t DeviceManagerImpl::CheckCredential(const std::string &pkgName, const std return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("Check credential to device completed."); + LOGI("Completed."); return DM_OK; } @@ -1141,8 +1134,7 @@ int32_t DeviceManagerImpl::ImportCredential(const std::string &pkgName, const st LOGE("import the credential is invalid para."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::ImportCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("start to ImportCredential."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::map requestParam; requestParam.emplace(DM_CREDENTIAL_TYPE, DM_TYPE_MINE); requestParam.emplace(DM_CREDENTIAL_REQJSONSTR, reqJsonStr); @@ -1164,7 +1156,7 @@ int32_t DeviceManagerImpl::ImportCredential(const std::string &pkgName, const st return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("import credential to device completed."); + LOGI("Completed."); return DM_OK; } @@ -1175,8 +1167,7 @@ int32_t DeviceManagerImpl::DeleteCredential(const std::string &pkgName, const st LOGE("Delete the credential is invalid para."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::DeleteCredential start, pkgName: %{public}s", pkgName.c_str()); - LOGI("start to DeleteCredential."); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::map requestParam; requestParam.emplace(DM_CREDENTIAL_TYPE, DM_TYPE_MINE); requestParam.emplace(DM_CREDENTIAL_REQJSONSTR, reqJsonStr); @@ -1198,13 +1189,13 @@ int32_t DeviceManagerImpl::DeleteCredential(const std::string &pkgName, const st return ret; } returnJsonStr = rsp->GetCredentialResult(); - LOGI("Delete credential to device completed."); + LOGI("Completed."); return DM_OK; } int32_t DeviceManagerImpl::OnDmServiceDied() { - LOGI("OnDmServiceDied begin"); + LOGI("Start"); int32_t ret = ipcClientProxy_->OnDmServiceDied(); if (ret != DM_OK) { LOGE("OnDmServiceDied failed, ret: %{public}d", ret); @@ -1221,7 +1212,7 @@ int32_t DeviceManagerImpl::GetEncryptedUuidByNetworkId(const std::string &pkgNam "%{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetEncryptedUuidByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1240,7 +1231,7 @@ int32_t DeviceManagerImpl::GetEncryptedUuidByNetworkId(const std::string &pkgNam return ret; } uuid = rsp->GetUuid(); - LOGI("GetEncryptedUuidByNetworkId complete, uuid: %{public}s", GetAnonyString(uuid).c_str()); + LOGI("Complete, uuid: %{public}s", GetAnonyString(uuid).c_str()); return DM_OK; } @@ -1251,7 +1242,7 @@ int32_t DeviceManagerImpl::GenerateEncryptedUuid(const std::string &pkgName, con LOGE("DeviceManagerImpl::GenerateEncryptedUuid error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GenerateEncryptedUuid start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1271,25 +1262,25 @@ int32_t DeviceManagerImpl::GenerateEncryptedUuid(const std::string &pkgName, con return ret; } encryptedUuid = rsp->GetUuid(); - LOGI("GenerateEncryptedUuid complete, encryptedUuid: %{public}s", GetAnonyString(encryptedUuid).c_str()); + LOGI("Complete, encryptedUuid: %{public}s", GetAnonyString(encryptedUuid).c_str()); return DM_OK; } int32_t DeviceManagerImpl::CheckAPIAccessPermission() { - LOGI("DeviceManagerImpl::CheckAPIAccessPermission"); + LOGI("Start"); return CheckApiPermission(SYSTEM_BASIC); } int32_t DeviceManagerImpl::CheckNewAPIAccessPermission() { - LOGI("DeviceManagerImpl::CheckNewAPIAccessPermission"); + LOGI("Start"); return CheckApiPermission(NORMAL); } int32_t DeviceManagerImpl::GetLocalDeviceNetWorkId(const std::string &pkgName, std::string &networkId) { - LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { @@ -1297,14 +1288,13 @@ int32_t DeviceManagerImpl::GetLocalDeviceNetWorkId(const std::string &pkgName, s return ret; } networkId = std::string(info.networkId); - LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId end, pkgName : %{public}s, networkId : %{public}s", - pkgName.c_str(), GetAnonyString(networkId).c_str()); + LOGI("End, networkId : %{public}s", GetAnonyString(networkId).c_str()); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceId(const std::string &pkgName, std::string &deviceId) { - LOGI("DeviceManagerImpl::GetLocalDeviceId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { @@ -1312,14 +1302,13 @@ int32_t DeviceManagerImpl::GetLocalDeviceId(const std::string &pkgName, std::str return ret; } deviceId = std::string(info.deviceId); - LOGI("DeviceManagerImpl::GetLocalDeviceId end, pkgName : %{public}s, deviceId : %{public}s", pkgName.c_str(), - GetAnonyString(deviceId).c_str()); + LOGI("End, deviceId : %{public}s", GetAnonyString(deviceId).c_str()); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceName(const std::string &pkgName, std::string &deviceName) { - LOGI("DeviceManagerImpl::GetLocalDeviceName start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { @@ -1327,14 +1316,13 @@ int32_t DeviceManagerImpl::GetLocalDeviceName(const std::string &pkgName, std::s return ret; } deviceName = std::string(info.deviceName); - LOGI("DeviceManagerImpl::GetLocalDeviceName end, pkgName : %{public}s, deviceName : %{public}s", pkgName.c_str(), - GetAnonyString(deviceName).c_str()); + LOGI("End, deviceName : %{public}s", GetAnonyString(deviceName).c_str()); return DM_OK; } int32_t DeviceManagerImpl::GetLocalDeviceType(const std::string &pkgName, int32_t &deviceType) { - LOGI("DeviceManagerImpl::GetLocalDeviceType start, pkgName : %{public}s", pkgName.c_str()); + LOGI("Start, pkgName : %{public}s", pkgName.c_str()); DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { @@ -1342,8 +1330,7 @@ int32_t DeviceManagerImpl::GetLocalDeviceType(const std::string &pkgName, int32 return ret; } deviceType = info.deviceTypeId; - LOGI("DeviceManagerImpl::GetLocalDeviceType end, pkgName : %{public}s, deviceType : %{public}d", pkgName.c_str(), - deviceType); + LOGI("End, deviceType : %{public}d", deviceType); return DM_OK; } @@ -1357,7 +1344,7 @@ int32_t DeviceManagerImpl::GetDeviceName(const std::string &pkgName, const std:: return ret; } deviceName = std::string(deviceInfo.deviceName); - LOGI("DeviceManagerImpl::GetDeviceName end, pkgName : %{public}s, networkId : %{public}s, deviceName = %{public}s", + LOGI("End, pkgName : %{public}s, networkId : %{public}s, deviceName = %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str(), GetAnonyString(deviceName).c_str()); return DM_OK; } @@ -1371,7 +1358,7 @@ int32_t DeviceManagerImpl::GetDeviceType(const std::string &pkgName, const std:: return ret; } deviceType = deviceInfo.deviceTypeId; - LOGI("DeviceManagerImpl::GetDeviceType end, pkgName : %{public}s, networkId : %{public}s, deviceType = %{public}d", + LOGI("End, pkgName : %{public}s, networkId : %{public}s, deviceType = %{public}d", pkgName.c_str(), GetAnonyString(networkId).c_str(), deviceType); return DM_OK; } @@ -1383,7 +1370,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy LOGE("BindDevice error: Invalid para. pkgName : %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("BindDevice start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, deviceId, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1403,7 +1390,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy return ret; } DmTraceEnd(); - LOGI("BindDevice end, pkgName: %{public}s", pkgName.c_str()); + LOGI("End"); return DM_OK; } @@ -1413,7 +1400,7 @@ int32_t DeviceManagerImpl::UnBindDevice(const std::string &pkgName, const std::s LOGE("UnBindDevice error: Invalid para. pkgName %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnBindDevice start, pkgName: %{public}s, deviceId: %{public}s", pkgName.c_str(), + LOGI("Start, pkgName: %{public}s, deviceId: %{public}s", pkgName.c_str(), GetAnonyString(std::string(deviceId)).c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1430,7 +1417,7 @@ int32_t DeviceManagerImpl::UnBindDevice(const std::string &pkgName, const std::s return ret; } - LOGI("UnBindDevice end, pkgName: %{public}s", pkgName.c_str()); + LOGI("End"); return DM_OK; } @@ -1442,7 +1429,7 @@ int32_t DeviceManagerImpl::GetNetworkTypeByNetworkId(const std::string &pkgName, "%{public}d", pkgName.c_str(), GetAnonyString(netWorkId).c_str(), netWorkType); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("GetNetworkTypeByNetworkId start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1471,7 +1458,7 @@ int32_t DeviceManagerImpl::ImportAuthCode(const std::string &pkgName, const std: GetAnonyString(authCode).c_str(), pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("ImportAuthCode start, authCode: %{public}s", GetAnonyString(authCode).c_str()); + LOGI("Start, authCode: %{public}s", GetAnonyString(authCode).c_str()); int32_t length = static_cast(authCode.length()); if (length != DM_IMPORT_AUTH_CODE_LENGTH) { LOGE("ImportAuthCode error: Invalid para, authCode size error."); @@ -1506,7 +1493,7 @@ int32_t DeviceManagerImpl::ImportAuthCode(const std::string &pkgName, const std: int32_t DeviceManagerImpl::ExportAuthCode(std::string &authCode) { - LOGI("ExportAuthCode start"); + LOGI("Start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -1524,7 +1511,7 @@ int32_t DeviceManagerImpl::ExportAuthCode(std::string &authCode) } authCode = rsp->GetAuthCode(); - LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); + LOGI("Success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); return DM_OK; } @@ -1536,7 +1523,7 @@ int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, LOGE("DeviceManagerImpl::StartDiscovering failed: input callback is null or pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StartDiscovering start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); @@ -1561,7 +1548,7 @@ int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, } DmTraceEnd(); - LOGI("StartDiscovering completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); return DM_OK; @@ -1574,7 +1561,7 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, LOGE("DeviceManagerImpl::StopDiscovering failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("StopDiscovering start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); if (subscribeId == DM_INVALID_FLAG_ID) { @@ -1599,7 +1586,7 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, return ret; } - LOGI("StopDiscovering completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1611,7 +1598,7 @@ int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, LOGE("DeviceManagerImpl::RegisterDiscoveryCallback failed: input callback is null or pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("RegisterDiscoveryCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); @@ -1633,7 +1620,7 @@ int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, LOGE("RegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } - LOGI("RegisterDiscoveryCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1643,7 +1630,7 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam LOGE("DeviceManagerImpl::UnRegisterDiscoveryCallback failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("UnRegisterDiscoveryCallback start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); if (subscribeId == DM_INVALID_FLAG_ID) { @@ -1668,7 +1655,7 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam LOGE("UnRegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } - LOGI("UnRegisterDiscoveryCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1679,7 +1666,7 @@ int32_t DeviceManagerImpl::StartAdvertising(const std::string &pkgName, LOGE("DeviceManagerImpl::StartAdvertising error: pkgName %{public}s invalid para", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::StartAdvertising start, pkgName %{public}s", pkgName.c_str()); + LOGI("Start, pkgName %{public}s", pkgName.c_str()); int32_t publishId; if (advertiseParam.find(PARAM_KEY_PUBLISH_ID) == advertiseParam.end()) { @@ -1705,7 +1692,7 @@ int32_t DeviceManagerImpl::StartAdvertising(const std::string &pkgName, return ret; } DeviceManagerNotify::GetInstance().RegisterPublishCallback(pkgName, publishId, callback); - LOGI("DeviceManagerImpl::StartAdvertising completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1716,7 +1703,7 @@ int32_t DeviceManagerImpl::StopAdvertising(const std::string &pkgName, LOGE("DeviceManagerImpl::StopAdvertising failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::StopAdvertising start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); int32_t publishId; if (advertiseParam.find(PARAM_KEY_PUBLISH_ID) == advertiseParam.end()) { @@ -1746,7 +1733,7 @@ int32_t DeviceManagerImpl::StopAdvertising(const std::string &pkgName, return ret; } DeviceManagerNotify::GetInstance().UnRegisterPublishCallback(pkgName, publishId); - LOGI("DeviceManagerImpl::StopAdvertising completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1757,7 +1744,7 @@ int32_t DeviceManagerImpl::BindTarget(const std::string &pkgName, const PeerTarg LOGE("DeviceManagerImpl::BindTarget failed: input pkgName or targetId is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::BindTarget start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::string bindParamStr = ConvertMapToJsonString(bindParam); std::shared_ptr req = std::make_shared(); @@ -1777,7 +1764,7 @@ int32_t DeviceManagerImpl::BindTarget(const std::string &pkgName, const PeerTarg } DeviceManagerNotify::GetInstance().RegisterBindCallback(pkgName, targetId, callback); - LOGI("DeviceManagerImpl::BindTarget completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1788,7 +1775,7 @@ int32_t DeviceManagerImpl::UnbindTarget(const std::string &pkgName, const PeerTa LOGE("DeviceManagerImpl::UnbindTarget failed: input pkgName or targetId is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::UnbindTarget start, pkgName: %{public}s", pkgName.c_str()); + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::string unbindParamStr = ConvertMapToJsonString(unbindParam); std::shared_ptr req = std::make_shared(); @@ -1808,7 +1795,7 @@ int32_t DeviceManagerImpl::UnbindTarget(const std::string &pkgName, const PeerTa } DeviceManagerNotify::GetInstance().RegisterUnbindCallback(pkgName, targetId, callback); - LOGI("DeviceManagerImpl::UnbindTarget completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } @@ -1833,7 +1820,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); - LOGI("DeviceManagerImpl::RegisterDeviceStateCallback completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } @@ -1841,7 +1828,7 @@ int32_t DeviceManagerImpl::CheckAccessToTarget(uint64_t tokenId, const std::stri { (void)tokenId; (void)targetId; - LOGI("DeviceManagerImpl::CheckAccessToTarget start"); + LOGI("Start"); return ERR_DM_UNSUPPORTED_METHOD; } @@ -1992,7 +1979,7 @@ int32_t DeviceManagerImpl::DestroyPinHolder(const std::string &pkgName, const Pe int32_t DeviceManagerImpl::DpAclAdd(const int64_t accessControlId, const std::string &udid, const int32_t bindType) { - LOGI("DpAclAdd start."); + LOGI("Start."); if (bindType != IDENTICAL_ACCOUNT) { LOGI("DeviceManagerImpl::DpAclAdd is not identical account"); return DM_OK; @@ -2010,7 +1997,7 @@ int32_t DeviceManagerImpl::DpAclAdd(const int64_t accessControlId, const std::st LOGE("DpAclAdd error: Failed with ret %{public}d", ret); return ret; } - LOGI("DeviceManagerImpl::DpAclAdd completed"); + LOGI("Completed"); return DM_OK; } @@ -2022,7 +2009,7 @@ int32_t DeviceManagerImpl::GetDeviceSecurityLevel(const std::string &pkgName, co pkgName.c_str(), GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerImpl::GetDeviceSecurityLevel start: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), + LOGI("Start: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); std::shared_ptr req = std::make_shared(); @@ -2047,7 +2034,7 @@ int32_t DeviceManagerImpl::GetDeviceSecurityLevel(const std::string &pkgName, co int32_t DeviceManagerImpl::CheckApiPermission(int32_t permissionLevel) { - LOGI("DeviceManagerImpl::CheckApiPermission permissionLevel: %{public}d", permissionLevel); + LOGI("permissionLevel: %{public}d", permissionLevel); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPermissionLevel(permissionLevel); @@ -2062,7 +2049,6 @@ int32_t DeviceManagerImpl::CheckApiPermission(int32_t permissionLevel) LOGE("Check permission failed with ret: %{public}d", ret); return ret; } - LOGI("The caller declare the DM permission!"); return DM_OK; } @@ -2090,7 +2076,7 @@ bool DeviceManagerImpl::IsSameAccount(const std::string &netWorkId) bool DeviceManagerImpl::CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee) { - LOGI("DeviceManagerImpl::CheckAccessControl"); + LOGI("Start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetAccessCaller(caller); @@ -2110,7 +2096,7 @@ bool DeviceManagerImpl::CheckAccessControl(const DmAccessCaller &caller, const D bool DeviceManagerImpl::CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) { - LOGI("DeviceManagerImpl::CheckIsSameAccount"); + LOGI("Start"); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetAccessCaller(caller); @@ -2139,7 +2125,7 @@ int32_t DeviceManagerImpl::GetErrCode(int32_t errCode) int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) { - LOGI("ShiftLNNGear start. for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start. pkgName = %{public}s", pkgName.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -2153,7 +2139,7 @@ int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) LOGE("ShiftLNNGear error: Failed with ret %{public}d", ret); return ret; } - LOGI("DeviceManagerImpl::ShiftLNNGear completed"); + LOGI("Completed"); return DM_OK; } } // namespace DistributedHardware diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 61b9f45f5..54adce21d 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -39,7 +39,7 @@ void DmDeathRecipient::OnRemoteDied(const wptr &remote) int32_t IpcClientManager::ClientInit() { - LOGI("InitDeviceManagerService start"); + LOGI("Start"); if (dmInterface_ != nullptr) { LOGI("DeviceManagerService Already Init"); return DM_OK; @@ -64,7 +64,7 @@ int32_t IpcClientManager::ClientInit() LOGE("InitDeviceManagerService: AddDeathRecipient Failed"); } dmInterface_ = iface_cast(object); - LOGI("DeviceManager::InitDeviceManagerService completed"); + LOGI("Completed"); return DM_OK; } diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 72d72c9e3..46377271c 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 @@ -46,13 +46,13 @@ void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgN #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) if (ffrtQueue_ != nullptr) { - LOGI("DeviceManagerNotify ffrtQueue has created!"); + LOGI("FfrtQueue has created!"); return; } ffrtQueue_ = std::make_shared(DEVICE_STATE_INIT_QUEUE, ffrt::queue_attr().qos(ffrt::qos_default)); if (ffrtQueue_ == nullptr) { - LOGE("DeviceManagerNotify ffrtQueue create failed!"); + LOGE("FfrtQueue create failed!"); return; } #endif @@ -316,19 +316,19 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOnline with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Online with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); auto iter = deviceStatusCallback_.find(pkgName); if (iter == deviceStatusCallback_.end()) { - LOGE("OnDeviceOnline error, device status callback not register."); + LOGE("Error, device status callback not register."); return; } tempCbk = iter->second; } if (tempCbk == nullptr) { - LOGE("OnDeviceOnline error, registered device status callback is nullptr."); + LOGE("Error, registered device status callback is nullptr."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -350,19 +350,19 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOffline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Offline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); auto iter = deviceStateCallback_.find(pkgName); if (iter == deviceStateCallback_.end()) { - LOGE("OnDeviceOffline error, device state callback not register."); + LOGE("Error, device state callback not register."); return; } tempCbk = iter->second; } if (tempCbk == nullptr) { - LOGE("OnDeviceOffline error, registered device state callback is nullptr."); + LOGE("Error, registered device state callback is nullptr."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp index e8a67d920..f7483510e 100644 --- a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -993,7 +993,7 @@ void DeviceManagerNapi::CallGetAvailableDeviceListStatus(napi_env env, napi_stat DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo) { for (unsigned int i = 0; i < deviceBasicInfoListAsyncCallbackInfo->devList.size(); i++) { - LOGI("DeviceManager::GetAvailableDeviceList deviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", + LOGI("DeviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", GetAnonyString(deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(), GetAnonyString(deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceName).c_str(), deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceTypeId); @@ -1096,7 +1096,6 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in napi_value DeviceManagerNapi::GetAvailableDeviceListSync(napi_env env, napi_callback_info info) { - LOGI("GetAvailableDeviceListSync in"); int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); if (ret != 0) { CreateBusinessError(env, ret); @@ -1125,7 +1124,6 @@ napi_value DeviceManagerNapi::GetAvailableDeviceListSync(napi_env env, napi_call CreateBusinessError(env, ret); return result; } - LOGI("DeviceManager::GetAvailableDeviceListSync"); if (devList.size() > 0) { for (size_t i = 0; i != devList.size(); ++i) { DeviceBasicInfoToJsArray(env, devList, (int32_t)i, result); @@ -1887,7 +1885,7 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_info info) { - LOGI("CreateDeviceManager in"); + LOGI("In"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); if (!CheckArgsCount(env, argc == DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1")) { return nullptr; @@ -1921,7 +1919,7 @@ napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_in napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) { - LOGI("DeviceManagerNapi Constructor in"); + LOGI("In"); GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); if (!CheckArgsCount(env, argc >= DM_NAPI_ARGS_ONE, "Wrong number of arguments, required 1")) { return nullptr; @@ -1931,7 +1929,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) return nullptr; } - LOGI("create DeviceManagerNapi for packageName:%{public}s", bundleName.c_str()); + LOGI("create for packageName:%{public}s", bundleName.c_str()); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); if (obj == nullptr) { return nullptr; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index e4f6d0e12..3d09c41b9 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -196,7 +196,7 @@ int32_t DeviceManagerService::InitDMServiceListener() if (pinHolder_ == nullptr) { pinHolder_ = std::make_shared(listener_); } - LOGI("DeviceManagerServiceListener init success."); + LOGI("Init success."); return DM_OK; } @@ -205,7 +205,7 @@ void DeviceManagerService::UninitDMServiceListener() listener_ = nullptr; advertiseMgr_ = nullptr; discoveryMgr_ = nullptr; - LOGI("DeviceManagerServiceListener uninit."); + LOGI("uninit."); } void DeviceManagerService::RegisterDeviceManagerListener(const std::string &pkgName) @@ -227,7 +227,7 @@ void DeviceManagerService::UnRegisterDeviceManagerListener(const std::string &pk int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, std::vector &deviceList) { - LOGI("DMSrc::GetTrustedDeviceList begin for pkgName = %{public}s.", pkgName.c_str()); + LOGI("Begin for pkgName = %{public}s.", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -276,7 +276,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std::string &callerId, bool isRefresh, bool isWakeUp) { - LOGD("DeviceManagerService::ShiftLNNGear begin for pkgName = %{public}s, callerId = %{public}s, isRefresh =" + LOGD("Begin for pkgName = %{public}s, callerId = %{public}s, isRefresh =" "%{public}d, isWakeUp = %{public}d", pkgName.c_str(), GetAnonyString(callerId).c_str(), isRefresh, isWakeUp); if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call ShiftLNNGear, pkgName = %{public}s", pkgName.c_str()); @@ -299,7 +299,7 @@ int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std int32_t DeviceManagerService::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info) { - LOGI("DeviceManagerService::GetDeviceInfo begin networkId %{public}s.", GetAnonyString(networkId).c_str()); + LOGI("Begin networkId %{public}s.", GetAnonyString(networkId).c_str()); if (!PermissionManager::GetInstance().CheckPermission() && !PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call GetDeviceInfo."); @@ -319,7 +319,7 @@ int32_t DeviceManagerService::GetDeviceInfo(const std::string &networkId, DmDevi int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - LOGI("DeviceManagerService::GetLocalDeviceInfo begin."); + LOGI("Begin."); bool isOnlyShowNetworkId = false; if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call GetLocalDeviceInfo."); @@ -391,7 +391,7 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StartDeviceDiscovery begin for pkgName = %{public}s, extra = %{public}s", + LOGI("Begin for pkgName = %{public}s, extra = %{public}s", pkgName.c_str(), extra.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -417,7 +417,7 @@ int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, c LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("StartDeviceDiscovery begin for pkgName = %{public}s, filterOptions = %{public}s, subscribeId = %{public}d", + LOGI("Begin for pkgName = %{public}s, filterOptions = %{public}s, subscribeId = %{public}d", pkgName.c_str(), filterOptions.c_str(), subscribeId); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -441,7 +441,7 @@ int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, ui LOGE("The caller: %{public}s does not have permission to call StopDeviceDiscovery.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StopDeviceDiscovery begin for pkgName = %{public}s", pkgName.c_str()); + LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -456,7 +456,7 @@ int32_t DeviceManagerService::PublishDeviceDiscovery(const std::string &pkgName, LOGE("The caller: %{public}s does not have permission to call PublishDeviceDiscovery.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::PublishDeviceDiscovery begin for pkgName = %{public}s", pkgName.c_str()); + LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -519,7 +519,7 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c LOGE("The caller: %{public}s does not have permission to call UnAuthenticateDevice.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::UnAuthenticateDevice begin for pkgName = %{public}s, networkId = %{public}s", + LOGI("Begin for pkgName = %{public}s, networkId = %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); if (pkgName.empty() || networkId.empty()) { LOGE("DeviceManagerService::UnAuthenticateDevice error: Invalid parameter, pkgName: %{public}s", @@ -569,7 +569,7 @@ int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std LOGE("The caller does not have permission to call UnBindDevice."); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::UnBindDevice begin for pkgName = %{public}s, deviceId = %{public}s", + LOGI("Begin for pkgName = %{public}s, deviceId = %{public}s", pkgName.c_str(), GetAnonyString(deviceId).c_str()); if (pkgName.empty() || deviceId.empty()) { LOGE("DeviceManagerService::UnBindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str()); @@ -641,19 +641,19 @@ void DeviceManagerService::OnBytesReceived(int sessionId, const void *data, unsi int DeviceManagerService::OnPinHolderSessionOpened(int sessionId, int result) { - LOGI("DeviceManagerService::OnPinHolderSessionOpened"); + LOGI("In"); return PinHolderSession::OnSessionOpened(sessionId, result); } void DeviceManagerService::OnPinHolderSessionClosed(int sessionId) { - LOGI("DeviceManagerService::OnPinHolderSessionClosed"); + LOGI("In"); PinHolderSession::OnSessionClosed(sessionId); } void DeviceManagerService::OnPinHolderBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - LOGI("DeviceManagerService::OnPinHolderBytesReceived"); + LOGI("In"); PinHolderSession::OnBytesReceived(sessionId, data, dataLen); } @@ -924,7 +924,7 @@ int32_t DeviceManagerService::GetEncryptedUuidByNetworkId(const std::string &pkg LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerService::GetEncryptedUuidByNetworkId for pkgName = %{public}s", pkgName.c_str()); + LOGI("PkgName = %{public}s", pkgName.c_str()); CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); int32_t ret = softbusListener_->GetUuidByNetworkId(networkId.c_str(), uuid); if (ret != DM_OK) { @@ -953,7 +953,7 @@ int32_t DeviceManagerService::GenerateEncryptedUuid(const std::string &pkgName, int32_t DeviceManagerService::CheckApiPermission(int32_t permissionLevel) { - LOGI("DeviceManagerService::CheckApiPermission permissionLevel: %{public}d", permissionLevel); + LOGI("PermissionLevel: %{public}d", permissionLevel); int32_t ret = ERR_DM_NO_PERMISSION; switch (permissionLevel) { case NORMAL: @@ -988,7 +988,7 @@ int32_t DeviceManagerService::GetNetworkTypeByNetworkId(const std::string &pkgNa LOGE("The caller: %{public}s does not have permission to call GetNetworkTypeByNetworkId.", pkgName.c_str()); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::GetNetworkTypeByNetworkId begin for pkgName = %{public}s", pkgName.c_str()); + LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty() || netWorkId.empty()) { LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(), GetAnonyString(netWorkId).c_str()); @@ -1050,7 +1050,7 @@ int32_t DeviceManagerService::ExportAuthCode(std::string &authCode) void DeviceManagerService::UnloadDMServiceImplSo() { - LOGI("DeviceManagerService::UnloadDMServiceImplSo start."); + LOGI("Start."); std::lock_guard lock(isImplLoadLock_); if (dmServiceImpl_ != nullptr) { dmServiceImpl_->Release(); @@ -1064,7 +1064,7 @@ void DeviceManagerService::UnloadDMServiceImplSo() bool DeviceManagerService::IsDMServiceAdapterLoad() { - LOGI("DeviceManagerService::IsDMServiceAdapterLoad start."); + LOGI("Start."); std::lock_guard lock(isAdapterLoadLock_); if (isAdapterSoLoaded_ && (dmServiceImplExt_ != nullptr)) { return true; @@ -1092,13 +1092,13 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() return false; } isAdapterSoLoaded_ = true; - LOGI("DeviceManagerService::IsDMServiceAdapterLoad sucess."); + LOGI("Success."); return true; } void DeviceManagerService::UnloadDMServiceAdapter() { - LOGI("DeviceManagerService::UnloadDMServiceAdapter start."); + LOGI("Start."); std::lock_guard lock(isAdapterLoadLock_); if (dmServiceImplExt_ != nullptr) { dmServiceImplExt_->Release(); @@ -1119,7 +1119,7 @@ int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName, LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StartDiscovering for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1138,7 +1138,7 @@ int32_t DeviceManagerService::StopDiscovering(const std::string &pkgName, LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StopDiscovering for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1161,7 +1161,7 @@ int32_t DeviceManagerService::EnableDiscoveryListener(const std::string &pkgName LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::EnableDiscoveryListener for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1178,7 +1178,7 @@ int32_t DeviceManagerService::DisableDiscoveryListener(const std::string &pkgNam LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::DisableDiscoveryListener for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1194,7 +1194,7 @@ int32_t DeviceManagerService::StartAdvertising(const std::string &pkgName, LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StartAdvertising for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1210,7 +1210,7 @@ int32_t DeviceManagerService::StopAdvertising(const std::string &pkgName, LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::StopAdvertising for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1233,7 +1233,7 @@ int32_t DeviceManagerService::BindTarget(const std::string &pkgName, const PeerT LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::BindTarget for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1273,7 +1273,7 @@ int32_t DeviceManagerService::UnbindTarget(const std::string &pkgName, const Pee LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService::UnbindTarget for pkgName = %{public}s", pkgName.c_str()); + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; @@ -1354,7 +1354,7 @@ int32_t DeviceManagerService::DestroyPinHolder(const std::string &pkgName, const LOGE("The caller: %{public}s is not in white list.", processName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("DeviceManagerService::DestroyPinHolder begin."); + LOGI("Begin."); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName: %{public}s.", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; @@ -1396,7 +1396,7 @@ int32_t DeviceManagerService::DpAclAdd(const std::string &udid) LOGE("The caller does not have permission to call DpAclAdd."); return ERR_DM_NO_PERMISSION; } - LOGI("DeviceManagerService DpAclAdd start."); + LOGI("Start."); if (!IsDMServiceImplReady()) { LOGE("DpAclAdd failed, instance not init or init failed."); return ERR_DM_NOT_INIT; @@ -1409,7 +1409,7 @@ int32_t DeviceManagerService::DpAclAdd(const std::string &udid) int32_t DeviceManagerService::GetDeviceSecurityLevel(const std::string &pkgName, const std::string &networkId, int32_t &securityLevel) { - LOGI("DeviceManagerService::GetDeviceSecurityLevel begin pkgName: %{public}s, networkId: %{public}s", + LOGI("Begin pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller: %{public}s does not have permission to call GetDeviceSecurityLevel.", pkgName.c_str()); @@ -1431,7 +1431,7 @@ int32_t DeviceManagerService::GetDeviceSecurityLevel(const std::string &pkgName, int32_t DeviceManagerService::IsSameAccount(const std::string &networkId) { - LOGI("DeviceManagerService::IsSameAccount networkId %{public}s.", GetAnonyString(networkId).c_str()); + LOGI("NetworkId %{public}s.", GetAnonyString(networkId).c_str()); if (!PermissionManager::GetInstance().CheckPermission()) { return ERR_DM_NO_PERMISSION; } @@ -1485,7 +1485,7 @@ int32_t DeviceManagerService::InitAccountInfo() { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) SubscribeAccountCommonEvent(); - LOGI("InitAccountInfo success."); + LOGI("Success."); #endif return DM_OK; } @@ -1494,7 +1494,7 @@ int32_t DeviceManagerService::InitScreenLockEvent() { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) SubscribeScreenLockEvent(); - LOGI("InitScreenLockEvent success."); + LOGI("Success."); #endif return DM_OK; } @@ -1502,7 +1502,7 @@ int32_t DeviceManagerService::InitScreenLockEvent() #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void DeviceManagerService::SubscribeAccountCommonEvent() { - LOGI("DeviceManagerServiceImpl::SubscribeAccountCommonEvent"); + LOGI("Start"); if (accountCommonEventManager_ == nullptr) { accountCommonEventManager_ = std::make_shared(); } @@ -1514,14 +1514,14 @@ void DeviceManagerService::SubscribeAccountCommonEvent() AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGIN); if (accountCommonEventManager_->SubscribeAccountCommonEvent(AccountCommonEventVec, callback)) { - LOGI("subscribe account common event success"); + LOGI("Success"); } return; } void DeviceManagerService::SubscribeScreenLockEvent() { - LOGI("DeviceManagerServiceImpl::SubscribeScreenLockEvent"); + LOGI("Start"); if (screenCommonEventManager_ == nullptr) { screenCommonEventManager_ = std::make_shared(); } @@ -1529,14 +1529,14 @@ void DeviceManagerService::SubscribeScreenLockEvent() std::vector screenEventVec; screenEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED); if (screenCommonEventManager_->SubscribeScreenCommonEvent(screenEventVec, callback)) { - LOGI("subscribe screen common event success"); + LOGI("Success"); } return; } void DeviceManagerService::AccountCommonEventCallback(int32_t userId, std::string commonEventType) { - LOGI("AccountCommonEventCallback start, commonEventType: %{public}s", commonEventType.c_str()); + LOGI("Start, commonEventType: %{public}s", commonEventType.c_str()); if ((commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED || commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN)) { std::string accountId = MultipleUserConnector::GetOhosAccountId(); @@ -1579,7 +1579,7 @@ void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) { - LOGI("DeviceManagerService::HandleDeviceNotTrust."); + LOGI("Start."); if (msg.empty()) { LOGE("DeviceManagerService::HandleDeviceNotTrust msg is empty."); return; @@ -1596,7 +1596,7 @@ void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) std::string networkId = msgJsonObj[NETWORKID].get(); std::string udid = ""; SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid); - LOGI("HandleDeviceNotTrust networkId: %{public}s, udid: %{public}s.", + LOGI("NetworkId: %{public}s, udid: %{public}s.", GetAnonyString(networkId).c_str(), GetAnonyString(udid).c_str()); if (IsDMImplSoLoaded()) { dmServiceImpl_->HandleDeviceNotTrust(udid); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index e0dee7d74..c447d2c8b 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -67,7 +67,7 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetPkgName(pkgName); pReq->SetDeviceState(state); pReq->SetDeviceInfo(deviceInfo); @@ -82,7 +82,7 @@ std::string DeviceManagerServiceListener::ComposeOnlineKey(const std::string &pk void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { - LOGI("DeviceManagerServiceListener::ProcessDeviceStateChange"); + LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); @@ -124,7 +124,7 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState void DeviceManagerServiceListener::ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { - LOGI("DeviceManagerServiceListener::ProcessAppStateChange"); + LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 94177b459..8004a0fb8 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -381,7 +381,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t std::lock_guard autoLock(subIdMapLocks_); subscribeId = pkgName2SubIdMap_[pkgName]; } - LOGI("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); + LOGI("PkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); listener_->OnDeviceFound(pkgName, subscribeId, info); return; } diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 58061195a..0396f2a01 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -189,10 +189,10 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< std::lock_guard autoLock(listenerLock_); auto iter = dmListener_.find(pkgName); if (iter != dmListener_.end()) { - LOGI("RegisterDeviceManagerListener: listener already exists"); + LOGI("Listener already exists"); auto recipientIter = appRecipient_.find(pkgName); if (recipientIter == appRecipient_.end()) { - LOGI("RegisterDeviceManagerListener: appRecipient not exists"); + LOGI("AppRecipient not exists"); dmListener_.erase(pkgName); } else { auto listener = iter->second; @@ -205,11 +205,11 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< sptr appRecipient = sptr(new AppDeathRecipient()); if (!listener->AsObject()->AddDeathRecipient(appRecipient)) { - LOGE("RegisterDeviceManagerListener: AddDeathRecipient Failed"); + LOGE("AddDeathRecipient Failed"); } dmListener_[pkgName] = listener; appRecipient_[pkgName] = appRecipient; - LOGI("RegisterDeviceManagerListener: Register listener complete."); + LOGI("Register listener complete."); return DM_OK; } @@ -223,12 +223,12 @@ int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) std::lock_guard autoLock(listenerLock_); auto listenerIter = dmListener_.find(pkgName); if (listenerIter == dmListener_.end()) { - LOGI("UnRegisterDeviceManagerListener: listener not exists"); + LOGI("Listener not exists"); return DM_OK; } auto recipientIter = appRecipient_.find(pkgName); if (recipientIter == appRecipient_.end()) { - LOGI("UnRegisterDeviceManagerListener: appRecipient not exists"); + LOGI("AppRecipient not exists"); dmListener_.erase(pkgName); return DM_OK; } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index e11c68472..a9d634984 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -341,7 +341,7 @@ void SoftbusListener::OnSoftbusDeviceFound(const DeviceInfo *device) } } } - LOGI("OnSoftbusDeviceFound: devId=%{public}s, devName=%{public}s, devType=%{public}d, range=%{public}d," + LOGI("DevId=%{public}s, devName=%{public}s, devType=%{public}d, range=%{public}d," "isOnline=%{public}d", GetAnonyString(dmDevInfo.deviceId).c_str(), GetAnonyString(dmDevInfo.deviceName).c_str(), dmDevInfo.deviceTypeId, dmDevInfo.range, device->isOnline); @@ -523,7 +523,7 @@ int32_t SoftbusListener::StopRefreshSoftbusLNN(uint16_t subscribeId) int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const std::string &capability, const std::string &customData) { - LOGI("PublishSoftbusLNN begin, publishId: %{public}d.", dmPubInfo.publishId); + LOGI("Begin, publishId: %{public}d.", dmPubInfo.publishId); PublishInfo publishInfo; publishInfo.publishId = dmPubInfo.publishId; publishInfo.mode = static_cast(dmPubInfo.mode); @@ -534,8 +534,8 @@ int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const publishInfo.dataLen = customData.length(); publishInfo.ranging = dmPubInfo.ranging; - LOGI("PublishSoftbusLNN begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:" - "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.publishId, publishInfo.mode, + LOGI("Begin, mode: 0x%{public}x, medium: %{public}d, capability:" + "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.mode, publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq); int32_t ret = ::PublishLNN(DM_PKG_NAME, &publishInfo, &softbusPublishCallback_); @@ -548,7 +548,7 @@ int32_t SoftbusListener::PublishSoftbusLNN(const DmPublishInfo &dmPubInfo, const int32_t SoftbusListener::StopPublishSoftbusLNN(int32_t publishId) { - LOGI("StopPublishSoftbusLNN begin, publishId: %{public}d.", publishId); + LOGI("Begin, publishId: %{public}d.", publishId); int32_t ret = ::StopPublishLNN(DM_PKG_NAME, publishId); if (ret != DM_OK) { LOGE("[SOFTBUS]StopPublishLNN failed, ret: %{public}d.", ret); @@ -596,7 +596,7 @@ int32_t SoftbusListener::GetTrustedDeviceList(std::vector &deviceI LOGE("ReportGetTrustDeviceList failed"); } } - LOGI("GetTrustedDeviceList success from cache deviceInfoList size is %{public}zu.", deviceCount); + LOGI("Success from cache deviceInfoList size is %{public}zu.", deviceCount); return ret; } diff --git a/services/service/src/softbus/softbus_publish.cpp b/services/service/src/softbus/softbus_publish.cpp index 99967a8b5..e717c639f 100644 --- a/services/service/src/softbus/softbus_publish.cpp +++ b/services/service/src/softbus/softbus_publish.cpp @@ -99,7 +99,7 @@ void SoftbusPublish::OnSoftbusPublishResult(int publishId, PublishResult result) int32_t SoftbusPublish::PublishSoftbusLNN() { - LOGI("SoftbusPublish::PublishSoftbusLNN begin."); + LOGI("Begin."); PublishInfo publishInfo; publishInfo.publishId = DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID; publishInfo.mode = DiscoverMode::DISCOVER_MODE_PASSIVE; @@ -108,7 +108,7 @@ int32_t SoftbusPublish::PublishSoftbusLNN() publishInfo.capability = DM_CAPABILITY_OSD; publishInfo.ranging = false; - LOGI("PublishSoftbusLNN begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:" + LOGI("Begin, publishId: %{public}d, mode: 0x%{public}x, medium: %{public}d, capability:" "%{public}s, ranging: %{public}d, freq: %{public}d.", publishInfo.publishId, publishInfo.mode, publishInfo.medium, publishInfo.capability, publishInfo.ranging, publishInfo.freq); @@ -122,7 +122,7 @@ int32_t SoftbusPublish::PublishSoftbusLNN() int32_t SoftbusPublish::StopPublishSoftbusLNN(int32_t publishId) { - LOGI("StopPublishSoftbusLNN begin, publishId: %{public}d.", publishId); + LOGI("Begin, publishId: %{public}d.", publishId); int32_t ret = StopPublishLNN(DM_PKG_NAME, publishId); if (ret != DM_OK) { LOGE("[SOFTBUS]StopPublishLNN failed, ret: %{public}d.", ret); -- Gitee From 727e6e7286f4290608f0e16cd7c21c8a370546be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 13 Aug 2024 17:46:56 +0800 Subject: [PATCH 068/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../inner_kits/native_cpp/src/device_manager_impl.cpp | 2 +- .../native_cpp/src/notify/device_manager_notify.cpp | 8 ++++---- .../src/dependency/softbus/softbus_connector.cpp | 4 ++-- services/service/src/device_manager_service.cpp | 2 +- services/service/src/device_manager_service_listener.cpp | 1 - 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 8dcf42f79..8cc4882d9 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2034,7 +2034,7 @@ int32_t DeviceManagerImpl::GetDeviceSecurityLevel(const std::string &pkgName, co int32_t DeviceManagerImpl::CheckApiPermission(int32_t permissionLevel) { - LOGI("permissionLevel: %{public}d", permissionLevel); + LOGI("PermissionLevel: %{public}d", permissionLevel); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPermissionLevel(permissionLevel); 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 46377271c..3683b9f13 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 @@ -282,7 +282,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOnline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Online with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); @@ -384,19 +384,19 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe LOGE("Invalid parameter, pkgName is empty."); return; } - LOGI("DeviceManagerNotify::OnDeviceOffline with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); + LOGI("Offline with DmDeviceBasicInfo, pkgName:%{public}s", pkgName.c_str()); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); auto iter = deviceStatusCallback_.find(pkgName); if (iter == deviceStatusCallback_.end()) { - LOGE("OnDeviceOffline error, device status callback not register."); + LOGE("Error, device status callback not register."); return; } tempCbk = iter->second; } if (tempCbk == nullptr) { - LOGE("OnDeviceOffline error, registered device status callback is nullptr."); + LOGE("Error, registered device status callback is nullptr."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 57ad2c710..e36474338 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -661,14 +661,14 @@ void SoftbusConnector::SetPkgNameVec(std::vector pkgNameVec) std::vector SoftbusConnector::GetPkgName() { - LOGI("SoftbusConnector::GetPkgName"); + LOGI("In"); std::lock_guard lock(pkgNameVecMutex_); return pkgNameVec_; } void SoftbusConnector::ClearPkgName() { - LOGI("SoftbusConnector::SetPkgName vec"); + LOGI("In"); std::lock_guard lock(pkgNameVecMutex_); pkgNameVec_.clear(); } diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 3d09c41b9..003551c17 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -853,7 +853,7 @@ bool DeviceManagerService::IsDMServiceImplReady() bool DeviceManagerService::IsDMImplSoLoaded() { - LOGI("DeviceManagerService::IsDMImplSoLoaded"); + LOGI("In"); std::lock_guard lock(isImplLoadLock_); return isImplsoLoaded_; } diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index c447d2c8b..f8f373d7e 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -67,7 +67,6 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetPkgName(pkgName); pReq->SetDeviceState(state); pReq->SetDeviceInfo(deviceInfo); -- Gitee From 008d12c8f647d9d5c9ae8b3fc363614431a61fcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 14 Aug 2024 09:50:22 +0800 Subject: [PATCH 069/520] =?UTF-8?q?=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/softbusunittest/UTTest_softbus_listener.cpp | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 978b6ad4d..e24d744cd 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -102,22 +102,6 @@ HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_001, testing::ext::TestSize. EXPECT_EQ(softbusListener->isRadarSoLoad_, true); } -/** - * @tc.name: OnSoftbusDeviceOnline_002 - * @tc.type: FUNC - */ -HWTEST_F(SoftbusListenerTest, OnSoftbusDeviceOnline_002, testing::ext::TestSize.Level0) -{ - NodeBasicInfo *info = nullptr; - if (softbusListener == nullptr) { - softbusListener = std::make_shared(); - } - softbusListener->OnSoftbusDeviceOnline(info); - softbusListener->OnSoftbusDeviceOffline(info); - softbusListener->OnLocalDevInfoChange(); - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); -} - /** * @tc.name: ShiftLNNGear_001 * @tc.desc: return DM_OK -- Gitee From dd50aec549c8019a88bdf1b3b082f6d57c545827 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 14 Aug 2024 14:57:05 +0800 Subject: [PATCH 070/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E7=BA=A7=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/deviceprofile_connector.cpp | 34 +++++++++---------- .../src/discovery/discovery_manager.cpp | 4 +-- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 60dde1581..a847450b7 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -99,19 +99,19 @@ int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, if (std::count(bindTypes.begin(), bindTypes.end(), DmAuthForm::IDENTICAL_ACCOUNT) > 0) { isOnline = true; authForm = DmAuthForm::IDENTICAL_ACCOUNT; - LOGI("GetDeviceAclParam, The found device is identical account device bind type."); + LOGI("The found device is identical account device bind type."); return DM_OK; } if (std::count(bindTypes.begin(), bindTypes.end(), DmAuthForm::PEER_TO_PEER) > 0) { isOnline = true; authForm = DmAuthForm::PEER_TO_PEER; - LOGI("GetDeviceAclParam, The found device is peer-to-peer device bind-level."); + LOGI("The found device is peer-to-peer device bind-level."); return DM_OK; } if (std::count(bindTypes.begin(), bindTypes.end(), DmAuthForm::ACROSS_ACCOUNT) > 0) { isOnline = true; authForm = DmAuthForm::ACROSS_ACCOUNT; - LOGI("GetDeviceAclParam, The found device is across-account device bind-level."); + LOGI("The found device is across-account device bind-level."); return DM_OK; } authForm = DmAuthForm::INVALID_TYPE; @@ -153,7 +153,7 @@ int32_t DeviceProfileConnector::HandleDmAuthForm(AccessControlProfile profiles, uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::string requestDeviceId) { - LOGI("CheckBindType start."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); uint32_t highestPriority = INVALIED_TYPE; @@ -172,7 +172,7 @@ uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::s int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, const std::string &trustDev, const std::string &reqDev) { - LOGI("DeviceProfileConnector::GetAuthForm bindType %{public}d, bindLevel %{public}d", + LOGI("BindType %{public}d, bindLevel %{public}d", profiles.GetBindType(), profiles.GetBindLevel()); uint32_t priority = INVALIED_TYPE; uint32_t bindType = profiles.GetBindType(); @@ -212,7 +212,7 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont std::vector DeviceProfileConnector::GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid) { - LOGI("GetBindTypeByPkgName start."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector bindTypeVec; @@ -353,7 +353,7 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId) { - LOGI("GetPkgNameFromAcl start."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector pkgNameVec; @@ -373,7 +373,7 @@ std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string & DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) { - LOGI("DeviceProfileConnector::GetOfflineParamFromAcl, trustDeviceId = %{public}s and requestDeviceId = %{public}s", + LOGI("TrustDeviceId = %{public}s and requestDeviceId = %{public}s", GetAnonyString(trustDeviceId).c_str(), GetAnonyString(requestDeviceId).c_str()); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); @@ -409,7 +409,7 @@ DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustD int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee) { - LOGI("DeviceProfileConnector::PutAccessControlList start."); + LOGI("Start."); Accesser accesser; accesser.SetAccesserDeviceId(dmAccesser.requestDeviceId); accesser.SetAccesserUserId(dmAccesser.requestUserId); @@ -441,16 +441,16 @@ int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccess int32_t DeviceProfileConnector::DeleteAccessControlList(int32_t userId, std::string &accountId) { - LOGI("DeleteAccessControlList by userId and accountId."); + LOGI("Start."); std::vector profiles; std::map queryParams; queryParams["userId"] = std::to_string(userId); if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { LOGE("DP GetAccessControlProfile failed."); } - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + LOGI("Size is %{public}zu", profiles.size()); for (auto &item : profiles) { - LOGI("AccessControlProfile bindType is : %{public}d.", item.GetBindType()); + LOGI("BindType is : %{public}d.", item.GetBindType()); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); } return DM_OK; @@ -458,13 +458,13 @@ int32_t DeviceProfileConnector::DeleteAccessControlList(int32_t userId, std::str void DeviceProfileConnector::DeleteAccessControlList(const std::string &udid) { - LOGI("DeleteAccessControlList by udid: %{public}s.", GetAnonyString(udid).c_str()); + LOGI("Udid: %{public}s.", GetAnonyString(udid).c_str()); if (udid.empty()) { LOGE("DeleteAccessControlList udid is empty."); return; } std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + LOGI("Size is %{public}zu", profiles.size()); for (const auto &item : profiles) { if (item.GetTrustDeviceId() == udid) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); @@ -475,9 +475,9 @@ void DeviceProfileConnector::DeleteAccessControlList(const std::string &udid) DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId) { - LOGI("DeleteAccessControlList by pkgName, localDeviceId, remoteDeviceId."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + LOGI("Size is %{public}zu", profiles.size()); DmOfflineParam offlineParam; offlineParam.bindType = INVALIED_TYPE; offlineParam.leftAclNumber = 0; @@ -494,7 +494,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(std::string pkgNa offlineParam.leftAclNumber++; if (item.GetBindLevel() == DEVICE && item.GetBindType() != DM_IDENTICAL_ACCOUNT && item.GetAccesser().GetAccesserBundleName() == pkgName) { - LOGI("DeleteAccessControlList device unbind."); + LOGI("Device unbind."); offlineParam.bindType = DEVICE_PEER_TO_PEER_TYPE; } } diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 8004a0fb8..35740d886 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -381,7 +381,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t std::lock_guard autoLock(subIdMapLocks_); subscribeId = pkgName2SubIdMap_[pkgName]; } - LOGI("PkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); + LOGD("PkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); listener_->OnDeviceFound(pkgName, subscribeId, info); return; } @@ -394,7 +394,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t return; } } - LOGI("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); + LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); } } -- Gitee From 0628e4a10d48a4aee4b4640707443e8b7112f09d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 14 Aug 2024 15:03:19 +0800 Subject: [PATCH 071/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/deviceprofile_connector.cpp | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index a847450b7..8b7498980 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -525,7 +525,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(std::string pkgNa int32_t DeviceProfileConnector::UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId) { - LOGI("UpdateAccessControlList by userId and accountId."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { @@ -549,7 +549,7 @@ int32_t DeviceProfileConnector::UpdateAccessControlList(int32_t userId, std::str bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::string &accountId) { - LOGI("DeviceProfileConnector::CheckIdenticalAccount"); + LOGI("Start"); std::vector profiles; std::map queryParams; queryParams["userId"] = std::to_string(userId); @@ -566,7 +566,7 @@ bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::st } int32_t DeviceProfileConnector::DeleteP2PAccessControlList(int32_t userId, std::string &accountId) { - LOGI("DeviceProfileConnector::DeleteP2PAccessControlList"); + LOGI("Start"); std::vector profiles; std::map queryParams; queryParams["userId"] = std::to_string(userId); @@ -590,7 +590,7 @@ int32_t DeviceProfileConnector::DeleteP2PAccessControlList(int32_t userId, std:: bool DeviceProfileConnector::CheckSrcDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) { - LOGI("DeviceProfileConnector::CheckSrcDeviceIdInAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { @@ -605,7 +605,7 @@ bool DeviceProfileConnector::CheckSrcDeviceIdInAcl(const std::string &pkgName, c bool DeviceProfileConnector::CheckSinkDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) { - LOGI("DeviceProfileConnector::CheckSinkDeviceIdInAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { @@ -625,7 +625,7 @@ bool DeviceProfileConnector::CheckDeviceIdInAcl(const std::string &pkgName, cons uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId) { - LOGI("DeviceProfileConnector::DeleteTimeOutAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); uint32_t res = 0; @@ -644,7 +644,7 @@ uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId) int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) { - LOGI("DeviceProfileConnector::DeleteTimeOutAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); int32_t trustNumber = 0; @@ -659,7 +659,7 @@ int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) bool DeviceProfileConnector::CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId) { - LOGI("DeviceProfileConnector::CheckPkgnameInAcl"); + LOGI("Start"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { @@ -688,7 +688,7 @@ bool DeviceProfileConnector::CheckPkgnameInAcl(std::string pkgName, std::string int32_t DeviceProfileConnector::IsSameAccount(const std::string &udid) { - LOGI("DeviceProfileConnector::IsSameAccount start."); + LOGI("Start."); std::vector profiles = GetAccessControlProfile(); for (auto &item : profiles) { if (item.GetTrustDeviceId() == udid && item.GetStatus() == ACTIVE) { @@ -704,7 +704,7 @@ int32_t DeviceProfileConnector::IsSameAccount(const std::string &udid) int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) { - LOGI("DeviceProfileConnector::CheckAccessControl pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", + LOGI("PkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); std::vector profiles = GetAccessControlProfile(); for (auto &item : profiles) { @@ -722,7 +722,7 @@ int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::AccessControlProfile &profile, const DmAccessCaller &caller, const DmAccessCallee &callee) { - LOGI("DeviceProfileConnector::SingleUserProcess bindType %{public}d, bindLevel %{public}d.", + LOGI("BindType %{public}d, bindLevel %{public}d.", profile.GetBindType(), profile.GetBindLevel()); uint32_t bindType = profile.GetBindType(); bool ret = false; @@ -756,7 +756,7 @@ bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::A int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) { - LOGI("DeviceProfileConnector::CheckAccessControl pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", + LOGI("PkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); std::vector profiles = GetAccessControlProfile(); for (auto &item : profiles) { -- Gitee From 2f1200ff8dd0028ecbd99ffb21662b73a16593ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 14 Aug 2024 17:00:51 +0800 Subject: [PATCH 072/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8hea?= =?UTF-8?q?der?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c | 1 - 1 file changed, 1 deletion(-) diff --git a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c index 55d6dc537..53dc9b8cf 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c +++ b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c @@ -20,7 +20,6 @@ #include "cJSON.h" #include "cmsis_os2.h" -#include "discovery_service.h" #include "hichain_adapter.h" #include "inner_session.h" #include "los_config.h" -- Gitee From 9021c7ad961837b1f1fdd6c26f1d09823330d6a1 Mon Sep 17 00:00:00 2001 From: zhanglei Date: Wed, 14 Aug 2024 17:09:11 +0800 Subject: [PATCH 073/520] add UT Signed-off-by: zhanglei --- .../UTTest_softbus_listener.cpp | 129 ++++++++++++++++++ .../UTTest_softbus_publish.cpp | 55 ++++++++ test/softbusunittest/UTTest_softbus_publish.h | 46 +++++++ test/unittest/BUILD.gn | 29 ++++ 4 files changed, 259 insertions(+) create mode 100644 test/softbusunittest/UTTest_softbus_publish.cpp create mode 100644 test/softbusunittest/UTTest_softbus_publish.h diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index e24d744cd..33ff94e30 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -297,6 +297,81 @@ HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_001, testing::ext::Tes EXPECT_EQ(softbusListener->isRadarSoLoad_, true); } +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_ETH, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_003, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BR, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_004, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_MAX, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + HWTEST_F(SoftbusListenerTest, GetNetworkTypeByNetworkId_001, testing::ext::TestSize.Level0) { char *networkId; @@ -446,6 +521,18 @@ HWTEST_F(SoftbusListenerTest, GetTrustedDeviceList_001, testing::ext::TestSize.L EXPECT_EQ(ret, DM_OK); } +HWTEST_F(SoftbusListenerTest, GetTrustedDeviceList_002, testing::ext::TestSize.Level0) +{ + std::vector deviceInfoList; + DmDeviceInfo deviceInfo; + deviceInfoList.push_back(deviceInfo); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTrustedDeviceList(deviceInfoList); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(SoftbusListenerTest, GetDeviceInfo_001, testing::ext::TestSize.Level0) { std::string networkId = "networkId"; @@ -627,6 +714,48 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. int32_t ret = softbusListener->StopRefreshSoftbusLNN(subscribeId); EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } + +HWTEST_F(SoftbusListenerTest, OnLocalDevInfoChange_001, testing::ext::TestSize.Level0) +{ + char *msg = nullptr; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->OnLocalDevInfoChange(); + EXPECT_EQ(msg, nullptr); +} + +HWTEST_F(SoftbusListenerTest, OnDeviceNotTrusted_001, testing::ext::TestSize.Level0) +{ + char *msg = nullptr; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->OnDeviceNotTrusted(nullptr); + EXPECT_EQ(msg, nullptr); +} + +HWTEST_F(SoftbusListenerTest, OnDeviceNotTrusted_002, testing::ext::TestSize.Level0) +{ + char msg[MAX_SOFTBUS_MSG_LEN + 1] = "This is a long message"; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->OnDeviceNotTrusted(msg); + EXPECT_NE(msg, nullptr); +} + +HWTEST_F(SoftbusListenerTest, OnDeviceNotTrusted_003, testing::ext::TestSize.Level0) +{ + char msg[MAX_SOFTBUS_MSG_LEN - 1] = "Valid message"; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->OnDeviceNotTrusted(msg); + EXPECT_NE(msg, nullptr); +} + + } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/softbusunittest/UTTest_softbus_publish.cpp b/test/softbusunittest/UTTest_softbus_publish.cpp new file mode 100644 index 000000000..d305d2ed0 --- /dev/null +++ b/test/softbusunittest/UTTest_softbus_publish.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "UTTest_softbus_publish.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" +#include "softbus_connector.h" +#include "softbus_error_code.h" + +namespace OHOS { +namespace DistributedHardware { +void SoftbusPublishTest::SetUp() +{ +} +void SoftbusPublishTest::TearDown() +{ +} +void SoftbusPublishTest::SetUpTestCase() +{ +} +void SoftbusPublishTest::TearDownTestCase() +{ +} + +namespace { +HWTEST_F(SoftbusPublishTest, OnSoftbusPublishResult_001, testing::ext::TestSize.Level0) +{ + int publishId = 1; + SoftbusPublish::OnSoftbusPublishResult(publishId, PUBLISH_LNN_SUCCESS); + EXPECT_EQ(publishId, 1); +} + +HWTEST_F(SoftbusPublishTest, PublishSoftbusLNN_001, testing::ext::TestSize.Level0) +{ + SoftbusPublish spftbusPublish; + int32_t ret = spftbusPublish.PublishSoftbusLNN(); + EXPECT_EQ(ret, ERR_DM_PUBLISH_FAILED); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/softbusunittest/UTTest_softbus_publish.h b/test/softbusunittest/UTTest_softbus_publish.h new file mode 100644 index 000000000..981cfe371 --- /dev/null +++ b/test/softbusunittest/UTTest_softbus_publish.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_UTTEST_DM_SOFTBUS_PUBLISH_H +#define OHOS_UTTEST_DM_SOFTBUS_PUBLISH_H + +#include +#include + +#include +#include +#include +#include +#include + +#include "auth_response_state.h" +#include "device_manager_service_listener.h" +#include "dm_auth_manager.h" +#include "dm_device_state_manager.h" +#include "dm_discovery_manager.h" +#include "inner_session.h" +#include "softbus_publish.h" + +namespace OHOS { +namespace DistributedHardware { +class SoftbusPublishTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 0967feabe..a4e480a72 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -68,6 +68,7 @@ group("unittest") { ":UTTest_softbus_adapter", ":UTTest_softbus_connector", ":UTTest_softbus_listener", + ":UTTest_softbus_publish", ":UTTest_softbus_session", ] } @@ -463,6 +464,34 @@ ohos_unittest("UTTest_softbus_listener") { ## UnitTest UTTest_softbus_listener }}} +## UnitTest UTTest_softbus_publish {{{ +ohos_unittest("UTTest_softbus_publish") { + module_out_path = module_out_path + + include_dirs = [ + "${devicemanager_path}/test/softbusunittest", + "${services_path}/src/softbus", + ] + + sources = [ + "${devicemanager_path}/test/softbusunittest/UTTest_softbus_publish.cpp", + "${devicemanager_path}/test/unittest/mock/parameter.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "hisysevent:libhisysevent", + "hitrace:hitrace_meter", + ] +} + +## UnitTest UTTest_softbus_publish }}} + ## UnitTest UTTest_softbus_session {{{ ohos_unittest("UTTest_softbus_session") { module_out_path = module_out_path -- Gitee From 18ab5385c34cb72b070be665f86d1fe03f381ab0 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 14 Aug 2024 19:04:31 +0800 Subject: [PATCH 074/520] =?UTF-8?q?=E8=A1=A5=E5=85=85fuzz=20Signed-off-by:?= =?UTF-8?q?=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/commonfuzztest/BUILD.gn | 4 + .../authenticate_device_fuzzer.cpp | 100 ++++++++++++++++++ .../BUILD.gn | 1 + .../hichain_connector_fuzzer.cpp | 17 ++- 4 files changed, 121 insertions(+), 1 deletion(-) diff --git a/test/commonfuzztest/BUILD.gn b/test/commonfuzztest/BUILD.gn index 0757b9120..83cb6a5e3 100644 --- a/test/commonfuzztest/BUILD.gn +++ b/test/commonfuzztest/BUILD.gn @@ -17,10 +17,14 @@ group("fuzztest") { deps = [ "authenticatedevice_fuzzer:fuzztest", "authenticatedeviceservice_fuzzer:fuzztest", + "authenticatedeviceserviceimpl_fuzzer:fuzztest", + "dmauthmanager_fuzzer:fuzztest", "dmcommoneventmanager_fuzzer:fuzztest", "dmcredentialimpl_fuzzer:fuzztest", + "dmdiscoverymanager_fuzzer:fuzztest", "generateencrypteduuid_fuzzer:fuzztest", "getdeviceinfo_fuzzer:fuzztest", + "hichainconnector_fuzzer:fuzztest", "ondatareceived_fuzzer:fuzztest", "onerror_fuzzer:fuzztest", "onfinish_fuzzer:fuzztest", diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index d8cb654bd..caad363bd 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -275,6 +275,104 @@ void AuthenticateDeviceThirdFuzzTest(const uint8_t* data, size_t size) DeviceManager::GetInstance().UnRegisterDevStateCallback(str); DeviceManager::GetInstance().UnRegisterDevStatusCallback(str); } + +void AuthenticateDeviceFourthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + AddPermission(); + std::string str(reinterpret_cast(data), size); + + DeviceManagerImpl::GetInstance().ipcClientProxy_ = + std::make_shared(std::make_shared()); + std::string emptyStr = ""; + DmDeviceInfo info; + DmDeviceBasicInfo deviceBasicInfo; + int32_t indexTwo = 2; + int32_t numOne = 1; + int32_t numOneTwoTimes = 11; + int32_t numOneThreeTimes = 111; + int32_t numOneSixTimes = 111111; + + DeviceManagerImpl::GetInstance().ConvertDeviceInfoToDeviceBasicInfo(info, deviceBasicInfo); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(emptyStr, emptyStr, g_deviceList); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(emptyStr, emptyStr, false, g_deviceList); + DeviceManagerImpl::GetInstance().GetDeviceInfo(emptyStr, emptyStr, info); + DeviceManagerImpl::GetInstance().RegisterDevStatusCallback(emptyStr, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(emptyStr); + DeviceManagerImpl::GetInstance().UnRegisterDevStatusCallback(emptyStr); + DeviceManagerImpl::GetInstance().StartDeviceDiscovery(emptyStr, g_subscribeInfo, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().StartDeviceDiscovery(emptyStr, numOneSixTimes, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().StopDeviceDiscovery(emptyStr, numOneTwoTimes); + DeviceManagerImpl::GetInstance().StopDeviceDiscovery(numOneThreeTimes, ""); + DeviceManagerImpl::GetInstance().PublishDeviceDiscovery(emptyStr, g_publishInfo, nullptr); + DeviceManagerImpl::GetInstance().UnPublishDeviceDiscovery(emptyStr, numOneTwoTimes); + DeviceManagerImpl::GetInstance().AuthenticateDevice(emptyStr, numOne, info, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().RegisterDeviceManagerFaCallback(emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDeviceManagerFaCallback(emptyStr); + DeviceManagerImpl::GetInstance().VerifyAuthentication(emptyStr, emptyStr, nullptr); + PeerTargetId targetId; + std::map discoverParam; + DeviceManagerImpl::GetInstance().BindTarget(emptyStr, targetId, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().UnbindTarget(emptyStr, targetId, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(emptyStr, discoverParam, false, g_deviceList); + DeviceManagerImpl::GetInstance().RegisterDevStateCallback(emptyStr, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().AddDiscoveryCallback("test", nullptr); + DeviceManagerImpl::GetInstance().RemoveDiscoveryCallback("test"); + DeviceManagerImpl::GetInstance().AddPublishCallback("test"); + DeviceManagerImpl::GetInstance().RemovePublishCallback("test"); + DeviceManagerImpl::GetInstance().RegisterPinHolderCallback(emptyStr, nullptr); + DeviceManagerImpl::GetInstance().GetDeviceSecurityLevel(emptyStr, emptyStr, indexTwo); + DeviceManagerImpl::GetInstance().IsSameAccount(emptyStr); +} + +void AuthenticateDeviceFifthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size == 0)) { + return; + } + AddPermission(); + std::string str(reinterpret_cast(data), size); + + DeviceManagerImpl::GetInstance().ipcClientProxy_ = + std::make_shared(std::make_shared()); + std::string emptyStr = ""; + DmDeviceInfo info; + DmDeviceBasicInfo deviceBasicInfo; + int32_t indexTwo = 2; + DmAuthParam dmFaParam; + DeviceManagerImpl::GetInstance().GetFaParam(emptyStr, dmFaParam); + DeviceManagerImpl::GetInstance().SetUserOperation(emptyStr, 1, emptyStr); + DeviceManagerImpl::GetInstance().GetUdidByNetworkId(emptyStr, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().GetUuidByNetworkId(emptyStr, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().RegisterDevStateCallback(emptyStr, emptyStr); + DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(emptyStr, emptyStr); + DeviceManagerImpl::GetInstance().RegisterUiStateCallback(emptyStr); + DeviceManagerImpl::GetInstance().UnRegisterUiStateCallback(emptyStr); + DeviceManagerImpl::GetInstance().RequestCredential(emptyStr, g_reqJsonStr, g_returnStr); + DeviceManagerImpl::GetInstance().ImportCredential(emptyStr, emptyStr); + DeviceManagerImpl::GetInstance().DeleteCredential(emptyStr, emptyStr); + DeviceManagerImpl::GetInstance().RegisterCredentialCallback(emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterCredentialCallback(emptyStr); + DeviceManagerImpl::GetInstance().NotifyEvent(emptyStr, 1, emptyStr); + DeviceManagerImpl::GetInstance().RequestCredential(emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().CheckCredential(emptyStr, g_reqJsonStr, g_returnStr); + DeviceManagerImpl::GetInstance().GetEncryptedUuidByNetworkId(emptyStr, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().GenerateEncryptedUuid(emptyStr, emptyStr, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().BindDevice(emptyStr, 1, emptyStr, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnBindDevice(emptyStr, emptyStr); + DeviceManagerImpl::GetInstance().GetNetworkTypeByNetworkId(emptyStr, emptyStr, indexTwo); + DeviceManagerImpl::GetInstance().ImportAuthCode(emptyStr, emptyStr); + DeviceManagerImpl::GetInstance().ExportAuthCode(g_returnStr); + std::map discoverParam; + DeviceManagerImpl::GetInstance().StartDiscovering(emptyStr, discoverParam, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().StopDiscovering(emptyStr, discoverParam); + DeviceManagerImpl::GetInstance().RegisterDiscoveryCallback(emptyStr, discoverParam, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDiscoveryCallback(emptyStr); + DeviceManagerImpl::GetInstance().StartAdvertising(emptyStr, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().StopAdvertising(emptyStr, discoverParam); +} } } @@ -285,5 +383,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) OHOS::DistributedHardware::AuthenticateDeviceFirstFuzzTest(data, size); OHOS::DistributedHardware::AuthenticateDeviceSecondFuzzTest(data, size); OHOS::DistributedHardware::AuthenticateDeviceThirdFuzzTest(data, size); + OHOS::DistributedHardware::AuthenticateDeviceFourthFuzzTest(data, size); + OHOS::DistributedHardware::AuthenticateDeviceFifthFuzzTest(data, size); return 0; } diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn index 6a63d4b29..a0c4d3da6 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn @@ -67,6 +67,7 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { ] external_deps = [ + "ability_base:want", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 34fc06070..e9f8f286c 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -101,6 +101,21 @@ void HiChainConnectorFuzzTest(const uint8_t* data, size_t size) hichainConnector->GetRelatedGroupsCommon(deviceId, pkgNameStr.data(), groupList); hichainConnector->UnRegisterHiChainCallback(); } + +void HiChainConnectorSecondFuzzTest(const uint8_t* data, size_t size) +{ + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + + std::vector groupList; + nlohmann::json jsonDeviceList; + GroupInfo groupInfo; + std::vector syncGroupList; + hichainConnector->GetSyncGroupList(groupList, syncGroupList); + hichainConnector->IsGroupInfoInvalid(groupInfo); + hichainConnector->UnRegisterHiChainGroupCallback(); + hichainConnector->GetJsonStr(jsonDeviceList, "key"); +} } } @@ -109,6 +124,6 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { /* Run your code on data */ OHOS::DistributedHardware::HiChainConnectorFuzzTest(data, size); - + OHOS::DistributedHardware::HiChainConnectorSecondFuzzTest(data, size); return 0; } \ No newline at end of file -- Gitee From dc52acaf2e55e130c7711548d529af8058fdabc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 14 Aug 2024 22:40:55 +0800 Subject: [PATCH 075/520] =?UTF-8?q?=E5=AD=97=E4=BD=93=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- display/AppScope/app.json | 7 ++++--- .../src/main/resources/base/profile/configuration.json | 6 ++++++ 2 files changed, 10 insertions(+), 3 deletions(-) create mode 100644 display/entry/src/main/resources/base/profile/configuration.json diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 346650e60..8b8059ce6 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -4,14 +4,15 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000019, - "versionName": "1.0.19", + "versionCode": 1000020, + "versionName": "1.0.20", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, "targetAPIVersion": 10, "distributedNotificationEnabled": true, "apiReleaseType": "Beta3", - "debug": false + "debug": false, + "configuration":"$profile:configuration" } } diff --git a/display/entry/src/main/resources/base/profile/configuration.json b/display/entry/src/main/resources/base/profile/configuration.json new file mode 100644 index 000000000..b2635e1f4 --- /dev/null +++ b/display/entry/src/main/resources/base/profile/configuration.json @@ -0,0 +1,6 @@ +{ + "configuration": { + "fontSizeScale" : "followSystem", + "fontSizeMaxScale" : "3.2" + } +} \ No newline at end of file -- Gitee From 586fb6de276d3b881cd05b02b5668908276def45 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 14 Aug 2024 23:06:56 +0800 Subject: [PATCH 076/520] =?UTF-8?q?=E5=85=BC=E5=AE=B9=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- common/include/dm_anonymous.h | 2 + common/include/dm_constants.h | 1 + common/src/dm_anonymous.cpp | 30 +++- .../include/deviceprofile_connector.h | 12 +- .../src/deviceprofile_connector.cpp | 49 ++--- .../authentication/auth_message_processor.h | 1 + .../include/authentication/dm_auth_manager.h | 11 +- .../authentication/auth_message_processor.cpp | 4 + .../authentication/auth_response_state.cpp | 6 +- .../src/authentication/dm_auth_manager.cpp | 169 ++++++++++++++---- .../src/device_manager_service_listener.cpp | 2 +- .../UTTest_dm_auth_manager_first.cpp | 8 +- .../UTTest_dm_deviceprofile_connector.cpp | 28 +-- .../device_profile_connector_fuzzer.cpp | 2 +- 14 files changed, 233 insertions(+), 92 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index e95a8fcff..f7304e101 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -39,6 +39,8 @@ void ParseMapFromJsonString(const std::string &jsonStr, std::map &numVec); +bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 8bc56951d..d663bbc79 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -48,6 +48,7 @@ enum { ERR_DM_AUTH_CODE_INCORRECT = -20053, ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY = -20056, ERR_DM_SYNC_DELETE_DEVICE_REPEATED = -20058, + ERR_DM_VERSION_INCOMPATIBLE = -20059, ERR_DM_FAILED = 96929744, ERR_DM_NOT_INIT = 96929746, diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index fea9bde51..346d92348 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -15,7 +15,7 @@ #include "dm_anonymous.h" #include "dm_log.h" - +#include namespace OHOS { namespace DistributedHardware { namespace { @@ -204,5 +204,33 @@ int32_t StringToInt(const std::string &str, int32_t base) } return static_cast(result); } + +void StringSplitToInt(const std::string &str, const char split, std::vector &numVec) +{ + std::istringstream iss(str); + std::string token = ""; + while (getline(iss, token, split)) { + numVec.push_back(atoi(token.c_str())); + } +} + +bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum) +{ + for (uint32_t index = 0; index < std::min(srcVecNum.size(), sinkVecNum.size()); index++) { + if (srcVecNum[index] > sinkVecNum[index]) { + return true; + } else if (srcVecNum[index] < sinkVecNum[index]) { + return false; + } else { + continue; + } + } + if (srcVecNum.size() > sinkVecNum.size()){ + return true; + } else { + return false; + } + return false; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index d60e259cf..e55df1e4c 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -104,11 +104,11 @@ public: virtual std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId) = 0; virtual bool CheckIdenticalAccount(int32_t userId, const std::string &accountId) = 0; virtual int32_t DeleteP2PAccessControlList(int32_t userId, std::string &accountId) = 0; - virtual bool CheckSrcDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) = 0; - virtual bool CheckSinkDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) = 0; + virtual bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) = 0; + virtual bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) = 0; virtual uint32_t DeleteTimeOutAcl(const std::string &deviceId) = 0; virtual int32_t GetTrustNumber(const std::string &deviceId) = 0; - virtual bool CheckDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) = 0; + virtual bool CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) = 0; virtual bool CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId) = 0; virtual std::vector CompareBindType(std::vector profiles, std::string pkgName, std::vector &sinkBindType, std::string localDeviceId, @@ -136,11 +136,11 @@ public: std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); int32_t DeleteP2PAccessControlList(int32_t userId, std::string &accountId); - bool CheckSrcDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId); - bool CheckSinkDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId); + bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); + bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); uint32_t DeleteTimeOutAcl(const std::string &deviceId); int32_t GetTrustNumber(const std::string &deviceId); - bool CheckDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId); + bool CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); bool CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId); std::vector CompareBindType(std::vector profiles, std::string pkgName, std::vector &sinkBindType, std::string localDeviceId, std::string targetDeviceId); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 60dde1581..308046161 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -475,7 +475,8 @@ void DeviceProfileConnector::DeleteAccessControlList(const std::string &udid) DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId) { - LOGI("DeleteAccessControlList by pkgName, localDeviceId, remoteDeviceId."); + LOGI("DeleteAccessControlList by pkgName %{public}s, localDeviceId %{public}s, remoteDeviceId %{public}s.", + pkgName.c_str(), GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str()); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); DmOfflineParam offlineParam; @@ -493,7 +494,8 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(std::string pkgNa if (item.GetTrustDeviceId() == remoteDeviceId) { offlineParam.leftAclNumber++; if (item.GetBindLevel() == DEVICE && item.GetBindType() != DM_IDENTICAL_ACCOUNT && - item.GetAccesser().GetAccesserBundleName() == pkgName) { + (item.GetAccesser().GetAccesserBundleName() == pkgName || + item.GetAccesser().GetAccesserBundleName() == "")) { LOGI("DeleteAccessControlList device unbind."); offlineParam.bindType = DEVICE_PEER_TO_PEER_TYPE; } @@ -588,39 +590,41 @@ int32_t DeviceProfileConnector::DeleteP2PAccessControlList(int32_t userId, std:: return DM_OK; } -bool DeviceProfileConnector::CheckSrcDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) +bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { - LOGI("DeviceProfileConnector::CheckSrcDeviceIdInAcl"); + LOGI("DeviceProfileConnector::CheckSrcDevIdInAclForDevBind"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && item.GetAccessee().GetAccesseeBundleName() == pkgName && - item.GetAccessee().GetAccesseeUserId() == 0 && item.GetAccessee().GetAccesseeAccountId() == "") { + item.GetBindLevel() == DEVICE && (item.GetAccessee().GetAccesseeBundleName() == pkgName || + item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccessee().GetAccesseeUserId() == 0 && + item.GetAccessee().GetAccesseeAccountId() == "") { return true; } } return false; } -bool DeviceProfileConnector::CheckSinkDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) +bool DeviceProfileConnector::CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { - LOGI("DeviceProfileConnector::CheckSinkDeviceIdInAcl"); + LOGI("DeviceProfileConnector::CheckSinkDevIdInAclForDevBind"); std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { if (item.GetTrustDeviceId() == deviceId && item.GetStatus() == ACTIVE && - item.GetBindLevel() == DEVICE && item.GetAccesser().GetAccesserBundleName() == pkgName && - item.GetAccesser().GetAccesserUserId() == 0 && item.GetAccesser().GetAccesserAccountId() == "") { + item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || + item.GetAccesser().GetAccesserBundleName() == "") && item.GetAccesser().GetAccesserUserId() == 0 && + item.GetAccesser().GetAccesserAccountId() == "") { return true; } } return false; } -bool DeviceProfileConnector::CheckDeviceIdInAcl(const std::string &pkgName, const std::string &deviceId) +bool DeviceProfileConnector::CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { - return (CheckSinkDeviceIdInAcl(pkgName, deviceId) || CheckSrcDeviceIdInAcl(pkgName, deviceId)); + return (CheckSinkDevIdInAclForDevBind(pkgName, deviceId) || CheckSrcDevIdInAclForDevBind(pkgName, deviceId)); } uint32_t DeviceProfileConnector::DeleteTimeOutAcl(const std::string &deviceId) @@ -663,23 +667,22 @@ bool DeviceProfileConnector::CheckPkgnameInAcl(std::string pkgName, std::string std::vector profiles = GetAccessControlProfile(); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); for (auto &item : profiles) { - if (item.GetTrustDeviceId() != remoteDeviceId && item.GetStatus() != ACTIVE) { + if (item.GetTrustDeviceId() != remoteDeviceId || item.GetStatus() != ACTIVE || + item.GetBindType() == DM_IDENTICAL_ACCOUNT) { continue; } - if ((item.GetBindType() == DM_POINT_TO_POINT || item.GetBindType() == DM_ACROSS_ACCOUNT) && - item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || - item.GetAccessee().GetAccesseeBundleName() == pkgName)) { + if (item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || + item.GetAccessee().GetAccesseeBundleName() == pkgName || + item.GetAccesser().GetAccesserBundleName() == "" || item.GetAccessee().GetAccesseeBundleName() == "")) { LOGI("The pkgname %{public}s is peer-to-peer device unbind.", pkgName.c_str()); return true; - } else if ((item.GetBindType() == DM_POINT_TO_POINT || item.GetBindType() == DM_ACROSS_ACCOUNT) && - item.GetBindLevel() == APP && item.GetAccesser().GetAccesserBundleName() == pkgName && + } else if (item.GetBindLevel() == APP && item.GetAccesser().GetAccesserBundleName() == pkgName && item.GetAccesser().GetAccesserDeviceId() == localDeviceId) { - LOGI("The pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); + LOGI("The accesser pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); return true; - } else if ((item.GetBindType() == DM_POINT_TO_POINT || item.GetBindType() == DM_ACROSS_ACCOUNT) && - item.GetBindLevel() == APP && item.GetAccessee().GetAccesseeBundleName() == pkgName && + } else if (item.GetBindLevel() == APP && item.GetAccessee().GetAccesseeBundleName() == pkgName && item.GetAccessee().GetAccesseeDeviceId() == localDeviceId) { - LOGI("The pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); + LOGI("The accessee pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); return true; } } @@ -756,7 +759,7 @@ bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::A int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) { - LOGI("DeviceProfileConnector::CheckAccessControl pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", + LOGI("DeviceProfileConnector::CheckIsSameAccount pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); std::vector profiles = GetAccessControlProfile(); for (auto &item : profiles) { diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index f521c8f9a..dfac3abfd 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -71,6 +71,7 @@ constexpr const char* TAG_DATA = "data"; constexpr const char* TAG_DATA_LEN = "dataLen"; constexpr const char* TAG_IMPORT_AUTH_CODE = "IMPORT_AUTH_CODE"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; +constexpr const char* TAG_EDITION = "edition"; class DmAuthManager; struct DmAuthRequestContext; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 4ae25cbd3..48067f4d2 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -181,6 +181,7 @@ typedef struct DmAuthResponseContext { std::string importAuthCode; std::string hostPkgLabel; bool isFinish = false; + std::string edition; } DmAuthResponseContext; class AuthMessageProcessor; @@ -492,8 +493,8 @@ private: void InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra); void CompatiblePutAcl(); - void ProRespNegotiateExt(const int32_t &sessionId); - void ProRespNegotiate(const int32_t &sessionId); + void ProcRespNegotiateExt(const int32_t &sessionId); + void ProcRespNegotiate(const int32_t &sessionId); void AccountIdLogoutEventCallback(int32_t userId); void UserChangeEventCallback(int32_t userId); void GetAuthRequestContext(); @@ -502,6 +503,8 @@ private: void SrcSyncDeleteAclDone(); void SinkSyncDeleteAclDone(); int32_t CheckTrustState(); + void ProcIncompatible(const int32_t &sessionId); + bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); public: void RequestCredential(); @@ -543,6 +546,9 @@ private: void SrcAuthenticateFinish(); std::string GetBundleLable(const std::string &bundleName); bool IsScreenLocked(); + std::string ConvertSrcVersion(const std::string &version, const std::string &edition); + std::string ConvertSinkVersion(const std::string &version); + void NegotiateRespMsg(const std::string &version); private: std::shared_ptr softbusConnector_; @@ -575,6 +581,7 @@ private: bool isAuthDevice_ = false; bool isAuthenticateDevice_ = false; int32_t authForm_ = DmAuthForm::ACROSS_ACCOUNT; + std::string remoteVersion_ = ""; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index d3ef26986..5d465cb3a 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -187,6 +187,7 @@ void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) json[TAG_IDENTICAL_ACCOUNT] = authResponseContext_->isIdenticalAccount; json[TAG_HAVE_CREDENTIAL] = authResponseContext_->haveCredential; json[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; + json[TAG_EDITION] = authResponseContext_->edition; } void AuthMessageProcessor::CreateRespNegotiateMessage(nlohmann::json &json) @@ -545,6 +546,9 @@ void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) if (IsString(json, TAG_HOST)) { authResponseContext_->hostPkgName = json[TAG_HOST].get(); } + if (IsString(json, TAG_EDITION)) { + authResponseContext_->edition = json[TAG_EDITION].get(); + } ParsePkgNegotiateMessage(json); } diff --git a/services/implementation/src/authentication/auth_response_state.cpp b/services/implementation/src/authentication/auth_response_state.cpp index fae9f86eb..e86ef6fa2 100644 --- a/services/implementation/src/authentication/auth_response_state.cpp +++ b/services/implementation/src/authentication/auth_response_state.cpp @@ -162,7 +162,7 @@ int32_t AuthResponseCredential::Enter() { std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { - LOGE("AuthResponseFinishState authManager_ is null"); + LOGE("AuthResponseCredential authManager_ is null"); return ERR_DM_FAILED; } stateAuthManager->ResponseCredential(); @@ -178,7 +178,7 @@ int32_t AuthResponseSyncDeleteAcl::Enter() { std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { - LOGE("AuthResponseFinishState authManager_ is null"); + LOGE("AuthResponseSyncDeleteAcl authManager_ is null"); return ERR_DM_FAILED; } stateAuthManager->ResponseSyncDeleteAcl(); @@ -194,7 +194,7 @@ int32_t AuthResponseSyncDeleteAclNone::Enter() { std::shared_ptr stateAuthManager = authManager_.lock(); if (stateAuthManager == nullptr) { - LOGE("AuthResponseFinishState authManager_ is null"); + LOGE("AuthResponseSyncDeleteAclNone authManager_ is null"); return ERR_DM_FAILED; } stateAuthManager->SyncDeleteAclDone(); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index d2221fc04..87457c96d 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -71,8 +71,9 @@ constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; -constexpr const char* DM_VERSION = "4.1.5.1"; -constexpr const char* DM_NEW_VERSION = "5.0.1"; +constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; +constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; +constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; std::mutex g_authFinishLock; DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, @@ -88,7 +89,7 @@ DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, authUiStateMgr_ = std::make_shared(listener_); authenticationMap_[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; authenticationMap_[AUTH_TYPE_CRE] = nullptr; - dmVersion_ = DM_NEW_VERSION; + dmVersion_ = DM_VERSION_5_0_2; } DmAuthManager::~DmAuthManager() @@ -160,7 +161,7 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->localDeviceId = localUdid; authRequestContext_->deviceId = deviceId; authRequestContext_->ip = deviceId; - authRequestContext_->dmVersion = DM_NEW_VERSION; + authRequestContext_->dmVersion = DM_VERSION_5_0_2; authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); MultipleUserConnector::SetSwitchOldAccountId(authRequestContext_->localAccountId); authRequestContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -547,6 +548,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_AUTH); softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); + authResponseContext_->isFinish = true; authResponseState_->TransitionTo(std::make_shared()); } @@ -585,6 +587,10 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) if (status == DM_OK && authResponseContext_->requestId == requestId && authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + } else { + if (++authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->isFinish = false; + } } } else { LOGE("DmAuthManager::OnMemberJoin failed, authRequestState_ or authResponseState_ is invalid."); @@ -682,6 +688,7 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authResponseContext_->localAccountId = authRequestContext_->localAccountId; authResponseContext_->localUserId = authRequestContext_->localUserId; authResponseContext_->isIdenticalAccount = false; + authResponseContext_->edition = DM_VERSION_5_0_2; authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); @@ -698,7 +705,7 @@ void DmAuthManager::AbilityNegotiate() bool ret = hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, localDeviceId); if (ret) { LOGE("DmAuthManager::EstablishAuthChannel device is in group"); - if (!DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(authResponseContext_->hostPkgName, + if (!DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(authResponseContext_->hostPkgName, authResponseContext_->localDeviceId)) { CompatiblePutAcl(); } @@ -735,43 +742,68 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) remoteDeviceId_ = authResponseContext_->localDeviceId; authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId(); authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); - if (authResponseContext_->dmVersion == "") { - authResponseContext_->dmVersion = dmVersion_; - } else if (authResponseContext_->dmVersion == DM_VERSION) { + remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); + NegotiateRespMsg(remoteVersion_); + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && + authResponseContext_->bindLevel <= APP)) { + ProcRespNegotiateExt(sessionId); + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT, + [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { + ProcRespNegotiate(sessionId); + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT, + [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } else { + ProcIncompatible(sessionId); + } +} + +void DmAuthManager::NegotiateRespMsg(const std::string &version) +{ + if (version == DM_VERSION_5_0_1) { + authResponseContext_->dmVersion = DM_VERSION_5_0_1; + } else if (version < DM_VERSION_5_0_1) { authResponseContext_->dmVersion = ""; authResponseContext_->bindLevel = INVALIED_TYPE; + } else if (version > DM_VERSION_5_0_1) { + authResponseContext_->dmVersion = dmVersion_; } - LOGI("RespNegotiate dmversion %{public}s, level %{public}d", - authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { - ProRespNegotiateExt(sessionId); - } else { - ProRespNegotiate(sessionId); - } - timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); } void DmAuthManager::SendAuthRequest(const int32_t &sessionId) { + LOGI("DmAuthManager::SendAuthRequest sessionId %{public}d.", sessionId); if (authResponseContext_ == nullptr) { LOGE("failed to SendAuthRequest because authResponseContext_ is nullptr"); return; } - LOGI("DmAuthManager::SendAuthRequest session id"); + if (authResponseContext_->reply == ERR_DM_VERSION_INCOMPATIBLE) { + LOGE("The peer device version is not supported"); + authRequestContext_->reason = authResponseContext_->reply; + authRequestState_->TransitionTo(std::make_shared()); + return; + } remoteDeviceId_ = authResponseContext_->localDeviceId; + remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion); timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); if (authResponseContext_->cryptoSupport) { isCryptoSupport_ = true; } LOGI("SendAuthRequest dmversion %{public}s, level %{public}d", authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && + authResponseContext_->bindLevel <= APP)) { ProcessAuthRequestExt(sessionId); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { ProcessAuthRequest(sessionId); + } else { + LOGE("Invalied bind mode."); } } @@ -941,10 +973,14 @@ int32_t DmAuthManager::StartAuthProcess(const int32_t &action) if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { LOGE("ReportAuthConfirmBox failed"); } - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && + authResponseContext_->bindLevel <= APP)) { return ConfirmProcessExt(action); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { return ConfirmProcess(action); + } else { + LOGE("Invalied bind mode."); } return DM_OK; } @@ -1123,8 +1159,9 @@ void DmAuthManager::AuthenticateFinish() CompatiblePutAcl(); } if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 && - authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel == INVALIED_TYPE && - softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) { + CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + authResponseContext_->bindLevel == INVALIED_TYPE && softbusConnector_->CheckIsOnline(remoteDeviceId_) && + authResponseContext_->isFinish) { softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } @@ -1326,10 +1363,14 @@ void DmAuthManager::ShowStartAuthDialog() LOGE("failed to get auth code"); return; } - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (authResponseContext_->bindLevel >= DEVICE && authResponseContext_->bindLevel <= APP)) { AuthDevice(pinCode); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { AddMember(pinCode); + } else { + LOGE("Invalied bind mode."); } return; } @@ -1349,11 +1390,16 @@ int32_t DmAuthManager::ProcessPincode(int32_t pinCode) return ERR_DM_FAILED; } timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - if (authResponseContext_->dmVersion == DM_NEW_VERSION && authResponseContext_->bindLevel != INVALIED_TYPE) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && + authResponseContext_->bindLevel <= APP)) { return AuthDevice(pinCode); - } else { + } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || + authResponseContext_->bindLevel == INVALIED_TYPE) { return AddMember(pinCode); + } else { + LOGE("Invalied bind mode."); } + return ERR_DM_FAILED; } int32_t DmAuthManager::AuthDevice(int32_t pinCode) @@ -1768,6 +1814,7 @@ int32_t DmAuthManager::EstablishUnbindChannel(const std::string &deviceIdHash) LOGE("OpenAuthSession failed, stop the syncdeleteacl."); authResponseContext_ = std::make_shared(); authResponseContext_->state = AuthState::AUTH_REQUEST_SYNCDELETE; + authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; authRequestContext_->reason = sessionId; if (authRequestState_ != nullptr) { authRequestState_->TransitionTo(std::make_shared()); @@ -1803,7 +1850,7 @@ void DmAuthManager::SrcSyncDeleteAclDone() char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) && - DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(authResponseContext_->hostPkgName, + DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(authResponseContext_->hostPkgName, remoteDeviceId_)) { DeleteGroup(authResponseContext_->hostPkgName, remoteDeviceId_); } @@ -1829,7 +1876,7 @@ void DmAuthManager::SinkSyncDeleteAclDone() char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) && - DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(authResponseContext_->hostPkgName, + DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(authResponseContext_->hostPkgName, remoteDeviceId_)) { DeleteGroup(authResponseContext_->hostPkgName, remoteDeviceId_); } @@ -2164,9 +2211,9 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & return DM_OK; } -void DmAuthManager::ProRespNegotiateExt(const int32_t &sessionId) +void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) { - LOGI("DmAuthManager::ProRespNegotiateExt start."); + LOGI("DmAuthManager::ProcRespNegotiateExt start."); remoteDeviceId_ = authResponseContext_->localDeviceId; std::string accountId = MultipleUserConnector::GetOhosAccountId(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -2206,9 +2253,9 @@ void DmAuthManager::ProRespNegotiateExt(const int32_t &sessionId) softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } -void DmAuthManager::ProRespNegotiate(const int32_t &sessionId) +void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) { - LOGI("DmAuthManager::ProRespNegotiate session id"); + LOGI("DmAuthManager::ProcRespNegotiate session id"); AbilityNegotiate(); authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_RESP_NEGOTIATE); @@ -2245,6 +2292,17 @@ void DmAuthManager::ProRespNegotiate(const int32_t &sessionId) softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } +void DmAuthManager::ProcIncompatible(const int32_t &sessionId) +{ + LOGI("DmAuthManager::ProcIncompatible sessionId %{public}d.", sessionId); + nlohmann::json respNegotiateMsg; + respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; + respNegotiateMsg[TAG_VER] = DM_ITF_VER; + respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; + std::string message = respNegotiateMsg.dump(); + softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); +} + void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message) { authResponseContext_->sessionId = sessionId; @@ -2434,7 +2492,7 @@ int32_t DmAuthManager::CheckTrustState() if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT) { if (hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, authRequestContext_->localDeviceId)) { - if (!DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(authResponseContext_->hostPkgName, + if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName, authResponseContext_->localDeviceId)) { CompatiblePutAcl(); } @@ -2537,5 +2595,42 @@ void DmAuthManager::HandleDeviceNotTrust(const std::string &udid) CHECK_NULL_VOID(hiChainConnector_); hiChainConnector_->DeleteAllGroupByUdid(udid); } + +std::string DmAuthManager::ConvertSrcVersion(const std::string &version, const std::string &edition) +{ + std::string srcVersion = ""; + if (version == "" && edition != "") { + srcVersion = edition; + } else if (version == "" && edition == "") { + srcVersion = DM_VERSION_5_0_1; + } else if (version != "" && edition == "") { + srcVersion = version; + } + LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", + version.c_str(), edition.c_str(), srcVersion.c_str()); + return srcVersion; +} + +std::string DmAuthManager::ConvertSinkVersion(const std::string &version) +{ + std::string sinkVersion = ""; + if (version == "") { + sinkVersion = DM_VERSION_4_1_5_1; + } else { + sinkVersion = version; + } + LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str()); + return sinkVersion; +} + +bool DmAuthManager::CompareVersion(const std::string &remoteVersion, const std::string &oldVersion) +{ + LOGI("remoteVersion %{public}s, oldVersion %{public}s.", remoteVersion.c_str(), oldVersion.c_str()); + std::vector remoteVersionVec; + std::vector oldVersionVec; + StringSplitToInt(remoteVersion, '.', remoteVersionVec); + StringSplitToInt(oldVersion, '.', oldVersionVec); + return CompareVecNum(remoteVersionVec, oldVersionVec); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index e0dee7d74..dd0dcc65a 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -67,7 +67,7 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetPkgName(pkgName); pReq->SetDeviceState(state); pReq->SetDeviceInfo(deviceInfo); diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 19481affc..d2b35040c 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -981,17 +981,17 @@ HWTEST_F(DmAuthManagerTest, DeleteAcl001, testing::ext::TestSize.Level0) ASSERT_NE(ret, DM_OK); } -HWTEST_F(DmAuthManagerTest, ProRespNegotiateExt001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt001, testing::ext::TestSize.Level0) { int32_t sessionId = 0; - authManager_->ProRespNegotiateExt(sessionId); + authManager_->ProcRespNegotiateExt(sessionId); ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, ProRespNegotiate001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) { int32_t sessionId = 0; - authManager_->ProRespNegotiate(sessionId); + authManager_->ProcRespNegotiate(sessionId); ASSERT_EQ(authManager_->isAuthDevice_, false); } diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 295f3caae..ecf01409f 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -620,59 +620,59 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteP2PAccessControlList_003, testing::ex EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceProfileConnectorTest, CheckSrcDeviceIdInAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_001, testing::ext::TestSize.Level0) { std::string pkgName; std::string deviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSrcDeviceIdInAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_002, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "123456"; - bool ret = DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSrcDeviceIdInAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_003, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckSrcDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSinkDeviceIdInAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_001, testing::ext::TestSize.Level0) { std::string pkgName; std::string deviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSinkDeviceIdInAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_002, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "123456"; - bool ret = DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckSinkDeviceIdInAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_003, testing::ext::TestSize.Level0) { std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckSinkDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } -HWTEST_F(DeviceProfileConnectorTest, CheckDeviceIdInAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, CheckDevIdInAclForDevBind_001, testing::ext::TestSize.Level0) { std::string pkgName; std::string deviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(pkgName, deviceId); + bool ret = DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(pkgName, deviceId); EXPECT_EQ(ret, false); } diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index 257bef638..9d6dc7373 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -64,7 +64,7 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - DeviceProfileConnector::GetInstance().CheckDeviceIdInAcl(pkgName, localDeviceId); + DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(pkgName, localDeviceId); DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(localDeviceId); DeviceProfileConnector::GetInstance().GetTrustNumber(localDeviceId); } -- Gitee From 976eed4b42ed470e78117870f4f5f8eac755dbe3 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 14 Aug 2024 23:20:34 +0800 Subject: [PATCH 077/520] =?UTF-8?q?=E5=85=BC=E5=AE=B9=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- common/src/dm_anonymous.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 346d92348..f92626b16 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -225,8 +225,8 @@ bool CompareVecNum(const std::vector &srcVecNum, const std::vector sinkVecNum.size()){ - return true; + if (srcVecNum.size() > sinkVecNum.size()) { + return true; } else { return false; } -- Gitee From 38b5f807846d7e5cf2fad85eb383eed2ed0ec809 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Thu, 15 Aug 2024 13:58:19 +0800 Subject: [PATCH 078/520] =?UTF-8?q?=E5=85=BC=E5=AE=B9=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- common/include/dm_anonymous.h | 2 +- common/src/dm_anonymous.cpp | 10 ++++------ .../src/authentication/dm_auth_manager.cpp | 4 ++-- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index f7304e101..d533a4e88 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -39,7 +39,7 @@ void ParseMapFromJsonString(const std::string &jsonStr, std::map &numVec); +void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec); bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); } // namespace DistributedHardware } // namespace OHOS diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index f92626b16..7b75748fd 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -205,12 +205,12 @@ int32_t StringToInt(const std::string &str, int32_t base) return static_cast(result); } -void StringSplitToInt(const std::string &str, const char split, std::vector &numVec) +void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec) { std::istringstream iss(str); - std::string token = ""; - while (getline(iss, token, split)) { - numVec.push_back(atoi(token.c_str())); + std::string item = ""; + while (getline(iss, item, split)) { + numVec.push_back(atoi(item.c_str())); } } @@ -227,8 +227,6 @@ bool CompareVecNum(const std::vector &srcVecNum, const std::vector sinkVecNum.size()) { return true; - } else { - return false; } return false; } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 87457c96d..af977902e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2628,8 +2628,8 @@ bool DmAuthManager::CompareVersion(const std::string &remoteVersion, const std:: LOGI("remoteVersion %{public}s, oldVersion %{public}s.", remoteVersion.c_str(), oldVersion.c_str()); std::vector remoteVersionVec; std::vector oldVersionVec; - StringSplitToInt(remoteVersion, '.', remoteVersionVec); - StringSplitToInt(oldVersion, '.', oldVersionVec); + VersionSplitToInt(remoteVersion, '.', remoteVersionVec); + VersionSplitToInt(oldVersion, '.', oldVersionVec); return CompareVecNum(remoteVersionVec, oldVersionVec); } } // namespace DistributedHardware -- Gitee From 78d4a9f0c8a0adee77809804eefa57bbf58a634b Mon Sep 17 00:00:00 2001 From: pwx1285814 Date: Wed, 14 Aug 2024 16:17:55 +0800 Subject: [PATCH 079/520] =?UTF-8?q?=E8=A1=A5=E5=85=85services/implementati?= =?UTF-8?q?on/src/credential/dm=5Fcredential=5Fmanager.cpp=20UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: pwx1285814 Change-Id: I4b69d5277653a4ae7a35aeb82474e9bf54d44647 Signed-off-by: pwx1285814 --- .../UTTest_dm_credential_manager.cpp | 437 ++++++++++++++++-- .../UTTest_dm_credential_manager.h | 12 + test/unittest/BUILD.gn | 11 +- 3 files changed, 428 insertions(+), 32 deletions(-) diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index 04c49f6c6..a94b83115 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -17,11 +17,12 @@ #include "accesstoken_kit.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_credential_manager.cpp" #include "dm_random.h" -#include "parameter.h" #include "nativetoken_kit.h" -#include "token_setproc.h" +#include "parameter.h" #include "softbus_common.h" +#include "token_setproc.h" using namespace OHOS::Security::AccessToken; namespace OHOS { @@ -48,10 +49,16 @@ void DmCredentialManagerTest::SetUp() tokenId = GetAccessTokenId(&infoInstance); SetSelfTokenID(tokenId); OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); + hiChainConnector_ = std::make_shared(); + listener_ = std::make_shared(); + dmCreMgr_ = std::make_shared(hiChainConnector_, listener_); } void DmCredentialManagerTest::TearDown() { + dmCreMgr_ = nullptr; + hiChainConnector_ = nullptr; + listener_ = nullptr; } void DmCredentialManagerTest::SetUpTestCase() @@ -62,10 +69,6 @@ void DmCredentialManagerTest::TearDownTestCase() { } -namespace { -std::shared_ptr listener_ = std::make_shared(); -std::shared_ptr hiChainConnector_ = std::make_shared(); - /** * @tc.name: DmCredentialManager_001 * @tc.desc: Test whether the DmCredentialManager function can generate a new pointer @@ -147,6 +150,42 @@ HWTEST_F(DmCredentialManagerTest, UnRegisterCredentialCallback_002, testing::ext EXPECT_EQ(ret, ERR_DM_FAILED); } +/** + * @tc.name:UnRegisterCredentialCallback_003 + * @tc.desc: return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, UnRegisterCredentialCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + int32_t ret = dmCreMgr_->RegisterCredentialCallback(pkgName); + EXPECT_EQ(ret, DM_OK); + ret = dmCreMgr_->UnRegisterCredentialCallback(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name:RequestCredential_001 + * @tc.desc: get credential info and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, RequestCredential_001, testing::ext::TestSize.Level0) +{ + std::string reqJsonStr = "invalid json string"; + std::string returnJsonStr; + int32_t ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_FAILED); + + nlohmann::json jsonObject; + jsonObject["userId"] = "test"; + jsonObject["version"] = "test"; + reqJsonStr = jsonObject.dump(); + ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); + ASSERT_EQ(ret, ERR_DM_FAILED); +} + /** * @tc.name:RequestCredential_002 * @tc.desc: get credential info and return ERR_DM_FAILED @@ -205,18 +244,18 @@ HWTEST_F(DmCredentialManagerTest, RequestCredential_004, testing::ext::TestSize. } /** - * @tc.name: ImportCredential_002 + * @tc.name: ImportCredential_001 * @tc.desc: import local credential and return ERR_DM_FAILED * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DmCredentialManagerTest, ImportCredential_002, testing::ext::TestSize.Level0) +HWTEST_F(DmCredentialManagerTest, ImportCredential_001, testing::ext::TestSize.Level0) { - std::string pkgName = ""; + std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { "processType" : 1, - "authType" : 1, + "authType" : "test", "userId" : "123", "credentialData" : [ @@ -232,9 +271,45 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_002, testing::ext::TestSize.L ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - dmCreMgr->credentialVec_.push_back(pkgName); - int32_t ret = dmCreMgr->ImportCredential(pkgName, credentialInfo); + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + dmCreMgr_->credentialVec_.push_back(pkgName); + int32_t ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); + jsonObject["TType"] = 1; + jsonObject["processType"] = 1; + credentialInfo = jsonObject.dump(); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject["processType"] = -1; + credentialInfo = jsonObject.dump(); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject["processType"] = 2; + credentialInfo = jsonObject.dump(); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject["TType"] = "test"; + credentialInfo = jsonObject.dump(); + ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportCredential_002 + * @tc.desc: import local credential and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportCredential_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + std::string credentialInfo; + int32_t ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -269,12 +344,24 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_004, testing::ext::TestSize.L std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { - "userId" , "123" + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 1, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - dmCreMgr->credentialVec_.push_back(pkgName); - int32_t ret = dmCreMgr->ImportCredential(pkgName, credentialInfo); + dmCreMgr_->credentialVec_.push_back(pkgName); + int32_t ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -289,6 +376,7 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_005, testing::ext::TestSize.L std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { + "processType" : 0, "authType" : 1, "userId" : "123", "credentialData" : @@ -312,25 +400,47 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_005, testing::ext::TestSize.L } /** - * @tc.name: ImportCredential_006 - * @tc.desc: import local credential and return ERR_DM_FAILED + * @tc.name: ImportRemoteCredentialExt_001 + * @tc.desc: test ImportRemoteCredentialExt * @tc.type: FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(DmCredentialManagerTest, ImportCredential_006, testing::ext::TestSize.Level0) +HWTEST_F(DmCredentialManagerTest, ImportRemoteCredentialExt_001, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = ""; + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportRemoteCredentialExt(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportLocalCredential_001 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_001, testing::ext::TestSize.Level0) { - std::string pkgName = "com.ohos.helloworld"; std::string credentialInfo = R"( { - "processType" : 0, - "authType" : 1, + "processType" : 1, + "authType" : 2, "userId" : "123", "credentialData" : [ { - "credentialType" : 1, + "credentialType" : 0, "credentialId" : "104", - "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "authCode" : "12345", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + }, + { + "credentialType" : 0, + "credentialId" : "105", + "authCode" : "12345", "serverPk" : "", "pkInfoSignature" : "", "pkInfo" : "", @@ -339,9 +449,7 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_006, testing::ext::TestSize.L ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - dmCreMgr->credentialVec_.push_back(pkgName); - int32_t ret = dmCreMgr->ImportCredential(pkgName, credentialInfo); + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -487,6 +595,139 @@ HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_006, testing::ext::TestS EXPECT_EQ(ret, ERR_DM_FAILED); } +/** + * @tc.name: ImportLocalCredential_007 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_007, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 1, + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 0, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] + } + )"; + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportLocalCredential_008 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_008, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 1, + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 2, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] + } + )"; + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportLocalCredential_009 + * @tc.desc: test ImportLocalCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportLocalCredential_009, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 1, + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "credentialType" : 2, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "", + "pkInfoSignature" : "", + "pkInfo" : "", + "peerDeviceId" : "" + } + ] + } + )"; + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportLocalCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: ImportRemoteCredential_001 + * @tc.desc: import remote symmetry credential and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_001, testing::ext::TestSize.Level0) +{ + CredentialDataInfo credentialDataInfo; + credentialDataInfo.credentialType = SAME_ACCOUNT_TYPE; + credentialDataInfo.credentailId = "credential_id"; + credentialDataInfo.serverPk = "server_pk"; + credentialDataInfo.pkInfoSignature = "pk_info_signature"; + credentialDataInfo.pkInfo = "pk_info"; + credentialDataInfo.authCode = "auth_code"; + credentialDataInfo.peerDeviceId = "peer_device_id"; + credentialDataInfo.userId = "user_id"; + credentialDataInfo.credentialType = SAME_ACCOUNT_TYPE; + nlohmann::json jsonObject1 = nlohmann::json(credentialDataInfo); + nlohmann::json credentialJson = nlohmann::json::array(); + credentialJson.push_back(jsonObject1); + nlohmann::json jsonObject; + jsonObject[FIELD_CREDENTIAL_DATA] = credentialJson; + jsonObject[FIELD_AUTH_TYPE] = CROSS_ACCOUNT_TYPE; + jsonObject[FIELD_USER_ID] = 0; + jsonObject[FIELD_PEER_USER_ID] = "peerUserId"; + + std::string credentialInfo = jsonObject.dump(); + dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; + int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); + + jsonObject[FIELD_CREDENTIAL_DATA] = 0; + credentialInfo = jsonObject.dump(); + ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + /** * @tc.name: ImportRemoteCredential_002 * @tc.desc: import remote symmetry credential and return ERR_DM_FAILED @@ -662,8 +903,27 @@ HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_008, testing::ext::Test ] } )"; - std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); - int32_t ret = dmCreMgr->ImportRemoteCredential(credentialInfo); + int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +/** + * @tc.name: DeleteRemoteCredential_001 + * @tc.desc: delete remote credential and return ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, DeleteRemoteCredential_001, testing::ext::TestSize.Level0) +{ + std::string credentialInfo = R"( + { + "processType" : 2, + "authType" : 2, + "peerUserId": "123", + "peerCredentialInfo" : 0 + } + )"; + int32_t ret = dmCreMgr_->DeleteRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -896,6 +1156,32 @@ HWTEST_F(DmCredentialManagerTest, DeleteRemoteCredential_0011, testing::ext::Tes EXPECT_EQ(ret, ERR_DM_FAILED); } +/** + * @tc.name: DeleteCredential_001 + * @tc.desc: test DeleteCredential + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, DeleteCredential_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.helloworld"; + std::string resultInfo; + std::string credentialInfo = R"( + { + "processType" : 2, + "authType" : 2, + "userId" : "123" + } + )"; + dmCreMgr_->requestId_ = 1; + dmCreMgr_->OnGroupResult(0, 0, resultInfo); + dmCreMgr_->requestId_ = 0; + dmCreMgr_->OnGroupResult(0, 0, resultInfo); + dmCreMgr_->credentialVec_.push_back(pkgName); + int32_t ret = dmCreMgr_->DeleteCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + /** * @tc.name: DeleteCredential_002 * @tc.desc: delete local credential and return ERR_DM_FAILED @@ -1343,6 +1629,95 @@ HWTEST_F(DmCredentialManagerTest, GetCredentialData_008, testing::ext::TestSize. int32_t ret = dmCreMgr->GetCredentialData(credentialInfo, credentialData, jsonOutObj); EXPECT_EQ(ret, DM_OK); } -} // namespace + +/** + * @tc.name: from_json_001 + * @tc.desc: test from_json + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, from_json_001, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonOutObj; + CredentialDataInfo credentialDataInfo; + jsonOutObj[FIELD_CREDENTIAL_TYPE] = "test"; + from_json(jsonOutObj, credentialDataInfo); + + jsonOutObj[FIELD_CREDENTIAL_TYPE] = NONSYMMETRY_CREDENTIAL_TYPE; + jsonOutObj[FIELD_SERVER_PK] = 0; + jsonOutObj[FIELD_PKINFO_SIGNATURE] = 0; + jsonOutObj[FIELD_PKINFO] = 0; + jsonOutObj[FIELD_PEER_DEVICE_ID] = 0; + credentialDataInfo.serverPk = ""; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_TRUE(credentialDataInfo.serverPk.empty()); + + nlohmann::json jsonPkInfo; + jsonOutObj[FIELD_SERVER_PK] = "serverPk"; + jsonOutObj[FIELD_PKINFO_SIGNATURE] = "pkInfoSignature"; + jsonOutObj[FIELD_PKINFO] = jsonPkInfo.dump(); + jsonOutObj[FIELD_PEER_DEVICE_ID] = "peerDeviceId"; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_FALSE(credentialDataInfo.serverPk.empty()); + + jsonOutObj[FIELD_CREDENTIAL_TYPE] = SYMMETRY_CREDENTIAL_TYPE; + jsonOutObj[FIELD_AUTH_CODE] = 0; + credentialDataInfo.authCode = ""; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_TRUE(credentialDataInfo.authCode.empty()); + + jsonOutObj[FIELD_AUTH_CODE] = "authCode"; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_FALSE(credentialDataInfo.authCode.empty()); + + jsonOutObj[FIELD_CREDENTIAL_TYPE] = 0; + from_json(jsonOutObj, credentialDataInfo); + EXPECT_FALSE(credentialDataInfo.authCode.empty()); +} + +/** + * @tc.name: from_json_002 + * @tc.desc: test from_json + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, from_json_002, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + PeerCredentialInfo peerCredentialInfo; + jsonObject[FIELD_PEER_USER_ID] = "peerDeviceId"; + from_json(jsonObject, peerCredentialInfo); + EXPECT_EQ(peerCredentialInfo.peerDeviceId, "peerDeviceId"); +} + +/** + * @tc.name: to_json_001 + * @tc.desc: test to_json + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DmCredentialManagerTest, to_json_001, testing::ext::TestSize.Level0) +{ + CredentialDataInfo credentialDataInfo; + credentialDataInfo.peerDeviceId = "test"; + credentialDataInfo.userId = "test"; + credentialDataInfo.credentailId = "test"; + credentialDataInfo.credentialType = NONSYMMETRY_CREDENTIAL_TYPE; + credentialDataInfo.serverPk = "test"; + credentialDataInfo.pkInfoSignature = "test"; + credentialDataInfo.pkInfo = "test"; + credentialDataInfo.authCode = "test"; + nlohmann::json jsonObject; + to_json(jsonObject, credentialDataInfo); + EXPECT_EQ(jsonObject[FIELD_SERVER_PK].get(), "test"); + + credentialDataInfo.credentialType = SYMMETRY_CREDENTIAL_TYPE; + to_json(jsonObject, credentialDataInfo); + EXPECT_EQ(jsonObject[FIELD_AUTH_CODE].get(), "test"); + + credentialDataInfo.credentialType = UNKNOWN_CREDENTIAL_TYPE; + to_json(jsonObject, credentialDataInfo); + EXPECT_EQ(jsonObject[FIELD_AUTH_CODE].get(), "test"); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_credential_manager.h b/test/commonunittest/UTTest_dm_credential_manager.h index 9b3db1e42..1347ebfdb 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.h +++ b/test/commonunittest/UTTest_dm_credential_manager.h @@ -16,6 +16,7 @@ #ifndef OHOS_UTTEST_DM_CREDENTIAL_MANAGER_H #define OHOS_UTTEST_DM_CREDENTIAL_MANAGER_H +#include #include #include "device_auth.h" #include "dm_credential_manager.h" @@ -31,6 +32,17 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + + std::shared_ptr listener_; + std::shared_ptr hiChainConnector_; + std::shared_ptr dmCreMgr_; +}; + +class MockDeviceManagerServiceListener : public DeviceManagerServiceListener { +public: + MockDeviceManagerServiceListener() = default; + ~MockDeviceManagerServiceListener() = default; + void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 0967feabe..4f9eb424a 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -260,9 +260,18 @@ ohos_unittest("device_manager_impl_test") { ## UnitTest UTTest_dm_credential_manager {{{ ohos_unittest("UTTest_dm_credential_manager") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_out_path - include_dirs = [ "${devicemanager_path}/test/commonunittest" ] + include_dirs = [ + "${devicemanager_path}/test/commonunittest", + "${servicesimpl_path}/src/credential", + ] sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_credential_manager.cpp" ] -- Gitee From b51468d382f4954cba8b84295983f3e1e0789500 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 16 Aug 2024 11:33:53 +0800 Subject: [PATCH 080/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp | 2 +- interfaces/kits/js4.0/src/native_devicemanager_js.cpp | 2 +- services/service/src/device_manager_service.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 8cc4882d9..1bab684ee 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -369,7 +369,7 @@ int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterDeviceStatusCallback(pkgName, callback); - LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + LOGI("Completed"); return DM_OK; } diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp index f7483510e..4a86632ef 100644 --- a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -1929,7 +1929,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) return nullptr; } - LOGI("create for packageName:%{public}s", bundleName.c_str()); + LOGI("Create for packageName:%{public}s", bundleName.c_str()); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); if (obj == nullptr) { return nullptr; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 003551c17..99f7702fb 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -205,7 +205,7 @@ void DeviceManagerService::UninitDMServiceListener() listener_ = nullptr; advertiseMgr_ = nullptr; discoveryMgr_ = nullptr; - LOGI("uninit."); + LOGI("Uninit."); } void DeviceManagerService::RegisterDeviceManagerListener(const std::string &pkgName) -- Gitee From f06e0511c4821c644cbed39fa5c460882144ebfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 16 Aug 2024 14:55:25 +0800 Subject: [PATCH 081/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp | 1 + interfaces/kits/js4.0/src/native_devicemanager_js.cpp | 2 ++ services/service/src/device_manager_service_listener.cpp | 1 + services/service/src/discovery/discovery_manager.cpp | 2 +- 4 files changed, 5 insertions(+), 1 deletion(-) 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 1bab684ee..9fcfbbbbb 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2049,6 +2049,7 @@ int32_t DeviceManagerImpl::CheckApiPermission(int32_t permissionLevel) LOGE("Check permission failed with ret: %{public}d", ret); return ret; } + LOGD("The caller declare the DM permission!"); return DM_OK; } diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp index 4a86632ef..cdc023721 100644 --- a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -1096,6 +1096,7 @@ napi_value DeviceManagerNapi::CallDeviceList(napi_env env, napi_callback_info in napi_value DeviceManagerNapi::GetAvailableDeviceListSync(napi_env env, napi_callback_info info) { + LOGI("In"); int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); if (ret != 0) { CreateBusinessError(env, ret); @@ -1124,6 +1125,7 @@ napi_value DeviceManagerNapi::GetAvailableDeviceListSync(napi_env env, napi_call CreateBusinessError(env, ret); return result; } + LOGD("DeviceManager::GetAvailableDeviceListSync"); if (devList.size() > 0) { for (size_t i = 0; i != devList.size(); ++i) { DeviceBasicInfoToJsArray(env, devList, (int32_t)i, result); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index f8f373d7e..9d2e330bc 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -67,6 +67,7 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetPkgName(pkgName); pReq->SetDeviceState(state); pReq->SetDeviceInfo(deviceInfo); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 35740d886..5ff9e6f56 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -381,7 +381,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t std::lock_guard autoLock(subIdMapLocks_); subscribeId = pkgName2SubIdMap_[pkgName]; } - LOGD("PkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); + LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); listener_->OnDeviceFound(pkgName, subscribeId, info); return; } -- Gitee From f2366d92ef118c68a47ac8bd2e47bc06c5ecb011 Mon Sep 17 00:00:00 2001 From: Bobie Date: Mon, 19 Aug 2024 10:19:14 +0800 Subject: [PATCH 082/520] add tmplate of PR Signed-off-by: Bobie --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 35 +++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md new file mode 100644 index 000000000..b2dcb1881 --- /dev/null +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -0,0 +1,35 @@ +**Issue编号**: + +**描述**: + +**安全及低级编码自检:** +| 自检项 | 自检结果 | +| ------------------------------------------------------------------------------- | -------- | +| 变量使用前保证赋有效初值 | | +| 结构体预留字段也必须初始化为0,不允许出现随机值 | | +| 指针变量必须显示初始化为空 | | +| 涉及内存拷贝时合理校验目标内存大小,保证目标内存大于等于源内存 | | +| 进行字符串操作时,如字符串复制、申请字符串内存等,需要考虑字符串结束符 | | +| cJSON指针在异常分支里均需考虑内存释放(cJSON_free/cJSON_Delete),防止内存泄漏 | | +| 内存资源、文件句柄、管道资源、Socket句柄异常退出时要及时关闭 | | +| malloc申请内存后必须判断是否为空 | | +| 指针解引用或释放前判空(lamda表达式,异步任务等使用指针前需判空) | | +| 内存释放后立即置空,防止出现UAF | | +| 循环时容器的增、删、改操作,必须保证迭代器有效 | | +| 禁止将栈内存地址作为返回值或赋值给全局变量 | | +| 加法、乘法、减法操作,必须进行溢出和翻转保护,确保先校验再运算 | | +| 除法、求余操作必须进行除零保护 | | +| 循环变量用整型,禁止使用浮点型 | | +| 循环退出条件一定确保可达,防止出现死循环等问题 | | +| 不同大小结构体禁止强转 | | +| 禁止使用非安全函数,使用封装好的安全函数 | | +| 日志必须检查PassWord/位置信息/networkId/devId/uuid/udid等关键字,避免明文打印敏感信息 | | +| 对函数入参坚持先校验后使用的原则(指针判空、整型变量校验范围) | | +| 跨进程调用需注意权限校验,对外部传入的PID、tokenID进行权限校验 | | +| 共享数据均需加锁保护,并且锁配对使用 | | +| 条件变量正确加锁,消除条件变量唤醒丢失等问题 | | +| 加锁范围确保合理,避免过大或过小导致死锁问题 | | + +**TDD结果**: + +**XTS结果**: -- Gitee From 099b625039e3a0a5d93f4a4fa9094692f658dcb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 21 Aug 2024 13:56:47 +0800 Subject: [PATCH 083/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9UT=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/commonunittest/UTTest_dm_auth_manager_second.cpp | 2 +- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 5fbfd788d..ab5622022 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -776,7 +776,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level0) authManager_->authResponseContext_->dmVersion = "5.0.1"; authManager_->authResponseContext_->bindLevel = 1; ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, DM_OK); + ASSERT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 295f3caae..06a8e01dd 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -723,7 +723,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_004, testing::ext::TestSi std::string localDeviceId = "deviceId"; std::string remoteDeviceId = "deviceId"; bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_001, testing::ext::TestSize.Level0) -- Gitee From b587dde6d9fd5287e03ff236380732014c217859 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 21 Aug 2024 17:33:32 +0800 Subject: [PATCH 084/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=83=A8=E4=BB=B6?= =?UTF-8?q?=E5=8C=96=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/benchmarktest/device_manager_fa_test/BUILD.gn | 2 +- test/unittest/BUILD.gn | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/test/benchmarktest/device_manager_fa_test/BUILD.gn b/test/benchmarktest/device_manager_fa_test/BUILD.gn index 4ac558754..ef3c118f1 100644 --- a/test/benchmarktest/device_manager_fa_test/BUILD.gn +++ b/test/benchmarktest/device_manager_fa_test/BUILD.gn @@ -34,13 +34,13 @@ ohos_benchmarktest("DeviceManagerFaTest") { deps = [ "${common_path}/include/show_confirm_dialog/dialog_ui/js:dialog_js_files_etc", "${innerkits_path}/native_cpp:devicemanagersdk", - "//third_party/benchmark:benchmark", ] external_deps = [ "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "benchmark:benchmark", "bounds_checking_function:libsec_shared", "dsoftbus:softbus_client", "ipc:ipc_single", diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index ee0e5b2a2..f91a2141b 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1191,14 +1191,6 @@ config("device_manager_test_common_public_config") { "${devicemanager_path}/test/unittest/mock/", ] - if (os_account_part_exists) { - include_dirs += [ - "${os_account_path }/interfaces/innerkits/osaccount/native/include", - "${os_account_path }/frameworks/common/database/include", - "${os_account_path }/frameworks/common/account_error/include", - ] - } - cflags = [ "-Wall", "-Werror", -- Gitee From 2265fca7e8be32aa6522f93fa2b08f1c688368b2 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 22 Aug 2024 11:54:42 +0800 Subject: [PATCH 085/520] fix deviceid Signed-off-by: gaoqiang_strong --- services/implementation/src/authentication/dm_auth_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index af977902e..a1ac2513f 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -212,7 +212,7 @@ void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, authRequestState_ = std::make_shared(); authRequestState_->SetAuthManager(shared_from_this()); authRequestState_->SetAuthContext(authRequestContext_); - if (!DmRadarHelper::GetInstance().ReportAuthStart(deviceId, pkgName)) { + if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) { LOGE("ReportAuthStart failed"); } authRequestState_->Enter(); -- Gitee From 2a1ae8217c8bbd5adfbc26340149fea0f3390614 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 22 Aug 2024 12:12:10 +0800 Subject: [PATCH 086/520] fix state bug Signed-off-by: gaoqiang_strong --- .../implementation/src/authentication/dm_auth_manager.cpp | 4 ++++ services/service/src/pinholder/pin_holder.cpp | 2 ++ 2 files changed, 6 insertions(+) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index af977902e..4da687f3e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2560,6 +2560,10 @@ bool DmAuthManager::IsScreenLocked() void DmAuthManager::OnScreenLocked() { + if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType); + return; + } if (authRequestState_ == nullptr) { LOGE("OnScreenLocked authRequestState_ is nullptr."); return; diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 49c2d3b06..12fd51c33 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -123,6 +123,7 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, listener_->OnCreateResult(registerPkgName_, sessionId_); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, sessionId_, ""); + sessionId_ = SESSION_ID_INVALID; return sessionId_; } pinType_ = pinType; @@ -302,6 +303,7 @@ void PinHolder::ProcessCreateRespMsg(const std::string &message) listener_->OnCreateResult(registerPkgName_, ERR_DM_FAILED); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); session_->CloseSessionServer(sessionId_); + sessionId_ = SESSION_ID_INVALID; } } -- Gitee From f07dd04c249ed7267ea9dc658531a6944e245122 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 22 Aug 2024 14:32:44 +0800 Subject: [PATCH 087/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/benchmarktest/device_manager_fa_test/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/test/benchmarktest/device_manager_fa_test/BUILD.gn b/test/benchmarktest/device_manager_fa_test/BUILD.gn index ef3c118f1..fb237389e 100644 --- a/test/benchmarktest/device_manager_fa_test/BUILD.gn +++ b/test/benchmarktest/device_manager_fa_test/BUILD.gn @@ -40,7 +40,6 @@ ohos_benchmarktest("DeviceManagerFaTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", - "benchmark:benchmark", "bounds_checking_function:libsec_shared", "dsoftbus:softbus_client", "ipc:ipc_single", -- Gitee From b2a7f25edd6f96e54f4c9bd6759c2bfec437e305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 22 Aug 2024 20:04:24 +0800 Subject: [PATCH 088/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0SetDnPolicy=E5=8A=9F?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../device_manager_ipc_interface_code.h | 1 + common/include/dm_constants.h | 2 ++ .../native_cpp/include/device_manager.h | 8 +++++ .../native_cpp/include/device_manager_impl.h | 2 ++ .../native_cpp/src/device_manager_impl.cpp | 27 +++++++++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 30 +++++++++++++++++++ .../service/include/device_manager_service.h | 2 ++ .../include/softbus/softbus_listener.h | 1 + .../service/src/device_manager_service.cpp | 23 ++++++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 14 +++++++++ .../service/src/softbus/softbus_listener.cpp | 10 +++++++ 11 files changed, 120 insertions(+) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index f21309750..67beda3ae 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -90,6 +90,7 @@ enum DMIpcCmdInterfaceCode { CHECK_ACCESS_CONTROL, CHECK_SAME_ACCOUNT, SHIFT_LNN_GEAR, + SET_DN_POLICY, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index d663bbc79..4c4658e92 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -229,6 +229,8 @@ constexpr const char* DM_CONNECTION_DISCONNECTED = "DM_CONNECTION_DISCONNECTED"; constexpr const char* BIND_LEVEL = "bindLevel"; constexpr const char* TOKENID = "tokenId"; constexpr const char* DM_BIND_RESULT_NETWORK_ID = "DM_BIND_RESULT_NETWORK_ID"; +constexpr const char* PARAM_KEY_POLICY_STRATEGY_FOR_BLE = "DM_POLICY_STRATEGY_FOR_BLE"; +constexpr const char* PARAM_KEY_POLICY_TIME_OUT = "DM_POLICY_TIMEOUT"; // screen state constexpr int32_t DM_SCREEN_UNKNOWN = -1; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index caba88092..d90ccac3c 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -560,6 +560,14 @@ public: virtual int32_t DestroyPinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload) = 0; + /** + * @brief Set Dn Policy + * @param pkgName package name. + * @param policy policy and timeout. + * @return Returns 0 if success. + */ + virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; + /** * @brief Request credential information. * @param pkgName package name. diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 5505d0de3..b98d40b10 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -386,6 +386,8 @@ public: virtual int32_t GetErrCode(int32_t errCode) override; virtual int32_t ShiftLNNGear(const std::string &pkgName) override; + virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); + private: DeviceManagerImpl() = default; ~DeviceManagerImpl() = default; diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 9fcfbbbbb..df311838c 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2143,5 +2143,32 @@ int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) LOGI("Completed"); return DM_OK; } + +int32_t DeviceManagerImpl::SetDnPolicy(const std::string &pkgName, std::map &policy) +{ + if (pkgName.empty() || policy.size() == 0) { + LOGE("Para invalid: policy is null or pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start"); + std::string strategy = ConvertMapToJsonString(policy); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetFirstParam(strategy); + int32_t ret = ipcClientProxy_->SendRequest(SET_DN_POLICY, req, rsp); + if (ret != DM_OK) { + LOGE("Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("Failed with ret %{public}d", ret); + return ret; + } + LOGI("Completed"); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 b07d8a6bd..385b7e8ae 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 @@ -1390,6 +1390,36 @@ ON_IPC_READ_RESPONSE(DESTROY_PIN_HOLDER, MessageParcel &reply, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string policy = pReq->GetFirstParam(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(policy)) { + LOGE("write setDnPolicy parameter failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SET_DN_POLICY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_CMD(SERVER_CREATE_PIN_HOLDER, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 6e2e24356..1d347ae52 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -194,6 +194,8 @@ public: bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); void HandleDeviceNotTrust(const std::string &msg); + int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); + private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 362e132ce..01a7c0b70 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -91,6 +91,7 @@ public: static IRefreshCallback &GetSoftbusRefreshCb(); static void SetHostPkgName(const std::string hostName); static std::string GetHostPkgName(); + static int32_t SetDnPolicy(int32_t policy, uint8_t timeOut); private: int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 99f7702fb..c0693632f 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1606,5 +1606,28 @@ void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) } return; } + +int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::map &policy) +{ + if (!PermissionManager::GetInstance().CheckNewPermission()) { + LOGE("The caller does not have permission to call"); + return ERR_DM_NO_PERMISSION; + } + LOGI("Start for pkgName = %{public}s", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t policy = -1; + if (policy.find(DM_POLICY_STRATEGY_FOR_BLE) != policy.end()) { + policy = policy.find(DM_POLICY_STRATEGY_FOR_BLE)->second).c_str()); + } + uint8_t timeOut = 0; + if (policy.find(DM_POLICY_TIMEOUT) != policy.end()) { + timeOut = std::stoi((policy.find(DM_POLICY_TIMEOUT)->second).c_str()); + } + CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); + return softbusListener_->SetDnPolicy(pkgName, policy, timeOut); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 626580fbb..9954e2678 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1443,5 +1443,19 @@ ON_IPC_CMD(SHIFT_LNN_GEAR, MessageParcel &data, MessageParcel &reply) } return DM_OK; } + +ON_IPC_CMD(SET_DN_POLICY, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string policyStr = data.ReadString(); + std::map policy; + ParseMapFromJsonString(policyStr, policy); + int32_t result = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a9d634984..a2097684a 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -753,6 +753,16 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ return DM_OK; } +int32_t SoftbusListener::SetDnPolicy(int32_t policy, uint8_t timeOut) +{ + int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); + if (ret != DM_OK) { + LOGE("[SOFTBUS]CtrlLNNBleHb failed."); + return ret; + } + return DM_OK; +} + int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) { return SoftbusCache::GetInstance().GetSecurityDeviceLevel(networkId, securityLevel); -- Gitee From 5461e7f136b53640218a148a3d3099d7866c5db9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 22 Aug 2024 20:47:51 +0800 Subject: [PATCH 089/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_service.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 4576eae89..208a418fd 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -287,6 +287,7 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_002, testing::ext::TestS std::string pkgName = "ohos_test"; std::string extra = "jdddd"; std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, ERR_DM_POINT_NULL); } -- Gitee From eb35725e8621a0245ef45685ab93ef1672bc7b45 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Tue, 20 Aug 2024 15:28:14 +0800 Subject: [PATCH 090/520] modify timeout for clone Signed-off-by: gaoqiang_strong --- .../include/authentication/dm_auth_manager.h | 3 + .../src/authentication/dm_auth_manager.cpp | 104 ++++++++++++------ services/service/src/pinholder/pin_holder.cpp | 2 + .../UTTest_dm_auth_manager_second.cpp | 2 +- .../UTTest_dm_deviceprofile_connector.cpp | 2 +- .../UTTest_ipc_cmd_parser_service.cpp | 50 +++------ 6 files changed, 97 insertions(+), 66 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 48067f4d2..29838a6fd 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -549,6 +549,8 @@ private: std::string ConvertSrcVersion(const std::string &version, const std::string &edition); std::string ConvertSinkVersion(const std::string &version); void NegotiateRespMsg(const std::string &version); + void SetAuthType(int32_t authType); + int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); private: std::shared_ptr softbusConnector_; @@ -582,6 +584,7 @@ private: bool isAuthenticateDevice_ = false; int32_t authForm_ = DmAuthForm::ACROSS_ACCOUNT; std::string remoteVersion_ = ""; + std::atomic authType_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index af977902e..64ed27e38 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -51,6 +51,14 @@ const int32_t INPUT_TIMEOUT = 60; const int32_t ADD_TIMEOUT = 10; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; +const int32_t CLONE_CONFIRM_TIMEOUT = 5; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 5; +const int32_t CLONE_INPUT_TIMEOUT = 5; +const int32_t CLONE_ADD_TIMEOUT = 5; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 5; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 5; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 10; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; const int32_t DEVICE_ID_HALF = 2; const int32_t MAX_AUTH_TIMES = 3; @@ -67,6 +75,18 @@ const int32_t AUTH_DEVICE_TIMEOUT = 10; const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(INPUT_TIMEOUT_TASK), CLONE_INPUT_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; + constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; @@ -200,8 +220,8 @@ void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, if (timer_ == nullptr) { timer_ = std::make_shared(); } - timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), AUTHENTICATE_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); authMessageProcessor_ = std::make_shared(shared_from_this()); @@ -212,7 +232,7 @@ void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, authRequestState_ = std::make_shared(); authRequestState_->SetAuthManager(shared_from_this()); authRequestState_->SetAuthContext(authRequestContext_); - if (!DmRadarHelper::GetInstance().ReportAuthStart(deviceId, pkgName)) { + if (!DmRadarHelper::GetInstance().ReportAuthStart(peerTargetId_.deviceId, pkgName)) { LOGE("ReportAuthStart failed"); } authRequestState_->Enter(); @@ -223,6 +243,7 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au const std::string &deviceId, const std::string &extra) { LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); if (ret != DM_OK) { LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild."); @@ -349,12 +370,12 @@ void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int3 if (timer_ == nullptr) { timer_ = std::make_shared(); } - timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), AUTHENTICATE_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); - timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), WAIT_NEGOTIATE_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), + GetTaskTimeout(WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } else { @@ -561,20 +582,20 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) } LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_); if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { + authTimes_++; + timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { HandleMemberJoinImportAuthCode(requestId, status); return; } - authTimes_++; - timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); if (status != DM_OK || authResponseContext_->requestId != requestId) { if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; authRequestState_->TransitionTo(std::make_shared()); } else { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); @@ -692,8 +713,8 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), NEGOTIATE_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } @@ -747,15 +768,15 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && authResponseContext_->bindLevel <= APP)) { ProcRespNegotiateExt(sessionId); - timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || authResponseContext_->bindLevel == INVALIED_TYPE) { ProcRespNegotiate(sessionId); - timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + GetTaskTimeout(WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } else { @@ -828,8 +849,8 @@ void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); - timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), CONFIRM_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } @@ -902,8 +923,8 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); - timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), CONFIRM_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); } @@ -999,12 +1020,12 @@ void DmAuthManager::StartRespAuthProcess() action_ = USER_OPERATION_TYPE_ALLOW_AUTH; } if (authResponseContext_->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); - timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), SESSION_HEARTBEAT_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleSessionHeartbeat(name); }); listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, @@ -1048,8 +1069,8 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; std::string connectInfo = jsonObject.dump(); - timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), ADD_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), + GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); if (authUiStateMgr_ == nullptr) { @@ -2039,8 +2060,8 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID; authRequestState_->TransitionTo(std::make_shared()); } else { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), INPUT_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); }); authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); @@ -2461,8 +2482,8 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { - timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), SESSION_HEARTBEAT_TIMEOUT, - [this] (std::string name) { + timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleSessionHeartbeat(name); }); } @@ -2560,6 +2581,10 @@ bool DmAuthManager::IsScreenLocked() void DmAuthManager::OnScreenLocked() { + if (authResponseContext_ != nullptr && AUTH_TYPE_IMPORT_AUTH_CODE == authResponseContext_->authType) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", authResponseContext_->authType); + return; + } if (authRequestState_ == nullptr) { LOGE("OnScreenLocked authRequestState_ is nullptr."); return; @@ -2632,5 +2657,22 @@ bool DmAuthManager::CompareVersion(const std::string &remoteVersion, const std:: VersionSplitToInt(oldVersion, '.', oldVersionVec); return CompareVecNum(remoteVersionVec, oldVersionVec); } + +void DmAuthManager::SetAuthType(int32_t authType) +{ + authType_ = authType; +} + +int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType_.load()); + if (AUTH_TYPE_IMPORT_AUTH_CODE == authType_) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 49c2d3b06..12fd51c33 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -123,6 +123,7 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, listener_->OnCreateResult(registerPkgName_, sessionId_); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, sessionId_, ""); + sessionId_ = SESSION_ID_INVALID; return sessionId_; } pinType_ = pinType; @@ -302,6 +303,7 @@ void PinHolder::ProcessCreateRespMsg(const std::string &message) listener_->OnCreateResult(registerPkgName_, ERR_DM_FAILED); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); session_->CloseSessionServer(sessionId_); + sessionId_ = SESSION_ID_INVALID; } } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 5fbfd788d..ab5622022 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -776,7 +776,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level0) authManager_->authResponseContext_->dmVersion = "5.0.1"; authManager_->authResponseContext_->bindLevel = 1; ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, DM_OK); + ASSERT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index ecf01409f..8d67f7553 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -723,7 +723,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_004, testing::ext::TestSi std::string localDeviceId = "deviceId"; std::string remoteDeviceId = "deviceId"; bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_001, testing::ext::TestSize.Level0) diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 9a2b7683a..f47931e5b 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -23,6 +23,8 @@ #include "dm_device_info.h" #include "ipc_client_manager.h" #include "ipc_cmd_register.h" +#include "ipc_create_pin_holder_req.h" +#include "ipc_destroy_pin_holder_req.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_local_device_info_rsp.h" @@ -30,10 +32,12 @@ #include "ipc_get_trustdevice_rsp.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" -#include "ipc_notify_device_discovery_req.h" +#include "ipc_notify_credential_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_dmfa_result_req.h" #include "ipc_notify_event_req.h" +#include "ipc_notify_pin_holder_event_req.h" +#include "ipc_notify_publish_result_req.h" #include "ipc_publish_req.h" #include "ipc_register_listener_req.h" #include "ipc_req.h" @@ -272,7 +276,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_008, testing::ext::TestSize. { int32_t cmdCode = SERVER_CREDENTIAL_RESULT; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -280,7 +284,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_008, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); if (ptr) { ret = ptr(req, data); } @@ -339,7 +343,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_011, testing::ext::TestSize. { int32_t cmdCode = SERVER_CREATE_PIN_HOLDER; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -347,13 +351,9 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_011, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 100; - DmDeviceBasicInfo deviceBasicInfo; req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - req->SetDeviceBasicInfo(deviceBasicInfo); if (ptr) { ret = ptr(req, data); } @@ -376,7 +376,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_012, testing::ext::TestSize. { int32_t cmdCode = SERVER_DESTROY_PIN_HOLDER; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -384,13 +384,9 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_012, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 100; - DmDeviceBasicInfo deviceBasicInfo; req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - req->SetDeviceBasicInfo(deviceBasicInfo); if (ptr) { ret = ptr(req, data); } @@ -413,7 +409,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_013, testing::ext::TestSize. { int32_t cmdCode = SERVER_CREATE_PIN_HOLDER_RESULT; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -421,13 +417,9 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_013, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 100; - DmDeviceBasicInfo deviceBasicInfo; req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - req->SetDeviceBasicInfo(deviceBasicInfo); if (ptr) { ret = ptr(req, data); } @@ -450,7 +442,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_014, testing::ext::TestSize. { int32_t cmdCode = SERVER_DESTROY_PIN_HOLDER_RESULT; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -458,13 +450,9 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_014, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 100; - DmDeviceBasicInfo deviceBasicInfo; req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - req->SetDeviceBasicInfo(deviceBasicInfo); if (ptr) { ret = ptr(req, data); } @@ -1491,7 +1479,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_021, testing::ext::TestSize. { int32_t cmdCode = SERVER_ON_PIN_HOLDER_EVENT; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -1499,13 +1487,9 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_021, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 100; - DmDeviceBasicInfo deviceBasicInfo; req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - req->SetDeviceBasicInfo(deviceBasicInfo); if (ptr) { ret = ptr(req, data); } -- Gitee From 478c76a600717954b6b2c9706d5fe9c5f869eac0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 23 Aug 2024 15:06:02 +0800 Subject: [PATCH 091/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/ipc/standard/ipc_cmd_parser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 9954e2678..949515292 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1450,7 +1450,7 @@ ON_IPC_CMD(SET_DN_POLICY, MessageParcel &data, MessageParcel &reply) std::string policyStr = data.ReadString(); std::map policy; ParseMapFromJsonString(policyStr, policy); - int32_t result = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + int32_t result = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); if (!reply.WriteInt32(result)) { LOGE("write result failed"); return ERR_DM_IPC_WRITE_FAILED; -- Gitee From f38f07d14474afb639bf33e9f8564b515b6a689a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 23 Aug 2024 17:17:16 +0800 Subject: [PATCH 092/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index c0693632f..a2aea18e8 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1620,7 +1620,7 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond).c_str()); + policy = std::stoi((policy.find(DM_POLICY_STRATEGY_FOR_BLE)->second).c_str()); } uint8_t timeOut = 0; if (policy.find(DM_POLICY_TIMEOUT) != policy.end()) { -- Gitee From eabb9c5d229fa1795fef2188b20fd94ade000e53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 23 Aug 2024 18:16:02 +0800 Subject: [PATCH 093/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/include/device_manager_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index b98d40b10..cd2a6e7d3 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -386,7 +386,7 @@ public: virtual int32_t GetErrCode(int32_t errCode) override; virtual int32_t ShiftLNNGear(const std::string &pkgName) override; - virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); + virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) override; private: DeviceManagerImpl() = default; -- Gitee From 7838e7a1fb233e3eda134b006b51f157bbf981a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 24 Aug 2024 11:41:08 +0800 Subject: [PATCH 094/520] =?UTF-8?q?=E5=AE=89=E5=85=A8=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E5=91=8A=E8=AD=A6=E6=B8=85=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/authentication/dm_auth_manager.cpp | 23 +++++++++++-------- .../service/src/device_manager_service.cpp | 4 +++- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index e1d974325..50549affd 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -744,8 +744,9 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); NegotiateRespMsg(remoteVersion_); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && - authResponseContext_->bindLevel <= APP)) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { ProcRespNegotiateExt(sessionId); timer_->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), WAIT_REQUEST_TIMEOUT, [this] (std::string name) { @@ -796,8 +797,9 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) } LOGI("SendAuthRequest dmversion %{public}s, level %{public}d", authResponseContext_->dmVersion.c_str(), authResponseContext_->bindLevel); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && - authResponseContext_->bindLevel <= APP)) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { ProcessAuthRequestExt(sessionId); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || authResponseContext_->bindLevel == INVALIED_TYPE) { @@ -973,8 +975,9 @@ int32_t DmAuthManager::StartAuthProcess(const int32_t &action) if (!DmRadarHelper::GetInstance().ReportAuthConfirmBox(info)) { LOGE("ReportAuthConfirmBox failed"); } - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && - authResponseContext_->bindLevel <= APP)) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { return ConfirmProcessExt(action); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || authResponseContext_->bindLevel == INVALIED_TYPE) { @@ -1364,7 +1367,8 @@ void DmAuthManager::ShowStartAuthDialog() return; } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - (authResponseContext_->bindLevel >= DEVICE && authResponseContext_->bindLevel <= APP)) { + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { AuthDevice(pinCode); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || authResponseContext_->bindLevel == INVALIED_TYPE) { @@ -1390,8 +1394,9 @@ int32_t DmAuthManager::ProcessPincode(int32_t pinCode) return ERR_DM_FAILED; } timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (authResponseContext_->bindLevel >= DEVICE && - authResponseContext_->bindLevel <= APP)) { + if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && + (static_cast(authResponseContext_->bindLevel) >= DEVICE && + static_cast(authResponseContext_->bindLevel) <= APP)) { return AuthDevice(pinCode); } else if (!CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) || authResponseContext_->bindLevel == INVALIED_TYPE) { diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 99f7702fb..9f63d697f 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -148,7 +148,9 @@ void DeviceManagerService::QueryDependsSwitchState() publishSubScriber->SetWifiState(static_cast(OHOS::Wifi::WifiState::DISABLED)); } else { bool isWifiActive = false; - Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID)->IsWifiActive(isWifiActive); + auto wifiMgr = Wifi::WifiDevice::GetInstance(WIFI_DEVICE_ABILITY_ID); + CHECK_NULL_VOID(wifiMgr); + wifiMgr->IsWifiActive(isWifiActive); if (isWifiActive) { publishSubScriber->SetWifiState(static_cast(OHOS::Wifi::WifiState::ENABLED)); } else { -- Gitee From 6132fc15bd0772240fdc3a386a6fe6dd07068119 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 24 Aug 2024 14:24:10 +0800 Subject: [PATCH 095/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 3 +++ test/unittest/UTTest_device_manager_impl_three.cpp | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a2097684a..0303513fb 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -755,11 +755,14 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ int32_t SoftbusListener::SetDnPolicy(int32_t policy, uint8_t timeOut) { + /* int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); if (ret != DM_OK) { LOGE("[SOFTBUS]CtrlLNNBleHb failed."); return ret; } + */ + LOGI("CtrlLNNBleHb complete policy: %{public}d, timeOut: %{public}d.", policy, timeOut); return DM_OK; } diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 7aa9912fc..e96717fcb 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1095,6 +1095,19 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback002, testing::ext::T EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); DeviceManagerImpl::GetInstance().ipcClientProxy_->ipcClientManager_ = std::make_shared(); } + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy001, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + DeviceManager::GetInstance().UnInitDeviceManager(packName); + ASSERT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From b819d0f07102baf88d0898a42ba5b8d115de1843 Mon Sep 17 00:00:00 2001 From: y30033032 Date: Sat, 24 Aug 2024 15:47:26 +0800 Subject: [PATCH 096/520] bug fix: add distributed_bundle_framework to systemSaWhiteList Signed-off-by: y30033032 --- services/service/src/device_manager_service_listener.cpp | 2 +- .../service/src/permission/standard/permission_manager.cpp | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 9d2e330bc..104b0ef90 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -42,7 +42,7 @@ std::map DeviceManagerServiceListener::dmListenerMap_ std::map> DeviceManagerServiceListener::udidHashMap_ = {}; std::mutex DeviceManagerServiceListener::alreadyOnlineSetLock_; std::unordered_set DeviceManagerServiceListener::alreadyOnlineSet_ = {}; -const int32_t LAST_APP_ONLINE_NUMS = 5; +const int32_t LAST_APP_ONLINE_NUMS = 6; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 914ddf819..88a302c25 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -49,12 +49,13 @@ constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_ "CollaborationFwk", }; -#define SYSTEM_SA_WHITE_LIST_NUM (4) +#define SYSTEM_SA_WHITE_LIST_NUM (5) constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", "ohos.dslm", "ohos.deviceprofile", + "distributed_bundle_framework", }; } -- Gitee From c58ea38c7748316ab3164d30339c83c26e3d1816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 24 Aug 2024 16:26:28 +0800 Subject: [PATCH 097/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index a2aea18e8..6e3826542 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1618,16 +1618,16 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond).c_str()); + int32_t policyStrategy = -1; + if (policy.find(PARAM_KEY_POLICY_STRATEGY_FOR_BLE) != policy.end()) { + policyStrategy = std::stoi((policy.find(PARAM_KEY_POLICY_STRATEGY_FOR_BLE)->second).c_str()); } uint8_t timeOut = 0; - if (policy.find(DM_POLICY_TIMEOUT) != policy.end()) { - timeOut = std::stoi((policy.find(DM_POLICY_TIMEOUT)->second).c_str()); + if (policy.find(PARAM_KEY_POLICY_TIME_OUT) != policy.end()) { + timeOut = std::stoi((policy.find(PARAM_KEY_POLICY_TIME_OUT)->second).c_str()); } CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); - return softbusListener_->SetDnPolicy(pkgName, policy, timeOut); + return softbusListener_->SetDnPolicy(policyStrategy, timeOut); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 8bc29f9c2fc4f8ef317a269ea51d3360e66a726f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 24 Aug 2024 17:18:03 +0800 Subject: [PATCH 098/520] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../service/include/softbus/softbus_listener.h | 2 +- services/service/src/device_manager_service.cpp | 16 ++++++++++------ .../service/src/softbus/softbus_listener.cpp | 4 ++-- .../authenticate_device_fuzzer.cpp | 1 + 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 01a7c0b70..4227937bc 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -91,7 +91,7 @@ public: static IRefreshCallback &GetSoftbusRefreshCb(); static void SetHostPkgName(const std::string hostName); static std::string GetHostPkgName(); - static int32_t SetDnPolicy(int32_t policy, uint8_t timeOut); + static int32_t SetDnPolicy(int32_t policy, int32_t timeOut); private: int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 6e3826542..2a8ef3b10 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1618,14 +1618,18 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond).c_str()); + auto policyStrategyIter = policy.find(PARAM_KEY_POLICY_STRATEGY_FOR_BLE); + if (policyStrategyIter == policy.end()) { + LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is empty."); + return ERR_DM_INPUT_PARA_INVALID; } - uint8_t timeOut = 0; - if (policy.find(PARAM_KEY_POLICY_TIME_OUT) != policy.end()) { - timeOut = std::stoi((policy.find(PARAM_KEY_POLICY_TIME_OUT)->second).c_str()); + auto timeOutIter = policy.find(PARAM_KEY_POLICY_TIME_OUT); + if (timeOutIter == policy.end()) { + LOGE("Invalid parameter, DM_POLICY_TIMEOUT is empty."); + return ERR_DM_INPUT_PARA_INVALID; } + int32_t policyStrategy = std::stoi((policyStrategyIter->second).c_str()); + int32_t timeOut = std::stoi((timeOutIter->second).c_str()); CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); return softbusListener_->SetDnPolicy(policyStrategy, timeOut); } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 0303513fb..eb5fcdc4b 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -753,10 +753,10 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ return DM_OK; } -int32_t SoftbusListener::SetDnPolicy(int32_t policy, uint8_t timeOut) +int32_t SoftbusListener::SetDnPolicy(int32_t policy, int32_t timeOut) { /* - int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); + int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), static_casttimeOut); if (ret != DM_OK) { LOGE("[SOFTBUS]CtrlLNNBleHb failed."); return ret; diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index caad363bd..329265466 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -372,6 +372,7 @@ void AuthenticateDeviceFifthFuzzTest(const uint8_t* data, size_t size) DeviceManagerImpl::GetInstance().UnRegisterDiscoveryCallback(emptyStr); DeviceManagerImpl::GetInstance().StartAdvertising(emptyStr, discoverParam, nullptr); DeviceManagerImpl::GetInstance().StopAdvertising(emptyStr, discoverParam); + DeviceManagerImpl::GetInstance().SetDnPolicy(emptyStr, discoverParam); } } } -- Gitee From 0edb3bcba713a60316973b3b9991c1b2a8383ae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 24 Aug 2024 18:21:32 +0800 Subject: [PATCH 099/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/include/device_manager.h | 4 +++- services/service/src/softbus/softbus_listener.cpp | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index d90ccac3c..412649e92 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -563,7 +563,9 @@ public: /** * @brief Set Dn Policy * @param pkgName package name. - * @param policy policy and timeout. + * @param policy contain DM_POLICY_STRATEGY_FOR_BLE and DM_POLICY_TIMEOUT key and value. + * DM_POLICY_STRATEGY_FOR_BLE: Strategy BLE networking go-online policy, suppress or restore. + * DM_POLICY_TIMEOUT: Indicates the duration for suppressing ble networking. * @return Returns 0 if success. */ virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index eb5fcdc4b..19e4f0b30 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -756,7 +756,7 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ int32_t SoftbusListener::SetDnPolicy(int32_t policy, int32_t timeOut) { /* - int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), static_casttimeOut); + int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); if (ret != DM_OK) { LOGE("[SOFTBUS]CtrlLNNBleHb failed."); return ret; -- Gitee From 38c1eae9be40619d68884067edd3134f63875a12 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sat, 24 Aug 2024 22:38:52 +0800 Subject: [PATCH 100/520] add hash salt Signed-off-by: hwzhangchuang --- test/unittest/BUILD.gn | 16 ++++ test/unittest/UTTest_dm_crypto.cpp | 127 +++++++++++++++++++++++++++++ test/unittest/UTTest_dm_crypto.h | 33 ++++++++ utils/include/crypto/dm_crypto.h | 7 ++ utils/src/crypto/dm_crypto.cpp | 51 ++++++++++-- 5 files changed, 229 insertions(+), 5 deletions(-) create mode 100644 test/unittest/UTTest_dm_crypto.cpp create mode 100644 test/unittest/UTTest_dm_crypto.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index f91a2141b..6e68add3a 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -41,6 +41,7 @@ group("unittest") { ":UTTest_dm_discovery_filter", ":UTTest_dm_discovery_manager", ":UTTest_dm_distributed_hardware_load", + ":UTTest_dm_crypto", ":UTTest_dm_import_auth_code", ":UTTest_dm_pin_holder", ":UTTest_dm_publish_manager", @@ -1118,6 +1119,21 @@ ohos_unittest("UTTest_dm_distributed_hardware_load") { ## UnitTest UTTest_dm_distributed_hardware_load }}} +## UnitTest UTTest_dm_crypto {{{ +ohos_unittest("UTTest_dm_crypto") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ "${devicemanager_path}/test/unittest/UTTest_dm_crypto.cpp" ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [] +} + +## UnitTest UTTest_dm_crypto }}} + ## UnitTest UTTest_dm_publish_manager {{{ ohos_unittest("UTTest_dm_publish_manager") { module_out_path = module_out_path diff --git a/test/unittest/UTTest_dm_crypto.cpp b/test/unittest/UTTest_dm_crypto.cpp new file mode 100644 index 000000000..c56e7da01 --- /dev/null +++ b/test/unittest/UTTest_dm_crypto.cpp @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_crypto.h" + +#include +#include + +#include "dm_constants.h" +#include "dm_crypto.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + constexpr int32_t SALT_STRING_LENGTH = 16; + const std::string SALT_DEFAULT = "salt_defsalt_def"; + const std::string UDID_SAMPLE = "3fde738fb2b8c910023d949166125bc9ed49e9e2fc8f4826d652b2839def2238"; +} +void DmCryptoTest::SetUp() +{ +} +void DmCryptoTest::TearDown() +{ +} +void DmCryptoTest::SetUpTestCase() +{ +} +void DmCryptoTest::TearDownTestCase() +{ +} + +/** + * @tc.name: GetSecRandom_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetSecRandom_01, testing::ext::TestSize.Level0) +{ + const int32_t len = 8; + uint8_t buffer[len] = {0}; + int32_t ret = Crypto::GetSecRandom(buffer, len); + EXPECT_EQ(ret, 0); + char outBuf[len * 2 + 1] = {0}; + Crypto::ConvertBytesToHexString(outBuf, len * 2 + 1, buffer, len); + + // 打印生成的随机字节序列 + std::cout << "Random Bytes:"; + for (int i = 0; i < len * 2; ++i) { + std::cout << outBuf[i]; + } + std::cout << std::endl; +} + +/** + * @tc.name: GetSecSalt_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetSecSalt_01, testing::ext::TestSize.Level0) +{ + std::string salt = Crypto::GetSecSalt(); + EXPECT_EQ(salt.length(), SALT_STRING_LENGTH); + EXPECT_NE(salt, SALT_DEFAULT); + + std::cout << "Random Salt: " << salt << std::endl; +} + +/** + * @tc.name: GetUdidHash_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetUdidHash_01, testing::ext::TestSize.Level0) +{ + char udidHash[DEVICE_UUID_LENGTH] = {0}; + EXPECT_EQ(Crypto::GetUdidHash(UDID_SAMPLE, reinterpret_cast(udidHash)), DM_OK); + + std::string res(udidHash); + std::cout << "udidHash sample: " << res << std::endl; +} + +/** + * @tc.name: GetHashWithSalt_01 + * @tc.type: FUNC + */ +HWTEST_F(DmCryptoTest, GetHashWithSalt_01, testing::ext::TestSize.Level0) +{ + std::string text1 = "c9ed49e9e2fc8f4826d652b2839d"; + std::string text2 = "aaadfasdfasdfc9ed49e9e2sadfasdffc8f4826d6asdfasdf52basdf2839d"; + std::string salt1 = Crypto::GetSecSalt(); + std::string salt2 = Crypto::GetSecSalt(); + + std::string hash1 = Crypto::GetHashWithSalt(text1, salt1); + std::string hash2 = Crypto::GetHashWithSalt(text1, salt2); + + EXPECT_STRNE(hash1.c_str(), hash2.c_str()); + std::cout << "hash1: " << hash1 << std::endl; + std::cout << "hash2: " << hash2 << std::endl; + + std::string hash3 = Crypto::GetHashWithSalt(text1, salt1); + std::string hash4 = Crypto::GetHashWithSalt(text2, salt1); + EXPECT_STRNE(hash3.c_str(), hash4.c_str()); + std::cout << "hash1: " << hash3 << std::endl; + std::cout << "hash2: " << hash4 << std::endl; + + std::string hash5 = Crypto::GetHashWithSalt(text2, salt1); + EXPECT_STREQ(hash5.c_str(), hash4.c_str()); + std::cout << "hash5: " << hash5 << std::endl; + std::cout << "hash4: " << hash4 << std::endl; + + std::string hash6 = Crypto::GetHashWithSalt(text1, salt2); + EXPECT_STREQ(hash2.c_str(), hash6.c_str()); + + std::cout << "hash2: " << hash2 << std::endl; + std::cout << "hash6: " << hash6 << std::endl; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_crypto.h b/test/unittest/UTTest_dm_crypto.h new file mode 100644 index 000000000..5f709cb33 --- /dev/null +++ b/test/unittest/UTTest_dm_crypto.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_UTTEST_DM_CRYPTO_H +#define OHOS_UTTEST_DM_CRYPTO_H + +#include + +namespace OHOS { +namespace DistributedHardware { +class DmCryptoTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_CRYPTO_H \ No newline at end of file diff --git a/utils/include/crypto/dm_crypto.h b/utils/include/crypto/dm_crypto.h index 0ac12466c..712a14a95 100644 --- a/utils/include/crypto/dm_crypto.h +++ b/utils/include/crypto/dm_crypto.h @@ -21,12 +21,19 @@ namespace OHOS { namespace DistributedHardware { class Crypto { public: + static void DmGenerateStrHash(const void *data, size_t dataSize, unsigned char *outBuf, uint32_t outBufLen, + uint32_t startIndex); static std::string Sha256(const std::string &text, bool isUpper = false); static std::string Sha256(const void *data, size_t size, bool isUpper = false); static int32_t ConvertHexStringToBytes(unsigned char *outBuf, uint32_t outBufLen, const char *inBuf, uint32_t inLen); + static int32_t ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned char *inBuf, + uint32_t inLen); static int32_t GetUdidHash(const std::string &udid, unsigned char *udidHash); static std::string GetGroupIdHash(const std::string &groupId); + static int32_t GetSecRandom(uint8_t *out, size_t outLen); + static std::string GetSecSalt(); + static std::string GetHashWithSalt(const std::string &text, const std::string &salt); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/crypto/dm_crypto.cpp b/utils/src/crypto/dm_crypto.cpp index 3e707b21f..17b3a8b9c 100644 --- a/utils/src/crypto/dm_crypto.cpp +++ b/utils/src/crypto/dm_crypto.cpp @@ -17,6 +17,7 @@ #include #include +#include #include "openssl/sha.h" namespace OHOS { @@ -29,16 +30,19 @@ constexpr int DEC_MAX_NUM = 10; constexpr int HEX_MAX_BIT_NUM = 4; constexpr uint32_t ERR_DM_FAILED = 96929744; constexpr int32_t DM_OK = 0; +constexpr int32_t DM_ERR = -1; constexpr int32_t ERR_DM_INPUT_PARA_INVALID = 96929749; constexpr int HEX_DIGIT_MAX_NUM = 16; constexpr int SHORT_DEVICE_ID_HASH_LENGTH = 16; +constexpr int32_t SALT_LENGTH = 8; +const std::string SALT_DEFAULT = "salt_defsalt_def"; uint32_t HexifyLen(uint32_t len) { return len * HEX_TO_UINT8 + 1; } -void DmGenerateStrHash(const void *data, size_t dataSize, unsigned char *outBuf, uint32_t outBufLen, +void Crypto::DmGenerateStrHash(const void *data, size_t dataSize, unsigned char *outBuf, uint32_t outBufLen, uint32_t startIndex) { if (data == nullptr || outBuf == nullptr || startIndex > outBufLen) { @@ -51,7 +55,7 @@ void DmGenerateStrHash(const void *data, size_t dataSize, unsigned char *outBuf, SHA256_Final(&outBuf[startIndex], &ctx); } -int32_t ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned char *inBuf, +int32_t Crypto::ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned char *inBuf, uint32_t inLen) { if ((outBuf == nullptr) || (inBuf == nullptr) || (outBufLen < HexifyLen(inLen))) { @@ -84,7 +88,7 @@ std::string Crypto::Sha256(const std::string &text, bool isUpper) std::string Crypto::Sha256(const void *data, size_t size, bool isUpper) { unsigned char hash[SHA256_DIGEST_LENGTH * HEX_TO_UINT8 + 1] = ""; - DmGenerateStrHash(data, size, hash, HexifyLen(SHA256_DIGEST_LENGTH), SHA256_DIGEST_LENGTH); + Crypto::DmGenerateStrHash(data, size, hash, HexifyLen(SHA256_DIGEST_LENGTH), SHA256_DIGEST_LENGTH); // here we translate sha256 hash to hexadecimal. each 8-bit char will be presented by two characters([0-9a-f]) const char* hexCode = isUpper ? "0123456789ABCDEF" : "0123456789abcdef"; for (int32_t i = 0; i < SHA256_DIGEST_LENGTH; ++i) { @@ -102,7 +106,7 @@ std::string Crypto::Sha256(const void *data, size_t size, bool isUpper) int32_t Crypto::GetUdidHash(const std::string &udid, unsigned char *udidHash) { unsigned char hash[SHA256_DIGEST_LENGTH] = ""; - DmGenerateStrHash(udid.data(), udid.size(), hash, SHA256_DIGEST_LENGTH, 0); + Crypto::DmGenerateStrHash(udid.data(), udid.size(), hash, SHA256_DIGEST_LENGTH, 0); if (ConvertBytesToHexString(reinterpret_cast(udidHash), SHORT_DEVICE_ID_HASH_LENGTH + 1, reinterpret_cast(hash), SHORT_DEVICE_ID_HASH_LENGTH / HEX_TO_UINT8) != DM_OK) { LOGE("ConvertBytesToHexString failed."); @@ -154,12 +158,49 @@ int32_t Crypto::ConvertHexStringToBytes(unsigned char *outBuf, uint32_t outBufLe std::string Crypto::GetGroupIdHash(const std::string &groupId) { unsigned char hash[SHA256_DIGEST_LENGTH] = ""; - DmGenerateStrHash(groupId.data(), groupId.size(), hash, SHA256_DIGEST_LENGTH, 0); + Crypto::DmGenerateStrHash(groupId.data(), groupId.size(), hash, SHA256_DIGEST_LENGTH, 0); std::stringstream ss; for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { ss << std::hex << (int)hash[i]; } return ss.str().substr(0, SHORT_DEVICE_ID_HASH_LENGTH); } + +int32_t Crypto::GetSecRandom(uint8_t *out, size_t outLen) +{ + if (out == NULL) { + return DM_ERR; + } + + if (outLen == 0) { + return DM_ERR; + } + + RAND_poll(); + RAND_bytes(out, outLen); + return DM_OK; +} + +std::string Crypto::GetSecSalt() +{ + uint8_t out[SALT_LENGTH] = {0}; + if (Crypto::GetSecRandom(out, SALT_LENGTH) != DM_OK) { + return SALT_DEFAULT; + } + + char outHex[SALT_LENGTH * HEX_TO_UINT8 + 1] = {0}; + if (Crypto::ConvertBytesToHexString(outHex, SALT_LENGTH * HEX_TO_UINT8 + 1, out, SALT_LENGTH) != DM_OK) { + return SALT_DEFAULT; + } + + return std::string(outHex); +} + +std::string Crypto::GetHashWithSalt(const std::string &text, const std::string &salt) +{ + std::string rawText = text + salt; + return Crypto::Sha256(rawText); +} + } // namespace DistributedHardware } // namespace OHOS -- Gitee From 552b14f4ae9f68245a0c06cf21d4c0e0574e7aa7 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sat, 24 Aug 2024 22:45:35 +0800 Subject: [PATCH 101/520] modify bug Signed-off-by: hwzhangchuang --- test/unittest/UTTest_dm_crypto.cpp | 9 --------- utils/include/crypto/dm_crypto.h | 4 ---- utils/src/crypto/dm_crypto.cpp | 12 ++++++------ 3 files changed, 6 insertions(+), 19 deletions(-) diff --git a/test/unittest/UTTest_dm_crypto.cpp b/test/unittest/UTTest_dm_crypto.cpp index c56e7da01..e72f557c7 100644 --- a/test/unittest/UTTest_dm_crypto.cpp +++ b/test/unittest/UTTest_dm_crypto.cpp @@ -51,15 +51,6 @@ HWTEST_F(DmCryptoTest, GetSecRandom_01, testing::ext::TestSize.Level0) uint8_t buffer[len] = {0}; int32_t ret = Crypto::GetSecRandom(buffer, len); EXPECT_EQ(ret, 0); - char outBuf[len * 2 + 1] = {0}; - Crypto::ConvertBytesToHexString(outBuf, len * 2 + 1, buffer, len); - - // 打印生成的随机字节序列 - std::cout << "Random Bytes:"; - for (int i = 0; i < len * 2; ++i) { - std::cout << outBuf[i]; - } - std::cout << std::endl; } /** diff --git a/utils/include/crypto/dm_crypto.h b/utils/include/crypto/dm_crypto.h index 712a14a95..baf165049 100644 --- a/utils/include/crypto/dm_crypto.h +++ b/utils/include/crypto/dm_crypto.h @@ -21,14 +21,10 @@ namespace OHOS { namespace DistributedHardware { class Crypto { public: - static void DmGenerateStrHash(const void *data, size_t dataSize, unsigned char *outBuf, uint32_t outBufLen, - uint32_t startIndex); static std::string Sha256(const std::string &text, bool isUpper = false); static std::string Sha256(const void *data, size_t size, bool isUpper = false); static int32_t ConvertHexStringToBytes(unsigned char *outBuf, uint32_t outBufLen, const char *inBuf, uint32_t inLen); - static int32_t ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned char *inBuf, - uint32_t inLen); static int32_t GetUdidHash(const std::string &udid, unsigned char *udidHash); static std::string GetGroupIdHash(const std::string &groupId); static int32_t GetSecRandom(uint8_t *out, size_t outLen); diff --git a/utils/src/crypto/dm_crypto.cpp b/utils/src/crypto/dm_crypto.cpp index 17b3a8b9c..5db9fae62 100644 --- a/utils/src/crypto/dm_crypto.cpp +++ b/utils/src/crypto/dm_crypto.cpp @@ -42,7 +42,7 @@ uint32_t HexifyLen(uint32_t len) return len * HEX_TO_UINT8 + 1; } -void Crypto::DmGenerateStrHash(const void *data, size_t dataSize, unsigned char *outBuf, uint32_t outBufLen, +void DmGenerateStrHash(const void *data, size_t dataSize, unsigned char *outBuf, uint32_t outBufLen, uint32_t startIndex) { if (data == nullptr || outBuf == nullptr || startIndex > outBufLen) { @@ -55,7 +55,7 @@ void Crypto::DmGenerateStrHash(const void *data, size_t dataSize, unsigned char SHA256_Final(&outBuf[startIndex], &ctx); } -int32_t Crypto::ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned char *inBuf, +int32_t ConvertBytesToHexString(char *outBuf, uint32_t outBufLen, const unsigned char *inBuf, uint32_t inLen) { if ((outBuf == nullptr) || (inBuf == nullptr) || (outBufLen < HexifyLen(inLen))) { @@ -88,7 +88,7 @@ std::string Crypto::Sha256(const std::string &text, bool isUpper) std::string Crypto::Sha256(const void *data, size_t size, bool isUpper) { unsigned char hash[SHA256_DIGEST_LENGTH * HEX_TO_UINT8 + 1] = ""; - Crypto::DmGenerateStrHash(data, size, hash, HexifyLen(SHA256_DIGEST_LENGTH), SHA256_DIGEST_LENGTH); + DmGenerateStrHash(data, size, hash, HexifyLen(SHA256_DIGEST_LENGTH), SHA256_DIGEST_LENGTH); // here we translate sha256 hash to hexadecimal. each 8-bit char will be presented by two characters([0-9a-f]) const char* hexCode = isUpper ? "0123456789ABCDEF" : "0123456789abcdef"; for (int32_t i = 0; i < SHA256_DIGEST_LENGTH; ++i) { @@ -106,7 +106,7 @@ std::string Crypto::Sha256(const void *data, size_t size, bool isUpper) int32_t Crypto::GetUdidHash(const std::string &udid, unsigned char *udidHash) { unsigned char hash[SHA256_DIGEST_LENGTH] = ""; - Crypto::DmGenerateStrHash(udid.data(), udid.size(), hash, SHA256_DIGEST_LENGTH, 0); + DmGenerateStrHash(udid.data(), udid.size(), hash, SHA256_DIGEST_LENGTH, 0); if (ConvertBytesToHexString(reinterpret_cast(udidHash), SHORT_DEVICE_ID_HASH_LENGTH + 1, reinterpret_cast(hash), SHORT_DEVICE_ID_HASH_LENGTH / HEX_TO_UINT8) != DM_OK) { LOGE("ConvertBytesToHexString failed."); @@ -158,7 +158,7 @@ int32_t Crypto::ConvertHexStringToBytes(unsigned char *outBuf, uint32_t outBufLe std::string Crypto::GetGroupIdHash(const std::string &groupId) { unsigned char hash[SHA256_DIGEST_LENGTH] = ""; - Crypto::DmGenerateStrHash(groupId.data(), groupId.size(), hash, SHA256_DIGEST_LENGTH, 0); + DmGenerateStrHash(groupId.data(), groupId.size(), hash, SHA256_DIGEST_LENGTH, 0); std::stringstream ss; for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { ss << std::hex << (int)hash[i]; @@ -189,7 +189,7 @@ std::string Crypto::GetSecSalt() } char outHex[SALT_LENGTH * HEX_TO_UINT8 + 1] = {0}; - if (Crypto::ConvertBytesToHexString(outHex, SALT_LENGTH * HEX_TO_UINT8 + 1, out, SALT_LENGTH) != DM_OK) { + if (ConvertBytesToHexString(outHex, SALT_LENGTH * HEX_TO_UINT8 + 1, out, SALT_LENGTH) != DM_OK) { return SALT_DEFAULT; } -- Gitee From c56b9fe6a32ebba4ea2466740803e06322591073 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sat, 24 Aug 2024 22:53:35 +0800 Subject: [PATCH 102/520] modify bug Signed-off-by: hwzhangchuang --- test/unittest/UTTest_dm_crypto.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_dm_crypto.cpp b/test/unittest/UTTest_dm_crypto.cpp index e72f557c7..55fe57186 100644 --- a/test/unittest/UTTest_dm_crypto.cpp +++ b/test/unittest/UTTest_dm_crypto.cpp @@ -15,8 +15,8 @@ #include "UTTest_dm_crypto.h" -#include #include +#include #include "dm_constants.h" #include "dm_crypto.h" -- Gitee From ef76104c25bf9a5ae4868e418da0d9354cb9fb9a Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 25 Aug 2024 00:09:36 +0800 Subject: [PATCH 103/520] modify format Signed-off-by: hwzhangchuang --- test/unittest/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 6e68add3a..daa2ebe1b 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -35,13 +35,13 @@ group("unittest") { ":UTTest_dm_auth_manager_second", ":UTTest_dm_common_event_manager", ":UTTest_dm_credential_manager", + ":UTTest_dm_crypto", ":UTTest_dm_device_state_manager", ":UTTest_dm_deviceprofile_connector", ":UTTest_dm_dfx", ":UTTest_dm_discovery_filter", ":UTTest_dm_discovery_manager", ":UTTest_dm_distributed_hardware_load", - ":UTTest_dm_crypto", ":UTTest_dm_import_auth_code", ":UTTest_dm_pin_holder", ":UTTest_dm_publish_manager", -- Gitee From d8df95c7c337e14a659e9a7e89b482b131933717 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sun, 25 Aug 2024 14:42:23 +0800 Subject: [PATCH 104/520] fix ut Signed-off-by: gaoqiang_strong --- .../UTTest_device_manager_service.cpp | 108 ++++++++++++++++-- 1 file changed, 98 insertions(+), 10 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 43b01e53c..25f9cfabe 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -102,6 +102,7 @@ HWTEST_F(DeviceManagerServiceTest, InitDMServiceListener_001, testing::ext::Test { int ret = DeviceManagerService::GetInstance().InitDMServiceListener(); EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } /** @@ -150,6 +151,7 @@ HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_003, testing::ext::TestS DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); EXPECT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } /** @@ -164,7 +166,8 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSi uint16_t subscribeId = 1; DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_ERR); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } /** @@ -181,6 +184,21 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSi EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } +/** + * @tc.name:StopDeviceDiscovery_003 + * @tc.desc: StopDeviceDiscovery is initialized, pkgName is null, and its return value is ERR_DM_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) +{ + DeletePermission(); + std::string pkgName ="StopDeviceDiscovery_003";; + uint16_t subscribeId = 1; + int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + /** * @tc.name: PublishDeviceDiscovery_001 * @tc.desc: Publish device discovery and return ERR_DM_NO_PERMISSION @@ -229,7 +247,26 @@ HWTEST_F(DeviceManagerServiceTest, PublishDeviceDiscovery_003, testing::ext::Tes int ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); pkgName = "1com.ohos.test1"; ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +/** + * @tc.name: PublishDeviceDiscovery_004 + * @tc.desc: Call PublishDeviceDiscovery twice with pkgName not null and flag bit not false and return + * SOFTBUS_DISCOVER_MANAGER_DUPLICATE_PARAM + * @tc.type: FUNC + * @tc.require: I5N1K3 + */ +HWTEST_F(DeviceManagerServiceTest, PublishDeviceDiscovery_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "PublishDeviceDiscovery_004"; + DmPublishInfo publishInfo; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); + pkgName = "1com.ohos.test1"; + ret = DeviceManagerService::GetInstance().PublishDeviceDiscovery(pkgName, publishInfo); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_DISCOVER_MANAGER_DUPLICATE_PARAM); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } /** @@ -243,7 +280,7 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_001, testing::ext::T std::string pkgName = "com.ohos.test"; int32_t publishId = 1; int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } /** @@ -259,6 +296,23 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_002, testing::ext::T DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + +/** + * @tc.name: UnPublishDeviceDiscovery_003 + * @tc.desc: UnPublishDeviceDiscovery is initialized, pkgName is null, and its return ERR_DM_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: I5N1K3 + */ +HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test003"; + int32_t publishId = 1; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_ERR); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } /** @@ -292,6 +346,25 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_002, testing::ext::TestS EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +/** + * @tc.name: GetTrustedDeviceList_003 + * @tc.desc:Set the intFlag of GetTrustedDeviceList to true; Return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos_test"; + std::string extra = "jdddd"; + std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().InitDMServiceListener(); + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + /** * @tc.name: ShiftLNNGear_001 * @tc.desc:Set the pkgName to null, callerId not to null, and isRefresh to true; Return ERR_DM_INPUT_PARA_INVALID @@ -410,11 +483,12 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_005, testing::ext::TestSize.Leve */ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_006, testing::ext::TestSize.Level0) { - std::string pkgName = "com.ohos.test"; - std::string callerId = "com.ohos.test"; + std::string pkgName = "ShiftLNNGear_006"; + std::string callerId = "ShiftLNNGear_006"; bool isRefresh = true; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } /** @@ -1545,8 +1619,9 @@ HWTEST_F(DeviceManagerServiceTest, StartDiscovering_003, testing::ext::TestSize. std::map filterOptions; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == DM_OK || ret == SOFTBUS_DISCOVER_MANAGER_INNERFUNCTION_FAIL); DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, StartDiscovering_004, testing::ext::TestSize.Level0) @@ -1562,8 +1637,9 @@ HWTEST_F(DeviceManagerServiceTest, StartDiscovering_004, testing::ext::TestSize. std::map filterOptions; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StartDiscovering(pkgName, discoverParam, filterOptions); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == DM_OK || ret == SOFTBUS_DISCOVER_MANAGER_INNERFUNCTION_FAIL); DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, StopDiscovering_001, testing::ext::TestSize.Level0) @@ -1590,6 +1666,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDiscovering_003, testing::ext::TestSize.L DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StopDiscovering(pkgName, discoverParam); EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_001, testing::ext::TestSize.Level0) @@ -1642,7 +1719,7 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_003, testing::ext::T std::string pkgName = "pkgName"; std::map extraParam; int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); } HWTEST_F(DeviceManagerServiceTest, StartAdvertising_001, testing::ext::TestSize.Level0) @@ -1673,6 +1750,7 @@ HWTEST_F(DeviceManagerServiceTest, StartAdvertising_003, testing::ext::TestSize. DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StartAdvertising(pkgName, advertiseParam); EXPECT_NE(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, StopAdvertising_001, testing::ext::TestSize.Level0) @@ -1697,7 +1775,17 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_003, testing::ext::TestSize.L std::string pkgName = "pkgName"; std::map advertiseParam; int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); - EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, StopAdvertising_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "StopAdvertising_004"; + std::map advertiseParam; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_ERR); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, BindTarget_004, testing::ext::TestSize.Level0) -- Gitee From 5d1e23642ab880dfca1f3c78025ff76be86faaf9 Mon Sep 17 00:00:00 2001 From: l00797637 Date: Sun, 25 Aug 2024 18:28:26 +0800 Subject: [PATCH 105/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E7=BA=A7SA=E7=99=BD=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: Id1f6aef0558b3f207cbd085070f1306c8d5c64f3 Signed-off-by: l00797637 --- services/service/src/device_manager_service_listener.cpp | 2 +- .../service/src/permission/standard/permission_manager.cpp | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 104b0ef90..7b063a94b 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -42,7 +42,7 @@ std::map DeviceManagerServiceListener::dmListenerMap_ std::map> DeviceManagerServiceListener::udidHashMap_ = {}; std::mutex DeviceManagerServiceListener::alreadyOnlineSetLock_; std::unordered_set DeviceManagerServiceListener::alreadyOnlineSet_ = {}; -const int32_t LAST_APP_ONLINE_NUMS = 6; +const int32_t LAST_APP_ONLINE_NUMS = 8; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 88a302c25..cef804f68 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -49,13 +49,15 @@ constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_ "CollaborationFwk", }; -#define SYSTEM_SA_WHITE_LIST_NUM (5) +#define SYSTEM_SA_WHITE_LIST_NUM (7) constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", "ohos.dslm", "ohos.deviceprofile", "distributed_bundle_framework", + "ohos.dhardware", + "ohos.security.distributed_access_token", }; } -- Gitee From c3a71a75dfed0c363f90ef06385be08b871ada62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 26 Aug 2024 19:39:55 +0800 Subject: [PATCH 106/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=A0=E7=A9=BA?= =?UTF-8?q?=E6=AF=94=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h | 4 ++++ 1 file changed, 4 insertions(+) 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 83208d95e..d39b30365 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_subscribe_info.h @@ -81,6 +81,10 @@ typedef enum DmExchangeFreq { * Super-high */ DM_SUPER_HIGH = 3, + /** + * Extreme-high + */ + DM_EXTREME_HIGH = 4, DM_FREQ_BUTT } DmExchangeFreq; -- Gitee From a16344b8130f068696cc4768a16347e649bac037 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Tue, 27 Aug 2024 09:33:52 +0800 Subject: [PATCH 107/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=B3=A8=E5=86=8C?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E7=BB=91=E5=AE=9A=E5=9B=9E=E8=B0=83=E6=97=B6?= =?UTF-8?q?=E5=BA=8F=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/include/notify/device_manager_notify.h | 2 -- .../inner_kits/native_cpp/src/device_manager_impl.cpp | 3 +-- .../native_cpp/src/notify/device_manager_notify.cpp | 9 ++------- 3 files changed, 3 insertions(+), 11 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 5e3442fe7..f78a34573 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 @@ -123,8 +123,6 @@ private: std::map>> unbindCallback_; std::map> pinHolderCallback_; std::mutex bindLock_; - std::condition_variable cv_; - bool binding_ = false; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::shared_ptr ffrtQueue_; #endif 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 9fcfbbbbb..e0b8f1bf9 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -1746,7 +1746,7 @@ int32_t DeviceManagerImpl::BindTarget(const std::string &pkgName, const PeerTarg } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); std::string bindParamStr = ConvertMapToJsonString(bindParam); - + DeviceManagerNotify::GetInstance().RegisterBindCallback(pkgName, targetId, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); @@ -1762,7 +1762,6 @@ int32_t DeviceManagerImpl::BindTarget(const std::string &pkgName, const PeerTarg LOGE("BindTarget error: Failed with ret %{public}d", ret); return ret; } - DeviceManagerNotify::GetInstance().RegisterBindCallback(pkgName, targetId, callback); LOGI("Completed"); return DM_OK; diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 3683b9f13..5da56c942 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 @@ -24,7 +24,6 @@ namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerNotify); -constexpr uint32_t WAIT_BINDIND_TIME_OUT_SECOND = 1; #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEVICE_ONLINE = "deviceOnline"; constexpr const char* DEVICE_OFFLINE = "deviceOffline"; @@ -809,9 +808,7 @@ void DeviceManagerNotify::RegisterBindCallback(const std::string &pkgName, const pkgName.c_str()); return; } - std::unique_lock ulk(bindLock_); - cv_.wait_for(ulk, std::chrono::seconds(WAIT_BINDIND_TIME_OUT_SECOND), [this]() {return !binding_; }); - binding_ = true; + std::lock_guard autoLock(bindLock_); if (bindCallback_.count(pkgName) == 0) { bindCallback_[pkgName] = std::map>(); } @@ -843,7 +840,7 @@ void DeviceManagerNotify::OnBindResult(const std::string &pkgName, const PeerTar LOGI("DeviceManagerNotify::OnBindResult in, pkgName:%{public}s, result:%{public}d", pkgName.c_str(), result); std::shared_ptr tempCbk; { - std::lock_guard glk(bindLock_); + std::lock_guard autoLock(bindLock_); if (bindCallback_.count(pkgName) == 0) { LOGE("DeviceManagerNotify::OnBindResult error, callback not register for pkgName %{public}s.", pkgName.c_str()); @@ -862,8 +859,6 @@ void DeviceManagerNotify::OnBindResult(const std::string &pkgName, const PeerTar if (bindCallback_[pkgName].empty()) { bindCallback_.erase(pkgName); } - binding_ = false; - cv_.notify_one(); } } if (tempCbk == nullptr) { -- Gitee From 6433806a8b635fdf40666d79e0082d30dc3d5f0d Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Thu, 22 Aug 2024 11:00:58 +0800 Subject: [PATCH 108/520] =?UTF-8?q?=E8=BD=AC=E6=8D=A2udid=20Signed-off-by:?= =?UTF-8?q?=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bundle.json | 1 + sa_profile/device_manager.cfg | 19 +- services/service/BUILD.gn | 2 + .../service/include/device_manager_service.h | 7 +- .../include/device_manager_service_listener.h | 19 +- .../service/src/device_manager_service.cpp | 112 ++++++++-- .../src/device_manager_service_listener.cpp | 207 ++++++++++-------- .../src/ipc/standard/ipc_cmd_parser.cpp | 4 +- .../src/ipc/standard/ipc_server_stub.cpp | 14 ++ .../authenticatedeviceservice_fuzzer/BUILD.gn | 5 +- .../authenticate_device_service_fuzzer.cpp | 4 +- .../BUILD.gn | 1 + .../dmdiscoverymanager_fuzzer/BUILD.gn | 1 + .../hichainconnector_fuzzer/BUILD.gn | 1 + .../ondatareceived_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onerror_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onfinish_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onrequest_fuzzer/BUILD.gn | 1 + test/commonfuzztest/pinauth_fuzzer/BUILD.gn | 1 + test/commonfuzztest/pinauthui_fuzzer/BUILD.gn | 1 + test/commonfuzztest/pinholder_fuzzer/BUILD.gn | 1 + .../UTTest_dm_auth_manager_second.cpp | 2 +- .../UTTest_dm_deviceprofile_connector.cpp | 2 +- .../devicemanagerservice_fuzzer/BUILD.gn | 5 +- .../BUILD.gn | 5 +- .../shiftlnngeardeviceservice_fuzzer/BUILD.gn | 5 +- .../onbytesreceived_fuzzer/BUILD.gn | 1 + .../onsessionopened_fuzzer/BUILD.gn | 1 + .../softbusadapterobject_fuzzer/BUILD.gn | 1 + .../softbusconnectorregister_fuzzer/BUILD.gn | 2 + .../softbussessionobject_fuzzer/BUILD.gn | 2 + .../UTTest_device_manager_service.cpp | 28 +-- ...UTTest_device_manager_service_listener.cpp | 201 ++--------------- .../UTTest_device_manager_service_two.cpp | 6 +- utils/BUILD.gn | 12 +- utils/include/appInfo/lite/app_manager.h | 3 + utils/include/appInfo/standard/app_manager.h | 8 + utils/include/kvadapter/kv_adapter.h | 70 ++++++ utils/include/kvadapter/kv_adapter_manager.h | 55 +++++ utils/src/appInfo/lite/app_manager.cpp | 18 ++ utils/src/appInfo/standard/app_manager.cpp | 61 +++++- utils/src/kvadapter/kv_adapter.cpp | 207 ++++++++++++++++++ utils/src/kvadapter/kv_adapter_manager.cpp | 131 +++++++++++ 43 files changed, 894 insertions(+), 336 deletions(-) create mode 100644 utils/include/kvadapter/kv_adapter.h create mode 100644 utils/include/kvadapter/kv_adapter_manager.h create mode 100644 utils/src/kvadapter/kv_adapter.cpp create mode 100644 utils/src/kvadapter/kv_adapter_manager.cpp diff --git a/bundle.json b/bundle.json index 4270607a0..8e193b87c 100644 --- a/bundle.json +++ b/bundle.json @@ -48,6 +48,7 @@ "init", "ipc", "json", + "kv_store", "memmgr", "napi", "node", diff --git a/sa_profile/device_manager.cfg b/sa_profile/device_manager.cfg index ef994d6c8..c49440846 100644 --- a/sa_profile/device_manager.cfg +++ b/sa_profile/device_manager.cfg @@ -1,11 +1,25 @@ { + "jobs":[{ + "name" : "service:device_manager", + "cmds" : [ + "mkdir /data/service/el1/public/database 0711 ddms ddms", + "mkdir /data/service/el1/public/database/distributed_device_manager_service 02770 device_manager ddms" + ] + } + ], "services" : [{ "name" : "device_manager", "path" : ["/system/bin/sa_main", "/system/profile/device_manager.json"], "uid" : "device_manager", "gid" : ["device_manager", "access_token"], - "start-mode" : "boot", "apl" : "system_basic", + "start-on-demand" : { + "commonevent" : [ + { + "name" : "usual.event.BOOT_COMPLETED" + } + ] + }, "permission" : [ "ohos.permission.DISTRIBUTED_DATASYNC", "ohos.permission.DISTRIBUTED_SOFTBUS_CENTER", @@ -22,6 +36,9 @@ "ohos.permission.SET_TIME", "ohos.permission.SET_TIME_ZONE" ], + "jobs" : { + "on-start" : "service:device_manager" + }, "secon" : "u:r:device_manager:s0" } ] diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index 81665fbbf..bdd8a1470 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -40,6 +40,7 @@ if (defined(ohos_lite)) { "${utils_path}/include/appInfo/lite", "${utils_path}/include/crypto", "${utils_path}/include/fwkload/lite", + "${utils_path}/include/kvadapter", "${utils_path}/include/timer/lite", "${innerkits_path}/native_cpp/include", "${innerkits_path}/native_cpp/include/ipc", @@ -135,6 +136,7 @@ if (defined(ohos_lite)) { "${softbuscache_parh}/include", "${utils_path}/include/appInfo/standard", "${utils_path}/include/crypto", + "${utils_path}/include/kvadapter", "${utils_path}/include/timer", ] } diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 6e2e24356..a29f27369 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -52,9 +52,9 @@ public: int32_t InitSoftbusListener(); - void RegisterDeviceManagerListener(const std::string &pkgName); + void RegisterCallerAppId(const std::string &pkgName); - void UnRegisterDeviceManagerListener(const std::string &pkgName); + void UnRegisterCallerAppId(const std::string &pkgName); void UninitSoftbusListener(); @@ -205,6 +205,9 @@ private: void AccountCommonEventCallback(int32_t userId, std::string commonEventType); void SubscribeScreenLockEvent(); void ScreenCommonEventCallback(std::string commonEventType); + void ConvertUdidHashToAnoy(DmDeviceInfo &deviceInfo); + int32_t ConvertUdidHashToAnoy(const std::string &udidHash, std::string &result); + int32_t GetUdidHashByAnoyUdid(const std::string &anoyUdid, std::string &udidHash); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 3d9d26118..6ca02a843 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -23,6 +23,9 @@ #include "dm_device_info.h" #include "idevice_manager_service_listener.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "kv_adapter_manager.h" +#endif #if !defined(__LITEOS_M__) #include "ipc_notify_dmfa_result_req.h" #include "ipc_server_listener.h" @@ -61,14 +64,6 @@ public: void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, std::string content) override; - void DeleteDeviceIdFromMap(const std::string &deviceId, const std::string &pkgName); - void RegisterDmListener(const std::string &pkgName, const std::string &appId); - void UnRegisterDmListener(const std::string &pkgName); - std::string GetAppId(const std::string &pkgName); - std::string CalcDeviceId(const std::string &udidHash, const std::string &appId); - void SetUdidHashMap(const std::string &udidHash, const std::string &deviceId, const std::string &pkgName); - std::string GetDeviceId(const std::string &udidHash, const std::string &pkgName); - std::string GetUdidHash(const std::string &deviceId, const std::string &pkgName); void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, const std::string &payload) override; void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) override; @@ -87,13 +82,13 @@ private: void ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); std::string ComposeOnlineKey(const std::string &pkgName, const std::string &devId); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + int32_t ConfuseUdidHash(const std::string &pkgName, DmDeviceInfo &deviceInfo); + int32_t ConvertUdidHashToAnoy(const std::string &pkgName, const std::string &udidHash, std::string &result); +#endif private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; - static std::mutex dmListenerMapLock_; - static std::map dmListenerMap_; - static std::mutex udidHashMapLock_; - static std::map> udidHashMap_; static std::mutex alreadyOnlineSetLock_; static std::unordered_set alreadyOnlineSet_; #endif diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 99f7702fb..440a9d8f3 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -29,7 +29,9 @@ #include "permission_manager.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "common_event_support.h" +#include "datetime_ex.h" #include "iservice_registry.h" +#include "kv_adapter_manager.h" #include "multiple_user_connector.h" #if defined(SUPPORT_POWER_MANAGER) #include "power_mgr_client.h" @@ -205,23 +207,20 @@ void DeviceManagerService::UninitDMServiceListener() listener_ = nullptr; advertiseMgr_ = nullptr; discoveryMgr_ = nullptr; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + KVAdapterManager::GetInstance().UnInit(); +#endif LOGI("Uninit."); } -void DeviceManagerService::RegisterDeviceManagerListener(const std::string &pkgName) +void DeviceManagerService::RegisterCallerAppId(const std::string &pkgName) { - if (listener_ == nullptr) { - listener_ = std::make_shared(); - } - listener_->RegisterDmListener(pkgName, AppManager::GetInstance().GetAppId()); + AppManager::GetInstance().RegisterCallerAppId(pkgName); } -void DeviceManagerService::UnRegisterDeviceManagerListener(const std::string &pkgName) +void DeviceManagerService::UnRegisterCallerAppId(const std::string &pkgName) { - if (listener_ == nullptr) { - listener_ = std::make_shared(); - } - listener_->UnRegisterDmListener(pkgName); + AppManager::GetInstance().UnRegisterCallerAppId(pkgName); } int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, @@ -262,6 +261,9 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName); } for (auto item : onlineDeviceList) { +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ConvertUdidHashToAnoy(item); +#endif std::string udid = ""; SoftbusListener::GetUdidByNetworkId(item.networkId, udid); if (udidMap.find(udid) != udidMap.end()) { @@ -347,7 +349,17 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) localDeviceId_ = udidHash; } } - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHashTemp = ""; + if (ConvertUdidHashToAnoy(localDeviceId_, udidHashTemp) == DM_OK) { + (void)memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); + return ERR_DM_FAILED; + } + return DM_OK; + } +#endif if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, localDeviceId_.c_str(), localDeviceId_.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(localDeviceId_).c_str()); } @@ -498,10 +510,16 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int LOGE("AuthenticateDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - + std::string queryDeviceId = deviceId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHash = ""; + if (GetUdidHashByAnoyUdid(deviceId, udidHash) == DM_OK) { + queryDeviceId = udidHash; + } +#endif PeerTargetId targetId; ConnectionAddrType addrType; - int32_t ret = SoftbusListener::GetTargetInfoFromCache(deviceId, targetId, addrType); + int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType); if (ret != DM_OK) { LOGE("AuthenticateDevice failed, cannot get target info from cached discovered device map."); return ERR_DM_BIND_INPUT_PARA_INVALID; @@ -548,10 +566,16 @@ int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t aut LOGE("BindDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - + std::string queryDeviceId = deviceId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHash = ""; + if (GetUdidHashByAnoyUdid(deviceId, udidHash) == DM_OK) { + queryDeviceId = udidHash; + } +#endif PeerTargetId targetId; ConnectionAddrType addrType; - int32_t ret = SoftbusListener::GetTargetInfoFromCache(deviceId, targetId, addrType); + int32_t ret = SoftbusListener::GetTargetInfoFromCache(queryDeviceId, targetId, addrType); if (ret != DM_OK) { LOGE("BindDevice failed, cannot get target info from cached discovered device map."); return ERR_DM_BIND_INPUT_PARA_INVALID; @@ -579,7 +603,14 @@ int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std LOGE("UnBindDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - return dmServiceImpl_->UnBindDevice(pkgName, deviceId); + std::string realDeviceId = deviceId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string udidHash = ""; + if (GetUdidHashByAnoyUdid(deviceId, udidHash) == DM_OK) { + realDeviceId = udidHash; + } +#endif + return dmServiceImpl_->UnBindDevice(pkgName, realDeviceId); } int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms) @@ -1606,5 +1637,54 @@ void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) } return; } + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +void DeviceManagerService::ConvertUdidHashToAnoy(DmDeviceInfo &deviceInfo) +{ + std::string udidHashTemp = ""; + if (ConvertUdidHashToAnoy(deviceInfo.deviceId, udidHashTemp) == DM_OK) { + (void)memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); + } + } +} + +int32_t DeviceManagerService::ConvertUdidHashToAnoy(const std::string &udidHash, std::string &result) +{ + LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str()); + std::string appId = AppManager::GetInstance().GetAppId(); + if (appId.empty()) { + LOGI("GetAppId failed"); + return ERR_DM_FAILED; + } + std::string udidTemp = udidHash + appId; + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(udidTemp, reinterpret_cast(deviceIdHash)) != DM_OK) { + LOGE("get deviceIdHash by udidTemp: %{public}s failed.", GetAnonyString(udidTemp).c_str()); + return ERR_DM_FAILED; + } + result = std::string(deviceIdHash); + DmKVValue kvValue; + kvValue.udidHash = udidHash; + kvValue.appID = appId; + kvValue.lastModifyTime = GetSecondsSince1970ToNow(); + KVAdapterManager::GetInstance().Put(result, kvValue); + return DM_OK; +} + +int32_t DeviceManagerService::GetUdidHashByAnoyUdid(const std::string &anoyUdid, std::string &udidHash) +{ + LOGI("anoyUdid %{public}s.", GetAnonyString(anoyUdid).c_str()); + DmKVValue kvValue ; + if (KVAdapterManager::GetInstance().Get(anoyUdid, kvValue) != DM_OK) { + LOGE("Get kv value from DB failed"); + return ERR_DM_FAILED; + } + udidHash = kvValue.udidHash; + LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str()); + return DM_OK; +} +#endif } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 9d2e330bc..cfb84cb48 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -15,11 +15,13 @@ #include "device_manager_service_listener.h" +#include "app_manager.h" #include "device_manager_ipc_interface_code.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_log.h" +#include "dm_softbus_cache.h" #include "ipc_create_pin_holder_req.h" #include "ipc_destroy_pin_holder_req.h" #include "ipc_notify_auth_result_req.h" @@ -32,14 +34,15 @@ #include "ipc_notify_pin_holder_event_req.h" #include "ipc_notify_publish_result_req.h" #include "ipc_server_stub.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "datetime_ex.h" +#include "kv_adapter_manager.h" +#endif +#include "parameter.h" #include "permission_manager.h" namespace OHOS { namespace DistributedHardware { -std::mutex DeviceManagerServiceListener::dmListenerMapLock_; -std::mutex DeviceManagerServiceListener::udidHashMapLock_; -std::map DeviceManagerServiceListener::dmListenerMap_ = {}; -std::map> DeviceManagerServiceListener::udidHashMap_ = {}; std::mutex DeviceManagerServiceListener::alreadyOnlineSetLock_; std::unordered_set DeviceManagerServiceListener::alreadyOnlineSet_ = {}; const int32_t LAST_APP_ONLINE_NUMS = 5; @@ -70,6 +73,25 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetPkgName(pkgName); pReq->SetDeviceState(state); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string appId = ""; + if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + pReq->SetDeviceInfo(deviceInfo); + pReq->SetDeviceBasicInfo(deviceBasicInfo); + return; + } + DmDeviceInfo dmDeviceInfo = deviceInfo; + ConfuseUdidHash(pkgName, dmDeviceInfo); + DmDeviceBasicInfo dmDeviceBasicInfo = deviceBasicInfo; + (void)memset_s(dmDeviceBasicInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + if (memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), dmDeviceInfo.deviceId, + std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(dmDeviceInfo.deviceId))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); + } + pReq->SetDeviceInfo(dmDeviceInfo); + pReq->SetDeviceBasicInfo(dmDeviceBasicInfo); + return; +#endif pReq->SetDeviceInfo(deviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); } @@ -182,6 +204,9 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam } else { ProcessAppStateChange(pkgName, state, info, deviceBasicInfo); } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + KVAdapterManager::GetInstance().DeleteAgedEntry(); +#endif } void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, @@ -189,29 +214,25 @@ void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uin { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - + DmDeviceInfo deviceInfo = info; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ConfuseUdidHash(pkgName, deviceInfo); +#endif DmDeviceBasicInfo devBasicInfo; - ConvertDeviceInfoToDeviceBasicInfo(pkgName, info, devBasicInfo); + ConvertDeviceInfoToDeviceBasicInfo(pkgName, deviceInfo, devBasicInfo); pReq->SetDeviceBasicInfo(devBasicInfo); pReq->SetPkgName(pkgName); pReq->SetSubscribeId(subscribeId); - pReq->SetDeviceInfo(info); + pReq->SetDeviceInfo(deviceInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) { - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::string udIdHash = CalcDeviceId(pkgName, info.deviceId); - if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udIdHash.c_str(), udIdHash.length()) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); - } - pReq->SetPkgName(pkgName); - pReq->SetSubscribeId(subscribeId); - pReq->SetDeviceBasicInfo(info); - ipcServerListener_.SendRequest(SERVER_DEVICE_DISCOVERY, pReq, pRsp); + (void)pkgName; + (void)subscribeId; + (void)info; } void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, @@ -259,9 +280,14 @@ void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, cons if (status < STATUS_DM_AUTH_FINISH && status > STATUS_DM_AUTH_DEFAULT) { status = STATUS_DM_AUTH_DEFAULT; } - - pReq->SetPkgName(pkgName); pReq->SetDeviceId(deviceId); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + if (ConvertUdidHashToAnoy(pkgName, deviceId, deviceIdTemp) == DM_OK) { + pReq->SetDeviceId(deviceIdTemp); + } +#endif + pReq->SetPkgName(pkgName); pReq->SetToken(token); pReq->SetStatus(status); pReq->SetReason(reason); @@ -300,9 +326,17 @@ void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, cons if (status < STATUS_DM_AUTH_FINISH && status > STATUS_DM_AUTH_DEFAULT) { status = STATUS_DM_AUTH_DEFAULT; } - + PeerTargetId returnTargetId = targetId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + DmKVValue kvValue; + if (ConvertUdidHashToAnoy(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { + returnTargetId.deviceId = deviceIdTemp; + } +#endif pReq->SetPkgName(pkgName); - pReq->SetPeerTargetId(targetId); + pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetStatus(status); pReq->SetContent(content); @@ -314,84 +348,22 @@ void DeviceManagerServiceListener::OnUnbindResult(const std::string &pkgName, co { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - + PeerTargetId returnTargetId = targetId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + DmKVValue kvValue; + if (ConvertUdidHashToAnoy(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { + returnTargetId.deviceId = deviceIdTemp; + } +#endif pReq->SetPkgName(pkgName); - pReq->SetPeerTargetId(targetId); + pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetContent(content); ipcServerListener_.SendRequest(UNBIND_TARGET_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::RegisterDmListener(const std::string &pkgName, const std::string &appId) -{ - std::lock_guard autoLock(dmListenerMapLock_); - dmListenerMap_[pkgName] = appId; -} - -void DeviceManagerServiceListener::UnRegisterDmListener(const std::string &pkgName) -{ - std::lock_guard autoLock(dmListenerMapLock_); - dmListenerMap_.erase(pkgName); -} - -void DeviceManagerServiceListener::DeleteDeviceIdFromMap(const std::string &deviceId, const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - std::map &udidMap = udidHashMap_[pkgName]; - auto iter = udidMap.find(deviceId); - if (iter == udidMap.end()) { - return; - } - udidMap.erase(deviceId); -} -void DeviceManagerServiceListener::SetUdidHashMap(const std::string &udidHash, const std::string &deviceId, - const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - udidHashMap_[pkgName][deviceId] = udidHash; -} - -std::string DeviceManagerServiceListener::GetDeviceId(const std::string &udidHash, const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - std::map &udidMap = udidHashMap_[pkgName]; - for (auto iter = udidMap.begin(); iter != udidMap.end(); iter++) { - if (udidHash == iter->second) { - return iter->first; - } - } - return ""; -} - -std::string DeviceManagerServiceListener::GetUdidHash(const std::string &deviceId, const std::string &pkgName) -{ - std::lock_guard lock(udidHashMapLock_); - return udidHashMap_[pkgName].count(deviceId) > 0 ? udidHashMap_[pkgName][deviceId] : ""; -} - -std::string DeviceManagerServiceListener::GetAppId(const std::string &pkgName) -{ - std::lock_guard autoLock(dmListenerMapLock_); - return dmListenerMap_.count(pkgName) > 0 ? dmListenerMap_[pkgName] : ""; -} - -std::string DeviceManagerServiceListener::CalcDeviceId(const std::string &pkgName, const std::string &udidHash) -{ - std::string appId = GetAppId(pkgName); - LOGI("CalcDeviceId, appId : %{public}s, udidHash : %{public}s.", GetAnonyString(appId).c_str(), - GetAnonyString(udidHash).c_str()); - if (appId.empty()) { - return udidHash; - } - std::string deviceId = GetDeviceId(udidHash, pkgName); - if (deviceId.empty()) { - deviceId = Crypto::Sha256(appId + udidHash); - SetUdidHashMap(udidHash, deviceId, pkgName); - return deviceId; - } - return deviceId; -} - void DeviceManagerServiceListener::OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, const std::string &payload) { @@ -455,5 +427,54 @@ void DeviceManagerServiceListener::OnPinHolderEvent(const std::string &pkgName, pReq->SetContent(content); ipcServerListener_.SendRequest(SERVER_ON_PIN_HOLDER_EVENT, pReq, pRsp); } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +int32_t DeviceManagerServiceListener::ConfuseUdidHash(const std::string &pkgName, DmDeviceInfo &deviceInfo) +{ + LOGI("ConfuseUdidHash pkgName %{public}s.", pkgName.c_str()); + std::string deviceIdTemp = ""; + if (ConvertUdidHashToAnoy(pkgName, std::string(deviceInfo.deviceId), deviceIdTemp) != DM_OK) { + LOGE("ConvertUdidHashToAnoy failed."); + return ERR_DM_FAILED; + } + std::string appId = ""; + AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId); + if (appId.empty()) { + LOGE("GetAppIdByPkgName failed."); + return ERR_DM_FAILED; + } + + DmKVValue kvValue; + kvValue.udidHash = std::string(deviceInfo.deviceId); + kvValue.appID = appId; + kvValue.lastModifyTime = GetSecondsSince1970ToNow(); + (void)memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + if (memcpy_s(deviceInfo.deviceId, sizeof(deviceInfo.deviceId), deviceIdTemp.c_str(), + std::min(sizeof(deviceInfo.deviceId), deviceIdTemp.length())) != DM_OK) { + LOGE("ConfuseUdidHash copy deviceId data failed."); + return ERR_DM_FAILED; + } + KVAdapterManager::GetInstance().Put(deviceIdTemp, kvValue); + return DM_OK; +} + +int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoy(const std::string &pkgName, + const std::string &udidHash, std::string &result) +{ + LOGI("pkgName %{public}s, udidHash %{public}s.", pkgName.c_str(), GetAnonyString(udidHash).c_str()); + std::string appId = ""; + if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + LOGE("GetAppIdByPkgName failed"); + return ERR_DM_FAILED; + } + std::string udidTemp = udidHash + appId; + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(udidTemp, reinterpret_cast(deviceIdHash)) != DM_OK) { + LOGE("get deviceIdHash by udidTemp: %{public}s failed.", GetAnonyString(udidTemp).c_str()); + return ERR_DM_FAILED; + } + result = std::string(deviceIdHash); + return DM_OK; +} +#endif } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 626580fbb..b69a9f171 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -417,7 +417,7 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); return ERR_DM_POINT_NULL; } - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, callback); if (!reply.WriteInt32(result)) { LOGE("write result failed"); @@ -431,7 +431,7 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); if (!reply.WriteInt32(result)) { LOGE("write result failed"); diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 0396f2a01..07d01c90c 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -24,6 +24,9 @@ #include "ipc_skeleton.h" #include "ipc_types.h" #include "iservice_registry.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "kv_adapter_manager.h" +#endif #ifdef SUPPORT_MEMMGR #include "mem_mgr_client.h" #include "mem_mgr_proxy.h" @@ -63,6 +66,9 @@ void IpcServerStub::OnStart() AddSystemAbilityListener(SCREENLOCK_SERVICE_ID); AddSystemAbilityListener(SOFTBUS_SERVER_SA_ID); LOGI("called:AddAbilityListener end!"); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); +#endif } void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) @@ -96,6 +102,13 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin DeviceManagerService::GetInstance().InitScreenLockEvent(); return; } + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) { + KVAdapterManager::GetInstance().ReInit(); + return; + } +#endif } void IpcServerStub::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) @@ -119,6 +132,7 @@ bool IpcServerStub::Init() return false; } registerToService_ = true; + KVAdapterManager::GetInstance().Init(); } return true; } diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn index 64af696da..ffa5905f4 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn @@ -55,7 +55,10 @@ ohos_fuzztest("AuthenticateDeviceServiceFuzzTest") { ] sources = [ "authenticate_device_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] defines = [ "HI_LOG_ENABLE", diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp b/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp index 5e9988c72..160fdf58b 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/authenticate_device_service_fuzzer.cpp @@ -72,8 +72,8 @@ void AuthenticateDeviceServiceFuzzTest(const uint8_t* data, size_t size) DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, extra); DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); DeviceManagerService::GetInstance().SetUserOperation(pkgName, authType, network); - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, deviceId, udid); DeviceManagerService::GetInstance().CheckApiPermission(level); } diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn index a0c4d3da6..a0e8afe72 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { deps = [ "${devicemanager_path}/services/implementation:devicemanagerserviceimpl", "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn b/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn index 9684811db..ff9e6e54d 100644 --- a/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn +++ b/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn @@ -46,6 +46,7 @@ ohos_fuzztest("DmDiscoveryManagerFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn index efd8e79c2..77b80dd28 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn +++ b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn @@ -46,6 +46,7 @@ ohos_fuzztest("HichainConnectorFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn index 123369f49..af93d673e 100644 --- a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn +++ b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn @@ -46,6 +46,7 @@ ohos_fuzztest("OnDataReceivedFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/commonfuzztest/onerror_fuzzer/BUILD.gn b/test/commonfuzztest/onerror_fuzzer/BUILD.gn index 2752478a0..ab69405b3 100644 --- a/test/commonfuzztest/onerror_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onerror_fuzzer/BUILD.gn @@ -45,6 +45,7 @@ ohos_fuzztest("OnErrorFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn index 17165e254..4a69a47c2 100644 --- a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn @@ -45,6 +45,7 @@ ohos_fuzztest("OnFinishFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn index be167ff07..75ebd763e 100644 --- a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn @@ -46,6 +46,7 @@ ohos_fuzztest("OnRequestFuzzTest") { deps = [ "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/commonfuzztest/pinauth_fuzzer/BUILD.gn b/test/commonfuzztest/pinauth_fuzzer/BUILD.gn index 441b782bc..ff2b0b26c 100644 --- a/test/commonfuzztest/pinauth_fuzzer/BUILD.gn +++ b/test/commonfuzztest/pinauth_fuzzer/BUILD.gn @@ -66,6 +66,7 @@ ohos_fuzztest("PinAuthFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn b/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn index 41c97120d..9b772dab9 100644 --- a/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn +++ b/test/commonfuzztest/pinauthui_fuzzer/BUILD.gn @@ -67,6 +67,7 @@ ohos_fuzztest("PinAuthUiFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonfuzztest/pinholder_fuzzer/BUILD.gn b/test/commonfuzztest/pinholder_fuzzer/BUILD.gn index 6fa7a1097..9ac3303a8 100644 --- a/test/commonfuzztest/pinholder_fuzzer/BUILD.gn +++ b/test/commonfuzztest/pinholder_fuzzer/BUILD.gn @@ -67,6 +67,7 @@ ohos_fuzztest("PinHolderFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] defines = [ diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 5fbfd788d..ab5622022 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -776,7 +776,7 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level0) authManager_->authResponseContext_->dmVersion = "5.0.1"; authManager_->authResponseContext_->bindLevel = 1; ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, DM_OK); + ASSERT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index ecf01409f..8d67f7553 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -723,7 +723,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_004, testing::ext::TestSi std::string localDeviceId = "deviceId"; std::string remoteDeviceId = "deviceId"; bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_001, testing::ext::TestSize.Level0) diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn index 0c1a56a27..0b4beb80c 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn @@ -56,7 +56,10 @@ ohos_fuzztest("DeviceManagerServiceFuzzTest") { ] sources = [ "device_manager_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] defines = [ "HI_LOG_ENABLE", diff --git a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn index cdfdec4ac..ea08d678c 100644 --- a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn @@ -56,7 +56,10 @@ ohos_fuzztest("GetTrustedDeviceListServiceFuzzTest") { sources = [ "get_trusted_devicelist_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] external_deps = [ "ability_base:want", diff --git a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn index f923a5610..51f7c3fcb 100644 --- a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn @@ -56,7 +56,10 @@ ohos_fuzztest("ShiftLNNGearDeviceServiceFuzzTest") { sources = [ "shift_lnn_gear_device_service_fuzzer.cpp" ] - deps = [ "${devicemanager_path}/services/service:devicemanagerservice" ] + deps = [ + "${devicemanager_path}/services/service:devicemanagerservice", + "${utils_path}:devicemanagerutils", + ] external_deps = [ "ability_base:want", diff --git a/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn b/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn index 39dfc216e..6ee9bd3af 100644 --- a/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/onbytesreceived_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("OnBytesReceivedFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn index 5ba188f1d..2b3a6c249 100644 --- a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("OnSessionOpenedFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn index 0bc227f7d..eec0bda09 100644 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn @@ -49,6 +49,7 @@ ohos_fuzztest("SoftbusAdapterObjectFuzzTest") { "${innerkits_path}/native_cpp:devicemanagersdk", "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "safwk:system_ability_fwk" ] diff --git a/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn index 269c1656a..8228ac0c6 100644 --- a/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn @@ -45,7 +45,9 @@ ohos_fuzztest("SoftbusConnectorRegisterFuzzTest") { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", + "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "safwk:system_ability_fwk" ] diff --git a/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn b/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn index 96ffb16b6..359a1beb9 100644 --- a/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbussessionobject_fuzzer/BUILD.gn @@ -46,7 +46,9 @@ ohos_fuzztest("SoftbusSessionObjectFuzzTest") { deps = [ "${innerkits_path}/native_cpp:devicemanagersdk", + "${services_path}:devicemanagerservice", "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", ] external_deps = [ "safwk:system_ability_fwk" ] diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 45f12c768..9e13f5547 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1037,28 +1037,28 @@ HWTEST_F(DeviceManagerServiceTest, CheckApiPermission_001, testing::ext::TestSiz } /** - * @tc.name: RegisterDeviceManagerListener_001 + * @tc.name: RegisterCallerAppId_001 * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, RegisterCallerAppId_001, testing::ext::TestSize.Level0) { std::string pkgName; - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); - EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } /** - * @tc.name: RegisterDeviceManagerListener_002 + * @tc.name: RegisterCallerAppId_002 * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, RegisterCallerAppId_002, testing::ext::TestSize.Level0) { std::string pkgName; DeviceManagerService::GetInstance().listener_ = nullptr; - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); - EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } /** @@ -1066,11 +1066,11 @@ HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_002, testing::e * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, UnRegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, UnRegisterCallerAppId_001, testing::ext::TestSize.Level0) { std::string pkgName; - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); - EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } /** @@ -1078,12 +1078,12 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterDeviceManagerListener_001, testing: * @tc.desc: Set pkgName null * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, UnRegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, UnRegisterCallerAppId_002, testing::ext::TestSize.Level0) { std::string pkgName; DeviceManagerService::GetInstance().listener_ = nullptr; - DeviceManagerService::GetInstance().UnRegisterDeviceManagerListener(pkgName); - EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); + DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); + EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_004, testing::ext::TestSize.Level0) diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index fd0236720..f082355c3 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -63,7 +63,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext .deviceTypeId = 1, }; listener_->OnDeviceStateChange(pkgName, state, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -84,7 +84,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext .deviceTypeId = 1, }; listener_->OnDeviceStateChange(pkgName, state, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -102,7 +102,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestS int32_t status = 3; int32_t reason = 2006; listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -120,7 +120,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestS int32_t status = 8; int32_t reason = 2006; listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -138,7 +138,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_003, testing::ext::TestS int32_t status = -1; int32_t reason = 2006; listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -159,7 +159,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_001, testing::ext::Test }; uint16_t subscribeId = 1; listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -176,7 +176,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoveryFailed_001, testing::ext:: uint16_t subscribeId = 1; int32_t failedReason = 1; listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -191,7 +191,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoverySuccess_001, testing::ext: std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; listener_->OnDiscoverySuccess(pkgName, subscribeId); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -208,7 +208,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_001, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 1; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -224,7 +224,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_002, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 0; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -239,7 +239,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnUiCall_001, testing::ext::TestSize. std::string pkgName = "com.ohos.helloworld"; std::string paramJson = "ahaha"; listener_->OnUiCall(pkgName, paramJson); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -254,7 +254,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: int32_t action = 1; std::string resultInfo = "resultInfo"; listener_->OnCredentialResult(pkgName, action, resultInfo); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -271,7 +271,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestS int32_t status = 1; std::string content = "content"; listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -288,7 +288,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestS int32_t status = 8; std::string content = "content"; listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -305,7 +305,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestS int32_t status = -1; std::string content = "content"; listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -321,7 +321,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnUnbindResult_001, testing::ext::Tes int32_t result = 0; std::string content = "content"; listener_->OnUnbindResult(pkgName, targetId, result, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -355,150 +355,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_002, testing::ext::Test uint16_t subscribeId = 1; DmDeviceBasicInfo info; listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); -} - -/** - * @tc.name: RegisterDmListener_001 - * @tc.desc: RegisterDmListener, construct a dummy listener, pass in pkgName, appId - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, RegisterDmListener_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string appId = "appId"; - listener_->RegisterDmListener(pkgName, appId); - EXPECT_EQ(listener_->dmListenerMap_[pkgName], "appId"); -} - -/** - * @tc.name: UnRegisterDmListener_001 - * @tc.desc: UnRegisterDmListener, construct a dummy listener, pass in pkgName - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, UnRegisterDmListener_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - listener_->dmListenerMap_[pkgName] = "appId"; - listener_->UnRegisterDmListener(pkgName); - EXPECT_EQ(listener_->dmListenerMap_.find(pkgName), listener_->dmListenerMap_.end()); -} - -/** - * @tc.name: GetAppId_001 - * @tc.desc: GetAppId, construct a dummy listener, pass in pkgName - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetAppId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string str = listener_->GetAppId(pkgName); - EXPECT_EQ(str.empty(), true); -} - -/** - * @tc.name: SetUdidHashMap_001 - * @tc.desc: SetUdidHashMap, construct a dummy listener, pass in udidHash - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, SetUdidHashMap_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string udidHash; - std::string deviceId; - std::string pkgName = "com.ohos.helloworld"; - listener_->SetUdidHashMap(udidHash, deviceId, pkgName); - EXPECT_EQ(listener_->udidHashMap_.empty(), false); -} - -/** - * @tc.name: DeleteDeviceIdFromMap_001 - * @tc.desc: DeleteDeviceIdFromMap, construct a dummy listener, pass in deviceId - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, DeleteDeviceIdFromMap_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string deviceId; - std::string pkgName = "com.ohos.helloworld"; - listener_->DeleteDeviceIdFromMap(deviceId, pkgName); - EXPECT_EQ(listener_->udidHashMap_.empty(), false); -} - -/** - * @tc.name: GetDeviceId_001 - * @tc.desc: GetDeviceId, construct a dummy listener, pass in udidHash - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string udidHash; - std::string pkgName = "com.ohos.helloworld"; - std::string str = listener_->GetDeviceId(udidHash, pkgName); - EXPECT_EQ(str.empty(), true); -} - -/** - * @tc.name: GetDeviceId_002 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_002, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string udidHash = "123445676788908"; - std::string deviceId = "123"; - listener_->udidHashMap_[pkgName][deviceId] = udidHash; - std::string str = listener_->GetDeviceId(udidHash, pkgName); - EXPECT_EQ(str, deviceId); -} - -/** - * @tc.name: GetDeviceId_003 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetDeviceId_003, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string udidHash = "123445676788908"; - std::string udidHash2 = "123445676788909"; - std::string deviceId = "123"; - listener_->udidHashMap_[pkgName][deviceId] = udidHash; - std::string str = listener_->GetDeviceId(udidHash2, pkgName); - EXPECT_EQ(str, ""); -} - -/** - * @tc.name: GetUdidHash_001 - * @tc.desc: GetUdidHash, construct a dummy listener, pass in deviceId - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, GetUdidHash_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string deviceId; - std::string pkgName = "com.ohos.helloworld"; - std::string str = listener_->GetUdidHash(deviceId, pkgName); - EXPECT_EQ(str.empty(), true); -} - -/** - * @tc.name: CalcDeviceId_001 - * @tc.desc: CalcDeviceId, construct a dummy listener, pass in pkgName - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, CalcDeviceId_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName; - std::string udidHash; - std::string str = listener_->CalcDeviceId(pkgName, udidHash); - EXPECT_EQ(str.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -514,7 +371,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext:: DmPinType pinType = static_cast(1); std::string payload = "payload"; listener_->OnPinHolderCreate(pkgName, deviceId, pinType, payload); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -529,7 +386,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext: DmPinType pinType = static_cast(1); std::string payload = "payload"; listener_->OnPinHolderDestroy(pkgName, pinType, payload); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -543,7 +400,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::Tes std::string pkgName = "com.ohos.helloworld"; int32_t result = 0; listener_->OnCreateResult(pkgName, result); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -557,7 +414,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::Te std::string pkgName = "com.ohos.helloworld"; int32_t result = 0; listener_->OnDestroyResult(pkgName, result); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } /** @@ -573,21 +430,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::T int32_t result = 0; std::string content = "content"; listener_->OnPinHolderEvent(pkgName, event, result, content); - EXPECT_EQ(listener_->dmListenerMap_.empty(), true); -} - -/** - * @tc.name: ComposeOnlineKey_001 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceListenerTest, ComposeOnlineKey_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string str1 = "hello"; - std::string str2 = "world"; - std::string str = listener_->ComposeOnlineKey(str1, str2); - EXPECT_EQ(str, str1 + "_" + str2); + EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 3a5d354c5..20a725e98 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -51,14 +51,14 @@ void DeletePermission() } /** - * @tc.name: RegisterDeviceManagerListener_001 + * @tc.name: RegisterCallerAppId_201 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterDeviceManagerListener_201, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, RegisterCallerAppId_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; DeviceManagerService::GetInstance().listener_ = std::make_shared(); - DeviceManagerService::GetInstance().RegisterDeviceManagerListener(pkgName); + DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); EXPECT_EQ(DeviceManagerService::GetInstance().listener_ != nullptr, true); } diff --git a/utils/BUILD.gn b/utils/BUILD.gn index da08bdd68..07fd22f58 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-2024 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at @@ -73,6 +73,7 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "include/crypto", + "include/kvadapter", "include/threadManager", "include/fwkload/standard", "include/appInfo/standard", @@ -95,9 +96,12 @@ if (defined(ohos_lite)) { } sources = [ + "${common_path}/src/dm_anonymous.cpp", "src/appInfo/standard/app_manager.cpp", "src/crypto/dm_crypto.cpp", "src/dm_random.cpp", + "src/kvadapter/kv_adapter.cpp", + "src/kvadapter/kv_adapter_manager.cpp", "src/threadManager/dm_thread_manager.cpp", "src/timer/dm_timer.cpp", ] @@ -118,6 +122,7 @@ if (defined(ohos_lite)) { "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "cJSON:cjson", "c_utils:utils", "eventhandler:libeventhandler", "ffrt:libffrt", @@ -128,7 +133,10 @@ if (defined(ohos_lite)) { "samgr:samgr_proxy", ] - public_external_deps = [ "json:nlohmann_json_static" ] + public_external_deps = [ + "json:nlohmann_json_static", + "kv_store:distributeddata_inner", + ] if (support_jsapi) { external_deps += [ "bundle_framework:appexecfwk_core" ] diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index 25e513700..d5fef1751 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -26,6 +26,9 @@ class AppManager { public: const std::string GetAppId(); + void RegisterCallerAppId(const std::string &pkgName); + void UnRegisterCallerAppId(const std::string &pkgName); + int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 68feab27a..3671f0d74 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -16,6 +16,8 @@ #ifndef OHOS_DM_APP_MANAGER_H #define OHOS_DM_APP_MANAGER_H +#include +#include #include #include "dm_single_instance.h" @@ -26,6 +28,12 @@ class AppManager { public: const std::string GetAppId(); + void RegisterCallerAppId(const std::string &pkgName); + void UnRegisterCallerAppId(const std::string &pkgName); + int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); +private: + std::mutex appIdMapLock_; + std::map appIdMap_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/kvadapter/kv_adapter.h b/utils/include/kvadapter/kv_adapter.h new file mode 100644 index 000000000..055bfa644 --- /dev/null +++ b/utils/include/kvadapter/kv_adapter.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_KV_ADAPTER_H +#define OHOS_DM_KV_ADAPTER_H + +#include +#include +#include +#include +#include +#include +#include + +#include "distributed_kv_data_manager.h" +#include "kvstore_death_recipient.h" +#include "kvstore_observer.h" + +namespace OHOS { +namespace DistributedHardware { +typedef struct DmKVValue { + std::string udidHash; + std::string appID; + std::string udid; + int64_t lastModifyTime; + explicit DmKVValue() : udidHash(""), appID(""), udid(""), lastModifyTime(0) {} +} DmKVValue; +void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result); +void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue); +class KVAdapter : public DistributedKv::KvStoreDeathRecipient, public std::enable_shared_from_this { +public: + KVAdapter() = default; + virtual ~KVAdapter() = default; + int32_t Init(); + void UnInit(); + int32_t ReInit(); + int32_t Put(const std::string& key, const std::string& value); + int32_t Get(const std::string& key, std::string& value); + + void OnRemoteDied() override; + +private: + DistributedKv::Status GetLocalKvStorePtr(); + void RegisterKvStoreDeathListener(); + void UnregisterKvStoreDeathListener(); + +private: + DistributedKv::AppId appId_; + DistributedKv::StoreId storeId_; + DistributedKv::DistributedKvDataManager kvDataMgr_; + DistributedKv::DataType dataType_ = DistributedKv::DataType::TYPE_STATICS; + std::shared_ptr kvStorePtr_ = nullptr; + std::mutex kvAdapterMutex_; + std::atomic isInited_ = false; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_KV_ADAPTER_H diff --git a/utils/include/kvadapter/kv_adapter_manager.h b/utils/include/kvadapter/kv_adapter_manager.h new file mode 100644 index 000000000..aec0bd5da --- /dev/null +++ b/utils/include/kvadapter/kv_adapter_manager.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_KV_ADAPTER_MANAGER_H +#define OHOS_DM_KV_ADAPTER_MANAGER_H + +#include +#include +#include +#include + +#include "dm_single_instance.h" + +#include "kv_adapter.h" + +namespace OHOS { +namespace DistributedHardware { + +class KVAdapterManager { + DM_DECLARE_SINGLE_INSTANCE_BASE(KVAdapterManager); +public: + int32_t Init(); + void UnInit(); + void ReInit(); + int32_t Put(const std::string& key, const DmKVValue& value); + int32_t Get(const std::string& key, DmKVValue& value); + int32_t DeleteAgedEntry(); + +private: + KVAdapterManager() = default; + ~KVAdapterManager() = default; + inline bool IsTimeOut(int64_t sourceTime, int64_t targetTime, int64_t timeOut); + inline std::string AddPrefix(const std::string& key); + +private: + std::shared_ptr deathRecipient_ = nullptr; + std::shared_ptr kvAdapter_ = nullptr; + std::mutex idCacheMapMtx_; + std::map> idCacheMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_KV_ADAPTER_MANAGER_H diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index 4882c3193..72a9ac465 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -14,6 +14,7 @@ */ #include "app_manager.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { @@ -23,5 +24,22 @@ const std::string AppManager::GetAppId() { return ""; } + +void AppManager::RegisterCallerAppId(const std::string &pkgName) +{ + (void)pkgName; +} + +void AppManager::UnRegisterCallerAppId(const std::string &pkgName) +{ + (void)pkgName; +} + +int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &appId) +{ + (void)pkgName; + (void)appId; + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 188f2fc3e..951e8e5ae 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -15,6 +15,9 @@ #include "app_manager.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" #include "accesstoken_kit.h" #include "ipc_skeleton.h" @@ -26,17 +29,67 @@ DM_IMPLEMENT_SINGLE_INSTANCE(AppManager); const std::string AppManager::GetAppId() { + std::string appId = ""; AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) { - return ""; + LOGE("The caller is not token_hap."); + return appId; } HapTokenInfo tokenInfo; - auto result = AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); + int32_t result = AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); if (result != RET_SUCCESS) { - return ""; + LOGE("GetHapTokenInfo failed ret is %{public}d.", result); + return appId; } + appId = tokenInfo.appID; + return appId; +} + +void AppManager::RegisterCallerAppId(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::string appId = GetAppId(); + if (appId.empty()) { + LOGE("PkgName %{public}s get appid failed.", pkgName.c_str()); + return; + } + LOGI("PkgName %{public}s, appId %{public}s.", pkgName.c_str(), GetAnonyString(appId).c_str()); + std::lock_guard lock(appIdMapLock_); + appIdMap_[pkgName] = appId; +} + +void AppManager::UnRegisterCallerAppId(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + LOGI("PkgName %{public}s.", pkgName.c_str()); + std::lock_guard lock(appIdMapLock_); + if (appIdMap_.find(pkgName) == appIdMap_.end()) { + LOGE("AppIdMap not find pkgName."); + return; + } + appIdMap_.erase(pkgName); +} - return tokenInfo.appID; +int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &appId) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("PkgName %{public}s.", pkgName.c_str()); + std::lock_guard lock(appIdMapLock_); + if (appIdMap_.find(pkgName) == appIdMap_.end()) { + LOGE("AppIdMap not find pkgName."); + return ERR_DM_FAILED; + } + appId = appIdMap_[pkgName]; + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/kvadapter/kv_adapter.cpp b/utils/src/kvadapter/kv_adapter.cpp new file mode 100644 index 000000000..2ee487fb9 --- /dev/null +++ b/utils/src/kvadapter/kv_adapter.cpp @@ -0,0 +1,207 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "kv_adapter.h" + +#include +#include +#include + +#include "cJSON.h" +#include "datetime_ex.h" +#include "string_ex.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_thread_manager.h" + +namespace OHOS { +namespace DistributedHardware { +using namespace OHOS::DistributedKv; +namespace { + const std::string APP_ID = "distributed_device_manager_service"; + const std::string STORE_ID = "dm_kv_store"; + const std::string DATABASE_DIR = "/data/service/el1/public/database/distributed_device_manager_service"; + const std::string KV_REINIT_THREAD = "reinit_kv_store"; + const std::string UDID_HASH_KEY = "udidHash"; + const std::string APP_ID_KEY = "appID"; + const std::string UDID_ID_KEY = "udid"; + const std::string LAST_MODIFY_TIME_KEY = "lastModifyTime"; + constexpr uint32_t MAX_BATCH_SIZE = 128; + constexpr int32_t MAX_DEVICE_ITEM_SIZE = 1000; + constexpr int32_t MAX_STRING_LEN = 4096; + constexpr int32_t MAX_INIT_RETRY_TIMES = 20; + constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms +} + +void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) +{ + nlohmann::json jsonObj; + jsonObj[UDID_HASH_KEY] = kvValue.udidHash; + jsonObj[APP_ID_KEY] = kvValue.appID; + jsonObj[UDID_ID_KEY] = kvValue.udid; + jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; + result = jsonObj.dump(); +} + +void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) +{ + if (result.empty()) { + return; + } + nlohmann::json resultJson = nlohmann::json::parse(result, nullptr, false); + if (resultJson.is_discarded()) { + return; + } + if (IsString(resultJson, UDID_HASH_KEY)) { + kvValue.udidHash = resultJson[UDID_HASH_KEY].get(); + } + if (IsString(resultJson, APP_ID_KEY)) { + kvValue.appID = resultJson[APP_ID_KEY].get(); + } + if (IsString(resultJson, UDID_ID_KEY)) { + kvValue.udid = resultJson[UDID_ID_KEY].get(); + } + if (IsString(resultJson, LAST_MODIFY_TIME_KEY)) { + kvValue.lastModifyTime = resultJson[LAST_MODIFY_TIME_KEY].get(); + } +} + +int32_t KVAdapter::Init() +{ + LOGI("Init local DB, dataType: %{public}d", static_cast(dataType_)); + if (isInited_.load()) { + LOGI("Local DB already inited."); + return DM_OK; + } + this->appId_.appId = APP_ID; + this->storeId_.storeId = STORE_ID; + std::lock_guard lock(kvAdapterMutex_); + int32_t tryTimes = MAX_INIT_RETRY_TIMES; + while (tryTimes > 0) { + DistributedKv::Status status = GetLocalKvStorePtr(); + if (status == DistributedKv::Status::SUCCESS && kvStorePtr_) { + LOGI("Init KvStorePtr Success"); + RegisterKvStoreDeathListener(); + isInited_.store(true); + return DM_OK; + } + LOGD("CheckKvStore, left times: %{public}d", tryTimes); + usleep(INIT_RETRY_SLEEP_INTERVAL); + tryTimes--; + } + CHECK_NULL_RETURN(kvStorePtr_, ERR_DM_INIT_FAILED); + isInited_.store(true); + return DM_OK; +} + +void KVAdapter::UnInit() +{ + LOGI("KVAdapter Uninted"); + if (isInited_.load()) { + std::lock_guard lock(kvAdapterMutex_); + CHECK_NULL_VOID(kvStorePtr_); + UnregisterKvStoreDeathListener(); + kvStorePtr_.reset(); + isInited_.store(false); + } +} + +int32_t KVAdapter::ReInit() +{ + LOGI("KVAdapter ReInit"); + UnInit(); + return Init(); +} + +int32_t KVAdapter::Put(const std::string& key, const std::string& value) +{ + if (key.empty() || key.size() > MAX_STRING_LEN || value.empty() || value.size() > MAX_STRING_LEN) { + LOGE("Param is invalid!"); + return ERR_DM_FAILED; + } + DistributedKv::Status status; + { + std::lock_guard lock(kvAdapterMutex_); + CHECK_NULL_RETURN(kvStorePtr_, ERR_DM_POINT_NULL); + + DistributedKv::Key kvKey(key); + DistributedKv::Value kvValue(value); + status = kvStorePtr_->Put(kvKey, kvValue); + } + if (status != DistributedKv::Status::SUCCESS) { + LOGE("Put kv to db failed, ret: %{public}d", status); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t KVAdapter::Get(const std::string& key, std::string& value) +{ + LOGI("Get data by key: %{public}s", GetAnonyString(key).c_str()); + DistributedKv::Key kvKey(key); + DistributedKv::Value kvValue; + DistributedKv::Status status; + { + std::lock_guard lock(kvAdapterMutex_); + CHECK_NULL_RETURN(kvStorePtr_, ERR_DM_POINT_NULL); + status = kvStorePtr_->Get(kvKey, kvValue); + } + if (status != DistributedKv::Status::SUCCESS) { + LOGE("Get data from kv failed, key: %{public}s", GetAnonyString(key).c_str()); + return ERR_DM_FAILED; + } + value = kvValue.ToString(); + return DM_OK; +} + +void KVAdapter::OnRemoteDied() +{ + LOGI("OnRemoteDied, recover db begin"); + auto reInitTask = [this]() { + LOGI("ReInit, storeId:%{public}s", storeId_.storeId.c_str()); + ReInit(); + }; + ThreadManager::GetInstance().Submit(KV_REINIT_THREAD.c_str(), reInitTask); +} + +DistributedKv::Status KVAdapter::GetLocalKvStorePtr() +{ + DistributedKv::Options options = { + .createIfMissing = true, + .encrypt = false, + .autoSync = false, + .securityLevel = DistributedKv::SecurityLevel::S1, + .area = DistributedKv::EL1, + .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION, + .baseDir = DATABASE_DIR + }; + DistributedKv::Status status = kvDataMgr_.GetSingleKvStore(options, appId_, storeId_, kvStorePtr_); + return status; +} + +void KVAdapter::RegisterKvStoreDeathListener() +{ + LOGI("Register syncCompleted listener"); + kvDataMgr_.RegisterKvStoreServiceDeathRecipient(shared_from_this()); +} + +void KVAdapter::UnregisterKvStoreDeathListener() +{ + LOGI("UnRegister death listener"); + kvDataMgr_.UnRegisterKvStoreServiceDeathRecipient(shared_from_this()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/src/kvadapter/kv_adapter_manager.cpp b/utils/src/kvadapter/kv_adapter_manager.cpp new file mode 100644 index 000000000..75b9d02a8 --- /dev/null +++ b/utils/src/kvadapter/kv_adapter_manager.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "kv_adapter_manager.h" + +#include +#include + +#include "datetime_ex.h" +#include "string_ex.h" + +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const std::string DM_KV_STORE_PREFIX = "DM_"; +constexpr int64_t DM_KV_STORE_REFRESH_TIME = 24 * 60 * 60; // one day +constexpr int64_t MAX_SUPPORTED_EXIST_TIME = 3 * 24 * 60 * 60; // 3days +} + +DM_IMPLEMENT_SINGLE_INSTANCE(KVAdapterManager); + +int32_t KVAdapterManager::Init() +{ + LOGI("Init Kv-Adapter manager"); + { + std::lock_guard lock(idCacheMapMtx_); + idCacheMap_.clear(); + } + kvAdapter_ = std::make_shared(); + return kvAdapter_->Init(); +} + +void KVAdapterManager::UnInit() +{ + LOGI("Uninit Kv-Adapter manager"); + CHECK_NULL_VOID(kvAdapter_); + kvAdapter_->UnInit(); + kvAdapter_ = nullptr; +} + +void KVAdapterManager::ReInit() +{ + LOGI("Re init kv adapter"); + CHECK_NULL_VOID(kvAdapter_); + kvAdapter_->ReInit(); +} + +int32_t KVAdapterManager::Put(const std::string& key, const DmKVValue& value) +{ + std::string dmKey = AddPrefix(key); + std::lock_guard lock(idCacheMapMtx_); + auto idIter = idCacheMap_.find(dmKey); + if (idIter != idCacheMap_.end() && !IsTimeOut(idIter->second.second, value.lastModifyTime, + DM_KV_STORE_REFRESH_TIME)) { + LOGD("Kv value is existed"); + return DM_OK; + } + std::string valueStr = ""; + ConvertDmKVValueToJson(value, valueStr); + idCacheMap_[dmKey].first = value.udidHash; + idCacheMap_[dmKey].second = value.lastModifyTime; + CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); + if (kvAdapter_->Put(dmKey, valueStr) != DM_OK) { + LOGE("Insert value to DB failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t KVAdapterManager::Get(const std::string& key, DmKVValue& value) +{ + std::string dmKey = AddPrefix(key); + std::lock_guard lock(idCacheMapMtx_); + auto idIter = idCacheMap_.find(dmKey); + if (idIter != idCacheMap_.end()) { + value.udidHash = idIter->second.first; + value.lastModifyTime = idIter->second.second; + return DM_OK; + } + CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); + std::string valueStr; + if (kvAdapter_->Get(dmKey, valueStr) != DM_OK) { + LOGE("Get kv value failed, dmKey: %{public}s", GetAnonyString(dmKey).c_str()); + return ERR_DM_FAILED; + } + ConvertJsonToDmKVValue(valueStr, value); + idCacheMap_[dmKey].first = value.udidHash; + idCacheMap_[dmKey].second = value.lastModifyTime; + return DM_OK; +} + +int32_t KVAdapterManager::DeleteAgedEntry() +{ + int64_t nowTime = GetSecondsSince1970ToNow(); + std::lock_guard lock(idCacheMapMtx_); + for (auto it = idCacheMap_.begin(); it != idCacheMap_.end();) { + if (IsTimeOut(it->second.second, nowTime, MAX_SUPPORTED_EXIST_TIME)) { + it = idCacheMap_.erase(it); + } else { + ++it; + } + } + return DM_OK; +} + +inline bool KVAdapterManager::IsTimeOut(int64_t sourceTime, int64_t targetTime, int64_t timeOut) +{ + return targetTime - sourceTime >= timeOut ? true : false; +} + +inline std::string KVAdapterManager::AddPrefix(const std::string& key) +{ + return DM_KV_STORE_PREFIX + key; +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From b28e298a183bddcd30cc158624f99e0710a360bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 28 Aug 2024 09:24:27 +0800 Subject: [PATCH 109/520] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E5=B1=8F=E8=94=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 19e4f0b30..542c4ccc2 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -755,13 +755,11 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ int32_t SoftbusListener::SetDnPolicy(int32_t policy, int32_t timeOut) { - /* int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); if (ret != DM_OK) { LOGE("[SOFTBUS]CtrlLNNBleHb failed."); return ret; } - */ LOGI("CtrlLNNBleHb complete policy: %{public}d, timeOut: %{public}d.", policy, timeOut); return DM_OK; } -- Gitee From c3fc3d45279a2caaf584e4a57e3760eef9dd6565 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 28 Aug 2024 09:30:22 +0800 Subject: [PATCH 110/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index d9a3d6559..0693d3e7c 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1666,6 +1666,7 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapSetDnPolicy(policyStrategy, timeOut); } + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void DeviceManagerService::ConvertUdidHashToAnoy(DmDeviceInfo &deviceInfo) { -- Gitee From d27d88139993fc83e0030aea538da5067d0d9214 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=98=BF=E5=AE=85?= Date: Wed, 28 Aug 2024 16:18:53 +0800 Subject: [PATCH 111/520] =?UTF-8?q?feat(HiCar):=20HiCar=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=9D=83=E9=99=90=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 小阿宅 --- sa_profile/device_manager.cfg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sa_profile/device_manager.cfg b/sa_profile/device_manager.cfg index c49440846..0550cd7b9 100644 --- a/sa_profile/device_manager.cfg +++ b/sa_profile/device_manager.cfg @@ -34,7 +34,8 @@ "ohos.permission.GET_BUNDLE_RESOURCES", "ohos.permission.GET_WIFI_INFO", "ohos.permission.SET_TIME", - "ohos.permission.SET_TIME_ZONE" + "ohos.permission.SET_TIME_ZONE", + "ohos.permission.ALLOW_CONNECT_CAR" ], "jobs" : { "on-start" : "service:device_manager" -- Gitee From 05201ae9ad5785ed326cdd1be9bb486a6d3a541a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E9=98=BF=E5=AE=85?= Date: Wed, 28 Aug 2024 16:24:44 +0800 Subject: [PATCH 112/520] =?UTF-8?q?fix(kv=5Fadapter):=20=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E4=BA=86=E6=B2=A1=E6=9C=89=E4=BD=BF=E7=94=A8=E7=9A=84=E5=B8=B8?= =?UTF-8?q?=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MAX_BATCH_SIZE and MAX_DEVICE_ITEM_SIZE Signed-off-by: 小阿宅 --- utils/src/kvadapter/kv_adapter.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/utils/src/kvadapter/kv_adapter.cpp b/utils/src/kvadapter/kv_adapter.cpp index 2ee487fb9..2082afa97 100644 --- a/utils/src/kvadapter/kv_adapter.cpp +++ b/utils/src/kvadapter/kv_adapter.cpp @@ -39,8 +39,6 @@ namespace { const std::string APP_ID_KEY = "appID"; const std::string UDID_ID_KEY = "udid"; const std::string LAST_MODIFY_TIME_KEY = "lastModifyTime"; - constexpr uint32_t MAX_BATCH_SIZE = 128; - constexpr int32_t MAX_DEVICE_ITEM_SIZE = 1000; constexpr int32_t MAX_STRING_LEN = 4096; constexpr int32_t MAX_INIT_RETRY_TIMES = 20; constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms -- Gitee From bd8da598fdd7791745c5b53fd1f431b072dbc95a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 28 Aug 2024 19:32:31 +0800 Subject: [PATCH 113/520] =?UTF-8?q?=E6=89=93=E6=A1=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 542c4ccc2..baa6d1fbd 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -755,11 +755,11 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ int32_t SoftbusListener::SetDnPolicy(int32_t policy, int32_t timeOut) { - int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); + /* int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); if (ret != DM_OK) { LOGE("[SOFTBUS]CtrlLNNBleHb failed."); return ret; - } + } */ LOGI("CtrlLNNBleHb complete policy: %{public}d, timeOut: %{public}d.", policy, timeOut); return DM_OK; } -- Gitee From e8beb1a044e1139859f25d7ac4d70858cee8b150 Mon Sep 17 00:00:00 2001 From: Bobie Date: Wed, 28 Aug 2024 20:54:44 +0800 Subject: [PATCH 114/520] add template Signed-off-by: Bobie --- .gitee/PULL_REQUEST_TEMPLATE.zh-CN.md | 51 +++++++++++++-------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index b2dcb1881..7a44a95c9 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -3,32 +3,31 @@ **描述**: **安全及低级编码自检:** -| 自检项 | 自检结果 | -| ------------------------------------------------------------------------------- | -------- | -| 变量使用前保证赋有效初值 | | -| 结构体预留字段也必须初始化为0,不允许出现随机值 | | -| 指针变量必须显示初始化为空 | | -| 涉及内存拷贝时合理校验目标内存大小,保证目标内存大于等于源内存 | | -| 进行字符串操作时,如字符串复制、申请字符串内存等,需要考虑字符串结束符 | | -| cJSON指针在异常分支里均需考虑内存释放(cJSON_free/cJSON_Delete),防止内存泄漏 | | -| 内存资源、文件句柄、管道资源、Socket句柄异常退出时要及时关闭 | | -| malloc申请内存后必须判断是否为空 | | -| 指针解引用或释放前判空(lamda表达式,异步任务等使用指针前需判空) | | -| 内存释放后立即置空,防止出现UAF | | -| 循环时容器的增、删、改操作,必须保证迭代器有效 | | -| 禁止将栈内存地址作为返回值或赋值给全局变量 | | -| 加法、乘法、减法操作,必须进行溢出和翻转保护,确保先校验再运算 | | -| 除法、求余操作必须进行除零保护 | | -| 循环变量用整型,禁止使用浮点型 | | -| 循环退出条件一定确保可达,防止出现死循环等问题 | | -| 不同大小结构体禁止强转 | | -| 禁止使用非安全函数,使用封装好的安全函数 | | -| 日志必须检查PassWord/位置信息/networkId/devId/uuid/udid等关键字,避免明文打印敏感信息 | | -| 对函数入参坚持先校验后使用的原则(指针判空、整型变量校验范围) | | -| 跨进程调用需注意权限校验,对外部传入的PID、tokenID进行权限校验 | | -| 共享数据均需加锁保护,并且锁配对使用 | | -| 条件变量正确加锁,消除条件变量唤醒丢失等问题 | | -| 加锁范围确保合理,避免过大或过小导致死锁问题 | | + +- [ ] 【变量初始化】变量使用前保证赋有效初值 +- [ ] 【变量初始化】结构体预留字段也必须初始化为0,不允许出现随机值 +- [ ] 【变量初始化】指针变量必须显示初始化为空 +- [ ] 【内存和资源】涉及内存拷贝时合理校验目标内存大小,保证目标内存大于等于源内存 +- [ ] 【内存和资源】进行字符串操作时,如字符串复制、申请字符串内存等,需要考虑字符串结束符 +- [ ] 【内存和资源】cJSON指针在异常分支里均需考虑内存释放(cJSON_free/cJSON_Delete),防止内存泄漏 +- [ ] 【内存和资源】内存资源、文件句柄、管道资源、Socket句柄异常退出时要及时关闭 +- [ ] 【指针】malloc申请内存后必须判断是否为空 +- [ ] 【指针】指针解引用或释放前判空(lamda表达式,异步任务等使用指针前需判空) +- [ ] 【指针】内存释放后立即置空,防止出现UAF +- [ ] 【指针】循环时容器的增、删、改操作,必须保证迭代器有效 +- [ ] 【指针】禁止将栈内存地址作为返回值或赋值给全局变量 +- [ ] 【数值边界】加法、乘法、减法操作,必须进行溢出和翻转保护,确保先校验再运算 +- [ ] 【数值边界】除法、求余操作必须进行除零保护 +- [ ] 【数值边界】循环变量用整型,禁止使用浮点型 +- [ ] 【数值边界】循环退出条件一定确保可达,防止出现死循环等问题 +- [ ] 【数值边界】不同大小结构体禁止强转 +- [ ] 【安全隐私】禁止使用非安全函数,使用封装好的安全函数 +- [ ] 【安全隐私】日志必须检查PassWord/位置信息/networkId/devId/uuid/udid等关键字,避免明文打印敏感信息 +- [ ] 【入参及权限校验】对函数入参坚持先校验后使用的原则(指针判空、整型变量校验范围) +- [ ] 【入参及权限校验】跨进程调用需注意权限校验,对外部传入的PID、tokenID进行权限校验 +- [ ] 【条件竞争】共享数据均需加锁保护,并且锁配对使用 +- [ ] 【条件竞争】条件变量正确加锁,消除条件变量唤醒丢失等问题 +- [ ] 【条件竞争】加锁范围确保合理,避免过大或过小导致死锁问题 **TDD结果**: -- Gitee From a305da56dfce802425466630cd1c70d5a6cea007 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Thu, 29 Aug 2024 11:46:41 +0800 Subject: [PATCH 115/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9log=E7=BA=A7=E5=88=AB?= =?UTF-8?q?=EF=BC=8C=E5=87=8F=E5=B0=91log=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp | 4 ++-- .../native_cpp/src/notify/device_manager_notify.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index e0b8f1bf9..5ab6d2fa6 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -196,7 +196,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("Start, pkgName: %{public}s, extra: %{public}s", GetAnonyString(pkgName).c_str(), extra.c_str()); + LOGD("Start, pkgName: %{public}s, extra: %{public}s", GetAnonyString(pkgName).c_str(), extra.c_str()); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -226,7 +226,7 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("Start, pkgName: %{public}s, extra: %{public}s, isRefresh: %{public}d", GetAnonyString(pkgName).c_str(), + LOGD("Start, pkgName: %{public}s, extra: %{public}s, isRefresh: %{public}d", GetAnonyString(pkgName).c_str(), extra.c_str(), isRefresh); std::shared_ptr req = std::make_shared(); 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 5da56c942..3c8bdc38b 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 @@ -576,7 +576,7 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGI("Complete with devInfo, pkgName:%{public}s, subscribeId:%{public}d.", + LOGD("Complete with devInfo, pkgName:%{public}s, subscribeId:%{public}d.", GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceInfo); } -- Gitee From e5ab2e9655eba7ef82e4e0ee656cc88ce717d5d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 29 Aug 2024 14:29:39 +0800 Subject: [PATCH 116/520] =?UTF-8?q?=E6=89=93=E5=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index baa6d1fbd..542c4ccc2 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -755,11 +755,11 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ int32_t SoftbusListener::SetDnPolicy(int32_t policy, int32_t timeOut) { - /* int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); + int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); if (ret != DM_OK) { LOGE("[SOFTBUS]CtrlLNNBleHb failed."); return ret; - } */ + } LOGI("CtrlLNNBleHb complete policy: %{public}d, timeOut: %{public}d.", policy, timeOut); return DM_OK; } -- Gitee From a360f28739810173625c3f321bf96db743f56c47 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Thu, 29 Aug 2024 15:21:59 +0800 Subject: [PATCH 117/520] =?UTF-8?q?=E4=BE=9D=E8=B5=96=E6=95=B4=E6=94=B9?= =?UTF-8?q?=EF=BC=8C=E7=BB=9D=E5=AF=B9=E8=B7=AF=E5=BE=84=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E7=9B=B8=E5=AF=B9=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- test/unittest/BUILD.gn | 101 +++++++++++++++++++++++++++++++++++------ 1 file changed, 88 insertions(+), 13 deletions(-) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index daa2ebe1b..0a0aac456 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -91,6 +91,7 @@ ohos_unittest("UTTest_pin_auth") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -114,6 +115,7 @@ ohos_unittest("UTTest_pin_auth_ui") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -137,6 +139,7 @@ ohos_unittest("UTTest_ipc_cmd_parser_client") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", + "googletest:gmock", ] cflags = [ @@ -168,6 +171,7 @@ ohos_unittest("UTTest_ipc_cmd_parser_service") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", + "googletest:gmock", "hicollie:libhicollie", ] @@ -193,6 +197,7 @@ ohos_unittest("UTTest_ipc_cmd_register") { external_deps = [ "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -216,6 +221,7 @@ ohos_unittest("UTTest_dm_pin_holder") { "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -228,6 +234,8 @@ ohos_unittest("UTTest_ipc_get_device_info_rsp") { sources = [ "UTTest_ipc_get_device_info_rsp.cpp" ] deps = [ ":device_manager_test_common" ] + + external_deps = [ "googletest:gmock" ] } ## UnitTest UTTest_ipc_get_device_info_rsp }}} @@ -242,7 +250,10 @@ ohos_unittest("UTTest_dm_common_event_manager") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_common_event_manager }}} @@ -255,7 +266,10 @@ ohos_unittest("device_manager_impl_test") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest device_manager_impl_test }}} @@ -284,6 +298,7 @@ ohos_unittest("UTTest_dm_credential_manager") { "access_token:libnativetoken", "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", + "googletest:gmock", ] } @@ -307,6 +322,7 @@ ohos_unittest("UTTest_device_manager_service") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -326,6 +342,7 @@ ohos_unittest("UTTest_hichain_auth_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -347,6 +364,7 @@ ohos_unittest("UTTest_hichain_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -366,6 +384,7 @@ ohos_unittest("UTTest_mine_hichain_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -394,6 +413,7 @@ ohos_unittest("UTTest_mine_softbus_listener") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", "openssl:libcrypto_shared", @@ -418,6 +438,7 @@ ohos_unittest("UTTest_softbus_adapter") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -441,6 +462,7 @@ ohos_unittest("UTTest_softbus_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", "os_account:libaccountkits", @@ -470,6 +492,7 @@ ohos_unittest("UTTest_softbus_listener") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -498,6 +521,7 @@ ohos_unittest("UTTest_softbus_publish") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -521,6 +545,7 @@ ohos_unittest("UTTest_softbus_session") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -536,7 +561,10 @@ ohos_unittest("UTTest_dm_adapter_manager") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_adapter_manager }}} @@ -555,7 +583,10 @@ ohos_unittest("UTTest_dm_anonymous") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_anonymous }}} @@ -570,7 +601,10 @@ ohos_unittest("UTTest_dm_timer") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_dm_timer }}} @@ -586,6 +620,7 @@ ohos_unittest("UTTest_ipc_client_manager") { external_deps = [ "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -599,7 +634,10 @@ ohos_unittest("UTTest_ipc_client_proxy") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_ipc_client_proxy }}} @@ -612,7 +650,10 @@ ohos_unittest("UTTest_ipc_client_stub") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_ipc_client_stub }}} @@ -632,6 +673,7 @@ ohos_unittest("UTTest_ipc_server_client_proxy") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hicollie:libhicollie", ] } @@ -646,7 +688,10 @@ ohos_unittest("UTTest_ipc_server_listener") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_ipc_server_listener }}} @@ -663,6 +708,7 @@ ohos_unittest("UTTest_ipc_server_stub") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -686,6 +732,7 @@ ohos_unittest("UTTest_device_manager_impl") { "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -705,6 +752,7 @@ ohos_unittest("UTTest_dm_import_auth_code") { "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -725,6 +773,7 @@ ohos_unittest("UTTest_multiple_user_connector") { external_deps = [ "device_auth:deviceauth_sdk", + "googletest:gmock", "os_account:libaccountkits", "os_account:os_account_innerkits", ] @@ -749,6 +798,7 @@ ohos_unittest("UTTest_permission_manager") { "access_token:libnativetoken", "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", + "googletest:gmock", ] } @@ -769,6 +819,7 @@ ohos_unittest("UTTest_device_manager_notify") { external_deps = [ "device_auth:deviceauth_sdk", "ffrt:libffrt", + "googletest:gmock", ] } @@ -782,7 +833,10 @@ ohos_unittest("UTTest_ipc_client_server_proxy") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest UTTest_ipc_client_server_proxy }}} @@ -799,6 +853,7 @@ ohos_unittest("UTTest_dm_device_state_manager") { external_deps = [ "device_auth:deviceauth_sdk", + "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", ] @@ -818,6 +873,7 @@ ohos_unittest("UTTest_dm_dfx") { external_deps = [ "device_auth:deviceauth_sdk", + "googletest:gmock", "hitrace:hitrace_meter", ] } @@ -840,6 +896,7 @@ ohos_unittest("UTTest_dm_discovery_filter") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -861,6 +918,7 @@ ohos_unittest("UTTest_device_manager_service_impl") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "os_account:libaccountkits", "os_account:os_account_innerkits", ] @@ -880,6 +938,7 @@ ohos_unittest("UTTest_device_manager_service_listener") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -897,6 +956,7 @@ ohos_unittest("UTTest_auth_message_processor") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -914,6 +974,7 @@ ohos_unittest("UTTest_auth_response_state") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -931,6 +992,7 @@ ohos_unittest("UTTest_auth_request_state") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -944,7 +1006,10 @@ ohos_unittest("ipc_client_manager_test") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UnitTest ipc_client_manager_test }}} @@ -963,6 +1028,7 @@ ohos_unittest("UTTest_dm_auth_manager_first") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -982,6 +1048,7 @@ ohos_unittest("UTTest_dm_auth_manager_second") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -1002,7 +1069,10 @@ ohos_unittest("UTTest_dm_radar_helper_test") { deps = [ ":device_manager_test_common" ] - external_deps = [ "device_auth:deviceauth_sdk" ] + external_deps = [ + "device_auth:deviceauth_sdk", + "googletest:gmock", + ] } ## UTTest_dm_radar_helper_test }}} @@ -1023,6 +1093,7 @@ ohos_unittest("UTTest_discovery_filter") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -1044,6 +1115,7 @@ ohos_unittest("UTTest_discovery_manager") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hitrace:hitrace_meter", ] } @@ -1070,6 +1142,7 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { external_deps = [ "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", ] } @@ -1093,6 +1166,7 @@ ohos_unittest("UTTest_dm_discovery_manager") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hitrace:hitrace_meter", ] } @@ -1113,6 +1187,7 @@ ohos_unittest("UTTest_dm_distributed_hardware_load") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", "hitrace:hitrace_meter", ] } @@ -1129,7 +1204,7 @@ ohos_unittest("UTTest_dm_crypto") { deps = [ ":device_manager_test_common" ] - external_deps = [] + external_deps = [ "googletest:gmock" ] } ## UnitTest UTTest_dm_crypto }}} @@ -1160,6 +1235,7 @@ ohos_unittest("UTTest_dm_publish_manager") { "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", + "googletest:gmock", "hitrace:hitrace_meter", ] @@ -1247,7 +1323,6 @@ ohos_static_library("device_manager_test_common") { "${servicesimpl_path}:devicemanagerserviceimpl", "${softbuscache_parh}:dmdevicecache", "${utils_path}:devicemanagerutils", - "//third_party/googletest:gmock", ] external_deps = [ -- Gitee From 32c1134f91b35068b8b147a59a2f8059fc489f2e Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 28 Aug 2024 12:17:19 +0800 Subject: [PATCH 118/520] =?UTF-8?q?=E8=AE=A4=E8=AF=81=E5=89=8D=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E5=8F=AF=E4=BF=A1=E5=88=A0=E9=99=A4=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../include/authentication/dm_auth_manager.h | 4 +++ .../dependency/softbus/softbus_connector.h | 1 + .../softbus/softbus_state_callback.h | 1 + .../devicestate/dm_device_state_manager.h | 1 + .../src/authentication/dm_auth_manager.cpp | 33 ++++++++++++++++--- .../dependency/softbus/softbus_connector.cpp | 8 +++++ .../src/device_manager_service_impl.cpp | 7 +++- .../devicestate/dm_device_state_manager.cpp | 32 +++++++++++++++--- .../UTTest_dm_auth_manager_first.cpp | 1 + .../softbus_connector_state_fuzzer.cpp | 1 + .../UTTest_softbus_connector.cpp | 1 + utils/src/kvadapter/kv_adapter.cpp | 2 -- 12 files changed, 80 insertions(+), 12 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 29838a6fd..afa879bfb 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -29,6 +29,7 @@ #include "dm_adapter_manager.h" #include "dm_constants.h" #include "dm_device_info.h" +#include "dm_device_state_manager.h" #include "dm_timer.h" #include "hichain_auth_connector.h" #include "hichain_connector.h" @@ -551,6 +552,8 @@ private: void NegotiateRespMsg(const std::string &version); void SetAuthType(int32_t authType); int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); + void GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash); + void DeleteOffLineTimer(int32_t sessionId); private: std::shared_ptr softbusConnector_; @@ -585,6 +588,7 @@ private: int32_t authForm_ = DmAuthForm::ACROSS_ACCOUNT; std::string remoteVersion_ = ""; std::atomic authType_; + std::string remoteUdidHash_ = ""; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 099e7d791..ff406d11d 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -149,6 +149,7 @@ public: std::vector GetPkgName(); void ClearPkgName(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); + void DeleteOffLineTimer(std::string &udidHash); private: static void ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo); diff --git a/services/implementation/include/dependency/softbus/softbus_state_callback.h b/services/implementation/include/dependency/softbus/softbus_state_callback.h index 70ac7f3c9..b80a27bde 100644 --- a/services/implementation/include/dependency/softbus/softbus_state_callback.h +++ b/services/implementation/include/dependency/softbus/softbus_state_callback.h @@ -22,6 +22,7 @@ class ISoftbusStateCallback { public: virtual void OnDeviceOnline(std::string deviceId, int32_t authForm) = 0; virtual void OnDeviceOffline(std::string deviceId) = 0; + virtual void DeleteOffLineTimer(std::string udidHash) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index bf4e4d7d8..5a3242f61 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -94,6 +94,7 @@ public: void OnDeviceOffline(std::string deviceId); std::string GetUdidByNetWorkId(std::string networkId); bool CheckIsOnline(const std::string &udid); + void DeleteOffLineTimer(std::string udidHash); private: void StartEventThread(); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index c096060a1..15e7a94c5 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -356,10 +356,37 @@ void DmAuthManager::SyncDeleteAcl(const std::string &pkgName, const std::string authRequestState_->Enter(); } +void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash) +{ + std::string peerUdid = ""; + int32_t ret = softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); + if (ret != DM_OK) { + LOGE("DmAuthManager::GetPeerUdidHash failed."); + peerUdidHash = ""; + return; + } + char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(peerUdid, reinterpret_cast(udidHashTmp)) != DM_OK) { + LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(peerUdid).c_str()); + peerUdidHash = ""; + return; + } + peerUdidHash = std::string(udidHashTmp); +} + +void DmAuthManager::DeleteOffLineTimer(int32_t sessionId) +{ + GetPeerUdidHash(sessionId, remoteUdidHash_); + if (softbusConnector_ != nullptr) { + softbusConnector_->DeleteOffLineTimer(remoteUdidHash_); + } +} + void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { LOGI("DmAuthManager::OnSessionOpened, sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); + DeleteOffLineTimer(sessionId); if (sessionSide == AUTH_SESSION_SIDE_SERVER) { if (authResponseState_ == nullptr && authRequestState_ == nullptr) { authMessageProcessor_ = std::make_shared(shared_from_this()); @@ -394,10 +421,8 @@ void DmAuthManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int3 authMessageProcessor_->SetRequestContext(authRequestContext_); authRequestState_->SetAuthContext(authRequestContext_); authRequestState_->TransitionTo(std::make_shared()); - struct RadarInfo info = { - .funcName = "OnSessionOpened", - .channelId = sessionId, - }; + struct RadarInfo info = { .funcName = "OnSessionOpened" }; + info.channelId = sessionId; if (!DmRadarHelper::GetInstance().ReportAuthSendRequest(info)) { LOGE("ReportAuthSendRequest failed"); } diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index e36474338..8bdbf7e2e 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -687,6 +687,14 @@ void SoftbusConnector::HandleDeviceOffline(std::string deviceId) return; } +void SoftbusConnector::DeleteOffLineTimer(std::string &udidHash) +{ + LOGI("SoftbusConnector::DeleteOffLineTimer"); + if (deviceStateManagerCallback_ != nullptr) { + deviceStateManagerCallback_->DeleteOffLineTimer(udidHash); + } +} + bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) { LOGI("Check the device is online."); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index b27b42df7..a190eeaf5 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -155,6 +155,9 @@ int32_t DeviceManagerServiceImpl::AuthenticateDevice(const std::string &pkgName, "extra is %{public}s", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); return ERR_DM_INPUT_PARA_INVALID; } + if (deviceStateMgr_ != nullptr) { + deviceStateMgr_->DeleteOffLineTimer(deviceId); + } return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); } @@ -176,7 +179,9 @@ int32_t DeviceManagerServiceImpl::BindDevice(const std::string &pkgName, int32_t "%{public}s", pkgName.c_str(), GetAnonyString(udidHash).c_str(), bindParam.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - + if (deviceStateMgr_ != nullptr) { + deviceStateMgr_->DeleteOffLineTimer(udidHash); + } return authMgr_->AuthenticateDevice(pkgName, authType, udidHash, bindParam); } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 71932f11d..66c1c33b3 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -20,6 +20,7 @@ #include "dm_adapter_manager.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_crypto.h" #include "dm_distributed_hardware_load.h" #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -212,23 +213,28 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) LOGE("fail to get udid by networkId"); return; } - LOGI("Register offline timer for deviceUdid: %{public}s", GetAnonyString(deviceUdid).c_str()); + char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(deviceUdid, reinterpret_cast(udidHash)) != DM_OK) { + LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(deviceUdid).c_str()); + return; + } + LOGI("Register offline timer for udidHash: %{public}s", GetAnonyString(std::string(udidHash)).c_str()); std::lock_guard mutexLock(timerMapMutex_); for (auto &iter : stateTimerInfoMap_) { - if ((iter.first == deviceUdid) && (timer_ != nullptr)) { + if ((iter.first == std::string(udidHash)) && (timer_ != nullptr)) { timer_->DeleteTimer(iter.second.timerName); stateTimerInfoMap_.erase(iter.first); break; } } - if (stateTimerInfoMap_.find(deviceUdid) == stateTimerInfoMap_.end()) { - std::string timerName = std::string(STATE_TIMER_PREFIX) + GetAnonyString(deviceUdid); + if (stateTimerInfoMap_.find(std::string(udidHash)) == stateTimerInfoMap_.end()) { + std::string timerName = std::string(STATE_TIMER_PREFIX) + GetAnonyString(std::string(udidHash)); StateTimerInfo stateTimer = { .timerName = timerName, .networkId = deviceInfo.networkId, .isStart = false, }; - stateTimerInfoMap_[deviceUdid] = stateTimer; + stateTimerInfoMap_[std::string(udidHash)] = stateTimer; } } @@ -251,6 +257,22 @@ void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) } } +void DmDeviceStateManager::DeleteOffLineTimer(std::string udidHash) +{ + std::lock_guard mutexLock(timerMapMutex_); + LOGI("DELETE offline timer for networkId: %{public}s", GetAnonyString(udidHash).c_str()); + if (timer_ == nullptr || udidHash.empty()) { + return; + } + auto iter = stateTimerInfoMap_.find(udidHash); + if (iter != stateTimerInfoMap_.end()) { + timer_->DeleteTimer(iter->second.timerName); + iter->second.isStart = false; + stateTimerInfoMap_.erase(iter->first); + } + return; +} + void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) { std::lock_guard mutexLock(timerMapMutex_); diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index d2b35040c..1da5a193a 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -33,6 +33,7 @@ public: virtual ~SoftbusStateCallbackTest() {} void OnDeviceOnline(std::string deviceId, int32_t authForm) {} void OnDeviceOffline(std::string deviceId) {} + void DeleteOffLineTimer(std::string udidHash) {} }; void DmAuthManagerTest::SetUp() diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp index 1365cb4fb..660e74bce 100644 --- a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp @@ -32,6 +32,7 @@ public: void OnDeviceOnline(std::string deviceId, int32_t authForm) override {} void OnDeviceOffline(std::string deviceId) override {} + void DeleteOffLineTimer(std::string udidHash) override {} }; void SoftBusConnectorStateFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 8bb115a59..54a993956 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -42,6 +42,7 @@ public: virtual ~SoftbusStateCallbackTest() {} void OnDeviceOnline(std::string deviceId, int32_t authForm) {} void OnDeviceOffline(std::string deviceId) {} + void DeleteOffLineTimer(std::string udidHash) override {} }; class SoftbusDiscoveryCallbackTest : public ISoftbusDiscoveryCallback { diff --git a/utils/src/kvadapter/kv_adapter.cpp b/utils/src/kvadapter/kv_adapter.cpp index 2ee487fb9..2082afa97 100644 --- a/utils/src/kvadapter/kv_adapter.cpp +++ b/utils/src/kvadapter/kv_adapter.cpp @@ -39,8 +39,6 @@ namespace { const std::string APP_ID_KEY = "appID"; const std::string UDID_ID_KEY = "udid"; const std::string LAST_MODIFY_TIME_KEY = "lastModifyTime"; - constexpr uint32_t MAX_BATCH_SIZE = 128; - constexpr int32_t MAX_DEVICE_ITEM_SIZE = 1000; constexpr int32_t MAX_STRING_LEN = 4096; constexpr int32_t MAX_INIT_RETRY_TIMES = 20; constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms -- Gitee From b35d6cc9d6d07f4c32f70b266705c09e727eb050 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 29 Aug 2024 23:27:54 +0800 Subject: [PATCH 119/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=AE=9A=E6=97=B6?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/include/authentication/dm_auth_manager.h | 1 - .../implementation/src/authentication/dm_auth_manager.cpp | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index afa879bfb..464ded785 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -29,7 +29,6 @@ #include "dm_adapter_manager.h" #include "dm_constants.h" #include "dm_device_info.h" -#include "dm_device_state_manager.h" #include "dm_timer.h" #include "hichain_auth_connector.h" #include "hichain_connector.h" diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 15e7a94c5..318a7a28a 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -377,6 +377,10 @@ void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash void DmAuthManager::DeleteOffLineTimer(int32_t sessionId) { GetPeerUdidHash(sessionId, remoteUdidHash_); + if (remoteUdidHash_.empty()) { + LOGE("DeleteOffLineTimer remoteUdidHash is empty."); + return; + } if (softbusConnector_ != nullptr) { softbusConnector_->DeleteOffLineTimer(remoteUdidHash_); } -- Gitee From 980a275569fb527bad2cd3a9e743c001b23b3b28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 30 Aug 2024 10:07:58 +0800 Subject: [PATCH 120/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/include/i_dm_service_impl_ext.h | 7 +++++++ services/service/include/softbus/softbus_listener.h | 1 - services/service/src/device_manager_service.cpp | 7 +++++-- services/service/src/softbus/softbus_listener.cpp | 11 ----------- 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/services/service/include/i_dm_service_impl_ext.h b/services/service/include/i_dm_service_impl_ext.h index cb30d1dea..d01eed782 100644 --- a/services/service/include/i_dm_service_impl_ext.h +++ b/services/service/include/i_dm_service_impl_ext.h @@ -85,6 +85,13 @@ public: * @tc.type: FUNC */ virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + + /** + * @tc.name: IDMServiceImplExt::SetDnPolicy + * @tc.desc: SetDnPolicy + * @tc.type: FUNC + */ + virtual int32_t SetDnPolicy(int32_t policy, int32_t timeOut) = 0; }; using CreateDMServiceImplExtFuncPtr = IDMServiceImplExt *(*)(void); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 4227937bc..362e132ce 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -91,7 +91,6 @@ public: static IRefreshCallback &GetSoftbusRefreshCb(); static void SetHostPkgName(const std::string hostName); static std::string GetHostPkgName(); - static int32_t SetDnPolicy(int32_t policy, int32_t timeOut); private: int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0693d3e7c..bacadbfc5 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1663,8 +1663,11 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond).c_str()); int32_t timeOut = std::stoi((timeOutIter->second).c_str()); - CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); - return softbusListener_->SetDnPolicy(policyStrategy, timeOut); + if (!IsDMServiceAdapterLoad()) { + LOGE("SetDnPolicy failed, instance not init or init failed."); + return ERR_DM_UNSUPPORTED_METHOD; + } + return dmServiceImplExt_->SetDnPolicy(policyStrategy, timeOut); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 542c4ccc2..a9d634984 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -753,17 +753,6 @@ int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_ return DM_OK; } -int32_t SoftbusListener::SetDnPolicy(int32_t policy, int32_t timeOut) -{ - int32_t ret = CtrlLNNBleHb(DM_PKG_NAME, static_cast(policy), timeOut); - if (ret != DM_OK) { - LOGE("[SOFTBUS]CtrlLNNBleHb failed."); - return ret; - } - LOGI("CtrlLNNBleHb complete policy: %{public}d, timeOut: %{public}d.", policy, timeOut); - return DM_OK; -} - int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) { return SoftbusCache::GetInstance().GetSecurityDeviceLevel(networkId, securityLevel); -- Gitee From b064926469f1b532e1c9f2ed7263ab63531fd571 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 30 Aug 2024 10:55:53 +0800 Subject: [PATCH 121/520] =?UTF-8?q?=E6=94=B9=E5=8F=98=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index b6c546f2f..fd29216b2 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -99,6 +99,7 @@ const int32_t NORMAL = 0; const int32_t SYSTEM_BASIC = 1; const int32_t SYSTEM_CORE = 2; const int32_t USLEEP_TIME_MS = 100000; // 100ms +const uint32_t DM_MIN_PARAM = 2; uint16_t GenRandUint(uint16_t randMin, uint16_t randMax) { std::random_device randDevice; @@ -2145,8 +2146,8 @@ int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) int32_t DeviceManagerImpl::SetDnPolicy(const std::string &pkgName, std::map &policy) { - if (pkgName.empty() || policy.size() == 0) { - LOGE("Para invalid: policy is null or pkgName is empty."); + if (pkgName.empty() || policy.size() < DM_MIN_PARAM) { + LOGE("Para invalid: policy is less than two or pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start"); -- Gitee From 1a50f904355ab3ec94146e87ca3b1fbabefb1f2c Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Fri, 30 Aug 2024 17:51:50 +0800 Subject: [PATCH 122/520] =?UTF-8?q?lib=20crash=20=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../implementation/src/authentication/dm_auth_manager.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 318a7a28a..97a270206 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -707,6 +707,9 @@ int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) authResponseContext_ = std::make_shared(); } authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE; + if (authRequestContext_ == nullptr) { + authRequestContext_ = std::make_shared(); + } authRequestContext_->reason = sessionId; if (authRequestState_ != nullptr) { authRequestState_->TransitionTo(std::make_shared()); @@ -2709,4 +2712,4 @@ int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) return taskTimeOut; } } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS -- Gitee From 5ec7330c76fbd072988ea48413ed51c032c739d8 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Fri, 30 Aug 2024 18:38:32 +0800 Subject: [PATCH 123/520] =?UTF-8?q?lib=20crash=20=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../implementation/src/authentication/dm_auth_manager.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 97a270206..0c286ada5 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -707,9 +707,9 @@ int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) authResponseContext_ = std::make_shared(); } authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE; - if (authRequestContext_ == nullptr) { - authRequestContext_ = std::make_shared(); - } + if (authRequestContext_ == nullptr) { + authRequestContext_ = std::make_shared(); + } authRequestContext_->reason = sessionId; if (authRequestState_ != nullptr) { authRequestState_->TransitionTo(std::make_shared()); -- Gitee From d46022de5117acb658117dc18959284075345ae1 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Fri, 30 Aug 2024 18:39:07 +0800 Subject: [PATCH 124/520] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=8D=95=E7=AB=AF?= =?UTF-8?q?=E5=8F=AF=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../device_manager_ipc_interface_code.h | 1 + common/include/dm_anonymous.h | 1 + common/include/dm_constants.h | 1 - .../model/ipc_notify_devicetrustchange_req.h | 52 +-- common/src/dm_anonymous.cpp | 15 + .../include/deviceprofile_connector.h | 64 ++- .../include/multiple_user_connector.h | 24 + .../src/deviceprofile_connector.cpp | 409 ++++++++++++----- .../src/multiple_user_connector.cpp | 41 +- interfaces/inner_kits/native_cpp/BUILD.gn | 1 + .../native_cpp/include/device_manager.h | 2 + .../include/device_manager_callback.h | 8 + .../native_cpp/include/device_manager_impl.h | 2 + .../include/notify/device_manager_notify.h | 6 + .../native_cpp/src/device_manager_impl.cpp | 40 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 10 + .../src/mini/device_manager_impl_lite_m.c | 1 - .../native_cpp/src/mini/softbus_adapter.c | 2 - .../src/notify/device_manager_notify.cpp | 60 +++ .../kits/js/src/native_devicemanager_js.cpp | 1 - interfaces/kits/js4.0/src/dm_native_util.cpp | 5 +- .../authentication/auth_message_processor.h | 2 - .../authentication/auth_request_state.h | 18 - .../authentication/auth_response_state.h | 12 - .../include/authentication/dm_auth_manager.h | 39 +- .../dependency/hichain/hichain_connector.h | 2 - .../dependency/softbus/softbus_session.h | 3 - .../softbus/softbus_session_callback.h | 3 - .../include/device_manager_service_impl.h | 26 +- .../device_manager_service_impl_lite.h | 25 +- .../authentication/auth_message_processor.cpp | 28 -- .../src/authentication/auth_request_state.cpp | 48 -- .../authentication/auth_response_state.cpp | 32 -- .../src/authentication/dm_auth_manager.cpp | 391 +++------------- .../dependency/hichain/hichain_connector.cpp | 33 -- .../dependency/softbus/softbus_session.cpp | 43 -- .../src/device_manager_service_impl.cpp | 183 +++++--- .../src/device_manager_service_impl_lite.cpp | 115 +++-- services/service/BUILD.gn | 5 + .../service/include/device_manager_service.h | 19 +- .../include/device_manager_service_listener.h | 1 + .../include/idevice_manager_service_impl.h | 33 +- .../idevice_manager_service_listener.h | 7 + .../relationship_sync_mgr.h | 81 ++++ .../service/include/softbus/softbus_adapter.h | 49 -- .../include/softbus/softbus_listener.h | 4 +- .../service/src/device_manager_service.cpp | 245 +++++++--- .../src/device_manager_service_listener.cpp | 15 + .../src/ipc/standard/ipc_cmd_parser.cpp | 35 ++ .../dm_account_common_event.cpp | 10 +- .../relationship_sync_mgr.cpp | 419 ++++++++++++++++++ .../service/src/softbus/softbus_adapter.cpp | 164 ------- .../service/src/softbus/softbus_listener.cpp | 62 ++- .../softbuscache/include/dm_softbus_cache.h | 1 + .../softbuscache/src/dm_softbus_cache.cpp | 16 + ...uthenticate_device_service_impl_fuzzer.cpp | 7 +- .../dm_auth_manager_fuzzer.cpp | 6 +- .../hichain_connector_fuzzer.cpp | 1 - .../UTTest_dm_auth_manager_first.cpp | 306 ------------- .../UTTest_dm_auth_manager_second.cpp | 24 - .../UTTest_dm_deviceprofile_connector.cpp | 104 ----- .../UTTest_hichain_connector.cpp | 13 - .../device_profile_connector_fuzzer.cpp | 5 +- test/softbusfuzztest/BUILD.gn | 1 - .../on_bytes_received_fuzzer.cpp | 10 - .../on_session_opened_fuzzer.cpp | 10 - .../softbusadapterobject_fuzzer/BUILD.gn | 70 --- .../softbusadapterobject_fuzzer/corpus/init | 13 - .../softbusadapterobject_fuzzer/project.xml | 25 -- .../softbus_adapter_object_fuzzer.cpp | 66 --- .../softbus_adapter_object_fuzzer.h | 21 - .../softbus_connector_state_fuzzer.cpp | 1 - .../softbus_session_fuzzer.cpp | 14 - .../softbus_session_object_fuzzer.cpp | 10 - .../UTTest_mine_softbus_listener.h | 1 - .../UTTest_softbus_adapter.cpp | 180 -------- .../UTTest_softbus_listener.cpp | 32 -- .../softbusunittest/UTTest_softbus_listener.h | 1 - .../UTTest_softbus_session.cpp | 15 - test/unittest/BUILD.gn | 25 -- .../UTTest_auth_message_processor.cpp | 47 -- test/unittest/UTTest_auth_request_state.cpp | 84 ---- test/unittest/UTTest_auth_response_state.cpp | 66 --- .../UTTest_device_manager_service.cpp | 15 - .../UTTest_device_manager_service_impl.cpp | 279 ------------ utils/include/crypto/dm_crypto.h | 1 + utils/include/timer/dm_timer.h | 1 - utils/include/timer/lite/dm_timer.h | 1 - utils/src/crypto/dm_crypto.cpp | 12 + 89 files changed, 1706 insertions(+), 2676 deletions(-) rename test/softbusunittest/UTTest_softbus_adapter.h => common/include/ipc/model/ipc_notify_devicetrustchange_req.h (52%) create mode 100644 services/service/include/relationshipsyncmgr/relationship_sync_mgr.h delete mode 100644 services/service/include/softbus/softbus_adapter.h create mode 100644 services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp delete mode 100644 services/service/src/softbus/softbus_adapter.cpp delete mode 100644 test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn delete mode 100644 test/softbusfuzztest/softbusadapterobject_fuzzer/corpus/init delete mode 100644 test/softbusfuzztest/softbusadapterobject_fuzzer/project.xml delete mode 100644 test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.cpp delete mode 100644 test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.h delete mode 100644 test/softbusunittest/UTTest_softbus_adapter.cpp diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index f21309750..b13775823 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -90,6 +90,7 @@ enum DMIpcCmdInterfaceCode { CHECK_ACCESS_CONTROL, CHECK_SAME_ACCOUNT, SHIFT_LNN_GEAR, + REMOTE_DEVICE_TRUST_CHANGE, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index d533a4e88..597459d02 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -39,6 +39,7 @@ void ParseMapFromJsonString(const std::string &jsonStr, std::map &numVec); bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); } // namespace DistributedHardware diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index d663bbc79..c6102e7aa 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -129,7 +129,6 @@ constexpr const char* DM_ITF_VER = "1.1"; constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; constexpr const char* DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; constexpr const char* DM_PIN_HOLDER_SESSION_NAME = "ohos.distributedhardware.devicemanager.pinholder"; -constexpr const char* DM_UNBIND_SESSION_NAME = "ohos.distributedhardware.devicemanager.unbind"; constexpr const char* DM_CAPABILITY_OSD = "osdCapability"; constexpr const char* DM_CAPABILITY_APPROACH = "approach"; constexpr const char* DM_CAPABILITY_TOUCH = "touch"; diff --git a/test/softbusunittest/UTTest_softbus_adapter.h b/common/include/ipc/model/ipc_notify_devicetrustchange_req.h similarity index 52% rename from test/softbusunittest/UTTest_softbus_adapter.h rename to common/include/ipc/model/ipc_notify_devicetrustchange_req.h index 5d76e8024..ba4428035 100644 --- a/test/softbusunittest/UTTest_softbus_adapter.h +++ b/common/include/ipc/model/ipc_notify_devicetrustchange_req.h @@ -12,35 +12,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef OHOS_UTTEST_DM_SOFTBUS_ADAPTER_H -#define OHOS_UTTEST_DM_SOFTBUS_ADAPTER_H - -#include -#include - -#include -#include -#include -#include -#include - -#include "auth_response_state.h" -#include "device_manager_service_listener.h" -#include "dm_auth_manager.h" -#include "dm_device_state_manager.h" -#include "dm_discovery_manager.h" -#include "inner_session.h" -#include "softbus_adapter.h" +#ifndef OHOS_DM_IPC_NOTIFY_DEVICETRUSTCHANGE_REQ_H +#define OHOS_DM_IPC_NOTIFY_DEVICETRUSTCHANGE_REQ_H +#include "ipc_req.h" namespace OHOS { namespace DistributedHardware { -class SoftbusAdapterTest : public testing::Test { +class IpcNotifyDevTrustChangeReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyDevTrustChangeReq); + public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp() override; - void TearDown() override; + int32_t GetAuthForm() const + { + return authForm_; + } + void SetAuthForm(int32_t authForm) + { + authForm_ = authForm; + } + const std::string &GetDeviceId() const + { + return deviceId_; + } + void SetDeviceId(const std::string &deviceId) + { + deviceId_ = deviceId; + } + +private: + int32_t authForm_; + std::string deviceId_; }; } // namespace DistributedHardware } // namespace OHOS -#endif +#endif // OHOS_DM_IPC_NOTIFY_DEVICETRUSTCHANGE_REQ_H \ No newline at end of file diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 7b75748fd..52a6c4e3f 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -205,6 +205,21 @@ int32_t StringToInt(const std::string &str, int32_t base) return static_cast(result); } +int64_t StringToInt64(const std::string &str, int32_t base) +{ + if (str.empty()) { + LOGE("Str is empty."); + return 0; + } + char *nextPtr = nullptr; + int64_t result = strtoll(str.c_str(), &nextPtr, base); + if (errno == ERANGE || nextPtr == nullptr || nextPtr == str.c_str() || *nextPtr != '\0') { + LOGE("parse int error"); + return 0; + } + return result; +} + void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec) { std::istringstream iss(str); diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index e55df1e4c..63ad48e16 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -14,8 +14,9 @@ */ #ifndef OHOS_DM_DEVICEPROFILE_CONNECTOR_H #define OHOS_DM_DEVICEPROFILE_CONNECTOR_H -#include #include +#include +#include #include "access_control_profile.h" #include "dm_device_info.h" #include "dm_single_instance.h" @@ -33,7 +34,7 @@ constexpr uint32_t IDENTICAL_ACCOUNT_TYPE = 5; constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; constexpr uint32_t DM_POINT_TO_POINT = 256; constexpr uint32_t DM_ACROSS_ACCOUNT = 1282; - +constexpr uint32_t DM_INVALIED_BINDTYPE = 2048; constexpr uint32_t DEVICE = 1; constexpr uint32_t SERVICE = 2; constexpr uint32_t APP = 3; @@ -86,39 +87,14 @@ namespace DistributedHardware { class IDeviceProfileConnector { public: virtual ~IDeviceProfileConnector() {} - virtual std::vector GetAccessControlProfile() = 0; - virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; - virtual int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee) = 0; - virtual int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId) = 0; - virtual std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, - const std::string &deviceId) = 0; - virtual DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) = 0; - virtual std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, - std::string trustUdid) = 0; - virtual std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, - std::string localDeviceId, std::string targetDeviceId) = 0; virtual int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm) = 0; - virtual int32_t DeleteAccessControlList(int32_t userId, std::string &accountId) = 0; - virtual DmOfflineParam DeleteAccessControlList(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId) = 0; - virtual std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId) = 0; - virtual bool CheckIdenticalAccount(int32_t userId, const std::string &accountId) = 0; - virtual int32_t DeleteP2PAccessControlList(int32_t userId, std::string &accountId) = 0; - virtual bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) = 0; - virtual bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) = 0; - virtual uint32_t DeleteTimeOutAcl(const std::string &deviceId) = 0; - virtual int32_t GetTrustNumber(const std::string &deviceId) = 0; - virtual bool CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) = 0; - virtual bool CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId) = 0; - virtual std::vector CompareBindType(std::vector profiles, - std::string pkgName, std::vector &sinkBindType, std::string localDeviceId, - std::string targetDeviceId) = 0; }; class DeviceProfileConnector : public IDeviceProfileConnector { DM_DECLARE_SINGLE_INSTANCE(DeviceProfileConnector); public: std::vector GetAccessControlProfile(); + std::vector GetAccessControlProfileByUserId(int32_t userId); uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId); int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee); int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId); @@ -130,18 +106,17 @@ public: std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId); int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); - int32_t DeleteAccessControlList(int32_t userId, std::string &accountId); - DmOfflineParam DeleteAccessControlList(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId); + void DeleteAclForAccountLogOut(const std::string &localUdid, int32_t userId, const std::string &remoteUdid); + void DeleteAclForUserRemoved(int32_t userId); + DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, + const std::string &remoteDeviceId, int32_t bindLevel); std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); - int32_t DeleteP2PAccessControlList(int32_t userId, std::string &accountId); bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); uint32_t DeleteTimeOutAcl(const std::string &deviceId); int32_t GetTrustNumber(const std::string &deviceId); bool CheckDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); - bool CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, std::string remoteDeviceId); std::vector CompareBindType(std::vector profiles, std::string pkgName, std::vector &sinkBindType, std::string localDeviceId, std::string targetDeviceId); int32_t IsSameAccount(const std::string &udid); @@ -150,6 +125,15 @@ public: int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); void DeleteAccessControlList(const std::string &udid); + int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId); + std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId, + const std::string &localUdid); + int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid, const std::string &localUdid); + int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); + std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId, + const std::string &localUdid); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); @@ -161,8 +145,18 @@ private: const std::string &reqDev); int32_t CheckAuthForm(DmAuthForm form, DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); - bool SingleUserProcess(const DistributedDeviceProfile::AccessControlProfile &profile, - const DmAccessCaller &caller, const DmAccessCallee &callee); + bool SingleUserProcess(const DistributedDeviceProfile::AccessControlProfile &profile, const DmAccessCaller &caller, + const DmAccessCallee &callee); + void DeleteAppBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void DeleteDeviceBindLevel(DmOfflineParam &offlineParam, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void DeleteServiceBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void UpdateBindType(const std::string &udid, int32_t bindType, std::map &deviceMap); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 03fe99631..6cdbc214b 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -17,6 +17,7 @@ #define OHOS_DM_MULTIPLE_USER_CONNECTOR_H #include +#include #include namespace OHOS { namespace DistributedHardware { @@ -63,9 +64,32 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountId(void); + + /** + * @tc.name: MultipleUserConnector::SetSwitchOldAccountName + * @tc.desc: Set Switch Old AccountName of the Multiple User Connector + * @tc.type: FUNC + */ + static void SetSwitchOldAccountName(std::string accountName); + + /** + * @tc.name: MultipleUserConnector::GetOhosAccountName + * @tc.desc: Get Current AccountName of the Multiple User Connector + * @tc.type: FUNC + */ + static std::string GetOhosAccountName(void); + + /** + * @tc.name: MultipleUserConnector::GetSwitchOldAccountName + * @tc.desc: Get Switc Old AccountName of the Multiple User Connector + * @tc.type: FUNC + */ + static std::string GetSwitchOldAccountName(void); private: static int32_t oldUserId_; static std::string accountId_; + static std::string accountName_; + static std::mutex lock_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 42aecf04f..7f2f99aff 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -31,13 +31,24 @@ std::vector DeviceProfileConnector::GetAccessControlProfil std::vector profiles; std::map queryParams; int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - queryParams["userId"] = std::to_string(userId); + queryParams[USERID] = std::to_string(userId); if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { LOGE("DP GetAccessControlProfile failed."); } return profiles; } +std::vector DeviceProfileConnector::GetAccessControlProfileByUserId(int32_t userId) +{ + std::vector profiles; + std::map queryParams; + queryParams[USERID] = std::to_string(userId); + if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { + LOGE("DP GetAccessControlProfileByUserId failed."); + } + return profiles; +} + std::unordered_map DeviceProfileConnector::GetAppTrustDeviceList(const std::string &pkgName, const std::string &deviceId) { @@ -439,21 +450,28 @@ int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccess return ret; } -int32_t DeviceProfileConnector::DeleteAccessControlList(int32_t userId, std::string &accountId) +void DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t userId, + const std::string &remoteUdid) { - LOGI("Start."); - std::vector profiles; - std::map queryParams; - queryParams["userId"] = std::to_string(userId); - if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { - LOGE("DP GetAccessControlProfile failed."); + LOGI("localUdid %{public}s, userId %{public}d, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), userId, + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAccessControlProfileByUserId(userId); + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } } - LOGI("Size is %{public}zu", profiles.size()); - for (auto &item : profiles) { - LOGI("BindType is : %{public}d.", item.GetBindType()); - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); +} + +void DeviceProfileConnector::DeleteAclForUserRemoved(int32_t userId) +{ + LOGI("DeleteAclForUserRemoved userId %{public}d.", userId); + std::vector profiles = GetAccessControlProfileByUserId(userId); + for (const auto &item : profiles) { + if (item.GetAccesser().GetAccesserUserId() == userId || item.GetAccessee().GetAccesseeUserId() == userId) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } } - return DM_OK; } void DeviceProfileConnector::DeleteAccessControlList(const std::string &udid) @@ -472,56 +490,142 @@ void DeviceProfileConnector::DeleteAccessControlList(const std::string &udid) } } -DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId) +DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string &pkgName, + const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel) { - LOGI("DeleteAccessControlList by pkgName %{public}s, localDeviceId %{public}s, remoteDeviceId %{public}s.", - pkgName.c_str(), GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str()); - std::vector profiles = GetAccessControlProfile(); - LOGI("Size is %{public}zu", profiles.size()); + LOGI("pkgName %{public}s, localDeviceId %{public}s, remoteDeviceId %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); DmOfflineParam offlineParam; offlineParam.bindType = INVALIED_TYPE; - offlineParam.leftAclNumber = 0; + if (bindLevel > APP || bindLevel < DEVICE) { + LOGE("Invalied bindlevel."); + return offlineParam; + } + std::vector profiles = GetAccessControlProfile(); + if (profiles.empty()) { + LOGE("Acl is empty."); + return offlineParam; + } + switch (bindLevel) { + case APP: + DeleteAppBindLevel(offlineParam, pkgName, profiles, localDeviceId, remoteDeviceId); + break; + case SERVICE: + DeleteServiceBindLevel(offlineParam, pkgName, profiles, localDeviceId, remoteDeviceId); + break; + case DEVICE: + DeleteDeviceBindLevel(offlineParam, profiles, localDeviceId, remoteDeviceId); + break; + default: + break; + } + return offlineParam; +} + +void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; for (auto &item : profiles) { - if (item.GetTrustDeviceId() != remoteDeviceId || item.GetStatus() != ACTIVE) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { continue; } - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - LOGE("Identical account forbid unbind."); - offlineParam.bindType = INVALIED_TYPE; - return offlineParam; - } - if (item.GetTrustDeviceId() == remoteDeviceId) { - offlineParam.leftAclNumber++; - if (item.GetBindLevel() == DEVICE && item.GetBindType() != DM_IDENTICAL_ACCOUNT && - (item.GetAccesser().GetAccesserBundleName() == pkgName || - item.GetAccesser().GetAccesserBundleName() == "")) { - LOGI("DeleteAccessControlList device unbind."); - offlineParam.bindType = DEVICE_PEER_TO_PEER_TYPE; - } + bindNums++; + if (item.GetAccesser().GetAccesserBundleName() == pkgName && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if (item.GetAccessee().GetAccesseeBundleName() == pkgName && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; } } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, + const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; for (auto &item : profiles) { - if (item.GetTrustDeviceId() != remoteDeviceId || item.GetStatus() != ACTIVE) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT) { continue; } - if ((item.GetAccesser().GetAccesserDeviceId() == localDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == remoteDeviceId) || - (item.GetAccessee().GetAccesseeDeviceId() == localDeviceId && - item.GetAccesser().GetAccesserDeviceId() == remoteDeviceId)) { - if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - offlineParam.leftAclNumber--; - } else if (item.GetAccesser().GetAccesserBundleName() == pkgName && - item.GetAccessee().GetAccesseeBundleName() == pkgName) { - offlineParam.bindType = APP_PEER_TO_PEER_TYPE; - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - offlineParam.leftAclNumber--; - break; - } + bindNums++; + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = DEVICE; + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = DEVICE; + LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + continue; } } - return offlineParam; + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteServiceBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, + const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } + bindNums++; + if (item.GetAccesser().GetAccesserBundleName() == pkgName && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if (item.GetAccessee().GetAccesseeBundleName() == pkgName && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; } int32_t DeviceProfileConnector::UpdateAccessControlList(int32_t userId, std::string &oldAccountId, @@ -554,8 +658,8 @@ bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::st LOGI("Start"); std::vector profiles; std::map queryParams; - queryParams["userId"] = std::to_string(userId); - queryParams["accountId"] = accountId; + queryParams[USERID] = std::to_string(userId); + queryParams[ACCOUNTID] = accountId; if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { LOGE("DP GetAccessControlProfile failed."); } @@ -566,29 +670,6 @@ bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::st } return false; } -int32_t DeviceProfileConnector::DeleteP2PAccessControlList(int32_t userId, std::string &accountId) -{ - LOGI("Start"); - std::vector profiles; - std::map queryParams; - queryParams["userId"] = std::to_string(userId); - queryParams["accountId"] = accountId; - if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { - LOGE("DP GetAccessControlProfile failed."); - } - for (auto &item : profiles) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetStatus() != ACTIVE) { - continue; - } - if ((item.GetAccesser().GetAccesserUserId() == userId && - item.GetAccesser().GetAccesserAccountId() == accountId) || - (item.GetAccessee().GetAccesseeUserId() == userId && - item.GetAccessee().GetAccesseeAccountId() == accountId)) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - } - } - return DM_OK; -} bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { @@ -660,35 +741,6 @@ int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) return trustNumber; } -bool DeviceProfileConnector::CheckPkgnameInAcl(std::string pkgName, std::string localDeviceId, - std::string remoteDeviceId) -{ - LOGI("Start"); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - for (auto &item : profiles) { - if (item.GetTrustDeviceId() != remoteDeviceId || item.GetStatus() != ACTIVE || - item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - continue; - } - if (item.GetBindLevel() == DEVICE && (item.GetAccesser().GetAccesserBundleName() == pkgName || - item.GetAccessee().GetAccesseeBundleName() == pkgName || - item.GetAccesser().GetAccesserBundleName() == "" || item.GetAccessee().GetAccesseeBundleName() == "")) { - LOGI("The pkgname %{public}s is peer-to-peer device unbind.", pkgName.c_str()); - return true; - } else if (item.GetBindLevel() == APP && item.GetAccesser().GetAccesserBundleName() == pkgName && - item.GetAccesser().GetAccesserDeviceId() == localDeviceId) { - LOGI("The accesser pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); - return true; - } else if (item.GetBindLevel() == APP && item.GetAccessee().GetAccesseeBundleName() == pkgName && - item.GetAccessee().GetAccesseeDeviceId() == localDeviceId) { - LOGI("The accessee pkgname %{public}s is peer-to-peer app unbind.", pkgName.c_str()); - return true; - } - } - return false; -} - int32_t DeviceProfileConnector::IsSameAccount(const std::string &udid) { LOGI("Start."); @@ -775,6 +827,155 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, return ERR_DM_FAILED; } +int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + LOGI("pkgName %{public}s, tokenId %{public}" PRId64", udid %{public}s.", pkgName.c_str(), + tokenId, GetAnonyString(udid).c_str()); + std::vector profiles = GetAccessControlProfile(); + int32_t bindLevel = INVALIED_TYPE; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != udid) { + continue; + } + if (item.GetAccesser().GetAccesserBundleName() == pkgName && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == udid) { + tokenId = item.GetAccesser().GetAccesserTokenId(); + bindLevel = item.GetBindLevel(); + LOGI("Src get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); + continue; + } + if (item.GetAccessee().GetAccesseeBundleName() == pkgName && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == udid) { + tokenId = item.GetAccessee().GetAccesseeTokenId(); + bindLevel = item.GetBindLevel(); + LOGI("Sink get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); + continue; + } + } + return bindLevel; +} + +std::map DeviceProfileConnector::GetDeviceIdAndBindType(int32_t userId, + const std::string &accountId, const std::string &localUdid) +{ + LOGI("userId %{public}d, accountId %{public}s.", userId, GetAnonyString(accountId).c_str()); + std::vector profiles = GetAccessControlProfileByUserId(userId); + std::map deviceIdMap; + for (const auto &item : profiles) { + if (item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccesser().GetAccesserAccountId() == accountId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Account logout localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + } else if (item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccessee().GetAccesseeAccountId() == accountId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Account logout localUdid %{public}s is sink.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + } + } + return deviceIdMap; +} + +void DeviceProfileConnector::UpdateBindType(const std::string &udid, int32_t bindType, + std::map &deviceMap) +{ + LOGI("BindType %{public}d.", bindType); + if (deviceMap.find(udid) == deviceMap.end()) { + deviceMap[udid] = bindType; + } else { + deviceMap[udid] = std::min(deviceMap[udid], bindType); + } +} + +int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid, const std::string &localUdid) +{ + LOGI("RemoteUserId %{public}d, remoteAccountHash %{public}s, remoteUdid %{public}s, localUdid %{public}s.", + remoteUserId, GetAnonyString(remoteAccountHash).c_str(), GetAnonyString(remoteUdid).c_str(), + GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAccessControlProfile(); + int32_t bindType = DM_INVALIED_BINDTYPE; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid) { + continue; + } + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = DM_IDENTICAL_ACCOUNT; + } + return bindType; +} + +int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid) +{ + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, + GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAccessControlProfile(); + int32_t bindType = DM_INVALIED_BINDTYPE; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid) { + continue; + } + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + bindType = DM_IDENTICAL_ACCOUNT; + continue; + } + if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Src device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Sink device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } + } + return bindType; +} + +std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId, + const std::string &localUdid) +{ + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}" PRId64", localUdid %{public}s.", + remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAccessControlProfile(); + std::string pkgName = ""; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + if (item.GetAccesser().GetAccesserUserId() == remoteUserId && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Src device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + pkgName = item.GetAccesser().GetAccesserBundleName(); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Sink device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + pkgName = item.GetAccessee().GetAccesseeBundleName(); + continue; + } + } + return pkgName; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index f51559ab1..7302e7d96 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -30,7 +30,8 @@ namespace OHOS { namespace DistributedHardware { int32_t MultipleUserConnector::oldUserId_ = -1; std::string MultipleUserConnector::accountId_ = ""; - +std::string MultipleUserConnector::accountName_ = ""; +std::mutex MultipleUserConnector::lock_; #ifndef OS_ACCOUNT_PART_EXISTS const int32_t DEFAULT_OS_ACCOUNT_ID = 0; // 0 is the default id when there is no os_account part #endif // OS_ACCOUNT_PART_EXISTS @@ -73,24 +74,62 @@ std::string MultipleUserConnector::GetOhosAccountId(void) #endif } +std::string MultipleUserConnector::GetOhosAccountName(void) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return ""; +#else +#ifdef OS_ACCOUNT_PART_EXISTS + auto accountInfo = OhosAccountKits::GetInstance().QueryOhosAccountInfo(); + if (!accountInfo.first) { + LOGE("QueryOhosAccountInfo failed."); + return ""; + } + if (accountInfo.second.name_.empty()) { + LOGE("QueryOhosAccountInfo name empty."); + return ""; + } + return accountInfo.second.name_; +#else // OS_ACCOUNT_PART_EXISTS + return ""; +#endif // OS_ACCOUNT_PART_EXISTS +#endif +} + void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) { + std::lock_guard lock(lock_); oldUserId_ = userId; } int32_t MultipleUserConnector::GetSwitchOldUserId(void) { + std::lock_guard lock(lock_); return oldUserId_; } void MultipleUserConnector::SetSwitchOldAccountId(std::string accountId) { + std::lock_guard lock(lock_); accountId_ = accountId; } std::string MultipleUserConnector::GetSwitchOldAccountId(void) { + std::lock_guard lock(lock_); return accountId_; } + +void MultipleUserConnector::SetSwitchOldAccountName(std::string accountName) +{ + std::lock_guard lock(lock_); + accountName_ = accountName; +} + +std::string MultipleUserConnector::GetSwitchOldAccountName(void) +{ + std::lock_guard lock(lock_); + return accountName_; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index d2ed0b1f4..9b6299e42 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -175,6 +175,7 @@ if (defined(ohos_lite)) { external_deps = [ "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index caba88092..4d11d292c 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -606,6 +606,8 @@ public: virtual bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) = 0; virtual int32_t GetErrCode(int32_t errCode) = 0; virtual int32_t ShiftLNNGear(const std::string &pkgName) = 0; + virtual int32_t RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; }; } // 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 b33857718..e84d0f387 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -132,6 +132,14 @@ public: virtual void OnDestroyResult(int32_t result) = 0; virtual void OnPinHolderEvent(DmPinHolderEvent event, int32_t result, const std::string &content) = 0; }; + +class DevTrustChangeCallback { +public: + virtual ~DevTrustChangeCallback() + { + } + virtual void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) = 0; +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_CALLBACK_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 5505d0de3..2e7b7c32f 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -385,6 +385,8 @@ public: virtual bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee) override; virtual int32_t GetErrCode(int32_t errCode) override; virtual int32_t ShiftLNNGear(const std::string &pkgName) override; + virtual int32_t RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) override; private: DeviceManagerImpl() = default; 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 f78a34573..995871b0e 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 @@ -66,6 +66,8 @@ public: std::string content); void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, std::string content); void RegisterPinHolderCallback(const std::string &pkgName, std::shared_ptr callback); + void RegDevTrustChangeCallback(const std::string &pkgName, std::shared_ptr callback); + public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -80,6 +82,8 @@ public: std::shared_ptr tempCbk); static void DeviceBasicInfoReady(const DmDeviceBasicInfo &deviceBasicInfo, std::shared_ptr tempCbk); + static void DeviceTrustChange(const std::string &deviceId, DmAuthForm authForm, + std::shared_ptr tempCbk); public: void OnRemoteDied(); void OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo); @@ -107,6 +111,7 @@ public: void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content); std::map> GetDmInitCallback(); + void OnDeviceTrustChange(const std::string &pkgName, const std::string &deviceId, int32_t authForm); private: #if !defined(__LITEOS_M__) std::mutex lock_; @@ -122,6 +127,7 @@ private: std::map>> bindCallback_; std::map>> unbindCallback_; std::map> pinHolderCallback_; + std::map> devTrustChangeCallback_; std::mutex bindLock_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::shared_ptr ffrtQueue_; 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 5ab6d2fa6..56457c3ce 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -51,6 +51,7 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" +#include "ipc_skeleton.h" #include "ipc_start_discovery_req.h" #include "ipc_start_discover_req.h" #include "ipc_stop_discovery_req.h" @@ -621,10 +622,18 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ std::string strDeviceId = deviceInfo.deviceId; DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, strDeviceId, callback); + nlohmann::json extraJson = nlohmann::json::parse(extra, nullptr, false); + if (extraJson.is_discarded()) { + LOGE("extra bindParam %{public}s.", extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + extraJson[TOKENID] = std::to_string(OHOS::IPCSkeleton::GetSelfTokenID()); +#endif std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetExtra(extra); + req->SetExtra(extraJson.dump()); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); @@ -1370,12 +1379,20 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy LOGE("BindDevice error: Invalid para. pkgName : %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + LOGI("BindDevice start, pkgName: %{public}s", pkgName.c_str()); + nlohmann::json paramJson = nlohmann::json::parse(bindParam, nullptr, false); + if (paramJson.is_discarded()) { + LOGE("BindDevice bindParam %{public}s.", bindParam.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + paramJson[TOKENID] = std::to_string(OHOS::IPCSkeleton::GetSelfTokenID()); +#endif DeviceManagerNotify::GetInstance().RegisterAuthenticateCallback(pkgName, deviceId, callback); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetBindParam(bindParam); + req->SetBindParam(paramJson.dump()); req->SetBindType(bindType); req->SetDeviceId(deviceId); int32_t ret = ipcClientProxy_->SendRequest(BIND_DEVICE, req, rsp); @@ -1744,7 +1761,10 @@ int32_t DeviceManagerImpl::BindTarget(const std::string &pkgName, const PeerTarg LOGE("DeviceManagerImpl::BindTarget failed: input pkgName or targetId is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + LOGI("DeviceManagerImpl::BindTarget start, pkgName: %{public}s", pkgName.c_str()); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + bindParam[TOKENID] = std::to_string(OHOS::IPCSkeleton::GetSelfTokenID()); +#endif std::string bindParamStr = ConvertMapToJsonString(bindParam); DeviceManagerNotify::GetInstance().RegisterBindCallback(pkgName, targetId, callback); std::shared_ptr req = std::make_shared(); @@ -2142,5 +2162,17 @@ int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) LOGI("Completed"); return DM_OK; } + +int32_t DeviceManagerImpl::RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + LOGI("PkgName %{public}s.", pkgName.c_str()); + if (pkgName.empty() || callback == nullptr) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 b07d8a6bd..af9b08f40 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 @@ -1605,5 +1605,15 @@ ON_IPC_READ_RESPONSE(SHIFT_LNN_GEAR, MessageParcel &reply, std::shared_ptrSetErrCode(reply.ReadInt32()); return DM_OK; } + +ON_IPC_CMD(REMOTE_DEVICE_TRUST_CHANGE, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string deviceId = data.ReadString(); + int32_t authForm = data.ReadInt32(); + DeviceManagerNotify::GetInstance().OnDeviceTrustChange(pkgName, deviceId, authForm); + reply.WriteInt32(DM_OK); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c b/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c index d99d72c97..033b7466e 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c +++ b/interfaces/inner_kits/native_cpp/src/mini/device_manager_impl_lite_m.c @@ -23,7 +23,6 @@ #include "device_manager_common.h" #include "hichain_adapter.h" -#include "softbus_adapter.h" static const char * const FILED_PKG_NAME = "pkgName"; static const char * const FILED_BIND_TYPE = "bindType"; diff --git a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c index 53dc9b8cf..56564b020 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c +++ b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c @@ -13,8 +13,6 @@ * limitations under the License. */ -#include "softbus_adapter.h" - #include #include 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 3c8bdc38b..1229abfbf 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 @@ -29,9 +29,12 @@ constexpr const char* DEVICE_ONLINE = "deviceOnline"; constexpr const char* DEVICE_OFFLINE = "deviceOffline"; constexpr const char* DEVICEINFO_CHANGE = "deviceInfoChange"; constexpr const char* DEVICE_READY = "deviceReady"; +constexpr const char* DEVICE_TRUST_CHANGE = "deviceTrustChange"; #else constexpr const char* DEVICE_STATE_INIT_QUEUE = "deviceStateInitQueue"; #endif +const int32_t MIN_AUTHFORM = -1; +const int32_t MAX_AUTHFORM = 2; void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback) @@ -1076,5 +1079,62 @@ void DeviceManagerNotify::DeviceBasicInfoReady(const DmDeviceBasicInfo &deviceBa { tempCbk->OnDeviceReady(deviceBasicInfo); } + +void DeviceManagerNotify::RegDevTrustChangeCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + devTrustChangeCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const std::string &deviceId, int32_t authForm) +{ + LOGI("PkgName %{public}s, deviceId %{public}s, authForm %{public}d", pkgName.c_str(), + GetAnonyString(deviceId).c_str(), authForm); + if (pkgName.empty() || authForm < MIN_AUTHFORM || authForm > MAX_AUTHFORM) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + auto iter = devTrustChangeCallback_.find(pkgName); + if (iter == devTrustChangeCallback_.end()) { + LOGE("PkgName %{public}s device_trust_change callback not register.", pkgName.c_str()); + return; + } + tempCbk = iter->second; + } + if (tempCbk == nullptr) { + LOGE("OnDeviceReady error, registered device status callback is nullptr."); + return; + } + DmAuthForm dmAuthForm = static_cast(authForm); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (ffrtQueue_ != nullptr) { + ffrtQueue_->submit([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); + } +#else + std::thread deviceTrustChange([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); + if (pthread_setname_np(deviceTrustChange.native_handle(), DEVICE_TRUST_CHANGE) != DM_OK) { + LOGE("deviceTrustChange set name failed."); + } + deviceTrustChange.detach(); +#endif +} + +void DeviceManagerNotify::DeviceTrustChange(const std::string &deviceId, DmAuthForm authForm, + std::shared_ptr tempCbk) +{ + if (tempCbk == nullptr) { + LOGE("Callback ptr is nullptr."); + return; + } + tempCbk->OnDeviceTrustChange(deviceId, authForm); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 37102786b..111711b17 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1190,7 +1190,6 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec jsonObj[APP_OPERATION] = appOperationStr; jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr; jsonObj[BIND_LEVEL] = bindLevel; - jsonObj[TOKENID] = OHOS::IPCSkeleton::GetSelfTokenID(); JsToJsonObject(env, object, "extraInfo", jsonObj); extra = jsonObj.dump(); LOGI("appOperationLen %{public}zu, customDescriptionLen %{public}zu", appOperationStr.size(), diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index bf6a82ec2..8632ba7e1 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -327,7 +327,6 @@ void JsToBindParam(const napi_env &env, const napi_value &object, std::string &b jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP); jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort; jsonObj[BIND_LEVEL] = bindLevel; - jsonObj[TOKENID] = OHOS::IPCSkeleton::GetSelfTokenID(); bindParam = jsonObj.dump(); } @@ -428,6 +427,10 @@ void InsertMapParames(nlohmann::json &bindParamObj, std::map(); bindParamMap.insert(std::pair(PARAM_KEY_AUTH_TOKEN, authToken)); } + if (IsInt32(bindParamObj, BIND_LEVEL)) { + int32_t bindLevel = bindParamObj[BIND_LEVEL].get(); + bindParamMap.insert(std::pair(BIND_LEVEL, std::to_string(bindLevel))); + } } bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, std::string &strValue) diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index dfac3abfd..959d3a87a 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -108,8 +108,6 @@ private: void ParsePkgNegotiateMessage(const nlohmann::json &json); void CreatePublicKeyMessageExt(nlohmann::json &json); void ParsePublicKeyMessageExt(nlohmann::json &json); - void CreateSyncDeleteMessageExt(nlohmann::json &json); - void ParseSyncDeleteMessageExt(nlohmann::json &json); void GetJsonObj(nlohmann::json &jsonObj); private: diff --git a/services/implementation/include/authentication/auth_request_state.h b/services/implementation/include/authentication/auth_request_state.h index 21327c4ac..05b4642df 100644 --- a/services/implementation/include/authentication/auth_request_state.h +++ b/services/implementation/include/authentication/auth_request_state.h @@ -193,24 +193,6 @@ public: int32_t GetStateType() override; int32_t Enter() override; }; - -class AuthRequestDeleteInit : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestSyncDeleteAcl : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthRequestSyncDeleteAclNone : public AuthRequestState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_AUTH_REQUEST_STATE_H diff --git a/services/implementation/include/authentication/auth_response_state.h b/services/implementation/include/authentication/auth_response_state.h index 53c395f3f..c84a83aeb 100644 --- a/services/implementation/include/authentication/auth_response_state.h +++ b/services/implementation/include/authentication/auth_response_state.h @@ -112,18 +112,6 @@ public: int32_t GetStateType() override; int32_t Enter() override; }; - -class AuthResponseSyncDeleteAcl : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; - -class AuthResponseSyncDeleteAclNone : public AuthResponseState { -public: - int32_t GetStateType() override; - int32_t Enter() override; -}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_AUTH_RESPONSE_STATE_H diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 464ded785..d855786d9 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -47,9 +47,6 @@ typedef enum AuthState { AUTH_REQUEST_FINISH, AUTH_REQUEST_CREDENTIAL, AUTH_REQUEST_CREDENTIAL_DONE, - AUTH_REQUEST_DELETE_INIT, - AUTH_REQUEST_SYNCDELETE, - AUTH_REQUEST_SYNCDELETE_DONE, AUTH_RESPONSE_INIT = 20, AUTH_RESPONSE_NEGOTIATE, @@ -58,8 +55,6 @@ typedef enum AuthState { AUTH_RESPONSE_SHOW, AUTH_RESPONSE_FINISH, AUTH_RESPONSE_CREDENTIAL, - AUTH_RESPONSE_SYNCDELETE, - AUTH_RESPONSE_SYNCDELETE_DONE, } AuthState; enum DmMsgType : int32_t { @@ -79,8 +74,6 @@ enum DmMsgType : int32_t { MSG_TYPE_RESP_AUTH_EXT, MSG_TYPE_REQ_PUBLICKEY, MSG_TYPE_RESP_PUBLICKEY, - MSG_TYPE_REQ_SYNC_DELETE, - MSG_TYPE_REQ_SYNC_DELETE_DONE, MSG_TYPE_REQ_AUTH_DEVICE_NEGOTIATE = 600, MSG_TYPE_RESP_AUTH_DEVICE_NEGOTIATE = 700, }; @@ -127,7 +120,7 @@ typedef struct DmAuthRequestContext { int64_t tokenId; std::string remoteAccountId; int32_t remoteUserId; - std::string ip; + std::string addr; std::string hostPkgLabel; } DmAuthRequestContext; @@ -210,7 +203,7 @@ public: * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); /** * @brief UnBind device. @@ -218,7 +211,7 @@ public: * @param deviceId device id. * @return Return 0 if success. */ - int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); /** * @tc.name: DmAuthManager::OnSessionOpened @@ -416,13 +409,6 @@ public: */ int32_t OnUserOperation(int32_t action, const std::string ¶ms); - /** - * @tc.name: DmAuthManager::UserSwitchEventCallback - * @tc.desc: User Switch Event Callback of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void UserSwitchEventCallback(int32_t userId); - /** * @tc.name: DmAuthManager::SetPageId * @tc.desc: Set PageId of the DeviceManager Authenticate Manager @@ -495,13 +481,9 @@ private: void CompatiblePutAcl(); void ProcRespNegotiateExt(const int32_t &sessionId); void ProcRespNegotiate(const int32_t &sessionId); - void AccountIdLogoutEventCallback(int32_t userId); - void UserChangeEventCallback(int32_t userId); void GetAuthRequestContext(); void SinkAuthDeviceFinish(); void SrcAuthDeviceFinish(); - void SrcSyncDeleteAclDone(); - void SinkSyncDeleteAclDone(); int32_t CheckTrustState(); void ProcIncompatible(const int32_t &sessionId); bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); @@ -510,37 +492,28 @@ public: void RequestCredential(); void GenerateCredential(std::string &publicKey); void RequestCredentialDone(); - void RequestSyncDeleteAcl(); void ResponseCredential(); - void ResponseSyncDeleteAcl(); bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen); void AuthDeviceFinish(int64_t requestId); void AuthDeviceError(int64_t requestId, int32_t errorCode); void GetRemoteDeviceId(std::string &deviceId); - int32_t EstablishUnbindChannel(const std::string &deviceIdHash); - void SyncDeleteAclDone(); void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); - void CommonEventCallback(int32_t userId, std::string commonEventType); void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); - void BindSocketSuccess(int32_t socket); - void BindSocketFail(); void OnScreenLocked(); void HandleDeviceNotTrust(const std::string &udid); + int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); private: int32_t ImportCredential(std::string &deviceId, std::string &publicKey); void GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra); - void HandleSyncDeleteTimeout(std::string name); - int32_t DeleteAcl(const std::string &pkgName, const std::string &deviceId); + int32_t DeleteAcl(const std::string &pkgName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel); void ProcessAuthRequestExt(const int32_t &sessionId); void ProcessAuthRequest(const int32_t &sessionId); int32_t ConfirmProcess(const int32_t &action); int32_t ConfirmProcessExt(const int32_t &action); int32_t AddMember(int32_t pinCode); int32_t AuthDevice(int32_t pinCode); - void SyncDeleteAcl(const std::string &pkgName, const std::string &deviceId); - int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); void PutAccessControlList(); void SinkAuthenticateFinish(); void SrcAuthenticateFinish(); diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index c4e0e2df6..f47ea5796 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -228,8 +228,6 @@ public: int32_t addMultiMembersExt(const std::string &credentialInfo); void DeleteAllGroup(int32_t userId); - - void DeleteP2PGroup(int32_t userId); int32_t GetRelatedGroupsExt(const std::string &deviceId, std::vector &groupList); diff --git a/services/implementation/include/dependency/softbus/softbus_session.h b/services/implementation/include/dependency/softbus/softbus_session.h index b78281ac8..99387bb76 100644 --- a/services/implementation/include/dependency/softbus/softbus_session.h +++ b/services/implementation/include/dependency/softbus/softbus_session.h @@ -34,7 +34,6 @@ public: static int OnSessionOpened(int sessionId, int result); static void OnSessionClosed(int sessionId); static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); - static void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); public: SoftbusSession(); @@ -81,8 +80,6 @@ public: * @tc.type: FUNC */ int32_t GetPeerDeviceId(int32_t sessionId, std::string &peerDevId); - int32_t OpenUnbindSession(const std::string &netWorkId); - int32_t CloseUnbindSession(int32_t socket); int32_t SendHeartbeatData(int32_t sessionId, std::string &message); private: diff --git a/services/implementation/include/dependency/softbus/softbus_session_callback.h b/services/implementation/include/dependency/softbus/softbus_session_callback.h index d267f26b2..c3f90824c 100644 --- a/services/implementation/include/dependency/softbus/softbus_session_callback.h +++ b/services/implementation/include/dependency/softbus/softbus_session_callback.h @@ -24,10 +24,7 @@ public: virtual void OnSessionClosed(int32_t sessionId) = 0; virtual void OnDataReceived(int32_t sessionId, std::string message) = 0; virtual bool GetIsCryptoSupport() = 0; - virtual void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) = 0; virtual void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) = 0; - virtual void BindSocketSuccess(int32_t socket) = 0; - virtual void BindSocketFail() = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 09d1fe4ea..79dcc1733 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -56,15 +56,9 @@ public: int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId); - int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); - - int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam); - - int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); @@ -123,25 +117,31 @@ public: const std::map &bindParam); std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); - void OnUnbindSessionCloseed(int32_t socket); - void OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen); int32_t DpAclAdd(const std::string &udid); int32_t IsSameAccount(const std::string &udid); - void AccountCommonEventCallback(int32_t userId, std::string commonEventType); void ScreenCommonEventCallback(std::string commonEventType); int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); void HandleDeviceNotTrust(const std::string &udid); + int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId); + void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); void HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo); void HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo); void PutIdenticalAccountToAcl(std::string requestDeviceId, std::string trustDeviceId); + std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId); + void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid); + void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); + void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId); + void HandleUserRemoved(int32_t preUserId); + DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); private: std::shared_ptr authMgr_; @@ -155,6 +155,8 @@ private: std::shared_ptr credentialMgr_; std::shared_ptr commonEventManager_; std::shared_ptr hiChainAuthConnector_; + std::shared_ptr listener_; + std::atomic isCredentialType_ = false; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index b7c7de380..7bef9fd01 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -50,16 +50,10 @@ public: int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId); - int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra); - - int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); - - int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam); - - int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); void HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo); @@ -122,19 +116,24 @@ public: int32_t DestroyPinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload); std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); - void OnUnbindSessionOpened(int32_t sessionId, PeerSocketInfo info); - void OnUnbindSessionCloseed(int32_t sessionId); - void OnUnbindBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); int32_t DpAclAdd(const std::string &udid); int32_t IsSameAccount(const std::string &udid); - void AccountCommonEventCallback(int32_t userId, std::string commonEventType); void ScreenCommonEventCallback(std::string commonEventType); int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid); void HandleDeviceNotTrust(const std::string &udid); + int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId); + std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId); + void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid); + void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); + void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId); + void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); + void HandleUserRemoved(int32_t preUserId); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 5d465cb3a..725bc8ff8 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -125,29 +125,18 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) CreateResponseAuthMessageExt(jsonObj); break; case MSG_TYPE_REQ_AUTH_TERMINATE: - case MSG_TYPE_REQ_SYNC_DELETE_DONE: CreateResponseFinishMessage(jsonObj); break; case MSG_TYPE_REQ_PUBLICKEY: case MSG_TYPE_RESP_PUBLICKEY: CreatePublicKeyMessageExt(jsonObj); break; - case MSG_TYPE_REQ_SYNC_DELETE: - CreateSyncDeleteMessageExt(jsonObj); - break; default: break; } return jsonObj.dump(); } -void AuthMessageProcessor::CreateSyncDeleteMessageExt(nlohmann::json &json) -{ - json[TAG_LOCAL_DEVICE_ID] = authResponseContext_->localDeviceId; - json[TAG_HOST_PKGNAME] = authResponseContext_->hostPkgName; - json[TAG_REPLY] = DM_OK; -} - void AuthMessageProcessor::CreatePublicKeyMessageExt(nlohmann::json &json) { json[TAG_PUBLICKEY] = authResponseContext_->publicKey; @@ -294,35 +283,18 @@ int32_t AuthMessageProcessor::ParseMessage(const std::string &message) ParseAuthResponseMessageExt(jsonObject); break; case MSG_TYPE_REQ_AUTH_TERMINATE: - case MSG_TYPE_REQ_SYNC_DELETE_DONE: ParseResponseFinishMessage(jsonObject); break; case MSG_TYPE_REQ_PUBLICKEY: case MSG_TYPE_RESP_PUBLICKEY: ParsePublicKeyMessageExt(jsonObject); break; - case MSG_TYPE_REQ_SYNC_DELETE: - ParseSyncDeleteMessageExt(jsonObject); - break; default: break; } return DM_OK; } -void AuthMessageProcessor::ParseSyncDeleteMessageExt(nlohmann::json &json) -{ - if (IsString(json, TAG_LOCAL_DEVICE_ID)) { - authResponseContext_->localDeviceId = json[TAG_LOCAL_DEVICE_ID].get(); - } - if (IsString(json, TAG_HOST_PKGNAME)) { - authResponseContext_->hostPkgName = json[TAG_HOST_PKGNAME].get(); - } - if (IsInt32(json, TAG_REPLY)) { - authResponseContext_->reply = json[TAG_REPLY].get(); - } -} - void AuthMessageProcessor::ParsePublicKeyMessageExt(nlohmann::json &json) { if (IsString(json, TAG_PUBLICKEY)) { diff --git a/services/implementation/src/authentication/auth_request_state.cpp b/services/implementation/src/authentication/auth_request_state.cpp index 1d479538a..77f670978 100644 --- a/services/implementation/src/authentication/auth_request_state.cpp +++ b/services/implementation/src/authentication/auth_request_state.cpp @@ -204,53 +204,5 @@ int32_t AuthRequestCredentialDone::Enter() stateAuthManager->RequestCredentialDone(); return DM_OK; } - -int32_t AuthRequestDeleteInit::GetStateType() -{ - return AuthState::AUTH_REQUEST_DELETE_INIT; -} - -int32_t AuthRequestDeleteInit::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return ERR_DM_FAILED; - } - stateAuthManager->EstablishUnbindChannel(context_->deviceId); - return DM_OK; -} - -int32_t AuthRequestSyncDeleteAcl::GetStateType() -{ - return AuthState::AUTH_REQUEST_SYNCDELETE; -} - -int32_t AuthRequestSyncDeleteAcl::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return ERR_DM_FAILED; - } - stateAuthManager->RequestSyncDeleteAcl(); - return DM_OK; -} - -int32_t AuthRequestSyncDeleteAclNone::GetStateType() -{ - return AuthState::AUTH_REQUEST_SYNCDELETE_DONE; -} - -int32_t AuthRequestSyncDeleteAclNone::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return ERR_DM_FAILED; - } - stateAuthManager->SyncDeleteAclDone(); - return DM_OK; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_response_state.cpp b/services/implementation/src/authentication/auth_response_state.cpp index e86ef6fa2..7f1803fa0 100644 --- a/services/implementation/src/authentication/auth_response_state.cpp +++ b/services/implementation/src/authentication/auth_response_state.cpp @@ -168,37 +168,5 @@ int32_t AuthResponseCredential::Enter() stateAuthManager->ResponseCredential(); return DM_OK; } - -int32_t AuthResponseSyncDeleteAcl::GetStateType() -{ - return AuthState::AUTH_RESPONSE_SYNCDELETE; -} - -int32_t AuthResponseSyncDeleteAcl::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthResponseSyncDeleteAcl authManager_ is null"); - return ERR_DM_FAILED; - } - stateAuthManager->ResponseSyncDeleteAcl(); - return DM_OK; -} - -int32_t AuthResponseSyncDeleteAclNone::GetStateType() -{ - return AuthState::AUTH_RESPONSE_SYNCDELETE_DONE; -} - -int32_t AuthResponseSyncDeleteAclNone::Enter() -{ - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthResponseSyncDeleteAclNone authManager_ is null"); - return ERR_DM_FAILED; - } - stateAuthManager->SyncDeleteAclDone(); - return DM_OK; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 318a7a28a..75f026ea9 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -70,10 +70,10 @@ const int32_t DM_AUTH_TYPE_MAX = 5; const int32_t DM_AUTH_TYPE_MIN = 0; const int32_t AUTH_SESSION_SIDE_SERVER = 0; const int32_t USLEEP_TIME_MS = 500000; // 500ms -const int32_t SYNC_DELETE_TIMEOUT = 60; const int32_t AUTH_DEVICE_TIMEOUT = 10; const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; +const int32_t STRTOLL_BASE = 10; // clone task timeout map const std::map TASK_TIME_OUT_MAP = { @@ -180,7 +180,7 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->localDeviceTypeId = softbusConnector_->GetLocalDeviceTypeId(); authRequestContext_->localDeviceId = localUdid; authRequestContext_->deviceId = deviceId; - authRequestContext_->ip = deviceId; + authRequestContext_->addr = deviceId; authRequestContext_->dmVersion = DM_VERSION_5_0_2; authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); MultipleUserConnector::SetSwitchOldAccountId(authRequestContext_->localAccountId); @@ -203,8 +203,8 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, if (IsString(jsonObject, APP_THUMBNAIL)) { authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); } - if (IsInt64(jsonObject, TAG_TOKENID)) { - authRequestContext_->tokenId = jsonObject[TAG_TOKENID].get(); + if (IsString(jsonObject, TAG_TOKENID)) { + authRequestContext_->tokenId = StringToInt64(jsonObject[TAG_TOKENID].get(), STRTOLL_BASE); } if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { authRequestContext_->bindLevel = jsonObject[TAG_BIND_LEVEL].get(); @@ -261,7 +261,7 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au return DM_OK; } -int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) +int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -275,39 +275,65 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st authRequestState_->TransitionTo(std::make_shared()); return DM_OK; } else { - LOGE("UnBindDevice is syncchronizing sink acl data."); + LOGE("UnAuthenticateDevice is syncchronizing sink acl data."); return ERR_DM_FAILED; } } - std::string deviceUdid = ""; - int32_t ret = SoftbusConnector::GetUdidByNetworkId(networkId.c_str(), deviceUdid); - if (ret != DM_OK) { - LOGE("UnAuthenticateDevice GetNodeKeyInfo failed"); - return ret; - } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); struct RadarInfo info = { .funcName = "UnAuthenticateDevice", .toCallPkg = HICHAINNAME, .hostName = pkgName, - .peerNetId = networkId, .localUdid = localDeviceId, - .peerUdid = deviceUdid, + .peerUdid = udid, }; if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) { LOGE("ReportDeleteTrustRelation failed"); } - if (!DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, deviceUdid)) { - LOGE("The pkgName %{public}s cannot unbind.", pkgName.c_str()); + remoteDeviceId_ = udid; + if (bindLevel == DEVICE) { + DeleteGroup(pkgName, udid); + } + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel); +} + +int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel) +{ + LOGI("DeleteAcl pkgName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + pkgName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + DmOfflineParam offlineParam = + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localUdid, remoteUdid, bindLevel); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the pkgname bind data."); return ERR_DM_FAILED; } - remoteDeviceId_ = deviceUdid; - SyncDeleteAcl(pkgName, deviceUdid); - return DM_OK; + if (bindLevel == APP && offlineParam.leftAclNumber != 0) { + LOGI("The pkgName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetPkgName(pkgName); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return DM_OK; + } + if (bindLevel == APP && offlineParam.leftAclNumber == 0) { + LOGI("The pkgName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetPkgName(pkgName); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + if (bindLevel == DEVICE && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + return DM_OK; + } + if (bindLevel == DEVICE && offlineParam.leftAclNumber == 0) { + LOGI("Unbind deivce-level, retain null."); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + return ERR_DM_FAILED; } -int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udidHash) +int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -325,35 +351,12 @@ int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::strin return ERR_DM_FAILED; } } - remoteDeviceId_ = SoftbusConnector::GetDeviceUdidByUdidHash(udidHash); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - if (!DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId_)) { - LOGE("The pkgname %{public}s cannot unbind.", pkgName.c_str()); - return ERR_DM_FAILED; + if (bindLevel == DEVICE) { + DeleteGroup(pkgName, udid); } - SyncDeleteAcl(pkgName, remoteDeviceId_); - return DM_OK; -} - -void DmAuthManager::SyncDeleteAcl(const std::string &pkgName, const std::string &deviceId) -{ - LOGI("SyncDeleteAcl start."); - authMessageProcessor_ = std::make_shared(shared_from_this()); - authResponseContext_ = std::make_shared(); - authRequestContext_ = std::make_shared(); - - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = static_cast(localDeviceId); - authRequestContext_->localDeviceId = localUdid; - authRequestContext_->hostPkgName = pkgName; - authRequestContext_->deviceId = deviceId; - authMessageProcessor_->SetRequestContext(authRequestContext_); - authRequestState_ = std::make_shared(); - authRequestState_->SetAuthManager(shared_from_this()); - authRequestState_->SetAuthContext(authRequestContext_); - authRequestState_->Enter(); + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel); } void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash) @@ -473,13 +476,6 @@ void DmAuthManager::ProcessSourceMsg() authRequestState_->TransitionTo(std::make_shared()); } break; - case MSG_TYPE_REQ_SYNC_DELETE_DONE: - if (authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_SYNCDELETE) { - timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK)); - isFinishOfLocal_ = false; - authRequestState_->TransitionTo(std::make_shared()); - } - break; default: break; } @@ -519,18 +515,6 @@ void DmAuthManager::ProcessSinkMsg() authResponseState_->TransitionTo(std::make_shared()); } break; - case MSG_TYPE_REQ_SYNC_DELETE: - if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { - authResponseState_->TransitionTo(std::make_shared()); - } - break; - case MSG_TYPE_REQ_SYNC_DELETE_DONE: - if (authResponseState_->GetStateType() == AuthState::AUTH_REQUEST_SYNCDELETE) { - timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK)); - isFinishOfLocal_ = false; - authResponseState_->TransitionTo(std::make_shared()); - } - break; default: break; } @@ -934,7 +918,7 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) || (authResponseContext_->authed && !authResponseContext_->isOnline)) { - softbusConnector_->JoinLnn(authRequestContext_->deviceId); + softbusConnector_->JoinLnn(authRequestContext_->addr); authRequestContext_->reason = DM_OK; authRequestState_->TransitionTo(std::make_shared()); return; @@ -1115,7 +1099,7 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) return ERR_DM_FAILED; } isAddingMember_ = true; - int32_t ret = hiChainConnector_->AddMember(authRequestContext_->ip, connectInfo); + int32_t ret = hiChainConnector_->AddMember(authRequestContext_->addr, connectInfo); struct RadarInfo info = { .funcName = "AddMember", .stageRes = (ret == 0) ? @@ -1847,7 +1831,7 @@ void DmAuthManager::RequestCredentialDone() LOGE("ResponseCredential import credential failed."); } timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); - softbusConnector_->JoinLnn(authRequestContext_->ip); + softbusConnector_->JoinLnn(authRequestContext_->addr); authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestContext_->reason = DM_OK; authRequestState_->TransitionTo(std::make_shared()); @@ -1860,101 +1844,6 @@ int32_t DmAuthManager::ImportCredential(std::string &deviceId, std::string &publ return hiChainAuthConnector_->ImportCredential(osAccountId, deviceId, publicKey); } -int32_t DmAuthManager::EstablishUnbindChannel(const std::string &deviceIdHash) -{ - LOGI("DmAuthManager::EstablishUnbindChannel"); - std::string netWorkId = softbusConnector_->GetNetworkIdByDeviceId(deviceIdHash); - int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenUnbindSession(netWorkId); - if (sessionId < 0) { - LOGE("OpenAuthSession failed, stop the syncdeleteacl."); - authResponseContext_ = std::make_shared(); - authResponseContext_->state = AuthState::AUTH_REQUEST_SYNCDELETE; - authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; - authRequestContext_->reason = sessionId; - if (authRequestState_ != nullptr) { - authRequestState_->TransitionTo(std::make_shared()); - } - } - return DM_OK; -} - -void DmAuthManager::RequestSyncDeleteAcl() -{ - LOGI("RequestSyncDeleteAcl start."); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE); - softbusConnector_->GetSoftbusSession()->SendData(authRequestContext_->sessionId, message); - if (timer_ == nullptr) { - timer_ = std::make_shared(); - } - timer_->StartTimer(std::string(SYNC_DELETE_TIMEOUT_TASK), SYNC_DELETE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleSyncDeleteTimeout(name); - }); -} - -void DmAuthManager::SrcSyncDeleteAclDone() -{ - LOGI("DmAuthManager::SrcSyncDeleteAclDone, isFinishOfLocal: %{public}d", isFinishOfLocal_); - if (isFinishOfLocal_) { - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - usleep(USLEEP_TIME_MS); - } - if (authResponseContext_->reply == DM_OK) { - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) && - DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(authResponseContext_->hostPkgName, - remoteDeviceId_)) { - DeleteGroup(authResponseContext_->hostPkgName, remoteDeviceId_); - } - DeleteAcl(authResponseContext_->hostPkgName, remoteDeviceId_); - } - softbusConnector_->GetSoftbusSession()->CloseUnbindSession(authRequestContext_->sessionId); - timer_->DeleteAll(); - isFinishOfLocal_ = true; - authRequestContext_ = nullptr; - authResponseContext_ = nullptr; - authRequestState_ = nullptr; - authMessageProcessor_ = nullptr; -} - -void DmAuthManager::SinkSyncDeleteAclDone() -{ - LOGI("DmAuthManager::SinkSyncDeleteAclDone, isFinishOfLocal: %{public}d", isFinishOfLocal_); - if (isFinishOfLocal_) { - authMessageProcessor_->SetResponseContext(authResponseContext_); - std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE); - softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); - if (authResponseContext_->reply == DM_OK) { - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - if (hiChainConnector_->IsDevicesInP2PGroup(remoteDeviceId_, localUdid) && - DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(authResponseContext_->hostPkgName, - remoteDeviceId_)) { - DeleteGroup(authResponseContext_->hostPkgName, remoteDeviceId_); - } - DeleteAcl(authResponseContext_->hostPkgName, remoteDeviceId_); - } - } - timer_->DeleteAll(); - isFinishOfLocal_ = true; - authResponseContext_ = nullptr; - authResponseState_ = nullptr; - authMessageProcessor_ = nullptr; -} - -void DmAuthManager::SyncDeleteAclDone() -{ - LOGI("SyncDeleteAclDone start."); - if (authRequestState_ != nullptr) { - SrcSyncDeleteAclDone(); - } else if (authResponseState_ != nullptr) { - SinkSyncDeleteAclDone(); - } -} - void DmAuthManager::ResponseCredential() { LOGI("DmAuthManager::ResponseCredential start."); @@ -1968,14 +1857,6 @@ void DmAuthManager::ResponseCredential() softbusConnector_->GetSoftbusSession()->SendData(authResponseContext_->sessionId, message); } -void DmAuthManager::ResponseSyncDeleteAcl() -{ - LOGI("ResponseSyncDeleteAcl start."); - timer_->DeleteTimer(std::string(SYNC_DELETE_TIMEOUT_TASK)); - remoteDeviceId_ = authResponseContext_->localDeviceId; - authResponseState_->TransitionTo(std::make_shared()); -} - bool DmAuthManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) { LOGI("DmAuthManager::onTransmit start."); @@ -2004,7 +1885,8 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH || (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && authResponseContext_->haveCredential)) { - if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) { + if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && + !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); @@ -2017,7 +1899,8 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && !authResponseContext_->haveCredential) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) { + if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && + !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); @@ -2026,7 +1909,7 @@ void DmAuthManager::SrcAuthDeviceFinish() } } if (!authResponseContext_->isOnline && authResponseContext_->haveCredential) { - softbusConnector_->JoinLnn(authRequestContext_->ip); + softbusConnector_->JoinLnn(authRequestContext_->addr); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); authRequestContext_->reason = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; @@ -2047,9 +1930,7 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - if (authResponseContext_->bindLevel == APP && !authResponseContext_->isIdenticalAccount) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); - } + softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -2164,108 +2045,6 @@ void DmAuthManager::CompatiblePutAcl() DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee); } -void DmAuthManager::CommonEventCallback(int32_t userId, std::string commonEventType) -{ - LOGI("DmAuthManager::CommonEventCallback"); - if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - AccountIdLogoutEventCallback(userId); - } else if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - LOGI("user_switched event accountId: %{public}s, userId: %{public}s", - GetAnonyString(accountId).c_str(), GetAnonyInt32(userId).c_str()); - if (userId > 0) { - MultipleUserConnector::SetSwitchOldUserId(userId); - MultipleUserConnector::SetSwitchOldAccountId(accountId); - } - } -} - -void DmAuthManager::AccountIdLogoutEventCallback(int32_t userId) -{ - LOGI("DmAuthManager::AccountIdLogoutEventCallback"); - std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId(); - std::string currentAccountId = MultipleUserConnector::GetOhosAccountId(); - MultipleUserConnector::SetSwitchOldAccountId(currentAccountId); - if (oldAccountId == currentAccountId) { - LOGE("The account logout is error."); - return; - } - if (currentAccountId == "ohosAnonymousUid" && - DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, oldAccountId)) { - DeviceProfileConnector::GetInstance().DeleteAccessControlList(userId, oldAccountId); - hiChainConnector_->DeleteAllGroup(userId); - } -} - -void DmAuthManager::UserSwitchEventCallback(int32_t userId) -{ - LOGI("UserSwitchEventCallback start."); - std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId(); - int32_t oldUserId = MultipleUserConnector::GetSwitchOldUserId(); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(oldUserId, oldAccountId); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, oldAccountId); - hiChainConnector_->DeleteP2PGroup(userId); -} - -void DmAuthManager::UserChangeEventCallback(int32_t userId) -{ - LOGI("DmAuthManager::UserChangeEventCallback"); - std::string oldAccountId = MultipleUserConnector::GetSwitchOldAccountId(); - int32_t oldUseId = MultipleUserConnector::GetSwitchOldUserId(); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(oldUseId, oldAccountId); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, oldAccountId); - hiChainConnector_->DeleteP2PGroup(userId); -} - -void DmAuthManager::HandleSyncDeleteTimeout(std::string name) -{ - LOGI("DmAuthManager::HandleSyncDeleteTimeout start timer name %{public}s", name.c_str()); - if (authRequestState_ != nullptr && authRequestState_->GetStateType() != AuthState::AUTH_REQUEST_SYNCDELETE_DONE) { - if (authResponseContext_ == nullptr) { - authResponseContext_ = std::make_shared(); - } - authResponseContext_->state = authRequestState_->GetStateType(); - authResponseContext_->reply = ERR_DM_TIME_OUT; - authRequestState_->TransitionTo(std::make_shared()); - } - - if (authResponseState_ != nullptr && - authResponseState_->GetStateType() != AuthState::AUTH_RESPONSE_SYNCDELETE_DONE) { - authResponseContext_->state = authResponseState_->GetStateType(); - authResponseContext_->reply = ERR_DM_TIME_OUT; - authResponseState_->TransitionTo(std::make_shared()); - } - LOGI("DmAuthManager::HandleSyncDeleteTimeout start complete"); -} - -int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &deviceId) -{ - char localUdid[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string localDeviceId = static_cast(localUdid); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, deviceId); - if (offlineParam.bindType == INVALIED_TYPE) { - LOGE("Acl not contain the pkgName bind data."); - return ERR_DM_FAILED; - } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber != 0) { - LOGI("The pkgName unbind app-level type leftAclNumber not zero."); - softbusConnector_->SetPkgName(pkgName); - softbusConnector_->HandleDeviceOffline(deviceId); - } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber == 0) { - LOGI("The pkgName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetPkgName(pkgName); - hiChainAuthConnector_->DeleteCredential(deviceId, MultipleUserConnector::GetCurrentAccountUserID()); - } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber != 0) { - LOGI("Unbind deivce-level, retain identical account bind type."); - } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE && offlineParam.leftAclNumber == 0) { - LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(deviceId, MultipleUserConnector::GetCurrentAccountUserID()); - } - return DM_OK; -} - void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) { LOGI("DmAuthManager::ProcRespNegotiateExt start."); @@ -2377,60 +2156,6 @@ void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std: hiChainAuthConnector_->ProcessAuthData(authResponseContext_->requestId, authData, osAccountId); } -void DmAuthManager::BindSocketFail() -{ - LOGE("BindSocketFail"); - authResponseContext_->reply = DM_OK; - isFinishOfLocal_ = false; - authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; -} - -void DmAuthManager::BindSocketSuccess(int32_t socket) -{ - LOGI("BindSocketSuccess"); - if (authResponseState_ == nullptr && authRequestState_ != nullptr && - authRequestState_->GetStateType() == AuthState::AUTH_REQUEST_DELETE_INIT) { - authRequestContext_->sessionId = socket; - authRequestState_->SetAuthContext(authRequestContext_); - authMessageProcessor_->SetRequestContext(authRequestContext_); - authResponseContext_->localDeviceId = authRequestContext_->localDeviceId; - authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; - authMessageProcessor_->SetResponseContext(authResponseContext_); - authRequestState_->TransitionTo(std::make_shared()); - } else { - softbusConnector_->GetSoftbusSession()->CloseUnbindSession(socket); - LOGE("DmAuthManager::BindSocketSuccess but request state is wrong"); - } -} - -void DmAuthManager::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) -{ - LOGI("DmAuthManager::OnUnbindSessionOpened socket: %{public}d, peerSocketName: %{public}s, peerNetworkId:" - "%{public}s, peerPkgName: %{public}s", socket, info.name, GetAnonyString(info.networkId).c_str(), info.pkgName); - if (authResponseState_ == nullptr && authRequestState_ == nullptr) { - authMessageProcessor_ = std::make_shared(shared_from_this()); - authResponseState_ = std::make_shared(); - authResponseState_->SetAuthManager(shared_from_this()); - authResponseState_->Enter(); - authResponseContext_ = std::make_shared(); - if (timer_ == nullptr) { - timer_ = std::make_shared(); - } - timer_->StartTimer(std::string(SYNC_DELETE_TIMEOUT_TASK), SYNC_DELETE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleSyncDeleteTimeout(name); - }); - } else { - std::shared_ptr authMessageProcessor = - std::make_shared(shared_from_this()); - std::shared_ptr authResponseContext = std::make_shared(); - authResponseContext->reply = ERR_DM_SYNC_DELETE_DEVICE_REPEATED; - authMessageProcessor->SetResponseContext(authResponseContext); - std::string message = authMessageProcessor->CreateSimpleMessage(MSG_TYPE_REQ_SYNC_DELETE_DONE); - softbusConnector_->GetSoftbusSession()->SendData(socket, message); - } -} - int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) { LOGI("DmAuthManager::DeleteGroup"); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 4721bd730..fb44191f6 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -1131,39 +1131,6 @@ void HiChainConnector::DeleteAllGroup(int32_t userId) } } -void HiChainConnector::DeleteP2PGroup(int32_t userId) -{ - LOGI("switch user event happen and this user groups will be deleted with userId: %{public}d", userId); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - std::string queryParams = jsonObj.dump(); - std::vector groupList; - - int32_t oldUserId = MultipleUserConnector::GetSwitchOldUserId(); - MultipleUserConnector::SetSwitchOldUserId(userId); - if (!GetGroupInfo(oldUserId, queryParams, groupList)) { - LOGE("failed to get the old user id groups"); - return; - } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - int32_t ret = DeleteGroup(oldUserId, iter->groupId); - if (ret != DM_OK) { - LOGE("failed to delete the old user id group"); - } - } - - if (!GetGroupInfo(userId, queryParams, groupList)) { - LOGE("failed to get the user id groups"); - return; - } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - int32_t ret = DeleteGroup(userId, iter->groupId); - if (ret != DM_OK) { - LOGE("failed to delete the user id group"); - } - } -} - int32_t HiChainConnector::GetRelatedGroupsCommon(const std::string &deviceId, const char* pkgName, std::vector &groupList) { diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index ba32951e4..54b5138ca 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -118,13 +118,6 @@ int32_t SoftbusSession::CloseAuthSession(int32_t sessionId) return DM_OK; } -int32_t SoftbusSession::CloseUnbindSession(int32_t socket) -{ - LOGI("CloseUnbindSession."); - Shutdown(socket); - return DM_OK; -} - int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) { char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; @@ -216,41 +209,5 @@ void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned i } LOGI("completed."); } - -void SoftbusSession::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) -{ - sessionCallback_->OnUnbindSessionOpened(socket, info); - LOGI("SoftbusSession::OnUnbindSessionOpened success, socket: %{public}d.", socket); -} - -int32_t SoftbusSession::OpenUnbindSession(const std::string &netWorkId) -{ - std::string localSessionName = DM_UNBIND_SESSION_NAME + netWorkId.substr(0, INTERCEPT_STRING_LENGTH); - SocketInfo info = { - .name = const_cast(localSessionName.c_str()), - .peerName = const_cast(DM_UNBIND_SESSION_NAME), - .peerNetworkId = const_cast(netWorkId.c_str()), - .pkgName = const_cast(DM_PKG_NAME), - .dataType = DATA_TYPE_BYTES - }; - - int32_t socket = Socket(info); - if (socket <= 0) { - LOGE("[SOFTBUS]create socket failed, socket: %{public}d", socket); - return socket; - } - - int32_t ret = Bind(socket, g_qosInfo, g_qosTVParamIndex, &iSocketListener_); - if (ret < DM_OK) { - LOGE("[SOFTBUS]OpenUnbindSession failed, netWorkId: %{public}s, socket: %{public}d", - GetAnonyString(netWorkId).c_str(), socket); - sessionCallback_->BindSocketFail(); - Shutdown(socket); - return ret; - } - LOGI("OpenUnbindSession success. socket: %{public}d.", socket); - sessionCallback_->BindSocketSuccess(socket); - return socket; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a190eeaf5..2b462bb06 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -79,6 +79,7 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr(hiChainConnector_, listener); } + listener_ = listener; LOGI("Init success, singleton initialized"); return DM_OK; } @@ -147,52 +148,26 @@ int32_t DeviceManagerServiceImpl::UnPublishDeviceDiscovery(const std::string &pk return publishMgr_->UnPublishDeviceDiscovery(pkgName, publishId); } -int32_t DeviceManagerServiceImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) +int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { - if (pkgName.empty() || deviceId.empty()) { - LOGE("DeviceManagerServiceImpl::AuthenticateDevice failed, pkgName is %{public}s, deviceId is %{public}s," - "extra is %{public}s", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerServiceImpl::UnAuthenticateDevice failed, pkgName is %{public}s, udid is %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - if (deviceStateMgr_ != nullptr) { - deviceStateMgr_->DeleteOffLineTimer(deviceId); - } - return authMgr_->AuthenticateDevice(pkgName, authType, deviceId, extra); -} - -int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) -{ - if (pkgName.empty() || networkId.empty()) { - LOGE("DeviceManagerServiceImpl::UnAuthenticateDevice failed, pkgName is %{public}s, networkId is %{public}s", - pkgName.c_str(), GetAnonyString(networkId).c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - return authMgr_->UnAuthenticateDevice(pkgName, networkId); -} - -int32_t DeviceManagerServiceImpl::BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam) -{ - if (pkgName.empty() || udidHash.empty()) { - LOGE("DeviceManagerServiceImpl::BindDevice failed, pkgName is %{public}s, udidHash is %{public}s, bindParam is" - "%{public}s", pkgName.c_str(), GetAnonyString(udidHash).c_str(), bindParam.c_str()); - return ERR_DM_INPUT_PARA_INVALID; - } - if (deviceStateMgr_ != nullptr) { - deviceStateMgr_->DeleteOffLineTimer(udidHash); - } - return authMgr_->AuthenticateDevice(pkgName, authType, udidHash, bindParam); + return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); } -int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udidHash) +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { - if (pkgName.empty() || udidHash.empty()) { - LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udidHash is %{public}s", - pkgName.c_str(), GetAnonyString(udidHash).c_str()); + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerServiceImpl::UnBindDevice failed, pkgName is %{public}s, udid is %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnBindDevice(pkgName, udidHash); + return authMgr_->UnBindDevice(pkgName, udid, bindLevel); } int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action, @@ -225,7 +200,7 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf } char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string requestDeviceId = static_cast(localUdid); + std::string requestDeviceId = std::string(localUdid); DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); LOGI("The offline device bind type is %{public}d.", offlineParam.bindType); @@ -263,10 +238,10 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo } char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); - std::string requestDeviceId = static_cast(localUdid); + std::string requestDeviceId = std::string(localUdid); uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); LOGI("The online device bind type is %{public}d.", bindType); - if (bindType == INVALIED_TYPE) { + if (bindType == INVALIED_TYPE && isCredentialType_.load()) { PutIdenticalAccountToAcl(requestDeviceId, trustDeviceId); devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; } else if (bindType == IDENTICAL_ACCOUNT_TYPE) { @@ -372,6 +347,7 @@ int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, c LOGE("credentialMgr_ is nullptr"); return ERR_DM_POINT_NULL; } + isCredentialType_.store(true); return credentialMgr_->ImportCredential(pkgName, credentialInfo); } @@ -386,6 +362,7 @@ int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, c LOGE("credentialMgr_ is nullptr"); return ERR_DM_POINT_NULL; } + isCredentialType_.store(false); return credentialMgr_->DeleteCredential(pkgName, deleteInfo); } @@ -426,6 +403,7 @@ int32_t DeviceManagerServiceImpl::ImportCredential(const std::string &pkgName, c LOGE("failed to import devices credential"); return ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED; } + isCredentialType_.store(true); return DM_OK; } @@ -441,6 +419,7 @@ int32_t DeviceManagerServiceImpl::DeleteCredential(const std::string &pkgName, c LOGE("failed to delete devices credential"); return ERR_DM_HICHAIN_CREDENTIAL_DELETE_FAILED; } + isCredentialType_.store(false); return DM_OK; } @@ -615,7 +594,7 @@ void DeviceManagerServiceImpl::PutIdenticalAccountToAcl(std::string requestDevic LOGI("DeviceManagerServiceImpl::PutIdenticalAccountAcl start."); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; Crypto::GetUdidHash(requestDeviceId, reinterpret_cast(localDeviceId)); - std::string localUdidHash = static_cast(localDeviceId); + std::string localUdidHash = std::string(localDeviceId); DmAclInfo aclInfo; aclInfo.bindType = IDENTICAL_ACCOUNT; aclInfo.trustDeviceId = trustDeviceId; @@ -664,36 +643,30 @@ std::unordered_map DeviceManagerServiceImpl::GetAppTrus return DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgname, deviceId); } -void DeviceManagerServiceImpl::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) -{ - SoftbusSession::OnUnbindSessionOpened(socket, info); -} - -void DeviceManagerServiceImpl::OnUnbindSessionCloseed(int32_t socket) +void DeviceManagerServiceImpl::LoadHardwareFwkService() { - SoftbusSession::OnSessionClosed(socket); + DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); } -void DeviceManagerServiceImpl::OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen) +void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &udid, int32_t userId, + const std::string &accountId) { - SoftbusSession::OnBytesReceived(socket, data, dataLen); + LOGI("Udid %{public}s, userId %{public}d, accountId %{public}s.", GetAnonyString(udid).c_str(), + userId, GetAnonyString(accountId).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, userId, udid); + CHECK_NULL_VOID(hiChainConnector_); + authMgr_->DeleteGroup(DM_PKG_NAME, udid); } -void DeviceManagerServiceImpl::LoadHardwareFwkService() +void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) { - DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); -} - -void DeviceManagerServiceImpl::AccountCommonEventCallback(int32_t userId, std::string commonEventType) -{ - if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED || - commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - authMgr_->CommonEventCallback(userId, commonEventType); - LOGI("DeviceManagerServiceImpl::account event: %{public}s, userId: %{public}s", - commonEventType.c_str(), GetAnonyInt32(userId).c_str()); - return; - } - LOGI("DeviceManagerServiceImpl::AccountCommonEventCallback error."); + LOGI("PreUserId %{public}d.", preUserId); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(preUserId); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(preUserId); } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -729,6 +702,86 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) authMgr_->HandleDeviceNotTrust(udid); } +int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + return DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); +} + +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId, + const std::string &accountId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindType(userId, accountId, localUdid); +} + +void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + int32_t bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, + remoteUdid, localUdid); + if (bindType == DM_INVALIED_BINDTYPE) { + LOGE("Invalied bindtype."); + return; + } + CHECK_NULL_VOID(authMgr_); + authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); + CHECK_NULL_VOID(listener_); + listener_->OnDeviceTrustChange(remoteUdid, ConvertBindTypeToAuthForm(bindType)); +} + +DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) +{ + LOGI("BindType %{public}d.", bindType); + DmAuthForm authForm = DmAuthForm::INVALID_TYPE; + if (bindType == DM_IDENTICAL_ACCOUNT) { + authForm = IDENTICAL_ACCOUNT; + } else if(bindType == DM_POINT_TO_POINT) { + authForm = PEER_TO_PEER; + } else if(bindType == DM_ACROSS_ACCOUNT) { + authForm = ACROSS_ACCOUNT; + } else { + LOGE("Invalied bindType."); + } + return authForm; +} + +void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + if (bindType == DM_INVALIED_BINDTYPE) { + LOGE("Invalied bindtype."); + return; + } + CHECK_NULL_VOID(authMgr_); + authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); +} + +void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int64_t tokenId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::string pkgName = + DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + if (pkgName.empty()) { + LOGE("Pkgname is empty."); + return; + } + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetPkgName(pkgName); + softbusConnector_->HandleDeviceOffline(remoteUdid); +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 2864f44b7..4d2ad6989 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -24,6 +24,7 @@ namespace OHOS { namespace DistributedHardware { +constexpr uint32_t DEVICE_BIUND_LEVEL = 1; DeviceManagerServiceImpl::DeviceManagerServiceImpl() { LOGI("DeviceManagerServiceImpl constructor"); @@ -109,37 +110,21 @@ int32_t DeviceManagerServiceImpl::UnPublishDeviceDiscovery(const std::string &pk return DM_OK; } -int32_t DeviceManagerServiceImpl::AuthenticateDevice(const std::string &pkgName, int32_t authType, - const std::string &deviceId, const std::string &extra) +int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { (void)pkgName; - (void)authType; - (void)deviceId; - (void)extra; - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) -{ - (void)pkgName; - (void)networkId; - return DM_OK; -} - -int32_t DeviceManagerServiceImpl::BindDevice(const std::string &pkgName, int32_t authType, const std::string &udidHash, - const std::string &bindParam) -{ - (void)pkgName; - (void)authType; - (void)udidHash; - (void)bindParam; + (void)udid; + (void)bindLevel; return DM_OK; } -int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udidHash) +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) { (void)pkgName; - (void)udidHash; + (void)udid; + (void)bindLevel; return DM_OK; } @@ -416,24 +401,6 @@ std::unordered_map DeviceManagerServiceImpl::GetAppTrus return tmp; } -void DeviceManagerServiceImpl::OnUnbindSessionOpened(int32_t sessionId, PeerSocketInfo info) -{ - (void)sessionId; - (void)info; -} - -void DeviceManagerServiceImpl::OnUnbindSessionCloseed(int32_t sessionId) -{ - (void)sessionId; -} - -void DeviceManagerServiceImpl::OnUnbindBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) -{ - (void)sessionId; - (void)data; - (void)dataLen; -} - void DeviceManagerServiceImpl::LoadHardwareFwkService() { } @@ -450,12 +417,6 @@ int32_t DeviceManagerServiceImpl::IsSameAccount(const std::string &udid) return DM_OK; } -void DeviceManagerServiceImpl::AccountCommonEventCallback(int32_t userId, std::string commonEventType) -{ - (void)userId; - (void)commonEventType; -} - void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) { (void)commonEventType; @@ -487,6 +448,64 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) return; } +int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + (void)pkgName; + (void)udid; + (void)tokenId; + (void)localUdid; + return DEVICE_BIUND_LEVEL; +} + +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId, + const std::string &accountId) +{ + (void)userId; + (void)accountId; + return std::map {}; +} + +void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid) +{ + (void)remoteUserId; + (void)remoteAccountHash; + (void)remoteUdid; + return; +} + +void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) +{ + (void)remoteUserId; + (void)remoteUdid; + return; +} + +void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int64_t tokenId) +{ + (void)remoteUserId; + (void)remoteUdid; + (void)tokenId; + return; +} + +void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &udid, int32_t userId, + const std::string &accountId) +{ + (void)udid; + (void)userId; + (void)accountId; + return; +} + +void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) +{ + (void)preUserId; + return; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index bdd8a1470..ef19386c7 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -30,6 +30,7 @@ if (defined(ohos_lite)) { "include/ipc/lite", "include/permission/lite", "include/pinholder", + "include/relationshipsyncmgr", "${common_path}/include", "${common_path}/include/ipc", "${common_path}/include/ipc/lite", @@ -71,6 +72,7 @@ if (defined(ohos_lite)) { "src/permission/lite/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", + "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", ] @@ -123,6 +125,7 @@ if (defined(ohos_lite)) { "include/permission/standard", "include/pinholder", "include/publishcommonevent", + "include/relationshipsyncmgr", "include/softbus", "${common_path}/include", "${common_path}/include/dfx", @@ -171,6 +174,7 @@ if (defined(ohos_lite)) { "src/pinholder/pin_holder_session.cpp", "src/publishcommonevent/dm_account_common_event.cpp", "src/publishcommonevent/dm_screen_common_event.cpp", + "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", ] @@ -194,6 +198,7 @@ if (defined(ohos_lite)) { "ability_base:want", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index a29f27369..4e6f3ae8b 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -95,7 +95,7 @@ public: int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &bindParam); - int32_t UnBindDevice(const std::string &pkgName, const std::string &deviceId); + int32_t UnBindDevice(const std::string &pkgName, const std::string &udidHash); int32_t SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms); @@ -180,10 +180,6 @@ public: int32_t UnbindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &unbindParam); - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info); - void OnUnbindSessionCloseed(int32_t socket); - void OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen); - int32_t DpAclAdd(const std::string &udid); int32_t GetDeviceSecurityLevel(const std::string &pkgName, const std::string &networkId, int32_t &networkType); @@ -193,6 +189,7 @@ public: bool CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee); bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); void HandleDeviceNotTrust(const std::string &msg); + void HandleDeviceTrustedChange(const std::string &msg); private: bool IsDMServiceImplReady(); @@ -200,14 +197,24 @@ private: bool IsDMImplSoLoaded(); void UnloadDMServiceImplSo(); void UnloadDMServiceAdapter(); + void SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, + int32_t bindLevel); + void SendDeviceUnBindBroadCast(const std::vector &peerUdids, int32_t userId); + void SendAppUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId); + void SendServiceUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId); + void SendAccountLogoutBroadCast(const std::vector &peerUdids, const std::string &accountId, + const std::string &accountName, int32_t userId); + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void SubscribeAccountCommonEvent(); - void AccountCommonEventCallback(int32_t userId, std::string commonEventType); + void AccountCommonEventCallback(int32_t userId, const std::string commonEventType); void SubscribeScreenLockEvent(); void ScreenCommonEventCallback(std::string commonEventType); void ConvertUdidHashToAnoy(DmDeviceInfo &deviceInfo); int32_t ConvertUdidHashToAnoy(const std::string &udidHash, std::string &result); int32_t GetUdidHashByAnoyUdid(const std::string &anoyUdid, std::string &udidHash); + void HandleAccountLogout(int32_t userId, const std::string &accountId); + void HandleUserRemoved(int32_t preUserId); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 6ca02a843..279d5a5aa 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -71,6 +71,7 @@ public: void OnDestroyResult(const std::string &pkgName, int32_t result) override; void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content) override; + void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index d0d06323a..87c1e2b19 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -83,35 +83,19 @@ public: */ virtual int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId) = 0; - /** - * @tc.name: IDeviceManagerServiceImpl::AuthenticateDevice - * @tc.desc: Authenticate Device of the device manager service impl - * @tc.type: FUNC - */ - virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &extra) = 0; - /** * @tc.name: IDeviceManagerServiceImpl::UnAuthenticateDevice * @tc.desc: UnAuthenticate Device of the device manager service impl * @tc.type: FUNC */ - virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId) = 0; - - /** - * @tc.name: IDeviceManagerServiceImpl::BindDevice - * @tc.desc: Bind Device of the device manager service impl - * @tc.type: FUNC - */ - virtual int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, - const std::string &bindParam) = 0; + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; /** * @tc.name: IDeviceManagerServiceImpl::UnBindDevice * @tc.desc: UnBindDevice Device of the device manager service impl * @tc.type: FUNC */ - virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &deviceId) = 0; + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; /** * @tc.name: IDeviceManagerServiceImpl::SetUserOperation @@ -270,18 +254,23 @@ public: virtual int32_t UnRegisterUiStateCallback(const std::string &pkgName) = 0; virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname) = 0; - virtual void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) = 0; - virtual void OnUnbindSessionCloseed(int32_t socket) = 0; - virtual void OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen) = 0; virtual int32_t DpAclAdd(const std::string &udid) = 0; virtual int32_t IsSameAccount(const std::string &udid) = 0; - virtual void AccountCommonEventCallback(int32_t userId, std::string commonEventType) = 0; virtual void ScreenCommonEventCallback(std::string commonEventType) = 0; virtual int32_t CheckIsSameAccount(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + virtual std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId) = 0; + virtual void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid) = 0; + virtual void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) = 0; + virtual void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId) = 0; + virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) = 0; + virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; + virtual void HandleUserRemoved(int32_t preUserId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 5253a5e6d..bce45fe33 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -144,6 +144,13 @@ public: */ virtual void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content) = 0; + + /** + * @tc.name: IDeviceManagerServiceListener::SetNotOfflinePkgname + * @tc.desc: Set the pkgname that not offline + * @tc.type: FUNC + */ + virtual void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h new file mode 100644 index 000000000..4de8c129f --- /dev/null +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_RELATIONSHIP_SYNC_MGR_H +#define OHOS_RELATIONSHIP_SYNC_MGR_H + +#include +#include +#include "cJSON.h" +#include "dm_single_instance.h" +namespace OHOS { +namespace DistributedHardware { +enum class RelationShipChangeType : uint32_t { + ACCOUNT_LOGOUT = 0, + DEVICE_UNBIND = 1, + APP_UNBIND = 2, + SERVICE_UNBIND = 3, + DEL_USER = 4, + APP_UNINSTALL = 5, + TYPE_MAX = 6 +}; + +struct RelationShipChangeMsg { + RelationShipChangeType type; + uint32_t userId; + std::string accountId; + uint64_t tokenId; + std::vector peerUdids; + std::string peerUdid; + std::string accountName; + + explicit RelationShipChangeMsg(); + bool ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) const; + bool FromBroadcastPayLoad(const cJSON *payloadJson, RelationShipChangeType type); + bool IsValid() const; + bool IsChangeTypeValid(); + bool IsChangeTypeValid(uint32_t type); + /** + * @brief parse change type from json msg + * + * @param msg json msg + * @param len msg length + * @return RelationShipChangeType parsed msg, if invalid, return TYPE_MAX + */ + RelationShipChangeType ParseChangeType(const char *msg, const uint32_t len); + + void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + cJSON *ToArrayJson(cJSON *msg) const; + + bool FromAccountLogoutPayLoad(const cJSON *payloadJson); + bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); + bool FromAppUnbindPayLoad(const cJSON *payloadJson); + + std::string ToJson() const; + bool FromJson(const std::string &msgJson); +}; + +class ReleationShipSyncMgr { +DM_DECLARE_SINGLE_INSTANCE(ReleationShipSyncMgr); +public: + std::string SyncTrustRelationShip(const RelationShipChangeMsg &msg); + RelationShipChangeMsg ParseTrustRelationShipChange(const std::string &msgJson); +}; + +} // DistributedHardware +} // OHOS +#endif // OHOS_RELATIONSHIP_SYNC_MGR_H \ No newline at end of file diff --git a/services/service/include/softbus/softbus_adapter.h b/services/service/include/softbus/softbus_adapter.h deleted file mode 100644 index 24d6aacfe..000000000 --- a/services/service/include/softbus/softbus_adapter.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_SOFTBUS_ADAPTER -#define OHOS_SOFTBUS_ADAPTER - -#include -#include -#include - -#include "session.h" -#include "socket.h" -#include "dm_single_instance.h" -namespace OHOS { -namespace DistributedHardware { -class SoftbusAdapter { - DM_DECLARE_SINGLE_INSTANCE_BASE(SoftbusAdapter); -public: - SoftbusAdapter(); - ~SoftbusAdapter(); - int32_t CreateSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName); - int32_t RemoveSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName); - - void OnSoftbusSessionOpened(int32_t socket, PeerSocketInfo info); - void OnSoftbusSessionClosed(int32_t socket, ShutdownReason reason); - void OnBytesReceived(int32_t socket, const void *data, uint32_t dataLen); - void OnStreamReceived(int32_t socket, const StreamData *data, const StreamData *ext, - const StreamFrameInfo *frameInfo); - void OnMessageReceived(int32_t socket, const void *data, unsigned int dataLen) const; - void OnQosEvent(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) const; - -private: - ISocketListener iSocketListener_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif \ No newline at end of file diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 362e132ce..5f17ba1a0 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -53,8 +53,9 @@ public: static void DeviceOffLine(DmDeviceInfo deviceInfo); static void DeviceNameChange(DmDeviceInfo deviceInfo); static void OnLocalDevInfoChange(); - static void OnDeviceNotTrusted(const char *msg); + static void OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen); static void DeviceNotTrust(const std::string &msg); + static void DeviceTrustedChange(const std::string &msg); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); @@ -91,6 +92,7 @@ public: static IRefreshCallback &GetSoftbusRefreshCb(); static void SetHostPkgName(const std::string hostName); static std::string GetHostPkgName(); + void SendAclChangedBroadcast(const std::string &msg); private: int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 05b27ab0d..470f5dea9 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -27,6 +27,7 @@ #include "dm_softbus_cache.h" #include "parameter.h" #include "permission_manager.h" +#include "relationship_sync_mgr.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "common_event_support.h" #include "datetime_ex.h" @@ -64,6 +65,11 @@ const int32_t SYSTEM_BASIC = 1; const int32_t SYSTEM_CORE = 2; constexpr const char* ALL_PKGNAME = ""; constexpr const char* NETWORKID = "NETWORK_ID"; +constexpr uint32_t INVALIED_BIND_LEVEL = 0; +constexpr uint32_t DEVICE_BIND_LEVEL = 1; +constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; +constexpr uint32_t DM_POINT_TO_POINT = 256; +constexpr uint32_t DM_ACROSS_ACCOUNT = 1282; DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); @@ -546,11 +552,34 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } + std::string udid = ""; + if (SoftbusListener::GetUdidByNetworkId(networkId.c_str(), udid) != DM_OK) { + LOGE("UnAuthenticateDevice GetUdidByNetworkId error: udid: %{public}s", GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); if (!IsDMServiceImplReady()) { LOGE("UnAuthenticateDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - return dmServiceImpl_->UnAuthenticateDevice(pkgName, networkId); + uint64_t tokenId = 0; + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); + LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); + if (bindLevel == INVALIED_BIND_LEVEL) { + LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); + return ERR_DM_FAILED; + } + if (dmServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel) != DM_OK) { + LOGE("dmServiceImpl_ UnAuthenticateDevice failed."); + return ERR_DM_FAILED; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::vector peerUdids; + peerUdids.emplace_back(udid); + SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId, bindLevel); +#endif + return DM_OK; } int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, @@ -589,15 +618,14 @@ int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t aut return dmServiceImpl_->BindTarget(pkgName, targetId, bindParamMap); } -int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &deviceId) +int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std::string &udidHash) { if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call UnBindDevice."); return ERR_DM_NO_PERMISSION; } - LOGI("Begin for pkgName = %{public}s, deviceId = %{public}s", - pkgName.c_str(), GetAnonyString(deviceId).c_str()); - if (pkgName.empty() || deviceId.empty()) { + LOGI("Begin for pkgName = %{public}s, udidHash = %{public}s", pkgName.c_str(), GetAnonyString(udidHash).c_str()); + if (pkgName.empty() || udidHash.empty()) { LOGE("DeviceManagerService::UnBindDevice error: Invalid parameter, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } @@ -605,14 +633,37 @@ int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std LOGE("UnBindDevice failed, instance not init or init failed."); return ERR_DM_NOT_INIT; } - std::string realDeviceId = deviceId; + std::string realDeviceId = udidHash; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - std::string udidHash = ""; - if (GetUdidHashByAnoyUdid(deviceId, udidHash) == DM_OK) { - realDeviceId = udidHash; + std::string udidHashTemp = ""; + if (GetUdidHashByAnoyUdid(udidHash, udidHashTemp) == DM_OK) { + realDeviceId = udidHashTemp; } #endif - return dmServiceImpl_->UnBindDevice(pkgName, realDeviceId); + std::string udid = ""; + if (SoftbusCache::GetInstance().GetUdidByUdidHash(realDeviceId, udid) != DM_OK) { + LOGE("Get udid by udidhash failed."); + return ERR_DM_FAILED; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); + uint64_t tokenId = 0; + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); + LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); + if (bindLevel == INVALIED_BIND_LEVEL) { + LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); + return ERR_DM_FAILED; + } + if (dmServiceImpl_->UnBindDevice(pkgName, udid, bindLevel) != DM_OK) { + LOGE("dmServiceImpl_ UnBindDevice failed."); + return ERR_DM_FAILED; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::vector peerUdids; + peerUdids.emplace_back(udid); + SendUnBindBroadCast(peerUdids, MultipleUserConnector::GetCurrentAccountUserID(), tokenId, bindLevel); +#endif + return DM_OK; } int32_t DeviceManagerService::SetUserOperation(std::string &pkgName, int32_t action, const std::string ¶ms) @@ -1396,33 +1447,6 @@ int32_t DeviceManagerService::DestroyPinHolder(const std::string &pkgName, const return pinHolder_->DestroyPinHolder(pkgName, targetId, pinType, payload); } -void DeviceManagerService::OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) -{ - if (!IsDMServiceImplReady()) { - LOGE("OnUnbindSessionOpened failed, instance not init or init failed."); - return; - } - dmServiceImpl_->OnUnbindSessionOpened(socket, info); -} - -void DeviceManagerService::OnUnbindSessionCloseed(int32_t socket) -{ - if (!IsDMServiceImplReady()) { - LOGE("OnUnbindSessionCloseed failed, instance not init or init failed."); - return; - } - dmServiceImpl_->OnUnbindSessionCloseed(socket); -} - -void DeviceManagerService::OnUnbindBytesReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - if (!IsDMServiceImplReady()) { - LOGE("OnUnbindBytesReceived failed, instance not init or init failed."); - return; - } - dmServiceImpl_->OnUnbindBytesReceived(socket, data, dataLen); -} - int32_t DeviceManagerService::DpAclAdd(const std::string &udid) { if (!PermissionManager::GetInstance().CheckNewPermission()) { @@ -1544,6 +1568,7 @@ void DeviceManagerService::SubscribeAccountCommonEvent() }; std::vector AccountCommonEventVec; AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_REMOVED); AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_HWID_LOGIN); if (accountCommonEventManager_->SubscribeAccountCommonEvent(AccountCommonEventVec, callback)) { @@ -1567,39 +1592,81 @@ void DeviceManagerService::SubscribeScreenLockEvent() return; } -void DeviceManagerService::AccountCommonEventCallback(int32_t userId, std::string commonEventType) +void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std::string commonEventType) +{ + LOGI("CommonEventType: %{public}s", commonEventType.c_str()); + if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + MultipleUserConnector::SetSwitchOldUserId(userId); + MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); + MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); + } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { + MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); + MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); + } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { + HandleAccountLogout(MultipleUserConnector::GetCurrentAccountUserID(), + MultipleUserConnector::GetSwitchOldAccountId()); + } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + HandleUserRemoved(userId); + } else { + LOGE("Invalied account common event."); + } + return; +} + +void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string &accountId) { - LOGI("Start, commonEventType: %{public}s", commonEventType.c_str()); - if ((commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED || - commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN)) { - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - LOGI("accountId: %{public}s, userId: %{public}s", GetAnonyString(accountId).c_str(), - GetAnonyInt32(userId).c_str()); - if (userId > 0) { - MultipleUserConnector::SetSwitchOldUserId(userId); - MultipleUserConnector::SetSwitchOldAccountId(accountId); - } + LOGI("UserId %{public}d, accountId %{public}s.", userId, GetAnonyString(accountId).c_str()); + if (IsDMServiceAdapterLoad()) { + dmServiceImplExt_->AccountIdLogout(userId, accountId); + } + if (!IsDMServiceImplReady()) { + LOGE("Init impl failed."); return; } - - if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - std::vector onlineDeviceList; - CHECK_NULL_VOID(softbusListener_); - int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList); - if (ret != DM_OK) { - LOGE("GetTrustedDeviceList failed, ret: %{public}d", ret); - return; + std::map deviceMap; + std::vector peerUdids; + deviceMap = dmServiceImpl_->GetDeviceIdAndBindType(userId, accountId); + for (const auto &item : deviceMap) { + if (item.second == DM_IDENTICAL_ACCOUNT) { + dmServiceImpl_->HandleIdentAccountLogout(item.first, userId, accountId); + peerUdids.emplace_back(item.first); } - if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { - if (IsDMServiceAdapterLoad()) { - dmServiceImplExt_->AccountIdLogout(userId, MultipleUserConnector::GetSwitchOldAccountId()); - } - dmServiceImpl_->AccountCommonEventCallback(userId, commonEventType); + } + if (!peerUdids.empty()) { + char accountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accountId, reinterpret_cast(accountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return; } + std::string accountName = MultipleUserConnector::GetSwitchOldAccountName(); + SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); } } +void DeviceManagerService::HandleUserRemoved(int32_t preUserId) +{ + LOGI("PreUserId %{public}d.", preUserId); + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleUserRemoved(preUserId); + } +} + +void DeviceManagerService::SendAccountLogoutBroadCast(const std::vector &peerUdids, + const std::string &accountId, const std::string &accountName, int32_t userId) +{ + LOGI("accountId %{public}s, accountName %{public}s, userId %{public}d.", GetAnonyString(accountId).c_str(), + GetAnonyString(accountName).c_str(), userId); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = userId; + msg.peerUdids = peerUdids; + msg.accountId = accountId; + msg.accountName = accountName; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType) { if (!IsDMImplSoLoaded()) { @@ -1631,10 +1698,10 @@ void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid); LOGI("NetworkId: %{public}s, udid: %{public}s.", GetAnonyString(networkId).c_str(), GetAnonyString(udid).c_str()); - if (IsDMImplSoLoaded()) { + if (IsDMServiceImplReady()) { dmServiceImpl_->HandleDeviceNotTrust(udid); } - if (IsDMServiceImplReady()) { + if (IsDMServiceAdapterLoad()) { dmServiceImplExt_->HandleDeviceNotTrust(udid); } return; @@ -1687,6 +1754,56 @@ int32_t DeviceManagerService::GetUdidHashByAnoyUdid(const std::string &anoyUdid, LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str()); return DM_OK; } + +void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, + uint64_t tokenId, int32_t bindLevel) +{ + LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); + if (bindLevel == DEVICE) { + SendDeviceUnBindBroadCast(peerUdids, userId); + } else if (bindLevel == APP) { + SendAppUnBindBroadCast(peerUdids, userId, tokenId); + } else if (bindLevel == SERVICE) { + SendServiceUnBindBroadCast(peerUdids, userId, tokenId); + } +} + +void DeviceManagerService::SendDeviceUnBindBroadCast(const std::vector &peerUdids, int32_t userId) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEVICE_UNBIND; + msg.userId = userId; + msg.peerUdids = peerUdids; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::SendAppUnBindBroadCast(const std::vector &peerUdids, int32_t userId, + uint64_t tokenId) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = userId; + msg.peerUdids = peerUdids; + msg.tokenId = tokenId; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::SendServiceUnBindBroadCast(const std::vector &peerUdids, int32_t userId, + uint64_t tokenId) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SERVICE_UNBIND; + msg.userId = userId; + msg.peerUdids = peerUdids; + msg.tokenId = tokenId; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} #endif } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index ce622a6bb..357c450c3 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -27,6 +27,7 @@ #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" #include "ipc_notify_credential_req.h" +#include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_device_found_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_device_state_req.h" @@ -476,5 +477,19 @@ int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoy(const std::string &p return DM_OK; } #endif + +void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) +{ + LOGI("DeviceId %{public}s, authForm %{public}d.", GetAnonyString(deviceId).c_str(), authForm); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); + for (const auto &it : PkgNameVec) { + pReq->SetPkgName(it); + pReq->SetDeviceId(deviceId); + pReq->SetAuthForm(authForm); + ipcServerListener_.SendRequest(REMOTE_DEVICE_TRUST_CHANGE, pReq, pRsp); + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index b69a9f171..f03a03829 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -30,6 +30,7 @@ #include "ipc_def.h" #include "ipc_create_pin_holder_req.h" #include "ipc_destroy_pin_holder_req.h" +#include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" #include "ipc_notify_credential_req.h" @@ -1443,5 +1444,39 @@ ON_IPC_CMD(SHIFT_LNN_GEAR, MessageParcel &data, MessageParcel &reply) } return DM_OK; } + +ON_IPC_SET_REQUEST(REMOTE_DEVICE_TRUST_CHANGE, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = data.ReadString(); + std::string deviceId = pReq->GetDeviceId(); + int32_t authForm = pReq->GetAuthForm(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(deviceId)) { + LOGE("write deviceId failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(authForm)) { + LOGE("write authForm code failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(REMOTE_DEVICE_TRUST_CHANGE, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 92d6a317b..1ad84dfca 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -136,12 +136,14 @@ void DmAccountEventSubscriber::OnReceiveEvent(const CommonEventData &data) std::string receiveEvent = data.GetWant().GetAction(); LOGI("Received account event: %{public}s", receiveEvent.c_str()); int32_t userId = data.GetCode(); - if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED || + receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { userId = data.GetCode(); - } else if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - userId = data.GetWant().GetIntParam("userId", 0); - } else if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { + } else if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT || + receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { userId = data.GetWant().GetIntParam("userId", 0); + } else { + return; } if (userId <= 0) { LOGE("userId is less zero"); diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp new file mode 100644 index 000000000..e6a3b0f2a --- /dev/null +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -0,0 +1,419 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "relationship_sync_mgr.h" + +#include +#include +#include "dm_crypto.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { + DM_IMPLEMENT_SINGLE_INSTANCE(ReleationShipSyncMgr); +namespace { + /** + * @brief account logout payload length 8 + * | 2 bytes | 6 bytes | + * | userid lower 2 bytes | account id first 6 bytes | + */ + const int32_t ACCOUNT_LOGOUT_PAYLOAD_LEN = 8; + /** + * @brief device unbind payload length 2 + * | 2 bytes | + * | userid lower 2 bytes | + */ + const int32_t DEVICE_UNBIND_PAYLOAD_LEN = 2; + /** + * @brief app unbind payload length 6 + * | 2 bytes | 4 bytes | + * | userid lower 2 bytes | token id lower 4 bytes | + */ + const int32_t APP_UNBIND_PAYLOAD_LEN = 6; + const int32_t USERID_PAYLOAD_LEN = 2; + const int32_t ACCOUNTID_PAYLOAD_LEN = 6; + const int32_t TOKENID_PAYLOAD_LEN = 4; + const int32_t BIT_PER_BYTES = 8; + const int32_t UINT32_BYTES = 4; + const int32_t INVALIED_PAYLOAD_SIZE = 12; + + const char * const MSG_TYPE = "TYPE"; + const char * const MSG_VALUE = "VALUE"; + const char * const MSG_PEER_UDID = "PEER_UDID"; + const char * const MSG_ACCOUNTID = "ACCOUNTID"; +} + +RelationShipChangeMsg::RelationShipChangeMsg() : type(RelationShipChangeType::TYPE_MAX), + userId(UINT32_MAX), accountId(""), tokenId(UINT64_MAX), peerUdid("") +{ +} + +bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) const +{ + if (!IsValid()) { + LOGE("invalid"); + return false; + } + + bool ret = false; + switch (type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + ToAccountLogoutPayLoad(msg, len); + ret = true; + break; + case RelationShipChangeType::DEVICE_UNBIND: + ToDeviceUnbindPayLoad(msg, len); + ret = true; + break; + case RelationShipChangeType::APP_UNBIND: + ToAppUnbindPayLoad(msg, len); + ret = true; + break; + default: + LOGE("RelationShipChange type invalid"); + break; + } + return ret; +} + +bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, RelationShipChangeType type) +{ + LOGI("FromBroadcastPayLoad type %{public}d.", type); + if (type == RelationShipChangeType::TYPE_MAX) { + LOGE("ChangeType invalid, type: %{public}d", type); + return false; + } + bool ret = false; + switch (type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + ret = FromAccountLogoutPayLoad(payloadJson); + break; + case RelationShipChangeType::DEVICE_UNBIND: + ret = FromDeviceUnbindPayLoad(payloadJson); + break; + case RelationShipChangeType::APP_UNBIND: + ret = FromAppUnbindPayLoad(payloadJson); + break; + default: + LOGE("RelationShipChange type invalid"); + break; + } + return ret; +} + +bool RelationShipChangeMsg::IsValid() const +{ + bool ret = false; + switch (type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + ret = (userId != UINT32_MAX && accountId.length() >= ACCOUNTID_PAYLOAD_LEN); + break; + case RelationShipChangeType::DEVICE_UNBIND: + ret = (userId != UINT32_MAX); + break; + case RelationShipChangeType::APP_UNBIND: + ret = (userId != UINT32_MAX && tokenId != UINT64_MAX); + break; + case RelationShipChangeType::SERVICE_UNBIND: + case RelationShipChangeType::DEL_USER: + case RelationShipChangeType::APP_UNINSTALL: + // current NOT support + ret = false; + break; + case RelationShipChangeType::TYPE_MAX: + ret = false; + break; + default: + ret = false; + break; + } + return ret; +} + +bool RelationShipChangeMsg::IsChangeTypeValid() +{ + return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || + (type == RelationShipChangeType::APP_UNBIND); +} + +bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) +{ + return (type == (uint32_t)RelationShipChangeType::ACCOUNT_LOGOUT) || + (type == (uint32_t)RelationShipChangeType::DEVICE_UNBIND) || + (type == (uint32_t)RelationShipChangeType::APP_UNBIND); +} + +RelationShipChangeType RelationShipChangeMsg::ParseChangeType(const char *msg, const uint32_t len) +{ + if (msg == NULL || sizeof(msg) != len) { + LOGE("msg invalid"); + return RelationShipChangeType::TYPE_MAX; + } + + cJSON *msgObj = cJSON_Parse(msg); + if (msgObj == NULL) { + LOGE("parse msg failed"); + return RelationShipChangeType::TYPE_MAX; + } + + cJSON *typeJson = cJSON_GetObjectItem(msgObj, MSG_TYPE); + if (typeJson == NULL || !cJSON_IsNumber(typeJson) || !IsChangeTypeValid(typeJson->valueint)) { + LOGE("parse type failed."); + cJSON_Delete(msgObj); + return RelationShipChangeType::TYPE_MAX; + } + RelationShipChangeType type = (RelationShipChangeType)typeJson->valueint; + cJSON_Delete(msgObj); + return type; +} + +void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const +{ + msg = new uint8_t[ACCOUNT_LOGOUT_PAYLOAD_LEN](); + for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + } + + for (int j = USERID_PAYLOAD_LEN; j < ACCOUNT_LOGOUT_PAYLOAD_LEN; j++) { + msg[j] = accountId[j - USERID_PAYLOAD_LEN]; + } + len = ACCOUNT_LOGOUT_PAYLOAD_LEN; +} + +void RelationShipChangeMsg::ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const +{ + msg = new uint8_t[DEVICE_UNBIND_PAYLOAD_LEN](); + for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + } + len = DEVICE_UNBIND_PAYLOAD_LEN; +} + +void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const +{ + msg = new uint8_t[APP_UNBIND_PAYLOAD_LEN](); + for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + } + + for (int i = USERID_PAYLOAD_LEN; i < APP_UNBIND_PAYLOAD_LEN; i++) { + msg[i] |= (tokenId >> ((i - USERID_PAYLOAD_LEN) * BIT_PER_BYTES)) & 0xFF; + } + + len = APP_UNBIND_PAYLOAD_LEN; +} + +bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("Account logout payloadJson is null."); + return false; + } + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + LOGE("Payload invalied,the size is %{public}d.", arraySize); + return false; + } + userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + } + } + accountId = ""; + for (uint32_t j = USERID_PAYLOAD_LEN; j < ACCOUNT_LOGOUT_PAYLOAD_LEN; j++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, j); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + accountId += static_cast(payloadItem->valueint); + } + } + return true; +} + +bool RelationShipChangeMsg::FromDeviceUnbindPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("Device unbind payloadJson is null."); + return false; + } + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + LOGE("Payload invalied,the size is %{public}d.", arraySize); + return false; + } + userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + } + } + return true; +} + +bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("App unbind payloadJson is null."); + return false; + } + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + LOGE("Payload invalied,the size is %{public}d.", arraySize); + return false; + } + userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + } + } + tokenId = 0; + for (uint32_t j = USERID_PAYLOAD_LEN; j < APP_UNBIND_PAYLOAD_LEN; j++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, j); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + tokenId |= (static_cast(payloadItem->valueint)) << ((j - USERID_PAYLOAD_LEN) * BIT_PER_BYTES); + } + } + return true; +} + +cJSON *RelationShipChangeMsg::ToArrayJson(cJSON *msg) const +{ + if (msg == nullptr) { + LOGE("Msg is nullptr."); + return nullptr; + } + uint8_t *payload = nullptr; + uint32_t len = 0; + if (!this->ToBroadcastPayLoad(payload, len)) { + LOGE("Get broadcast payload failed"); + cJSON_Delete(msg); + return nullptr; + } + cJSON *arrayObj = cJSON_CreateArray(); + if (arrayObj == nullptr) { + LOGE("cJSON_CreateArray failed"); + cJSON_Delete(msg); + return nullptr; + } + for (uint32_t index = 0; index < len; index++) { + cJSON_AddItemToArray(arrayObj, cJSON_CreateNumber(payload[index])); + } + if (payload) { + delete[] payload; + } + return arrayObj; +} + +std::string RelationShipChangeMsg::ToJson() const +{ + cJSON *msg = cJSON_CreateObject(); + if (msg == NULL) { + LOGE("failed to create cjson object"); + return ""; + } + cJSON_AddNumberToObject(msg, MSG_TYPE, (uint32_t)type); + cJSON *arrayObj = ToArrayJson(msg); + if (arrayObj == nullptr) { + LOGE("ArrayObj is nullptr."); + return ""; + } + cJSON_AddItemToObject(msg, MSG_VALUE, arrayObj); + + cJSON *udidArrayObj = cJSON_CreateArray(); + if (udidArrayObj == nullptr) { + LOGE("cJSON_CreateArray failed"); + cJSON_Delete(msg); + return ""; + } + for (uint32_t index = 0; index < peerUdids.size(); index++) { + cJSON_AddItemToArray(udidArrayObj, cJSON_CreateString(peerUdids[index].c_str())); + } + cJSON_AddItemToObject(msg, MSG_PEER_UDID, udidArrayObj); + cJSON_AddStringToObject(msg, MSG_ACCOUNTID, accountName.c_str()); + char *retStr = cJSON_PrintUnformatted(msg); + if (retStr == nullptr) { + LOGE("to json is nullptr."); + cJSON_Delete(msg); + return ""; + } + std::string ret = std::string(retStr); + cJSON_Delete(msg); + cJSON_free(retStr); + return ret; +} + +bool RelationShipChangeMsg::FromJson(const std::string &msgJson) +{ + cJSON *msgObj = cJSON_Parse(msgJson.c_str()); + if (msgObj == NULL) { + LOGE("parse msg failed"); + return false; + } + + cJSON *typeJson = cJSON_GetObjectItem(msgObj, MSG_TYPE); + if (typeJson == NULL || !cJSON_IsNumber(typeJson) || !IsChangeTypeValid(typeJson->valueint)) { + LOGE("parse type failed."); + cJSON_Delete(msgObj); + return false; + } + this->type = (RelationShipChangeType)typeJson->valueint; + + cJSON *payloadJson = cJSON_GetObjectItem(msgObj, MSG_VALUE); + if (payloadJson == NULL || !cJSON_IsArray(payloadJson)) { + LOGE("parse payload failed."); + cJSON_Delete(msgObj); + return false; + } + if (!this->FromBroadcastPayLoad(payloadJson, type)) { + LOGE("parse payload error."); + cJSON_Delete(msgObj); + return false; + } + + cJSON *peerUdidJson = cJSON_GetObjectItem(msgObj, MSG_PEER_UDID); + if (peerUdidJson == NULL || !cJSON_IsString(peerUdidJson)) { + LOGE("parse peer udid failed."); + cJSON_Delete(msgObj); + return false; + } + this->peerUdid = std::string(peerUdidJson->valuestring); + cJSON_Delete(msgObj); + return true; +} + +std::string ReleationShipSyncMgr::SyncTrustRelationShip(const RelationShipChangeMsg &msg) +{ + return msg.ToJson(); +} + +RelationShipChangeMsg ReleationShipSyncMgr::ParseTrustRelationShipChange(const std::string &msgJson) +{ + RelationShipChangeMsg msgObj; + if (!msgObj.FromJson(msgJson)) { + LOGE("Parse json failed"); + } + return msgObj; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_adapter.cpp b/services/service/src/softbus/softbus_adapter.cpp deleted file mode 100644 index 3e3faf20a..000000000 --- a/services/service/src/softbus/softbus_adapter.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "softbus_adapter.h" - -#include -#include -#include "dm_log.h" -#include "softbus_bus_center.h" -#include "softbus_common.h" -#include "device_manager_service.h" -namespace OHOS { -namespace DistributedHardware { -namespace { -static QosTV g_qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, -}; -static uint32_t g_qosTVParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); -} -DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusAdapter); -static void DmOnSoftbusSessionBind(int32_t socket, PeerSocketInfo info) -{ - SoftbusAdapter::GetInstance().OnSoftbusSessionOpened(socket, info); -} - -static void DmOnSoftbusSessionClosed(int32_t socket, ShutdownReason reason) -{ - SoftbusAdapter::GetInstance().OnSoftbusSessionClosed(socket, reason); -} - -static void DmOnBytesReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - SoftbusAdapter::GetInstance().OnBytesReceived(socket, data, dataLen); -} - -static void DmOnStreamReceived(int32_t socket, const StreamData *data, const StreamData *ext, - const StreamFrameInfo *frameInfo) -{ - SoftbusAdapter::GetInstance().OnStreamReceived(socket, data, ext, frameInfo); -} - -static void DmOnMessageReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - SoftbusAdapter::GetInstance().OnMessageReceived(socket, data, dataLen); -} - -static void DmOnQosEvent(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) -{ - SoftbusAdapter::GetInstance().OnQosEvent(socket, eventId, qos, qosCount); -} - -SoftbusAdapter::SoftbusAdapter() -{ - LOGI("SoftbusAdapter"); - (void)memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)); - iSocketListener_.OnBind = DmOnSoftbusSessionBind; - iSocketListener_.OnShutdown = DmOnSoftbusSessionClosed; - iSocketListener_.OnBytes = DmOnBytesReceived; - iSocketListener_.OnMessage = DmOnMessageReceived; - iSocketListener_.OnStream = DmOnStreamReceived; - iSocketListener_.OnQos = DmOnQosEvent; - iSocketListener_.OnFile = nullptr; - iSocketListener_.OnError = nullptr; - iSocketListener_.OnNegotiate = nullptr; -} - -SoftbusAdapter::~SoftbusAdapter() -{ - LOGI("~SoftbusAdapter"); -} - -int32_t SoftbusAdapter::CreateSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName) -{ - LOGI("SoftbusAdapter::CreateSoftbusSessionServer."); - SocketInfo info = { - .name = const_cast(sessionName.c_str()), - .pkgName = const_cast(pkgname.c_str()), - .dataType = DATA_TYPE_BYTES - }; - int32_t socket = Socket(info); - if (socket <= 0) { - LOGE("[SOFTBUS]create socket failed, socket: %{public}d", socket); - return socket; - } - int32_t ret = Listen(socket, g_qosInfo, g_qosTVParamIndex, &iSocketListener_); - if (ret != DM_OK) { - LOGE("[SOFTBUS]Socket Listen failed, ret: %{public}d, socket: %{public}d.", ret, socket); - Shutdown(socket); - return ret; - } - LOGI("SoftbusAdapter::CreateSoftbusSessionServer success."); - return DM_OK; -} - -int32_t SoftbusAdapter::RemoveSoftbusSessionServer(const std::string &pkgname, const std::string &sessionName) -{ - LOGI("SoftbusAdapter::RemoveSoftbusSessionServer"); - int32_t ret = RemoveSessionServer(pkgname.c_str(), sessionName.c_str()); - if (ret != DM_OK) { - LOGE("RemoveSoftbusSessionServer failed."); - return ret; - } - LOGI("SoftbusAdapter::RemoveSoftbusSessionServer success."); - return DM_OK; -} - -void SoftbusAdapter::OnSoftbusSessionOpened(int32_t socket, PeerSocketInfo info) -{ - LOGI("SoftbusAdapter::OnSoftbusSessionOpened socket: %{public}d", socket); - DeviceManagerService::GetInstance().OnUnbindSessionOpened(socket, info); -} - -void SoftbusAdapter::OnSoftbusSessionClosed(int32_t socket, ShutdownReason reason) -{ - (void)reason; - LOGI("SoftbusAdapter::OnSoftbusSessionClosed socket: %{public}d", socket); - DeviceManagerService::GetInstance().OnUnbindSessionCloseed(socket); -} - -void SoftbusAdapter::OnBytesReceived(int32_t socket, const void *data, uint32_t dataLen) -{ - LOGI("SoftbusAdapter::OnBytesReceived socket: %{public}d", socket); - DeviceManagerService::GetInstance().OnUnbindBytesReceived(socket, data, dataLen); -} - -void SoftbusAdapter::OnStreamReceived(int32_t socket, const StreamData *data, const StreamData *ext, - const StreamFrameInfo *frameInfo) -{ - (void)data; - (void)ext; - (void)frameInfo; - LOGI("SoftbusAdapter::OnStreamReceived, socket: %{public}d", socket); -} - -void SoftbusAdapter::OnMessageReceived(int32_t socket, const void *data, unsigned int dataLen) const -{ - (void)data; - (void)dataLen; - LOGI("SoftbusAdapter::OnMessageReceived, socket: %{public}d", socket); -} - -void SoftbusAdapter::OnQosEvent(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) const -{ - (void)eventId; - (void)qos; - (void)qosCount; - LOGI("SoftbusAdapter::OnQosEvent, socket: %{public}d", socket); -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a9d634984..91b2e51bf 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -34,7 +34,6 @@ #endif #include "parameter.h" #include "system_ability_definition.h" -#include "softbus_adapter.cpp" namespace OHOS { namespace DistributedHardware { @@ -48,6 +47,7 @@ constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; +constexpr const char* DEVICE_TRUSTED_CHANGE = "deviceTrustedChange"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; constexpr static uint8_t BYTE_MASK = 0x0F; constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2; @@ -57,7 +57,7 @@ static std::mutex g_deviceMapMutex; static std::mutex g_lnnCbkMapMutex; static std::mutex g_radarLoadLock; static std::mutex g_onlineDeviceNumLock; -static std::mutex g_lockDeviceNotTrust; +static std::mutex g_lockDeviceTrustedChange; static std::mutex g_lockDeviceOnLine; static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; @@ -123,7 +123,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onNodeOffline = SoftbusListener::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusListener::OnSoftbusDeviceInfoChanged, .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, - .onNodeDeviceNotTrusted = SoftbusListener::OnDeviceNotTrusted, + .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -151,10 +151,16 @@ void SoftbusListener::DeviceNameChange(DmDeviceInfo deviceInfo) void SoftbusListener::DeviceNotTrust(const std::string &msg) { - std::lock_guard lock(g_lockDeviceNotTrust); + std::lock_guard lock(g_lockDeviceTrustedChange); DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); } +void SoftbusListener::DeviceTrustedChange(const std::string &msg) +{ + std::lock_guard lock(g_lockDeviceTrustedChange); + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); +} + void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) { LOGI("received device online callback from softbus."); @@ -295,24 +301,40 @@ void SoftbusListener::OnLocalDevInfoChange() SoftbusCache::GetInstance().UpDataLocalDevInfo(); } -void SoftbusListener::OnDeviceNotTrusted(const char *msg) +void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen) { - LOGI("SoftbusListener::OnDeviceNotTrusted."); - - if (msg == nullptr || strlen(msg) > MAX_SOFTBUS_MSG_LEN) { - LOGE("OnDeviceNotTrusted msg invalied."); + LOGI("OnDeviceTrustedChange."); + if (msg == nullptr || msgLen > MAX_SOFTBUS_MSG_LEN) { + LOGE("OnDeviceTrustedChange msg invalied."); return; } std::string softbusMsg = std::string(msg); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEVICE_NOT_TRUST, [=]() { DeviceNotTrust(softbusMsg); }); + if (type == TrustChangeType::DEVICE_NOT_TRUSTED) { + ThreadManager::GetInstance().Submit(DEVICE_NOT_TRUST, [=]() { DeviceNotTrust(softbusMsg); }); + } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { + ThreadManager::GetInstance().Submit(DEVICE_TRUSTED_CHANGE, [=]() { DeviceTrustedChange(softbusMsg); }); + } else { + LOGE("Invalied trust change type."); + } #else - std::thread deviceNotTrust([=]() { DeviceNotTrust(softbusMsg); }); - int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); - if (ret != DM_OK) { - LOGE("deviceNotTrust setname failed."); + if (type == TrustChangeType::DEVICE_NOT_TRUSTED) { + std::thread deviceNotTrust([=]() { DeviceNotTrust(softbusMsg); }); + int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); + if (ret != DM_OK) { + LOGE("deviceNotTrust setname failed."); + + deviceNotTrust.detach(); + } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { + std::thread deviceTrustedChange([=]() { DeviceTrustedChange(softbusMsg); }); + int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); + if (ret != DM_OK) { + LOGE("deviceTrustedChange setname failed."); + + deviceTrustedChange.detach(); + } else { + LOGE("Invalied trust change type."); } - deviceNotTrust.detach(); #endif } @@ -392,7 +414,6 @@ SoftbusListener::SoftbusListener() if (ret != DM_OK) { LOGE("[SOFTBUS]CreateSessionServer pin holder failed, ret: %{public}d.", ret); } - SoftbusAdapter::GetInstance().CreateSoftbusSessionServer(DM_PKG_NAME, DM_UNBIND_SESSION_NAME); #endif InitSoftbusListener(); ClearDiscoveredDevice(); @@ -403,7 +424,6 @@ SoftbusListener::~SoftbusListener() #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) RemoveSessionServer(DM_PKG_NAME, DM_SESSION_NAME); RemoveSessionServer(DM_PKG_NAME, DM_PIN_HOLDER_SESSION_NAME); - SoftbusAdapter::GetInstance().RemoveSoftbusSessionServer(DM_PKG_NAME, DM_UNBIND_SESSION_NAME); #endif LOGD("SoftbusListener destructor."); } @@ -951,6 +971,14 @@ std::string SoftbusListener::GetHostPkgName() return hostName_; } +void SoftbusListener::SendAclChangedBroadcast(const std::string &msg) +{ + LOGI("SendAclChangedBroadcast"); + // if (SyncTrustedRelationShip(DM_PKG_NAME, msg.c_str(), msg.length()) != DM_OK) { + // LOGE("SyncTrustedRelationShip failed."); + // } +} + IRefreshCallback &SoftbusListener::GetSoftbusRefreshCb() { return softbusRefreshCallback_; diff --git a/services/softbuscache/include/dm_softbus_cache.h b/services/softbuscache/include/dm_softbus_cache.h index b315a87d6..e3c2a6d8b 100644 --- a/services/softbuscache/include/dm_softbus_cache.h +++ b/services/softbuscache/include/dm_softbus_cache.h @@ -45,6 +45,7 @@ public: int32_t GetLocalDeviceInfo(DmDeviceInfo &nodeInfo); int32_t GetDevInfoByNetworkId(const std::string &networkId, DmDeviceInfo &nodeInfo); void UpDataLocalDevInfo(); + int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid); private: int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index a7c9a7e39..de4b171fb 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -371,5 +371,21 @@ int32_t SoftbusCache::GetDevInfoFromBus(const std::string &networkId, DmDeviceIn GetAnonyString(devInfo.deviceName).c_str(), devInfo.deviceTypeId); return ret; } + +int32_t SoftbusCache::GetUdidByUdidHash(const std::string &udidHash, std::string &udid) +{ + LOGI("udidHash %{public}s.", GetAnonyString(udidHash).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + for (const auto &item : deviceInfo_) { + if (std::string(item.second.second.deviceId) == udidHash) { + udid = item.first; + LOGI("GetUdidByUdidHash success udid %{public}s.", GetAnonyString(udid).c_str()); + return DM_OK; + } + } + } + return ERR_DM_FAILED; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp index 485f5a9a3..59eb99cad 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp @@ -114,6 +114,7 @@ void AuthenticateDeviceServiceImplFuzzTest(const uint8_t* data, size_t size) } std::string str(reinterpret_cast(data), size); + int32_t bindLevel = *(reinterpret_cast(data)); AddPermission(); DmSubscribeInfo subscribeInfo = { .subscribeId = 0, @@ -138,10 +139,8 @@ void AuthenticateDeviceServiceImplFuzzTest(const uint8_t* data, size_t size) deviceManagerServiceImpl->StopDeviceDiscovery(str, g_subscribeId); deviceManagerServiceImpl->PublishDeviceDiscovery(str, publishInfo); deviceManagerServiceImpl->UnPublishDeviceDiscovery(str, publishInfo.publishId); - deviceManagerServiceImpl->AuthenticateDevice(str, g_authType, str, str); - deviceManagerServiceImpl->UnAuthenticateDevice(str, str); - deviceManagerServiceImpl->BindDevice(str, g_authType, str, str); - deviceManagerServiceImpl->UnBindDevice(str, str); + deviceManagerServiceImpl->UnAuthenticateDevice(str, str, bindLevel); + deviceManagerServiceImpl->UnBindDevice(str, str, bindLevel); deviceManagerServiceImpl->SetUserOperation(str, g_action, str); deviceManagerServiceImpl->RequestCredential(g_reqJsonStr, g_returnJsonStr); deviceManagerServiceImpl->ImportCredential(str, g_credentialInfo); diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp index 48da00372..160243871 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp +++ b/test/commonfuzztest/dmauthmanager_fuzzer/dm_auth_manager_fuzzer.cpp @@ -62,6 +62,7 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) return; } std::string str(reinterpret_cast(data), size); + int32_t bindLevel = *(reinterpret_cast(data)); g_authManager->authMessageProcessor_ = std::make_shared(g_authManager); g_authManager->authMessageProcessor_->authResponseContext_ = std::make_shared(); g_authManager->authRequestContext_ = std::make_shared(); @@ -94,7 +95,6 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) g_authManager->StartRespAuthProcess(); g_authManager->CreateGroup(); g_authManager->ProcessPincode(g_pinCode); - g_authManager->UserSwitchEventCallback(g_userId); g_authManager->SetPageId(g_pageId); g_authManager->SetReasonAndFinish(g_reason, g_state); g_authManager->IsIdenticalAccount(); @@ -104,8 +104,8 @@ void DmAuthManagerFuzzTest(const uint8_t* data, size_t size) g_authManager->HandleAuthenticateTimeout(str); g_authManager->RegisterUiStateCallback(str); g_authManager->UnRegisterUiStateCallback(str); - g_authManager->UnAuthenticateDevice(str, str); - g_authManager->UnBindDevice(str, str); + g_authManager->UnAuthenticateDevice(str, str, bindLevel); + g_authManager->UnBindDevice(str, str, bindLevel); } } } diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index e9f8f286c..433615553 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -97,7 +97,6 @@ void HiChainConnectorFuzzTest(const uint8_t* data, size_t size) hichainConnector->GetTrustedDevices(deviceId); hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); hichainConnector->DeleteAllGroup(delUserid); - hichainConnector->DeleteP2PGroup(delUserid); hichainConnector->GetRelatedGroupsCommon(deviceId, pkgNameStr.data(), groupList); hichainConnector->UnRegisterHiChainCallback(); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 1da5a193a..9cf98278a 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -64,57 +64,6 @@ namespace { const int32_t MIN_PIN_CODE = 100000; const int32_t MAX_PIN_CODE = 999999; -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - std::string networkId = "222"; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "222"; - authManager_->authRequestState_ = nullptr; - authManager_->authResponseContext_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = false; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->authResponseContext_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = true; - authManager_->authRequestContext_ = std::make_shared(); - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = false; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string networkId = "networkId"; - authManager_->authRequestState_ = nullptr; - authManager_->authResponseContext_ = nullptr; - int32_t ret = authManager_->UnAuthenticateDevice(pkgName, networkId); - ASSERT_EQ(ret, SOFTBUS_IPC_ERR); -} - HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_001, testing::ext::TestSize.Level0) { std::string name = "test"; @@ -251,8 +200,6 @@ HWTEST_F(DmAuthManagerTest, JoinNetwork_001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, JoinNetwork_002, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; - int32_t userId = 1; - authManager_->UserSwitchEventCallback(userId); authManager_->AuthenticateFinish(); authManager_->CancelDisplay(); int32_t ret = authManager_->JoinNetwork(); @@ -582,58 +529,6 @@ HWTEST_F(DmAuthManagerTest, OnUserOperation_007, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -HWTEST_F(DmAuthManagerTest, UnBindDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string udidHash = "udidHash"; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnBindDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string udidHash = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = true; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, UnBindDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string udidHash = "222"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = false; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnBindDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string udidHash = "networkId"; - authManager_->authRequestState_ = nullptr; - authManager_->authResponseContext_ = nullptr; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DmAuthManagerTest, UnBindDevice_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string udidHash = "networkId"; - authManager_->authRequestState_ = std::make_shared(); - authManager_->authResponseContext_ = std::make_shared(); - authManager_->isAuthenticateDevice_ = false; - int32_t ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, ERR_DM_FAILED); - authManager_->isAuthenticateDevice_ = true; - ret = authManager_->UnBindDevice(pkgName, udidHash); - ASSERT_EQ(ret, DM_OK); -} - HWTEST_F(DmAuthManagerTest, RequestCredential001, testing::ext::TestSize.Level0) { authManager_->hiChainAuthConnector_ = std::make_shared(); @@ -672,67 +567,12 @@ HWTEST_F(DmAuthManagerTest, ImportCredential001, testing::ext::TestSize.Level0) ASSERT_NE(ret, DM_OK); } -HWTEST_F(DmAuthManagerTest, EstablishUnbindChannel001, testing::ext::TestSize.Level0) -{ - std::string deviceIdHash = "deviceIdHash"; - int32_t ret = authManager_->EstablishUnbindChannel(deviceIdHash); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, RequestSyncDeleteAcl001, testing::ext::TestSize.Level0) -{ - authManager_->RequestSyncDeleteAcl(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, RequestSyncDeleteAcl002, testing::ext::TestSize.Level0) -{ - authManager_->timer_ = nullptr; - authManager_->RequestSyncDeleteAcl(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SrcSyncDeleteAclDonel001, testing::ext::TestSize.Level0) -{ - authManager_->isFinishOfLocal_ = true; - authManager_->authResponseContext_->reply = 0; - authManager_->SrcSyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SinkSyncDeleteAclDone001, testing::ext::TestSize.Level0) -{ - authManager_->isFinishOfLocal_ = true; - authManager_->authResponseContext_->reply = 0; - authManager_->SinkSyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SyncDeleteAclDone001, testing::ext::TestSize.Level0) -{ - authManager_->SyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SyncDeleteAclDone002, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = nullptr; - authManager_->SyncDeleteAclDone(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, ResponseCredential001, testing::ext::TestSize.Level0) { authManager_->ResponseCredential(); ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, ResponseSyncDeleteAcl001, testing::ext::TestSize.Level0) -{ - authManager_->ResponseSyncDeleteAcl(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, AuthDeviceTransmit001, testing::ext::TestSize.Level0) { int64_t requestId = 0; @@ -938,50 +778,6 @@ HWTEST_F(DmAuthManagerTest, CompatiblePutAcl001, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, CommonEventCallback001, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - int32_t userId = 0; - authManager_->CommonEventCallback(userId, ""); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, AccountIdLogoutEventCallback001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - authManager_->AccountIdLogoutEventCallback(userId); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, UserSwitchEventCallback001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - authManager_->UserSwitchEventCallback(userId); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, UserChangeEventCallback001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - authManager_->UserChangeEventCallback(userId); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, HandleSyncDeleteTimeout001, testing::ext::TestSize.Level0) -{ - std::string name; - authManager_->HandleSyncDeleteTimeout(name); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, DeleteAcl001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string deviceId; - int32_t ret = authManager_->DeleteAcl(pkgName, deviceId); - ASSERT_NE(ret, DM_OK); -} - HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt001, testing::ext::TestSize.Level0) { int32_t sessionId = 0; @@ -1055,42 +851,6 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived005, testing::ext::TestSize. ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, OnUnbindSessionOpened001, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 1; - std::string name = "nameTest"; - std::string networkId = "159753681387291"; - std::string pkgName = "com.ohos.test"; - PeerSocketInfo info = { - .name = const_cast(name.c_str()), - .pkgName = const_cast(pkgName.c_str()), - .networkId = const_cast(networkId.c_str()), - }; - authManager_->authResponseState_ = nullptr; - authManager_->authRequestState_ = nullptr; - authManager_->timer_ = nullptr; - authManager_->OnUnbindSessionOpened(sessionId, info); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, OnUnbindSessionOpened002, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 1; - std::string name = "nameTest"; - std::string networkId = "159753681387291"; - std::string pkgName = "com.ohos.test"; - PeerSocketInfo info = { - .name = const_cast(name.c_str()), - .pkgName = const_cast(pkgName.c_str()), - .networkId = const_cast(networkId.c_str()), - }; - authManager_->authResponseState_ = std::make_shared(); - authManager_->authRequestState_ = std::make_shared(); - authManager_->timer_ = nullptr; - authManager_->OnUnbindSessionOpened(sessionId, info); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - HWTEST_F(DmAuthManagerTest, DeleteGroup001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -1119,38 +879,6 @@ HWTEST_F(DmAuthManagerTest, PutAccessControlList001, testing::ext::TestSize.Leve ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, BindSocketFail_001, testing::ext::TestSize.Level0) -{ - authManager_->BindSocketFail(); - ASSERT_EQ(authManager_->isFinishOfLocal_, false); -} - -HWTEST_F(DmAuthManagerTest, BindSocketSuccess_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - authManager_->authResponseState_ = nullptr; - authManager_->authRequestState_ = std::make_shared(); - authManager_->BindSocketSuccess(socket); - ASSERT_EQ(authManager_->authRequestContext_->sessionId, socket); -} - -HWTEST_F(DmAuthManagerTest, BindSocketSuccess_002, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - authManager_->authResponseState_ = std::make_shared(); - authManager_->authRequestState_ = nullptr; - authManager_->BindSocketSuccess(socket); - ASSERT_NE(authManager_->authRequestContext_->sessionId, socket); -} - -HWTEST_F(DmAuthManagerTest, SyncDeleteAcl_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::string deviceId = "deviceId"; - authManager_->SyncDeleteAcl(pkgName, deviceId); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_001, testing::ext::TestSize.Level0) { authManager_->authResponseContext_->msgType = 200; @@ -1231,14 +959,6 @@ HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_010, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } -HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_0011, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_->msgType = 505; - authManager_->authRequestState_ = std::make_shared(); - authManager_->ProcessSourceMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, false); -} - HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_0012, testing::ext::TestSize.Level0) { authManager_->authResponseContext_->msgType = 505; @@ -1247,14 +967,6 @@ HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_0012, testing::ext::TestSize.Level0 ASSERT_EQ(authManager_->isFinishOfLocal_, true); } -HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_013, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_->msgType = 1000; - authManager_->authRequestState_ = std::make_shared(); - authManager_->ProcessSourceMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_001, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = std::make_shared(); @@ -1317,24 +1029,6 @@ HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_007, testing::ext::TestSize.Level0) authManager_->ProcessSinkMsg(); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } - -HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_008, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_ = std::make_shared(); - authManager_->authResponseContext_->msgType = 505; - authManager_->authResponseState_ = std::make_shared(); - authManager_->ProcessSinkMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - -HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_009, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_ = std::make_shared(); - authManager_->authResponseContext_->msgType = 1000; - authManager_->authResponseState_ = std::make_shared(); - authManager_->ProcessSinkMsg(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index ab5622022..47341d14f 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -79,30 +79,6 @@ HWTEST_F(DmAuthManagerTest, OnDataReceived_003, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } -HWTEST_F(DmAuthManagerTest, OnDataReceived_004, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 0; - nlohmann::json jsonObject; - jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(); - authManager_->OnDataReceived(sessionId, message); - authManager_->authRequestState_ = std::make_shared(); - authManager_->authResponseState_ = nullptr; - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - -HWTEST_F(DmAuthManagerTest, OnDataReceived_005, testing::ext::TestSize.Level0) -{ - int32_t sessionId = 0; - nlohmann::json jsonObject; - jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(); - authManager_->OnDataReceived(sessionId, message); - authManager_->authRequestState_ = nullptr; - authManager_->authResponseState_ = std::make_shared(); - ASSERT_EQ(authManager_->isFinishOfLocal_, true); -} - HWTEST_F(DmAuthManagerTest, OnDataReceived_007, testing::ext::TestSize.Level0) { int32_t sessionId = 0; diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 8d67f7553..6b7280265 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -508,50 +508,6 @@ HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::Tes EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - std::string accountId; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string localDeviceId; - std::string remoteDeviceId; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "localDeviceId"; - std::string remoteDeviceId = "remoteDeviceId"; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "123456"; - std::string remoteDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "deviceId"; - std::string remoteDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - HWTEST_F(DeviceProfileConnectorTest, UpdateAccessControlList_001, testing::ext::TestSize.Level0) { int32_t userId = 0; @@ -596,30 +552,6 @@ HWTEST_F(DeviceProfileConnectorTest, CheckIdenticalAccount_001, testing::ext::Te EXPECT_EQ(ret, true); } -HWTEST_F(DeviceProfileConnectorTest, DeleteP2PAccessControlList_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - std::string accountId; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteP2PAccessControlList_002, testing::ext::TestSize.Level0) -{ - int32_t userId = 123456; - std::string accountId = "newAccountId"; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceProfileConnectorTest, DeleteP2PAccessControlList_003, testing::ext::TestSize.Level0) -{ - int32_t userId = 123456; - std::string accountId = "accountId"; - int32_t ret = DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); - EXPECT_EQ(ret, DM_OK); -} - HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -690,42 +622,6 @@ HWTEST_F(DeviceProfileConnectorTest, GetTrustNumber_001, testing::ext::TestSize. EXPECT_EQ(ret, DM_OK); } -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string localDeviceId; - std::string remoteDeviceId; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, false); -} - -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "localDeviceId"; - std::string remoteDeviceId = "remoteDeviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, false); -} - -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "deviceId"; - std::string remoteDeviceId = "remoteDeviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, false); -} - -HWTEST_F(DeviceProfileConnectorTest, CheckPkgnameInAcl_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "bundleName"; - std::string localDeviceId = "deviceId"; - std::string remoteDeviceId = "deviceId"; - bool ret = DeviceProfileConnector::GetInstance().CheckPkgnameInAcl(pkgName, localDeviceId, remoteDeviceId); - EXPECT_EQ(ret, false); -} - HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_001, testing::ext::TestSize.Level0) { std::string udid = "udid"; diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index e28fe09d1..f3176758f 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1363,19 +1363,6 @@ HWTEST_F(HichainConnectorTest, DeleteAllGroup_001, testing::ext::TestSize.Level0 EXPECT_NE(hiChainConnector->deviceGroupManager_, nullptr); } -/** - * @tc.name: DeleteP2PGroup_001 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(HichainConnectorTest, DeleteP2PGroup_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 1; - std::shared_ptr hiChainConnector = std::make_shared(); - hiChainConnector->DeleteP2PGroup(userId); - EXPECT_NE(hiChainConnector->deviceGroupManager_, nullptr); -} - /** * @tc.name: GetRelatedGroupsCommon_001 * @tc.desc: return ERR_DM_FAILED diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index 9d6dc7373..9cc167b05 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -53,17 +53,16 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) dmAccessee.trustBundleName = trustBundleName; int32_t userId = *(reinterpret_cast(data)); std::string accountId(reinterpret_cast(data), size); + int32_t bindLevel = *(reinterpret_cast(data)); DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); - DeviceProfileConnector::GetInstance().DeleteAccessControlList(userId, accountId); - DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId); + DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId, bindLevel); DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); - DeviceProfileConnector::GetInstance().DeleteP2PAccessControlList(userId, accountId); DeviceProfileConnector::GetInstance().CheckDevIdInAclForDevBind(pkgName, localDeviceId); DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(localDeviceId); DeviceProfileConnector::GetInstance().GetTrustNumber(localDeviceId); diff --git a/test/softbusfuzztest/BUILD.gn b/test/softbusfuzztest/BUILD.gn index 1771786ef..feb576219 100644 --- a/test/softbusfuzztest/BUILD.gn +++ b/test/softbusfuzztest/BUILD.gn @@ -24,7 +24,6 @@ group("fuzztest") { "onsoftbuslistenerdevicefound_fuzzer:fuzztest", "publishsoftbuslnn_fuzzer:fuzztest", "refreshsoftbuslnn_fuzzer:fuzztest", - "softbusadapterobject_fuzzer:fuzztest", "softbusconnector_fuzzer:fuzztest", "softbusconnectorcommon_fuzzer:fuzztest", "softbusconnectorpublish_fuzzer:fuzztest", diff --git a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp index 1c25c25ca..2d0979540 100644 --- a/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp +++ b/test/softbusfuzztest/onbytesreceived_fuzzer/on_bytes_received_fuzzer.cpp @@ -45,21 +45,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void OnBytesReceivedFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp b/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp index 0fbcade8b..1caed0d58 100644 --- a/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp +++ b/test/softbusfuzztest/onsessionopened_fuzzer/on_session_opened_fuzzer.cpp @@ -50,21 +50,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void OnSessionOpenedFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn deleted file mode 100644 index eec0bda09..000000000 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/BUILD.gn +++ /dev/null @@ -1,70 +0,0 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -#####################hydra-fuzz################### -import("//build/config/features.gni") -import("//build/test.gni") -import("//foundation/distributedhardware/device_manager/device_manager.gni") - -##############################fuzztest########################################## -ohos_fuzztest("SoftbusAdapterObjectFuzzTest") { - module_out_path = fuzz_test_output_path - fuzz_config_file = - "${devicemanager_path}/test/softbusfuzztest/softbusadapterobject_fuzzer" - - include_dirs = [ - "${utils_path}/include", - "${common_path}/include", - "${common_path}/include/ipc", - "${common_path}/include/ipc/model", - "${utils_path}/include/ipc/standard", - "${services_path}/include/softbus", - "${servicesimpl_path}/include", - "${servicesimpl_path}/include/dependency/commonevent", - "${servicesimpl_path}/include/dependency/softbus", - ] - - cflags = [ - "-g", - "-O0", - "-Dprivate=public", - "-Dprotected=public", - "-Wno-unused-variable", - "-fno-omit-frame-pointer", - ] - - sources = [ "softbus_adapter_object_fuzzer.cpp" ] - - deps = [ - "${innerkits_path}/native_cpp:devicemanagersdk", - "${services_path}:devicemanagerservice", - "${servicesimpl_path}:devicemanagerserviceimpl", - "${utils_path}:devicemanagerutils", - ] - - external_deps = [ "safwk:system_ability_fwk" ] - - defines = [ - "HI_LOG_ENABLE", - "DH_LOG_TAG=\"SoftbusAdapterObjectFuzzTest\"", - "LOG_DOMAIN=0xD004110", - ] -} - -############################################################################### -group("fuzztest") { - testonly = true - - deps = [ ":SoftbusAdapterObjectFuzzTest" ] -} -############################################################################### diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/corpus/init b/test/softbusfuzztest/softbusadapterobject_fuzzer/corpus/init deleted file mode 100644 index f7880ef1a..000000000 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/corpus/init +++ /dev/null @@ -1,13 +0,0 @@ -# Copyright (c) 2024 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -FUZZ \ No newline at end of file diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/project.xml b/test/softbusfuzztest/softbusadapterobject_fuzzer/project.xml deleted file mode 100644 index 6d3e765c7..000000000 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/project.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - 1000 - - 300 - - 4096 - - \ No newline at end of file diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.cpp b/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.cpp deleted file mode 100644 index f1458be55..000000000 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "device_manager_service_listener.h" -#include "softbus_bus_center.h" -#include "softbus_adapter.h" -#include "softbus_connector.h" -#include "softbus_adapter_object_fuzzer.h" - -namespace OHOS { -namespace DistributedHardware { -void SoftbusAdapterFuzzTest(const uint8_t* data, size_t size) -{ - if ((data == nullptr) || (size < sizeof(uint32_t))) { - return; - } - - int32_t socket = *(reinterpret_cast(data)); - std::string str(reinterpret_cast(data), size); - uint32_t qosCount = 3; - StreamData streamData; - StreamData ext; - StreamFrameInfo frameInfo; - QoSEvent eventId = static_cast(1); - QosTV qos[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 19000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 500 }, - }; - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - PeerSocketInfo info = { - .name = const_cast(str.c_str()), - .pkgName = const_cast(str.c_str()), - .networkId = const_cast(str.c_str()), - }; - - SoftbusAdapter::GetInstance().iSocketListener_.OnBind(socket, info); - SoftbusAdapter::GetInstance().iSocketListener_.OnShutdown(socket, reason); - SoftbusAdapter::GetInstance().iSocketListener_.OnBytes(socket, data, size); - SoftbusAdapter::GetInstance().iSocketListener_.OnMessage(socket, data, size); - SoftbusAdapter::GetInstance().iSocketListener_.OnStream(socket, &streamData, &ext, &frameInfo); - SoftbusAdapter::GetInstance().iSocketListener_.OnQos(socket, eventId, qos, qosCount); -} -} -} - -/* Fuzzer entry point */ -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) -{ - /* Run your code on data */ - OHOS::DistributedHardware::SoftbusAdapterFuzzTest(data, size); - - return 0; -} diff --git a/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.h b/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.h deleted file mode 100644 index 055da39fa..000000000 --- a/test/softbusfuzztest/softbusadapterobject_fuzzer/softbus_adapter_object_fuzzer.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SOFTBUS_ADAPTER_OBJECT_FUZZER_H -#define SOFTBUS_ADAPTER_OBJECT_FUZZER_H - -#define FUZZ_PROJECT_NAME "softbusadapterobject_fuzzer" - -#endif // SOFTBUS_ADAPTER_OBJECT_FUZZER_H \ No newline at end of file diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp index 660e74bce..1365cb4fb 100644 --- a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp @@ -32,7 +32,6 @@ public: void OnDeviceOnline(std::string deviceId, int32_t authForm) override {} void OnDeviceOffline(std::string deviceId) override {} - void DeleteOffLineTimer(std::string udidHash) override {} }; void SoftBusConnectorStateFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp index a64036b63..c73803398 100644 --- a/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp +++ b/test/softbusfuzztest/softbussession_fuzzer/softbus_session_fuzzer.cpp @@ -47,21 +47,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) @@ -73,7 +63,6 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) int result = *(reinterpret_cast(data)); int32_t sessionId = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); - PeerSocketInfo info; std::shared_ptr softbusSession = std::make_shared(); softbusSession->RegisterSessionCallback(std::make_shared()); @@ -81,9 +70,6 @@ void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) softbusSession->OpenAuthSession(str); softbusSession->CloseAuthSession(sessionId); softbusSession->OnBytesReceived(result, str.c_str(), str.size()); - softbusSession->OnUnbindSessionOpened(sessionId, info); - softbusSession->OpenUnbindSession(str); - softbusSession->CloseUnbindSession(sessionId); softbusSession->GetPeerDeviceId(sessionId, str); softbusSession->SendData(sessionId, str); softbusSession->SendHeartbeatData(sessionId, str); diff --git a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp index f3e72c466..fe688c42f 100644 --- a/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp +++ b/test/softbusfuzztest/softbussessionobject_fuzzer/softbus_session_object_fuzzer.cpp @@ -45,21 +45,11 @@ public: { return true; } - void OnUnbindSessionOpened(int32_t socket, PeerSocketInfo info) override - { - (void)socket; - (void)info; - } void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override { (void)sessionId; (void)message; } - void BindSocketSuccess(int32_t socket) override - { - (void)socket; - } - void BindSocketFail() override {} }; void SoftBusSessionFuzzTest(const uint8_t* data, size_t size) diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.h b/test/softbusunittest/UTTest_mine_softbus_listener.h index 314dafb9d..685e50c40 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.h +++ b/test/softbusunittest/UTTest_mine_softbus_listener.h @@ -23,7 +23,6 @@ #include #include -#include "softbus_adapter.h" #include "softbus_bus_center.h" #include "softbus_listener.h" #include "dm_device_info.h" diff --git a/test/softbusunittest/UTTest_softbus_adapter.cpp b/test/softbusunittest/UTTest_softbus_adapter.cpp deleted file mode 100644 index eea23fcaf..000000000 --- a/test/softbusunittest/UTTest_softbus_adapter.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "UTTest_softbus_adapter.h" - -#include "dm_anonymous.h" -#include "dm_constants.h" -#include "dm_log.h" -#include "nlohmann/json.hpp" -#include "softbus_adapter.h" -#include "softbus_connector.h" -#include "softbus_error_code.h" - -namespace OHOS { -namespace DistributedHardware { -void SoftbusAdapterTest::SetUp() -{ -} -void SoftbusAdapterTest::TearDown() -{ -} -void SoftbusAdapterTest::SetUpTestCase() -{ -} -void SoftbusAdapterTest::TearDownTestCase() -{ -} - -namespace { -HWTEST_F(SoftbusAdapterTest, CreateSoftbusSessionServer_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string sessionName; - int32_t ret = SoftbusAdapter::GetInstance().CreateSoftbusSessionServer(pkgName, sessionName); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); -} - -HWTEST_F(SoftbusAdapterTest, RemoveSoftbusSessionServer_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string sessionName; - int32_t ret = SoftbusAdapter::GetInstance().RemoveSoftbusSessionServer(pkgName, sessionName); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); -} - -HWTEST_F(SoftbusAdapterTest, OnSoftbusSessionOpened_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string str = "132131321345"; - PeerSocketInfo info = { - .name = const_cast(str.c_str()), - .pkgName = const_cast(str.c_str()), - .networkId = const_cast(str.c_str()), - }; - SoftbusAdapter::GetInstance().OnSoftbusSessionOpened(socket, info); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnSoftbusSessionClosed_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - SoftbusAdapter::GetInstance().OnSoftbusSessionClosed(socket, reason); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnBytesReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().OnBytesReceived(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnStreamReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - StreamData data; - StreamData exta; - StreamFrameInfo frameInfo; - SoftbusAdapter::GetInstance().OnStreamReceived(socket, &data, &exta, &frameInfo); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnMessageReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().OnMessageReceived(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, OnQosEvent_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - QoSEvent eventId = static_cast(1); - QosTV qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, - }; - uint32_t qosCount = 1; - SoftbusAdapter::GetInstance().OnQosEvent(socket, eventId, qosInfo, qosCount); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnError, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnSoftbusSessionBind_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string str = "132131321345"; - PeerSocketInfo info = { - .name = const_cast(str.c_str()), - .pkgName = const_cast(str.c_str()), - .networkId = const_cast(str.c_str()), - }; - SoftbusAdapter::GetInstance().iSocketListener_.OnBind(socket, info); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnError, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnSoftbusSessionClosed_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - SoftbusAdapter::GetInstance().iSocketListener_.OnShutdown(socket, reason); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnBytesReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().iSocketListener_.OnBytes(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnStreamReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - StreamData data; - StreamData exta; - StreamFrameInfo frameInfo; - SoftbusAdapter::GetInstance().iSocketListener_.OnStream(socket, &data, &exta, &frameInfo); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnMessageReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "data"; - SoftbusAdapter::GetInstance().iSocketListener_.OnMessage(socket, data.c_str(), data.size()); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} - -HWTEST_F(SoftbusAdapterTest, DmOnQosEvent_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - QoSEvent eventId = static_cast(1); - QosTV qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, - }; - uint32_t qosCount = 1; - SoftbusAdapter::GetInstance().iSocketListener_.OnQos(socket, eventId, qosInfo, qosCount); - EXPECT_EQ(SoftbusAdapter::GetInstance().iSocketListener_.OnFile, nullptr); -} -} // namespace -} // namespace DistributedHardware -} // namespace OHOS diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 33ff94e30..15b00afc3 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -724,38 +724,6 @@ HWTEST_F(SoftbusListenerTest, OnLocalDevInfoChange_001, testing::ext::TestSize.L softbusListener->OnLocalDevInfoChange(); EXPECT_EQ(msg, nullptr); } - -HWTEST_F(SoftbusListenerTest, OnDeviceNotTrusted_001, testing::ext::TestSize.Level0) -{ - char *msg = nullptr; - if (softbusListener == nullptr) { - softbusListener = std::make_shared(); - } - softbusListener->OnDeviceNotTrusted(nullptr); - EXPECT_EQ(msg, nullptr); -} - -HWTEST_F(SoftbusListenerTest, OnDeviceNotTrusted_002, testing::ext::TestSize.Level0) -{ - char msg[MAX_SOFTBUS_MSG_LEN + 1] = "This is a long message"; - if (softbusListener == nullptr) { - softbusListener = std::make_shared(); - } - softbusListener->OnDeviceNotTrusted(msg); - EXPECT_NE(msg, nullptr); -} - -HWTEST_F(SoftbusListenerTest, OnDeviceNotTrusted_003, testing::ext::TestSize.Level0) -{ - char msg[MAX_SOFTBUS_MSG_LEN - 1] = "Valid message"; - if (softbusListener == nullptr) { - softbusListener = std::make_shared(); - } - softbusListener->OnDeviceNotTrusted(msg); - EXPECT_NE(msg, nullptr); -} - - } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/softbusunittest/UTTest_softbus_listener.h b/test/softbusunittest/UTTest_softbus_listener.h index 5f738fbee..f840ea9e7 100644 --- a/test/softbusunittest/UTTest_softbus_listener.h +++ b/test/softbusunittest/UTTest_softbus_listener.h @@ -23,7 +23,6 @@ #include #include -#include "softbus_adapter.h" #include "softbus_bus_center.h" #include "softbus_listener.h" #include "dm_device_info.h" diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index 84ff8726a..155da5f75 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -179,21 +179,6 @@ HWTEST_F(SoftbusSessionTest, CloseAuthSession_001, testing::ext::TestSize.Level0 EXPECT_EQ(ret, DM_OK); } -/** - * @tc.name: CloseUnbindSession_001 - * @tc.desc: set socket = 1, and return DM_OK - * @tc.type: FUNC - */ -HWTEST_F(SoftbusSessionTest, CloseUnbindSession_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - if (softbusSession == nullptr) { - softbusSession = std::make_shared(); - } - int32_t ret = softbusSession->CloseUnbindSession(socket); - EXPECT_EQ(ret, DM_OK); -} - /** * @tc.name: GetPeerDeviceId_001 * @tc.desc: set sessionId = 3 and return DM_OK diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 0a0aac456..1dbbc7396 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -66,7 +66,6 @@ group("unittest") { ":UTTest_permission_manager", ":UTTest_pin_auth", ":UTTest_pin_auth_ui", - ":UTTest_softbus_adapter", ":UTTest_softbus_connector", ":UTTest_softbus_listener", ":UTTest_softbus_publish", @@ -422,30 +421,6 @@ ohos_unittest("UTTest_mine_softbus_listener") { ## UnitTest UTTest_mine_softbus_listener }}} -## UnitTest UTTest_softbus_adapter {{{ -ohos_unittest("UTTest_softbus_adapter") { - module_out_path = module_out_path - - include_dirs = [ "${devicemanager_path}/test/softbusunittest" ] - - sources = [ - "${devicemanager_path}/test/softbusunittest/UTTest_softbus_adapter.cpp", - ] - - deps = [ ":device_manager_test_common" ] - - external_deps = [ - "device_auth:deviceauth_sdk", - "device_info_manager:distributed_device_profile_common", - "device_info_manager:distributed_device_profile_sdk", - "googletest:gmock", - "hisysevent:libhisysevent", - "hitrace:hitrace_meter", - ] -} - -## UnitTest UTTest_softbus_adapter }}} - ## UnitTest UTTest_softbus_connector {{{ ohos_unittest("UTTest_softbus_connector") { module_out_path = module_out_path diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index cf84dcb08..eb392b1ee 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -1085,9 +1085,6 @@ HWTEST_F(AuthMessageProcessorTest, CreateSimpleMessage_001, testing::ext::TestSi msgType = MSG_TYPE_REQ_PUBLICKEY; ret = authMessageProcessor->CreateSimpleMessage(msgType); ASSERT_NE(ret.size(), 0); - msgType = MSG_TYPE_REQ_SYNC_DELETE; - ret = authMessageProcessor->CreateSimpleMessage(msgType); - ASSERT_NE(ret.size(), 0); msgType = MSG_TYPE_NEGOTIATE; ret = authMessageProcessor->CreateSimpleMessage(msgType); ASSERT_NE(ret.size(), 0); @@ -1423,20 +1420,6 @@ HWTEST_F(AuthMessageProcessorTest, GetJsonObj_002, testing::ext::TestSize.Level0 ASSERT_EQ(jsonObj[TAG_IS_SHOW_DIALOG], true); } -HWTEST_F(AuthMessageProcessorTest, CreateSyncDeleteMessageExt_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hiChainConnector_ = std::make_shared(); - std::shared_ptr data = - std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); - std::shared_ptr authMessageProcessor = std::make_shared(data); - authMessageProcessor->authResponseContext_ = std::make_shared(); - authMessageProcessor->authResponseContext_->localDeviceId = "13213521"; - authMessageProcessor->authResponseContext_->hostPkgName = "ohos_test"; - nlohmann::json jsonObj; - authMessageProcessor->CreateSyncDeleteMessageExt(jsonObj); - ASSERT_EQ(jsonObj[TAG_REPLY], DM_OK); -} - HWTEST_F(AuthMessageProcessorTest, CreatePublicKeyMessageExt_001, testing::ext::TestSize.Level0) { std::shared_ptr hiChainConnector_ = std::make_shared(); @@ -1492,36 +1475,6 @@ HWTEST_F(AuthMessageProcessorTest, CreateRespNegotiateMessage_002, testing::ext: ASSERT_EQ(jsonObj[TAG_CRYPTO_SUPPORT], true); } -HWTEST_F(AuthMessageProcessorTest, ParseSyncDeleteMessageExt_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr hiChainConnector_ = std::make_shared(); - std::shared_ptr data = - std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); - std::shared_ptr authMessageProcessor = std::make_shared(data); - authMessageProcessor->authResponseContext_ = std::make_shared(); - nlohmann::json jsonObj; - jsonObj[TAG_LOCAL_DEVICE_ID] = "12121213"; - jsonObj[TAG_HOST_PKGNAME] = "hostPkgname"; - jsonObj[TAG_REPLY] = 1212; - authMessageProcessor->ParseSyncDeleteMessageExt(jsonObj); - ASSERT_EQ(authMessageProcessor->authResponseContext_->reply, 1212); -} - -HWTEST_F(AuthMessageProcessorTest, ParseSyncDeleteMessageExt_002, testing::ext::TestSize.Level0) -{ - std::shared_ptr hiChainConnector_ = std::make_shared(); - std::shared_ptr data = - std::make_shared(softbusConnector, hiChainConnector_, listener, hiChainAuthConnector); - std::shared_ptr authMessageProcessor = std::make_shared(data); - authMessageProcessor->authResponseContext_ = std::make_shared(); - nlohmann::json jsonObj; - jsonObj[TAG_LOCAL_DEVICE_ID] = 2121; - jsonObj[TAG_HOST_PKGNAME] = 1231; - jsonObj[TAG_REPLY] = "1212"; - authMessageProcessor->ParseSyncDeleteMessageExt(jsonObj); - ASSERT_NE(authMessageProcessor->authResponseContext_->reply, 1212); -} - HWTEST_F(AuthMessageProcessorTest, ParsePublicKeyMessageExt_001, testing::ext::TestSize.Level0) { std::shared_ptr hiChainConnector_ = std::make_shared(); diff --git a/test/unittest/UTTest_auth_request_state.cpp b/test/unittest/UTTest_auth_request_state.cpp index 6057378d2..bfa9d9e19 100644 --- a/test/unittest/UTTest_auth_request_state.cpp +++ b/test/unittest/UTTest_auth_request_state.cpp @@ -689,90 +689,6 @@ HWTEST_F(AuthRequestStateTest, Enter_010, testing::ext::TestSize.Level0) int32_t ret = authRequestState->Enter(); ASSERT_EQ(ret, ERR_DM_FAILED); } - -/** - * @tc.name: AuthRequestDeleteInit::GetStateType_010 - * @tc.desc: 1 call AuthRequestDeleteInit::GetStateType - * 2 check ret is AUTH_REQUEST_DELETE_INIT - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, GetStateType_010, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret, AUTH_REQUEST_DELETE_INIT); -} - -/** - * @tc.name: AuthRequestDeleteInit::Enter_017 - * @tc.desc: 1 call AuthRequestDeleteInit::Enter - * 2 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, Enter_017, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -/** - * @tc.name: AuthRequestSyncDeleteAcl::GetStateType_011 - * @tc.desc: 1 call AuthRequestSyncDeleteAcl::GetStateType - * 2 check ret is AUTH_REQUEST_SYNCDELETE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, GetStateType_011, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret, AUTH_REQUEST_SYNCDELETE); -} - -/** - * @tc.name: AuthRequestSyncDeleteAcl::Enter_018 - * @tc.desc: 1 call AuthRequestSyncDeleteAcl::Enter - * 2 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, Enter_018, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -/** - * @tc.name: AuthRequestSyncDeleteAclNone::GetStateType_012 - * @tc.desc: 1 call AuthRequestSyncDeleteAclNone::GetStateType - * 2 check ret is AUTH_REQUEST_SYNCDELETE_DONE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, GetStateType_012, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->GetStateType(); - ASSERT_EQ(ret, AUTH_REQUEST_SYNCDELETE_DONE); -} - -/** - * @tc.name: AuthRequestSyncDeleteAclNone::Enter_019 - * @tc.desc: 1 call AuthRequestSyncDeleteAclNone::Enter - * 2 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthRequestStateTest, Enter_019, testing::ext::TestSize.Level0) -{ - std::shared_ptr authRequestState = std::make_shared(); - int32_t ret = authRequestState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_auth_response_state.cpp b/test/unittest/UTTest_auth_response_state.cpp index 078a47587..1a8aa6352 100644 --- a/test/unittest/UTTest_auth_response_state.cpp +++ b/test/unittest/UTTest_auth_response_state.cpp @@ -507,72 +507,6 @@ HWTEST_F(AuthResponseStateTest, Enter_012, testing::ext::TestSize.Level0) int32_t ret = authResponseState->Enter(); ASSERT_EQ(ret, ERR_DM_FAILED); } - -/** - * @tc.name: AuthResponseSyncDeleteAcl::GetStateType_011 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAcl::GetStateType with authManager = null - * 3 check ret is AUTH_RESPONSE_SYNCDELETE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, GetStateType_011, testing::ext::TestSize.Level0) -{ - std::shared_ptr authResponseState = std::make_shared(); - int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret, AUTH_RESPONSE_SYNCDELETE); -} - -/** - * @tc.name: AuthResponseSyncDeleteAcl::Enter_013 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAcl::Enter with authManager = null - * 3 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, Enter_013, testing::ext::TestSize.Level0) -{ - std::shared_ptr authManager = - std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); - std::shared_ptr authResponseState = std::make_shared(); - authResponseState->SetAuthManager(nullptr); - int32_t ret = authResponseState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} - -/** - * @tc.name: AuthResponseSyncDeleteAclNone::GetStateType_012 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAclNone::GetStateType with authManager = null - * 3 check ret is AUTH_RESPONSE_SYNCDELETE_DONE - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, GetStateType_012, testing::ext::TestSize.Level0) -{ - std::shared_ptr authResponseState = std::make_shared(); - int32_t ret = authResponseState->GetStateType(); - ASSERT_EQ(ret, AUTH_RESPONSE_SYNCDELETE_DONE); -} - -/** - * @tc.name: AuthResponseSyncDeleteAclNone::Enter_014 - * @tc.desc: 1 set authManager to null - * 2 call AuthResponseSyncDeleteAclNone::Enter with authManager = null - * 3 check ret is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(AuthResponseStateTest, Enter_014, testing::ext::TestSize.Level0) -{ - std::shared_ptr authManager = - std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); - std::shared_ptr authResponseState = std::make_shared(); - authResponseState->SetAuthManager(nullptr); - int32_t ret = authResponseState->Enter(); - ASSERT_EQ(ret, ERR_DM_FAILED); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 77340bc52..7b4808d50 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1982,21 +1982,6 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T DeviceManagerService::GetInstance().HandleDeviceStatusChange(devState, devInfo); EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } - -HWTEST_F(DeviceManagerServiceTest, OnUnbindSessionCloseed_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - DeviceManagerService::GetInstance().OnUnbindSessionCloseed(socket); - EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); -} - -HWTEST_F(DeviceManagerServiceTest, OnUnbindBytesReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "4152413541"; - DeviceManagerService::GetInstance().OnUnbindBytesReceived(socket, data.c_str(), data.size()); - EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index b40fa2128..47155fb11 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -981,244 +981,6 @@ HWTEST_F(DeviceManagerServiceImplTest, UnPublishDeviceDiscovery_002, testing::ex EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } -/** - * @tc.name: AuthenticateDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - int32_t authType = 1; - std::string deviceId = "deviceId"; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: AuthenticateDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 1; - std::string deviceId; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: AuthenticateDevice_003 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName; - int32_t authType = 1; - std::string deviceId; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: AuthenticateDevice_004 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, AuthenticateDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 1; - std::string deviceId = "deviceId"; - std::string extra; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string networkId = "networkId"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string networkId; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_003 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string networkId; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnAuthenticateDevice_004 - * @tc.desc: return SOFTBUS_IPC_ERR - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string networkId = "networkId"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); -} - -/** - * @tc.name: BindDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, BindDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 0; - std::string udidHash; - std::string bindParam; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->BindDevice(pkgName, authType, udidHash, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: BindDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, BindDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - int32_t authType = 0; - std::string udidHash = "udidHash"; - std::string bindParam; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->BindDevice(pkgName, authType, udidHash, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: BindDevice_003 - * @tc.desc: return DM_OK - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, BindDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 0; - std::string udidHash = "udidHash"; - std::string bindParam; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->BindDevice(pkgName, authType, udidHash, bindParam); - EXPECT_NE(ret, DM_OK); -} - -/** - * @tc.name: UnBindDevice_001 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string udidHash; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udidHash); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnBindDevice_002 - * @tc.desc: return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - std::string udidHash = "udidHash"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udidHash); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: UnBindDevice_003 - * @tc.desc: return DM_OK - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string udidHash = "udidHash"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udidHash); - EXPECT_NE(ret, DM_OK); -} - /** * @tc.name: GetUdidHashByNetWorkId_001 * @tc.desc: return ERR_DM_POINT_NULL @@ -1543,35 +1305,6 @@ HWTEST_F(DeviceManagerServiceImplTest, GetAppTrustDeviceIdList_003, testing::ext EXPECT_EQ(ret.empty(), true); } -/** - * @tc.name: OnUnbindSessionCloseed_001 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, OnUnbindSessionCloseed_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - deviceManagerServiceImpl_->OnUnbindSessionCloseed(socket); - EXPECT_NE(deviceManagerServiceImpl_->hiChainConnector_, nullptr); -} - -/** - * @tc.name: OnUnbindBytesReceived_001 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceImplTest, OnUnbindBytesReceived_001, testing::ext::TestSize.Level0) -{ - int32_t socket = 1; - std::string data = "15135135"; - if (deviceManagerServiceImpl_ == nullptr) { - deviceManagerServiceImpl_ = std::make_shared(); - } - deviceManagerServiceImpl_->OnUnbindBytesReceived(socket, data.c_str(), data.size()); - EXPECT_NE(deviceManagerServiceImpl_->hiChainConnector_, nullptr); -} - /** * @tc.name: LoadHardwareFwkService_001 * @tc.type: FUNC @@ -1585,18 +1318,6 @@ HWTEST_F(DeviceManagerServiceImplTest, LoadHardwareFwkService_001, testing::ext: EXPECT_NE(deviceManagerServiceImpl_->hiChainConnector_, nullptr); } -/** - * tc.name: AccountCommonEventCallback_001 - * tc.type: FUNC -*/ -HWTEST_F(DeviceManagerServiceImplTest, AccountCommonEventCallback_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 111111; - std::string commonEventType = "usual.event.USER_SWITCHED"; - deviceManagerServiceImpl_->AccountCommonEventCallback(userId, commonEventType); - EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); -} - /** * tc.name: ScreenCommonEventCallback_001 * tc.type: FUNC diff --git a/utils/include/crypto/dm_crypto.h b/utils/include/crypto/dm_crypto.h index baf165049..0c7f27c5d 100644 --- a/utils/include/crypto/dm_crypto.h +++ b/utils/include/crypto/dm_crypto.h @@ -30,6 +30,7 @@ public: static int32_t GetSecRandom(uint8_t *out, size_t outLen); static std::string GetSecSalt(); static std::string GetHashWithSalt(const std::string &text, const std::string &salt); + static int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index 950f96fd2..0dca4459c 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -39,7 +39,6 @@ constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNego constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* STATE_TIMER_PREFIX = "deviceManagerTimer:stateTimer_"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* SYNC_DELETE_TIMEOUT_TASK = "deviceManagerTimer:syncDelete_"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; using TimerCallback = std::function; diff --git a/utils/include/timer/lite/dm_timer.h b/utils/include/timer/lite/dm_timer.h index 25cd34ba7..3ba540a56 100644 --- a/utils/include/timer/lite/dm_timer.h +++ b/utils/include/timer/lite/dm_timer.h @@ -36,7 +36,6 @@ constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNego constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* STATE_TIMER_PREFIX = "deviceManagerTimer:stateTimer_"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* SYNC_DELETE_TIMEOUT_TASK = "deviceManagerTimer:syncDelete_"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; diff --git a/utils/src/crypto/dm_crypto.cpp b/utils/src/crypto/dm_crypto.cpp index 5db9fae62..7a7e51d79 100644 --- a/utils/src/crypto/dm_crypto.cpp +++ b/utils/src/crypto/dm_crypto.cpp @@ -36,6 +36,7 @@ constexpr int HEX_DIGIT_MAX_NUM = 16; constexpr int SHORT_DEVICE_ID_HASH_LENGTH = 16; constexpr int32_t SALT_LENGTH = 8; const std::string SALT_DEFAULT = "salt_defsalt_def"; +constexpr int SHORT_ACCOUNTID_ID_HASH_LENGTH = 6; uint32_t HexifyLen(uint32_t len) { @@ -202,5 +203,16 @@ std::string Crypto::GetHashWithSalt(const std::string &text, const std::string & return Crypto::Sha256(rawText); } +int32_t Crypto::GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) +{ + unsigned char hash[SHA256_DIGEST_LENGTH] = ""; + DmGenerateStrHash(accountId.data(), accountId.size(), hash, SHA256_DIGEST_LENGTH, 0); + if (ConvertBytesToHexString(reinterpret_cast(accountIdHash), SHORT_ACCOUNTID_ID_HASH_LENGTH + 1, + reinterpret_cast(hash), SHORT_ACCOUNTID_ID_HASH_LENGTH / HEX_TO_UINT8) != DM_OK) { + LOGE("ConvertBytesToHexString failed."); + return ERR_DM_FAILED; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 90cbd4acbdc536ca21bf0f52eaa18756f02cab79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 30 Aug 2024 20:23:21 +0800 Subject: [PATCH 125/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../authenticate_device_fuzzer.cpp | 5 +- .../UTTest_device_manager_impl_three.cpp | 69 ++++++++++++++++++- .../UTTest_device_manager_service_two.cpp | 58 ++++++++++++++++ 3 files changed, 130 insertions(+), 2 deletions(-) diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 329265466..8bed02a10 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -18,6 +18,7 @@ #include #include +#include "dm_constants.h" #include "device_manager.h" #include "device_manager_callback.h" #include "device_manager_impl.h" @@ -372,7 +373,9 @@ void AuthenticateDeviceFifthFuzzTest(const uint8_t* data, size_t size) DeviceManagerImpl::GetInstance().UnRegisterDiscoveryCallback(emptyStr); DeviceManagerImpl::GetInstance().StartAdvertising(emptyStr, discoverParam, nullptr); DeviceManagerImpl::GetInstance().StopAdvertising(emptyStr, discoverParam); - DeviceManagerImpl::GetInstance().SetDnPolicy(emptyStr, discoverParam); + discoverParam[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = str; + discoverParam[PARAM_KEY_POLICY_TIME_OUT] = str; + DeviceManagerImpl::GetInstance().SetDnPolicy(str, discoverParam); } } } diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index e96717fcb..cbdd95cfe 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1105,8 +1105,75 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy001, testing::ext::TestSize.Level0) std::shared_ptr callback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(packName, callback); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + bool bRet = false; + if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD) { + bRet = true; + } + ASSERT_EQ(bRet, true); DeviceManager::GetInstance().UnInitDeviceManager(packName); - ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy002, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy003, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy004, testing::ext::TestSize.Level0) +{ + std::string packName; + std::map policy; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy005, testing::ext::TestSize.Level0) +{ + std::string packName; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 20a725e98..4a776a9eb 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -284,6 +284,64 @@ HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_201, testing::ext DeviceManagerService::GetInstance().ScreenCommonEventCallback(commonEventType); EXPECT_NE(DeviceManagerService::GetInstance().accountCommonEventManager_, nullptr); } + +/** + * @tc.name: SetDnPolicy_201 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + bool bRet = false; + if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD) { + bRet = true; + } + ASSERT_EQ(bRet, true); +} + +/** + * @tc.name: SetDnPolicy_202 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_202, testing::ext::TestSize.Level0) +{ + std::string packName; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(bRet, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: SetDnPolicy_203 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_203, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(bRet, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: SetDnPolicy_204 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(bRet, ERR_DM_INPUT_PARA_INVALID); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From bbea2b71d663f614c3e43df6d4618351d23a5218 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Fri, 30 Aug 2024 20:23:22 +0800 Subject: [PATCH 126/520] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=8D=95=E7=AB=AF?= =?UTF-8?q?=E5=8F=AF=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../service/src/device_manager_service.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 470f5dea9..f335616e6 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1805,5 +1805,41 @@ void DeviceManagerService::SendServiceUnBindBroadCast(const std::vectorSendAclChangedBroadcast(broadCastMsg); } #endif + +void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) +{ + LOGI("HandleDeviceTrustedChange start msg %{public}s.", msg.c_str()); + if (msg.empty()) { + LOGE("Msg is empty."); + return; + } + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s, tokenId %{public}" PRId64"," + "peerUdid %{public}s, accountName %{public}s.", relationShipMsg.type, relationShipMsg.userId, + GetAnonyString(relationShipMsg.accountId).c_str(), relationShipMsg.tokenId, + GetAnonyString(relationShipMsg.peerUdid).c_str(), GetAnonyString(relationShipMsg.accountName).c_str()); + if (!IsDMServiceImplReady()) { + LOGE("Imp instance not init or init failed."); + return; + } + switch (relationShipMsg.type) { + case RelationShipChangeType::ACCOUNT_LOGOUT: + dmServiceImpl_->HandleAccountLogoutEvent(relationShipMsg.userId, relationShipMsg.accountId, + relationShipMsg.peerUdid); + break; + case RelationShipChangeType::DEVICE_UNBIND: + dmServiceImpl_->HandleDevUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid); + break; + case RelationShipChangeType::APP_UNBIND: + dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, + relationShipMsg.tokenId); + break; + default: + LOGI("Dm have not this event type."); + break; + } + return; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 50db833089a844286badfefa2b8806ecd4725451 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 30 Aug 2024 20:30:07 +0800 Subject: [PATCH 127/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 8bed02a10..329265466 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -18,7 +18,6 @@ #include #include -#include "dm_constants.h" #include "device_manager.h" #include "device_manager_callback.h" #include "device_manager_impl.h" @@ -373,9 +372,7 @@ void AuthenticateDeviceFifthFuzzTest(const uint8_t* data, size_t size) DeviceManagerImpl::GetInstance().UnRegisterDiscoveryCallback(emptyStr); DeviceManagerImpl::GetInstance().StartAdvertising(emptyStr, discoverParam, nullptr); DeviceManagerImpl::GetInstance().StopAdvertising(emptyStr, discoverParam); - discoverParam[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = str; - discoverParam[PARAM_KEY_POLICY_TIME_OUT] = str; - DeviceManagerImpl::GetInstance().SetDnPolicy(str, discoverParam); + DeviceManagerImpl::GetInstance().SetDnPolicy(emptyStr, discoverParam); } } } -- Gitee From a651d4ee813ba4631df68d5130bd5ceff9819e21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 30 Aug 2024 20:46:13 +0800 Subject: [PATCH 128/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_service_two.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 4a776a9eb..f3e8d16ec 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -314,7 +314,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_202, testing::ext::TestSize.Level policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(bRet, ERR_DM_INPUT_PARA_INVALID); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** @@ -327,7 +327,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_203, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(bRet, ERR_DM_INPUT_PARA_INVALID); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** @@ -340,7 +340,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(bRet, ERR_DM_INPUT_PARA_INVALID); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } } // namespace } // namespace DistributedHardware -- Gitee From ccc26a07e86a9dfcf27afe431e588378c2d4f118 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Fri, 30 Aug 2024 23:21:35 +0800 Subject: [PATCH 129/520] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=8D=95=E7=AB=AF?= =?UTF-8?q?=E5=8F=AF=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../include/deviceprofile_connector.h | 2 +- .../src/deviceprofile_connector.cpp | 13 +++++---- .../include/notify/device_manager_notify.h | 1 - .../src/notify/device_manager_notify.cpp | 5 ++-- .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 4 +-- .../src/device_manager_service_impl.cpp | 6 ++-- .../src/device_manager_service_impl_lite.cpp | 2 +- .../include/device_manager_service_listener.h | 2 +- .../include/idevice_manager_service_impl.h | 2 +- .../relationship_sync_mgr.h | 9 ------ .../service/src/device_manager_service.cpp | 11 ++++++-- .../src/device_manager_service_listener.cpp | 2 +- .../relationship_sync_mgr.cpp | 28 ++----------------- .../service/src/softbus/softbus_listener.cpp | 6 ++-- ...uthenticate_device_service_impl_fuzzer.cpp | 2 +- .../device_profile_connector_fuzzer.cpp | 2 +- .../softbus_connector_state_fuzzer.cpp | 1 + test/unittest/BUILD.gn | 2 ++ test/unittest/UTTest_dm_pin_holder.h | 6 ++++ utils/include/crypto/dm_crypto.h | 2 +- 22 files changed, 47 insertions(+), 65 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 63ad48e16..cf3c8e51f 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -132,7 +132,7 @@ public: int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid); int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); - std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId, + std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid); private: diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 7f2f99aff..141d99088 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -454,7 +454,7 @@ void DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localU const std::string &remoteUdid) { LOGI("localUdid %{public}s, userId %{public}d, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), userId, - GetAnonyString(remoteUdid).c_str()); + GetAnonyString(remoteUdid).c_str()); std::vector profiles = GetAccessControlProfileByUserId(userId); for (const auto &item : profiles) { if (item.GetTrustDeviceId() == remoteUdid) { @@ -469,7 +469,7 @@ void DeviceProfileConnector::DeleteAclForUserRemoved(int32_t userId) std::vector profiles = GetAccessControlProfileByUserId(userId); for (const auto &item : profiles) { if (item.GetAccesser().GetAccesserUserId() == userId || item.GetAccessee().GetAccesseeUserId() == userId) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); } } } @@ -870,11 +870,14 @@ std::map DeviceProfileConnector::GetDeviceIdAndBindType(in item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Account logout localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); - } else if (item.GetAccessee().GetAccesseeUserId() == userId && + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == userId && item.GetAccessee().GetAccesseeAccountId() == accountId && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Account logout localUdid %{public}s is sink.", GetAnonyString(localUdid).c_str()); UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + continue; } } return deviceIdMap; @@ -942,8 +945,8 @@ int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const return bindType; } -std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId, - const std::string &localUdid) +std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}" PRId64", localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); 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 995871b0e..69672229b 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 @@ -68,7 +68,6 @@ public: void RegisterPinHolderCallback(const std::string &pkgName, std::shared_ptr callback); void RegDevTrustChangeCallback(const std::string &pkgName, std::shared_ptr callback); - public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); static void DeviceInfoOffline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); 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 1229abfbf..288c64593 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 @@ -33,8 +33,6 @@ constexpr const char* DEVICE_TRUST_CHANGE = "deviceTrustChange"; #else constexpr const char* DEVICE_STATE_INIT_QUEUE = "deviceStateInitQueue"; #endif -const int32_t MIN_AUTHFORM = -1; -const int32_t MAX_AUTHFORM = 2; void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback) @@ -1095,7 +1093,8 @@ void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const { LOGI("PkgName %{public}s, deviceId %{public}s, authForm %{public}d", pkgName.c_str(), GetAnonyString(deviceId).c_str(), authForm); - if (pkgName.empty() || authForm < MIN_AUTHFORM || authForm > MAX_AUTHFORM) { + if (pkgName.empty() || authForm < static_Cast(INVALID_TYPE) || + authForm > static_cast(ACROSS_ACCOUNT)) { LOGE("Invalid parameter, pkgName is empty."); return; } diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 79dcc1733..fede64683 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -139,7 +139,7 @@ private: void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid); void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); - void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId); + void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleUserRemoved(int32_t preUserId); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 7bef9fd01..daabe948f 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -131,7 +131,7 @@ public: void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid); void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); - void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId); + void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 75f026ea9..b865abfbb 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -73,7 +73,7 @@ const int32_t USLEEP_TIME_MS = 500000; // 500ms const int32_t AUTH_DEVICE_TIMEOUT = 10; const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; -const int32_t STRTOLL_BASE = 10; +const int32_t STRTOLL_BASE_10 = 10; // clone task timeout map const std::map TASK_TIME_OUT_MAP = { @@ -204,7 +204,7 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); } if (IsString(jsonObject, TAG_TOKENID)) { - authRequestContext_->tokenId = StringToInt64(jsonObject[TAG_TOKENID].get(), STRTOLL_BASE); + authRequestContext_->tokenId = StringToInt64(jsonObject[TAG_TOKENID].get(), STRTOLL_BASE_10); } if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { authRequestContext_->bindLevel = jsonObject[TAG_BIND_LEVEL].get(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 2b462bb06..02f5af337 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -741,9 +741,9 @@ DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) DmAuthForm authForm = DmAuthForm::INVALID_TYPE; if (bindType == DM_IDENTICAL_ACCOUNT) { authForm = IDENTICAL_ACCOUNT; - } else if(bindType == DM_POINT_TO_POINT) { + } else if (bindType == DM_POINT_TO_POINT) { authForm = PEER_TO_PEER; - } else if(bindType == DM_ACROSS_ACCOUNT) { + } else if (bindType == DM_ACROSS_ACCOUNT) { authForm = ACROSS_ACCOUNT; } else { LOGE("Invalied bindType."); @@ -766,7 +766,7 @@ void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int64_t tokenId) + int32_t tokenId) { char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 4d2ad6989..b067a0ae8 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -483,7 +483,7 @@ void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int64_t tokenId) + int32_t tokenId) { (void)remoteUserId; (void)remoteUdid; diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 279d5a5aa..403d25a5e 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -71,7 +71,7 @@ public: void OnDestroyResult(const std::string &pkgName, int32_t result) override; void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content) override; - void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override; + void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 87c1e2b19..6bf3c2a32 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -266,7 +266,7 @@ public: virtual void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid) = 0; virtual void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) = 0; - virtual void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int64_t tokenId) = 0; + virtual void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId) = 0; virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index 4de8c129f..b471daaf0 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -47,15 +47,6 @@ struct RelationShipChangeMsg { bool IsValid() const; bool IsChangeTypeValid(); bool IsChangeTypeValid(uint32_t type); - /** - * @brief parse change type from json msg - * - * @param msg json msg - * @param len msg length - * @return RelationShipChangeType parsed msg, if invalid, return TYPE_MAX - */ - RelationShipChangeType ParseChangeType(const char *msg, const uint32_t len); - void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f335616e6..a9682defa 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1761,10 +1761,15 @@ void DeviceManagerService::SendUnBindBroadCast(const std::vector &p LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); if (bindLevel == DEVICE) { SendDeviceUnBindBroadCast(peerUdids, userId); - } else if (bindLevel == APP) { + return; + } + if (bindLevel == APP) { SendAppUnBindBroadCast(peerUdids, userId, tokenId); - } else if (bindLevel == SERVICE) { + return; + } + if (bindLevel == SERVICE) { SendServiceUnBindBroadCast(peerUdids, userId, tokenId); + return; } } @@ -1833,7 +1838,7 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) break; case RelationShipChangeType::APP_UNBIND: dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, - relationShipMsg.tokenId); + static_cast(relationShipMsg.tokenId)); break; default: LOGI("Dm have not this event type."); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 357c450c3..04613a802 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -480,7 +480,7 @@ int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoy(const std::string &p void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) { - LOGI("DeviceId %{public}s, authForm %{public}d.", GetAnonyString(deviceId).c_str(), authForm); + LOGI("DeviceId %{public}s, authForm %{public}d.", GetAnonyString(deviceId).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index e6a3b0f2a..a836dbd33 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -155,30 +155,6 @@ bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) (type == (uint32_t)RelationShipChangeType::APP_UNBIND); } -RelationShipChangeType RelationShipChangeMsg::ParseChangeType(const char *msg, const uint32_t len) -{ - if (msg == NULL || sizeof(msg) != len) { - LOGE("msg invalid"); - return RelationShipChangeType::TYPE_MAX; - } - - cJSON *msgObj = cJSON_Parse(msg); - if (msgObj == NULL) { - LOGE("parse msg failed"); - return RelationShipChangeType::TYPE_MAX; - } - - cJSON *typeJson = cJSON_GetObjectItem(msgObj, MSG_TYPE); - if (typeJson == NULL || !cJSON_IsNumber(typeJson) || !IsChangeTypeValid(typeJson->valueint)) { - LOGE("parse type failed."); - cJSON_Delete(msgObj); - return RelationShipChangeType::TYPE_MAX; - } - RelationShipChangeType type = (RelationShipChangeType)typeJson->valueint; - cJSON_Delete(msgObj); - return type; -} - void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const { msg = new uint8_t[ACCOUNT_LOGOUT_PAYLOAD_LEN](); @@ -271,7 +247,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { LOGE("App unbind payloadJson is null."); - return false; + return false; } int32_t arraySize = cJSON_GetArraySize(payloadJson); if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { @@ -319,7 +295,7 @@ cJSON *RelationShipChangeMsg::ToArrayJson(cJSON *msg) const for (uint32_t index = 0; index < len; index++) { cJSON_AddItemToArray(arrayObj, cJSON_CreateNumber(payload[index])); } - if (payload) { + if (payload != nullptr) { delete[] payload; } return arrayObj; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 91b2e51bf..a36a2851f 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -974,9 +974,9 @@ std::string SoftbusListener::GetHostPkgName() void SoftbusListener::SendAclChangedBroadcast(const std::string &msg) { LOGI("SendAclChangedBroadcast"); - // if (SyncTrustedRelationShip(DM_PKG_NAME, msg.c_str(), msg.length()) != DM_OK) { - // LOGE("SyncTrustedRelationShip failed."); - // } + if (SyncTrustedRelationShip(DM_PKG_NAME, msg.c_str(), msg.length()) != DM_OK) { + LOGE("SyncTrustedRelationShip failed."); + } } IRefreshCallback &SoftbusListener::GetSoftbusRefreshCb() diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp index 59eb99cad..32b0d79f9 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/authenticate_device_service_impl_fuzzer.cpp @@ -109,7 +109,7 @@ void AddPermission() void AuthenticateDeviceServiceImplFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size == 0)) { + if ((data == nullptr) || (size == 0) || (size < sizeof(int32_t))) { return; } diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index 9cc167b05..1d9b2bb50 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -24,7 +24,7 @@ namespace OHOS { namespace DistributedHardware { void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(DmAccesser))) { + if ((data == nullptr) || (size < sizeof(DmAccesser)) || (size < sizeof(int32_t))) { return; } diff --git a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp index 1365cb4fb..660e74bce 100644 --- a/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorstate_fuzzer/softbus_connector_state_fuzzer.cpp @@ -32,6 +32,7 @@ public: void OnDeviceOnline(std::string deviceId, int32_t authForm) override {} void OnDeviceOffline(std::string deviceId) override {} + void DeleteOffLineTimer(std::string udidHash) override {} }; void SoftBusConnectorStateFuzzTest(const uint8_t* data, size_t size) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 1dbbc7396..808a25ed0 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1206,6 +1206,7 @@ ohos_unittest("UTTest_dm_publish_manager") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -1307,6 +1308,7 @@ ohos_static_library("device_manager_test_common") { "access_token:libtoken_setproc", "bundle_framework:appexecfwk_base", "c_utils:utils", + "cJSON:cjson", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", "device_auth:deviceauth_sdk", diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 12ca2716e..6ac958aa4 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -179,6 +179,12 @@ public: (void)result; (void)content; } + + void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override + { + (void)deviceId; + (void)authForm; + } }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/crypto/dm_crypto.h b/utils/include/crypto/dm_crypto.h index 0c7f27c5d..93c9ff3f8 100644 --- a/utils/include/crypto/dm_crypto.h +++ b/utils/include/crypto/dm_crypto.h @@ -30,7 +30,7 @@ public: static int32_t GetSecRandom(uint8_t *out, size_t outLen); static std::string GetSecSalt(); static std::string GetHashWithSalt(const std::string &text, const std::string &salt); - static int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash); + static int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash); }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 7fb9bc8a8620f4b9fedb81d62f059d558a247887 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 31 Aug 2024 00:35:55 +0800 Subject: [PATCH 130/520] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=8D=95=E7=AB=AF?= =?UTF-8?q?=E5=8F=AF=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../inner_kits/native_cpp/src/notify/device_manager_notify.cpp | 2 +- test/unittest/BUILD.gn | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 288c64593..fac7395f7 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 @@ -1093,7 +1093,7 @@ void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const { LOGI("PkgName %{public}s, deviceId %{public}s, authForm %{public}d", pkgName.c_str(), GetAnonyString(deviceId).c_str(), authForm); - if (pkgName.empty() || authForm < static_Cast(INVALID_TYPE) || + if (pkgName.empty() || authForm < static_cast(INVALID_TYPE) || authForm > static_cast(ACROSS_ACCOUNT)) { LOGE("Invalid parameter, pkgName is empty."); return; diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 808a25ed0..7712f5e7d 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1307,8 +1307,8 @@ ohos_static_library("device_manager_test_common") { "access_token:libnativetoken", "access_token:libtoken_setproc", "bundle_framework:appexecfwk_base", - "c_utils:utils", "cJSON:cjson", + "c_utils:utils", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", "device_auth:deviceauth_sdk", -- Gitee From 4e71722aeb71fe5acc54b19fdc811d24dd55855f Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 31 Aug 2024 01:30:30 +0800 Subject: [PATCH 131/520] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=8D=95=E7=AB=AF?= =?UTF-8?q?=E5=8F=AF=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- commondependency/src/deviceprofile_connector.cpp | 2 +- services/service/src/softbus/softbus_listener.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 141d99088..b991776e5 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -948,7 +948,7 @@ int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) { - LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}" PRId64", localUdid %{public}s.", + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); std::vector profiles = GetAccessControlProfile(); std::string pkgName = ""; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a36a2851f..b20ed4382 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -323,14 +323,14 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); if (ret != DM_OK) { LOGE("deviceNotTrust setname failed."); - + } deviceNotTrust.detach(); } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { std::thread deviceTrustedChange([=]() { DeviceTrustedChange(softbusMsg); }); - int32_t ret = pthread_setname_np(deviceNotTrust.native_handle(), DEVICE_NOT_TRUST); + int32_t ret = pthread_setname_np(deviceTrustedChange.native_handle(), DEVICE_NOT_TRUST); if (ret != DM_OK) { LOGE("deviceTrustedChange setname failed."); - + } deviceTrustedChange.detach(); } else { LOGE("Invalied trust change type."); -- Gitee From 07a4aa8ba0c3a577d6583e81cdcb668a2443feca Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 31 Aug 2024 11:53:02 +0800 Subject: [PATCH 132/520] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=8D=95=E7=AB=AF?= =?UTF-8?q?=E5=8F=AF=E4=BF=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../src/multiple_user_connector.cpp | 16 ++++------ .../dependency/softbus/softbus_connector.cpp | 2 +- .../service/src/device_manager_service.cpp | 8 ++--- .../dm_account_common_event.cpp | 12 ++++---- .../UTTest_dm_publish_manager.cpp | 2 +- test/unittest/UTTest_device_manager_impl.cpp | 4 +-- .../UTTest_device_manager_impl_two.cpp | 30 +++++++++++-------- .../UTTest_device_manager_service.cpp | 2 +- 8 files changed, 39 insertions(+), 37 deletions(-) diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 7302e7d96..c284da7b8 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -40,8 +40,7 @@ int32_t MultipleUserConnector::GetCurrentAccountUserID(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return 0; -#else -#ifdef OS_ACCOUNT_PART_EXISTS +#elif OS_ACCOUNT_PART_EXISTS std::vector ids; ErrCode ret = OsAccountManager::QueryActiveOsAccountIds(ids); if (ret != 0 || ids.empty()) { @@ -51,7 +50,6 @@ int32_t MultipleUserConnector::GetCurrentAccountUserID(void) return ids[0]; #else // OS_ACCOUNT_PART_EXISTS return DEFAULT_OS_ACCOUNT_ID; -#endif // OS_ACCOUNT_PART_EXISTS #endif } @@ -59,8 +57,7 @@ std::string MultipleUserConnector::GetOhosAccountId(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return ""; -#else -#ifdef OS_ACCOUNT_PART_EXISTS +#elif OS_ACCOUNT_PART_EXISTS OhosAccountInfo accountInfo; ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfo(accountInfo); if (ret != 0 || accountInfo.uid_ == "") { @@ -68,9 +65,8 @@ std::string MultipleUserConnector::GetOhosAccountId(void) return ""; } return accountInfo.uid_; -#else // OS_ACCOUNT_PART_EXISTS +#else return ""; -#endif // OS_ACCOUNT_PART_EXISTS #endif } @@ -78,8 +74,7 @@ std::string MultipleUserConnector::GetOhosAccountName(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return ""; -#else -#ifdef OS_ACCOUNT_PART_EXISTS +#elif OS_ACCOUNT_PART_EXISTS auto accountInfo = OhosAccountKits::GetInstance().QueryOhosAccountInfo(); if (!accountInfo.first) { LOGE("QueryOhosAccountInfo failed."); @@ -90,9 +85,8 @@ std::string MultipleUserConnector::GetOhosAccountName(void) return ""; } return accountInfo.second.name_; -#else // OS_ACCOUNT_PART_EXISTS +#else return ""; -#endif // OS_ACCOUNT_PART_EXISTS #endif } diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 8bdbf7e2e..89dae5299 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -702,7 +702,7 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) NodeBasicInfo *nodeInfo = nullptr; if (GetAllNodeDeviceInfo(DM_PKG_NAME, &nodeInfo, &deviceCount) != DM_OK) { LOGE("[SOFTBUS]GetAllNodeDeviceInfo failed."); - return ERR_DM_FAILED; + return false; } for (int32_t i = 0; i < deviceCount; ++i) { NodeBasicInfo *nodeBasicInfo = nodeInfo + i; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index a9682defa..e9ec1b00a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1508,11 +1508,11 @@ bool DeviceManagerService::CheckAccessControl(const DmAccessCaller &caller, cons { if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller: %{public}s does not have permission to call CheckAccessControl.", caller.pkgName.c_str()); - return ERR_DM_NO_PERMISSION; + return false; } if (!IsDMServiceImplReady()) { LOGE("CheckAccessControl failed, instance not init or init failed."); - return ERR_DM_NOT_INIT; + return false; } std::string srcUdid = ""; SoftbusListener::GetUdidByNetworkId(caller.networkId.c_str(), srcUdid); @@ -1525,11 +1525,11 @@ bool DeviceManagerService::CheckIsSameAccount(const DmAccessCaller &caller, cons { if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller: %{public}s does not have permission to call CheckIsSameAccount.", caller.pkgName.c_str()); - return ERR_DM_NO_PERMISSION; + return false; } if (!IsDMServiceImplReady()) { LOGE("CheckIsSameAccount failed, instance not init or init failed."); - return ERR_DM_NOT_INIT; + return false; } std::string srcUdid = ""; SoftbusListener::GetUdidByNetworkId(caller.networkId.c_str(), srcUdid); diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 1ad84dfca..cd885c591 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -136,17 +136,19 @@ void DmAccountEventSubscriber::OnReceiveEvent(const CommonEventData &data) std::string receiveEvent = data.GetWant().GetAction(); LOGI("Received account event: %{public}s", receiveEvent.c_str()); int32_t userId = data.GetCode(); + bool accountValiedEvent = false; if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED || receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { userId = data.GetCode(); - } else if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT || + accountValiedEvent = true; + } + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT || receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { userId = data.GetWant().GetIntParam("userId", 0); - } else { - return; + accountValiedEvent = true; } - if (userId <= 0) { - LOGE("userId is less zero"); + if (userId <= 0 || !accountValiedEvent) { + LOGE("Invalied account type event."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/test/commonunittest/UTTest_dm_publish_manager.cpp b/test/commonunittest/UTTest_dm_publish_manager.cpp index fb1ba8042..1eef1fff1 100644 --- a/test/commonunittest/UTTest_dm_publish_manager.cpp +++ b/test/commonunittest/UTTest_dm_publish_manager.cpp @@ -111,7 +111,7 @@ HWTEST_F(DmPublishManagerTest, PublishDeviceDiscovery_002, testing::ext::TestSiz publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); pkgName = "com.ohos.helloworld.new"; int32_t ret = publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); - ASSERT_EQ(ret, SOFTBUS_IPC_ERR); + ASSERT_EQ(ret, SOFTBUS_INVALID_PARAM); publishMgr_->UnPublishDeviceDiscovery(pkgName, publishInfo.publishId); } diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index 80904a61e..243184706 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -636,7 +636,7 @@ HWTEST_F(DeviceManagerImplTest, BindDevice_103, testing::ext::TestSize.Level0) std::string packName = "com.ohos.test"; int32_t bindType = 0; std::string deviceId = "deviceId"; - std::string bindParam; + std::string bindParam = "{\"status\":1}"; std::shared_ptr callback = nullptr; int32_t ret = DeviceManager::GetInstance().BindDevice(packName, bindType, deviceId, bindParam, callback); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); @@ -1057,7 +1057,7 @@ HWTEST_F(DeviceManagerImplTest, UnAuthenticateDevice_101, testing::ext::TestSize // 3. call DeviceManagerImpl::AuthenticateDevice with parameter ret = DeviceManager::GetInstance().UnAuthenticateDevice(packName, deviceInfo); // 4. check ret is ERR_DM_FAILED - ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); DeviceManager::GetInstance().UnInitDeviceManager(packName); } diff --git a/test/unittest/UTTest_device_manager_impl_two.cpp b/test/unittest/UTTest_device_manager_impl_two.cpp index 171cc1ee6..7cd7c5d14 100644 --- a/test/unittest/UTTest_device_manager_impl_two.cpp +++ b/test/unittest/UTTest_device_manager_impl_two.cpp @@ -526,7 +526,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_002, testing::ext::TestSize.L // set dmDeviceInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_FAILED @@ -565,7 +565,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_003, testing::ext::TestSize.L // set dmAppImageInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return DM_OK @@ -604,7 +604,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_004, testing::ext::TestSize.L // set dmAppImageInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_INIT_FAILED @@ -643,7 +643,7 @@ HWTEST_F(DeviceManagerImplTest, AuthenticateDevice_005, testing::ext::TestSize.L // set dmAppImageInfo null DmDeviceInfo dmDeviceInfo; // set extra null - std::string extra = ""; + std::string extra = "{\"status\":1}"; // set callback null std::shared_ptr callback = std::make_shared(); // 2. MOCK IpcClientProxy SendRequest return ERR_DM_POINT_NULL @@ -1037,14 +1037,17 @@ HWTEST_F(DeviceManagerImplTest, GetUdidByNetworkId_003, testing::ext::TestSize.L std::string netWorkId = "111"; std::string udid = "222"; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::GetUdidByNetworkId with parameter - ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); + int32_t ret = DeviceManager::GetInstance().GetUdidByNetworkId(packName, netWorkId, udid); // 4. check ret is DM_OK ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); // DeviceManagerImpl::GetInstance().ipcClientProxy_ = nullptr; - DeviceManager::GetInstance().UnInitDeviceManager(packName); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** @@ -1182,13 +1185,16 @@ HWTEST_F(DeviceManagerImplTest, GetUuidByNetworkId_003, testing::ext::TestSize.L std::string netWorkId = "111"; std::string uuid = "222"; // 2. MOCK IpcClientProxy SendRequest return DM_OK - std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, callback); + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_FAILED)); // 3. call DeviceManagerImpl::GetUuidByNetworkId with parameter - ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); + int32_t ret = DeviceManager::GetInstance().GetUuidByNetworkId(packName, netWorkId, uuid); // 4. check ret is DM_OK ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); - DeviceManager::GetInstance().UnInitDeviceManager(packName); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } /** diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 7b4808d50..89bb32142 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -612,7 +612,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_004, testing::ext::TestS std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** -- Gitee From 44174e886464c2586c27ed1f976df88797a5b848 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 31 Aug 2024 15:39:34 +0800 Subject: [PATCH 133/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=B6=85=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/include/authentication/dm_auth_manager.h | 3 ++- services/implementation/src/authentication/dm_auth_manager.cpp | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 464ded785..7aec37ecf 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -92,6 +92,7 @@ enum DmAuthType : int32_t { AUTH_TYPE_NFC, AUTH_TYPE_NO_INTER_ACTION, AUTH_TYPE_IMPORT_AUTH_CODE, + AUTH_TYPE_UNKNOW, }; typedef struct DmAuthRequestContext { @@ -586,7 +587,7 @@ private: bool isAuthenticateDevice_ = false; int32_t authForm_ = DmAuthForm::ACROSS_ACCOUNT; std::string remoteVersion_ = ""; - std::atomic authType_; + std::atomic authType_ = AUTH_TYPE_UNKNOW; std::string remoteUdidHash_ = ""; }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 0c286ada5..2c9f68938 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1203,6 +1203,7 @@ void DmAuthManager::SrcAuthenticateFinish() void DmAuthManager::AuthenticateFinish() { + authType_ = AUTH_TYPE_UNKNOW; std::lock_guard autoLock(g_authFinishLock); if (authResponseContext_ == nullptr || authUiStateMgr_ == nullptr) { LOGE("failed to AuthenticateFinish because authResponseContext_ or authUiStateMgr is nullptr"); -- Gitee From 1336a3f69fe69458b31eb2c4c10c5225c1a156e5 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Sat, 31 Aug 2024 16:00:51 +0800 Subject: [PATCH 134/520] =?UTF-8?q?=E4=B8=8A=E6=BB=91=E4=B8=8D=E9=94=80?= =?UTF-8?q?=E6=AF=81=E5=BC=B9=E6=A1=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../implementation/src/ability/standard/dm_dialog_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 1953e5de9..9ff2a9e0d 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -201,6 +201,7 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param["deviceType"] = DmDialogManager::GetDeviceType(); param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); + param["disableUpGesture"] = 1; std::string paramStr = param.dump(); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); -- Gitee From 43d153c04bcd5ac5f401af258d8ae98985d6d720 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Fri, 30 Aug 2024 10:52:06 +0800 Subject: [PATCH 135/520] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E7=9A=84?= =?UTF-8?q?=E6=97=B6=E5=80=99=E4=B8=BB=E5=8A=A8=E6=8B=89=E8=B5=B7=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- interfaces/inner_kits/native_cpp/BUILD.gn | 1 + .../include/ipc/standard/dm_service_load.h | 41 ++++++++++ .../native_cpp/src/device_manager_impl.cpp | 3 +- .../src/ipc/standard/dm_service_load.cpp | 74 +++++++++++++++++++ .../src/ipc/standard/ipc_client_manager.cpp | 2 + 5 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 interfaces/inner_kits/native_cpp/include/ipc/standard/dm_service_load.h create mode 100644 interfaces/inner_kits/native_cpp/src/ipc/standard/dm_service_load.cpp diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index d2ed0b1f4..d3ebc8029 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -156,6 +156,7 @@ if (defined(ohos_lite)) { "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", + "src/ipc/standard/dm_service_load.cpp", "src/ipc/standard/ipc_client_manager.cpp", "src/ipc/standard/ipc_client_server_proxy.cpp", "src/ipc/standard/ipc_client_stub.cpp", diff --git a/interfaces/inner_kits/native_cpp/include/ipc/standard/dm_service_load.h b/interfaces/inner_kits/native_cpp/include/ipc/standard/dm_service_load.h new file mode 100644 index 000000000..beb819b5f --- /dev/null +++ b/interfaces/inner_kits/native_cpp/include/ipc/standard/dm_service_load.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SA_LOAD_H +#define OHOS_DM_SA_LOAD_H + +#include "dm_single_instance.h" +#include "iremote_object.h" +#include "system_ability_load_callback_stub.h" + +namespace OHOS { +namespace DistributedHardware { +class DMLoadCallback : public SystemAbilityLoadCallbackStub { +public: + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr &remoteObject) override; + void OnLoadSystemAbilityFail(int32_t systemAbilityId) override; +}; + +class DmServiceLoad { + DM_DECLARE_SINGLE_INSTANCE(DmServiceLoad); +public: + int32_t LoadDMService(void); + void SetLoadFinish(void); +private: + std::atomic isDMServiceLoading_ = false; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SA_LOAD_H diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 5ab6d2fa6..5760bdd79 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -64,7 +64,6 @@ #endif namespace OHOS { namespace DistributedHardware { -const int32_t SLEEP_TIME_MS = 50000; // 50ms constexpr const char* DM_INIT_DEVICE_MANAGER_SUCCESS = "DM_INIT_DEVICE_MANAGER_SUCCESS"; constexpr const char* DM_INIT_DEVICE_MANAGER_FAILED = "DM_INIT_DEVICE_MANAGER_FAILED"; @@ -129,7 +128,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh if (ret == DM_OK) { break; } - usleep(SLEEP_TIME_MS); + usleep(USLEEP_TIME_MS); retryNum++; if (retryNum == SERVICE_INIT_TRY_MAX_NUM) { LOGE("InitDeviceManager error, wait for device manager service starting timeout."); diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/dm_service_load.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/dm_service_load.cpp new file mode 100644 index 000000000..0e447d93f --- /dev/null +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/dm_service_load.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_service_load.h" + +#include "dm_constants.h" +#include "dm_log.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DmServiceLoad); + +int32_t DmServiceLoad::LoadDMService(void) +{ + LOGI("LoadDMService start"); + if (isDMServiceLoading_) { + LOGI("DM service is loading."); + return DM_OK; + } + isDMServiceLoading_ = true; + sptr samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + isDMServiceLoading_ = false; + LOGE("failed to get system ability mgr."); + return ERR_DM_POINT_NULL; + } + sptr dmLoadCallback_(new DMLoadCallback()); + int32_t ret = samgr->LoadSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, dmLoadCallback_); + if (ret != DM_OK) { + isDMServiceLoading_ = false; + LOGE("Failed to Load DM service, ret code:%{public}d", ret); + return ret; + } + return DM_OK; +} + +void DmServiceLoad::SetLoadFinish(void) +{ + isDMServiceLoading_ = false; +} + +void DMLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, + const sptr &remoteObject) +{ + LOGI("Load DM service success remoteObject result:%{public}s", (remoteObject != nullptr) ? "true" : "false"); + DmServiceLoad::GetInstance().SetLoadFinish(); + if (remoteObject == nullptr) { + LOGE("remoteObject is nullptr"); + return; + } +} + +void DMLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) +{ + LOGE("Load DM service failed."); + DmServiceLoad::GetInstance().SetLoadFinish(); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 54adce21d..fac75fe60 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -20,6 +20,7 @@ #include "device_manager_impl.h" #include "dm_constants.h" #include "dm_log.h" +#include "dm_service_load.h" #include "ipc_client_server_proxy.h" #include "ipc_client_stub.h" #include "ipc_register_listener_req.h" @@ -54,6 +55,7 @@ int32_t IpcClientManager::ClientInit() auto object = samgr->CheckSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); if (object == nullptr) { LOGE("Get DeviceManager SystemAbility Failed"); + DmServiceLoad::GetInstance().LoadDMService(); return ERR_DM_INIT_FAILED; } -- Gitee From e2da1250644d28fdcfc2c2daa18123e4445078a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 31 Aug 2024 17:53:54 +0800 Subject: [PATCH 136/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../service/src/device_manager_service.cpp | 15 +++++++-- .../UTTest_device_manager_impl_three.cpp | 32 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index bacadbfc5..2c068e126 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1661,12 +1661,23 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond).c_str()); - int32_t timeOut = std::stoi((timeOutIter->second).c_str()); + std::string policyStrategyStr = policyStrategyIter->second; + if (!isdigit(policyStrategyStr[0])) { + LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is not digit."); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string timeOutStr = timeOutIter->second; + if (!isdigit(timeOutStr[0])) { + LOGE("Invalid parameter, DM_POLICY_TIMEOUT is not digit."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t policyStrategy = std::stoi(policyStrategyStr); + int32_t timeOut = std::stoi(timeOutStr); if (!IsDMServiceAdapterLoad()) { LOGE("SetDnPolicy failed, instance not init or init failed."); return ERR_DM_UNSUPPORTED_METHOD; } + LOGD("strategy: %{public}d, timeOut: %{public}d", policyStrategy, timeOut); return dmServiceImplExt_->SetDnPolicy(policyStrategy, timeOut); } diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index cbdd95cfe..7920894b8 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1175,6 +1175,38 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy007, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100aggg"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; +} + +HWTEST_F(DeviceManagerImplTest, SetDnPolicy008, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10aaa"; + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 0ca757de4483592489871401c9d99294408e3f51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 31 Aug 2024 18:53:35 +0800 Subject: [PATCH 137/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 9c4829e0c..3c20297ca 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1728,23 +1728,21 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond; - if (!isdigit(policyStrategyStr[0])) { + if (!IsNumberString(policyStrategyIter->second)) { LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is not digit."); return ERR_DM_INPUT_PARA_INVALID; } - std::string timeOutStr = timeOutIter->second; - if (!isdigit(timeOutStr[0])) { + if (!IsNumberString(timeOutIter->second)) { LOGE("Invalid parameter, DM_POLICY_TIMEOUT is not digit."); return ERR_DM_INPUT_PARA_INVALID; } - int32_t policyStrategy = std::stoi(policyStrategyStr); - int32_t timeOut = std::stoi(timeOutStr); + int32_t policyStrategy = std::stoi(policyStrategyIter->second); + int32_t timeOut = std::stoi(timeOutIter->second); + LOGD("strategy: %{public}d, timeOut: %{public}d", policyStrategy, timeOut); if (!IsDMServiceAdapterLoad()) { LOGE("SetDnPolicy failed, instance not init or init failed."); return ERR_DM_UNSUPPORTED_METHOD; } - LOGD("strategy: %{public}d, timeOut: %{public}d", policyStrategy, timeOut); return dmServiceImplExt_->SetDnPolicy(policyStrategy, timeOut); } -- Gitee From 85700248ce73805542b60374f80222a413cdccde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 31 Aug 2024 19:20:33 +0800 Subject: [PATCH 138/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9ut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_impl_three.cpp | 26 +++++++------------ 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 7920894b8..d05a62422 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1180,16 +1180,13 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy007, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.test"; std::map policy; - policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100aggg"; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); } HWTEST_F(DeviceManagerImplTest, SetDnPolicy008, testing::ext::TestSize.Level0) @@ -1197,15 +1194,12 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy008, testing::ext::TestSize.Level0) std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; - policy[PARAM_KEY_POLICY_TIME_OUT] = "10aaa"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + policy[PARAM_KEY_POLICY_TIME_OUT] = "10aa"; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); } } // namespace } // namespace DistributedHardware -- Gitee From 276768580923a649944d14ea3d682d30974d8621 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 31 Aug 2024 19:22:53 +0800 Subject: [PATCH 139/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8F=8F=E8=BF=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 3c20297ca..f3379137a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1729,11 +1729,11 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond)) { - LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is not digit."); + LOGE("Invalid parameter, DM_POLICY_STRATEGY_FOR_BLE is not number."); return ERR_DM_INPUT_PARA_INVALID; } if (!IsNumberString(timeOutIter->second)) { - LOGE("Invalid parameter, DM_POLICY_TIMEOUT is not digit."); + LOGE("Invalid parameter, DM_POLICY_TIMEOUT is not number."); return ERR_DM_INPUT_PARA_INVALID; } int32_t policyStrategy = std::stoi(policyStrategyIter->second); -- Gitee From 4a4984be514f60f9b853ec211bdffec27b908e61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 31 Aug 2024 21:52:38 +0800 Subject: [PATCH 140/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/include/device_manager.h | 20 ++++++------- .../native_cpp/src/device_manager_impl.cpp | 4 +-- .../UTTest_device_manager_impl_three.cpp | 30 +++++++++---------- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 2c6ac4b44..a686e1c64 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -560,16 +560,6 @@ public: virtual int32_t DestroyPinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload) = 0; - /** - * @brief Set Dn Policy - * @param pkgName package name. - * @param policy contain DM_POLICY_STRATEGY_FOR_BLE and DM_POLICY_TIMEOUT key and value. - * DM_POLICY_STRATEGY_FOR_BLE: Strategy BLE networking go-online policy, suppress or restore. - * DM_POLICY_TIMEOUT: Indicates the duration for suppressing ble networking. - * @return Returns 0 if success. - */ - virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; - /** * @brief Request credential information. * @param pkgName package name. @@ -618,6 +608,16 @@ public: virtual int32_t ShiftLNNGear(const std::string &pkgName) = 0; virtual int32_t RegDevTrustChangeCallback(const std::string &pkgName, std::shared_ptr callback) = 0; + + /** + * @brief Set Dn Policy + * @param pkgName package name. + * @param policy contain DM_POLICY_STRATEGY_FOR_BLE and DM_POLICY_TIMEOUT key and value. + * DM_POLICY_STRATEGY_FOR_BLE: Strategy BLE networking go-online policy, suppress or restore. + * DM_POLICY_TIMEOUT: Indicates the duration for suppressing ble networking. + * @return Returns 0 if success. + */ + virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 9085f9d8e..55dea940d 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -100,7 +100,6 @@ const int32_t NORMAL = 0; const int32_t SYSTEM_BASIC = 1; const int32_t SYSTEM_CORE = 2; const int32_t USLEEP_TIME_MS = 100000; // 100ms -const uint32_t DM_MIN_PARAM = 2; uint16_t GenRandUint(uint16_t randMin, uint16_t randMax) { std::random_device randDevice; @@ -2166,7 +2165,8 @@ int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) int32_t DeviceManagerImpl::SetDnPolicy(const std::string &pkgName, std::map &policy) { - if (pkgName.empty() || policy.size() < DM_MIN_PARAM) { + const size_t SET_DN_POLICY_PARAM_SIZE = 2; + if (pkgName.empty() || policy.size() != SET_DN_POLICY_PARAM_SIZE) { LOGE("Para invalid: policy is less than two or pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index d05a62422..6549c89bf 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1164,24 +1164,21 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.test"; std::map policy; - policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - std::shared_ptr mockInstance = std::make_shared(); - std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; - DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); - DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); } HWTEST_F(DeviceManagerImplTest, SetDnPolicy007, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.test"; std::map policy; - policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; - policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10aa"; std::shared_ptr callback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(packName, callback); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); @@ -1194,12 +1191,15 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy008, testing::ext::TestSize.Level0) std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; - policy[PARAM_KEY_POLICY_TIME_OUT] = "10aa"; - std::shared_ptr callback = std::make_shared(); - DeviceManager::GetInstance().InitDeviceManager(packName, callback); + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + std::shared_ptr mockInstance = std::make_shared(); + std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; + DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; + EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) + .Times(1).WillOnce(testing::Return(ERR_DM_IPC_SEND_REQUEST_FAILED)); int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); - DeviceManager::GetInstance().UnInitDeviceManager(packName); + ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } } // namespace } // namespace DistributedHardware -- Gitee From 036b63849708821b77abf4cd0952bbfddf329cc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 31 Aug 2024 22:34:11 +0800 Subject: [PATCH 141/520] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../implementation/src/dependency/softbus/softbus_session.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 54b5138ca..b9d9ed4d2 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -31,12 +31,10 @@ static QosTV g_qosInfo[] = { { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, }; -static uint32_t g_qosTVParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); } std::shared_ptr SoftbusSession::sessionCallback_ = nullptr; constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; -constexpr int32_t INTERCEPT_STRING_LENGTH = 20; static void OnShutdown(int32_t socket, ShutdownReason reason) { -- Gitee From 6a9e2c77658722e1313eb6bbfabd9d7c7fbc4a38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 31 Aug 2024 22:51:10 +0800 Subject: [PATCH 142/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- commondependency/src/deviceprofile_connector.cpp | 2 +- .../src/dependency/softbus/softbus_session.cpp | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index b991776e5..6843b854e 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -497,7 +497,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string pkgName.c_str(), GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); DmOfflineParam offlineParam; offlineParam.bindType = INVALIED_TYPE; - if (bindLevel > APP || bindLevel < DEVICE) { + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < DEVICE) { LOGE("Invalied bindlevel."); return offlineParam; } diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index b9d9ed4d2..73efad2e5 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -25,14 +25,6 @@ namespace OHOS { namespace DistributedHardware { -namespace { -static QosTV g_qosInfo[] = { - { .qos = QOS_TYPE_MIN_BW, .value = 64 * 1024 }, - { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, - { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, -}; -} - std::shared_ptr SoftbusSession::sessionCallback_ = nullptr; constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; -- Gitee From 515eaa93fd60228a88911cb0ebcc8f8d9ad1858f Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 31 Aug 2024 23:50:35 +0800 Subject: [PATCH 143/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=9B=9E=E8=B0=83?= =?UTF-8?q?=E4=B8=A4=E6=AC=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../service/include/pinholder/pin_holder.h | 2 ++ services/service/src/pinholder/pin_holder.cpp | 36 +++++++++++-------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index b1aa7c149..9d9955340 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -21,6 +21,7 @@ #include "pin_holder_session.h" #include "pinholder_session_callback.h" +#include #include #include @@ -76,6 +77,7 @@ private: PinHolderState sourceState_; int32_t sessionId_ = -1; bool isRemoteSupported_ = false; + std::atomic isDestroy_ = false; }; } } diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 12fd51c33..cabbf279f 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -158,8 +158,10 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget LOGE("DestroyPinHolder failed, state is %{public}d.", sourceState_); return ERR_DM_FAILED; } - timer_->DeleteTimer(PINHOLDER_CREATE_TIMEOUT_TASK); - + if (timer_ != nullptr) { + timer_->DeleteTimer(PINHOLDER_CREATE_TIMEOUT_TASK); + } + isDestroy_.store(false); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; jsonObj[TAG_PIN_TYPE] = pinType; @@ -171,8 +173,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget ret = session_->SendData(sessionId_, message); int32_t stageRes = ret == DM_OK ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); - DmRadarHelper::GetInstance().ReportDestroyPinHolder(registerPkgName_, - targetId.deviceId, ret, stageRes); + DmRadarHelper::GetInstance().ReportDestroyPinHolder(registerPkgName_, targetId.deviceId, ret, stageRes); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); @@ -331,15 +332,18 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) if (sinkState_ != SINK_CREATE) { jsonObj[TAG_REPLY] = REPLY_FAILED; } else { - jsonObj[TAG_REPLY] = REPLY_SUCCESS; - sinkState_ = SINK_INIT; - sourceState_ = SOURCE_INIT; - listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); - nlohmann::json jsonContent; - jsonContent[TAG_PIN_TYPE] = pinType; - jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + if (!isDestroy_.load()) { + jsonObj[TAG_REPLY] = REPLY_SUCCESS; + sinkState_ = SINK_INIT; + sourceState_ = SOURCE_INIT; + listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); + nlohmann::json jsonContent; + jsonContent[TAG_PIN_TYPE] = pinType; + jsonContent[TAG_PAYLOAD] = payload; + std::string content = jsonContent.dump(); + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + isDestroy_.store(true); + } } std::string msg = jsonObj.dump(); @@ -361,13 +365,14 @@ void PinHolder::CloseSession(const std::string &name) nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); - if (listener_ != nullptr) { + if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + isDestroy_.store(true); } session_->CloseSessionServer(sessionId_); timer_->DeleteAll(); @@ -491,13 +496,14 @@ void PinHolder::OnSessionClosed(int32_t sessionId) nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); - if (listener_ != nullptr) { + if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + isDestroy_.store(true); } if (timer_ != nullptr) { timer_->DeleteAll(); -- Gitee From 23373995e55d40a35c121a139c81cc3175cd196f Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sun, 1 Sep 2024 08:25:27 +0800 Subject: [PATCH 144/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E4=B8=8D=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/src/dependency/softbus/softbus_session.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 54b5138ca..b9d9ed4d2 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -31,12 +31,10 @@ static QosTV g_qosInfo[] = { { .qos = QOS_TYPE_MAX_LATENCY, .value = 10000 }, { .qos = QOS_TYPE_MIN_LATENCY, .value = 2500 }, }; -static uint32_t g_qosTVParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); } std::shared_ptr SoftbusSession::sessionCallback_ = nullptr; constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; -constexpr int32_t INTERCEPT_STRING_LENGTH = 20; static void OnShutdown(int32_t socket, ShutdownReason reason) { -- Gitee From bc9c16d0f2ab3994e2d93004b458cbb4451698a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sun, 1 Sep 2024 09:46:22 +0800 Subject: [PATCH 145/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f3379137a..7d8b78ff5 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -66,10 +66,7 @@ const int32_t SYSTEM_CORE = 2; constexpr const char* ALL_PKGNAME = ""; constexpr const char* NETWORKID = "NETWORK_ID"; constexpr uint32_t INVALIED_BIND_LEVEL = 0; -constexpr uint32_t DEVICE_BIND_LEVEL = 1; constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; -constexpr uint32_t DM_POINT_TO_POINT = 256; -constexpr uint32_t DM_ACROSS_ACCOUNT = 1282; DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); -- Gitee From 143e79790163d8a8f4fddc4bf6b77634c3b9afdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sun, 1 Sep 2024 09:49:29 +0800 Subject: [PATCH 146/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_impl_three.cpp | 26 ----------------- .../UTTest_device_manager_service_two.cpp | 28 +++++++++++++++++++ 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 6549c89bf..cbdd95cfe 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1161,32 +1161,6 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy005, testing::ext::TestSize.Level0) } HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.test"; - std::map policy; - policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; - policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - std::shared_ptr callback = std::make_shared(); - DeviceManager::GetInstance().InitDeviceManager(packName, callback); - int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); - DeviceManager::GetInstance().UnInitDeviceManager(packName); -} - -HWTEST_F(DeviceManagerImplTest, SetDnPolicy007, testing::ext::TestSize.Level0) -{ - std::string packName = "com.ohos.test"; - std::map policy; - policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; - policy[PARAM_KEY_POLICY_TIME_OUT] = "10aa"; - std::shared_ptr callback = std::make_shared(); - DeviceManager::GetInstance().InitDeviceManager(packName, callback); - int32_t ret = DeviceManager::GetInstance().SetDnPolicy(packName, policy); - ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); - DeviceManager::GetInstance().UnInitDeviceManager(packName); -} - -HWTEST_F(DeviceManagerImplTest, SetDnPolicy008, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.test"; std::map policy; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index f3e8d16ec..efab942df 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -342,6 +342,34 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } + +/** + * @tc.name: SetDnPolicy_205 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_205, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: SetDnPolicy_206 + * @tc.type: FUNC + */ +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_206, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100a"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From c6539206344ff7fff23930b9c6d050cabfca3c50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sun, 1 Sep 2024 10:02:27 +0800 Subject: [PATCH 147/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=97=A0=E7=94=A8?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../service/src/relationshipsyncmgr/relationship_sync_mgr.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index a836dbd33..babb96ffd 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -44,9 +44,7 @@ namespace { const int32_t APP_UNBIND_PAYLOAD_LEN = 6; const int32_t USERID_PAYLOAD_LEN = 2; const int32_t ACCOUNTID_PAYLOAD_LEN = 6; - const int32_t TOKENID_PAYLOAD_LEN = 4; const int32_t BIT_PER_BYTES = 8; - const int32_t UINT32_BYTES = 4; const int32_t INVALIED_PAYLOAD_SIZE = 12; const char * const MSG_TYPE = "TYPE"; -- Gitee From b5c41bc4501a20bc2caed93ab3aadcf8ff71a475 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sun, 1 Sep 2024 14:05:09 +0800 Subject: [PATCH 148/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=A4=E6=AC=A1?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- services/service/include/pinholder/pin_holder.h | 2 +- services/service/src/pinholder/pin_holder.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index 9d9955340..d8f4b6205 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -77,7 +77,7 @@ private: PinHolderState sourceState_; int32_t sessionId_ = -1; bool isRemoteSupported_ = false; - std::atomic isDestroy_ = false; + std::atomic isDestroy_; }; } } diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index cabbf279f..2fb72d24e 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -161,7 +161,6 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget if (timer_ != nullptr) { timer_->DeleteTimer(PINHOLDER_CREATE_TIMEOUT_TASK); } - isDestroy_.store(false); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; jsonObj[TAG_PIN_TYPE] = pinType; @@ -466,6 +465,7 @@ void PinHolder::GetPeerDeviceId(int32_t sessionId, std::string &udidHash) void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { + isDestroy_.store(false); sessionId_ = sessionId; if (sessionSide == SESSION_SIDE_SERVER) { LOGI("[SOFTBUS]onSesssionOpened success, side is sink. sessionId: %{public}d.", sessionId); -- Gitee From 67e20b474770788285816f55ea54fc6f36d76d4c Mon Sep 17 00:00:00 2001 From: pwx1285814 Date: Mon, 2 Sep 2024 09:58:34 +0800 Subject: [PATCH 149/520] =?UTF-8?q?=E8=A1=A5=E5=85=85services/implementati?= =?UTF-8?q?on/src/authentication/dm=5Fauth=5Fmanager.cpp=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: pwx1285814 Change-Id: I42760cae802a986f2385be66fb22e642c2e3bba3 --- .../UTTest_dm_auth_manager_first.cpp | 113 ++++++++++--- .../UTTest_dm_auth_manager_first.h | 8 +- .../UTTest_dm_auth_manager_third.cpp | 151 ++++++++++++++++++ .../UTTest_dm_auth_manager_third.h | 49 ++++++ test/unittest/BUILD.gn | 39 +++++ .../UTTest_device_manager_service_two.cpp | 4 +- 6 files changed, 341 insertions(+), 23 deletions(-) create mode 100644 test/commonunittest/UTTest_dm_auth_manager_third.cpp create mode 100644 test/commonunittest/UTTest_dm_auth_manager_third.h diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 9cf98278a..0aa9a9879 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -17,15 +17,17 @@ #include "nlohmann/json.hpp" -#include "dm_log.h" -#include "dm_constants.h" -#include "dm_auth_manager.h" #include "auth_message_processor.h" +#include "common_event_support.h" #include "device_manager_service_listener.h" +#include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_log.h" #include "softbus_error_code.h" namespace OHOS { namespace DistributedHardware { +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; class SoftbusStateCallbackTest : public ISoftbusStateCallback { public: @@ -46,19 +48,13 @@ void DmAuthManagerTest::SetUp() authManager_->authResponseState_ = std::make_shared(); authManager_->hiChainAuthConnector_ = std::make_shared(); authManager_->softbusConnector_ = std::make_shared(); - authManager_->softbusConnector_->GetSoftbusSession()-> - RegisterSessionCallback(std::shared_ptr(authManager_)); + authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback( + std::shared_ptr(authManager_)); authManager_->timer_ = std::make_shared(); } -void DmAuthManagerTest::TearDown() -{ -} -void DmAuthManagerTest::SetUpTestCase() -{ -} -void DmAuthManagerTest::TearDownTestCase() -{ -} +void DmAuthManagerTest::TearDown() {} +void DmAuthManagerTest::SetUpTestCase() {} +void DmAuthManagerTest::TearDownTestCase() {} namespace { const int32_t MIN_PIN_CODE = 100000; @@ -269,6 +265,14 @@ HWTEST_F(DmAuthManagerTest, SetPageId_002, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } +HWTEST_F(DmAuthManagerTest, SetPageId_003, testing::ext::TestSize.Level0) +{ + int32_t pageId = 123; + authManager_->authResponseContext_ = nullptr; + int32_t ret = authManager_->SetPageId(pageId); + ASSERT_NE(ret, DM_OK); +} + HWTEST_F(DmAuthManagerTest, SetReasonAndFinish_001, testing::ext::TestSize.Level0) { const int32_t sessionId = 78; @@ -785,17 +789,58 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt001, testing::ext::TestSize.Leve ASSERT_EQ(authManager_->isAuthDevice_, false); } -HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, GenerateBindResultContent001, testing::ext::TestSize.Level0) { - int32_t sessionId = 0; - authManager_->ProcRespNegotiate(sessionId); - ASSERT_EQ(authManager_->isAuthDevice_, false); + auto ret = authManager_->GenerateBindResultContent(); + ASSERT_EQ(ret.empty(), false); } -HWTEST_F(DmAuthManagerTest, GenerateBindResultContent001, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, GenerateBindResultContent002, testing::ext::TestSize.Level0) { + authManager_->remoteDeviceId_ = "test"; auto ret = authManager_->GenerateBindResultContent(); - ASSERT_EQ(ret.empty(), false); + ASSERT_FALSE(ret.empty()); +} + + +HWTEST_F(DmAuthManagerTest, OnScreenLocked001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_ = nullptr; + authManager_->authRequestState_ = nullptr; + authManager_->OnScreenLocked(); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authRequestState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; + authManager_->OnScreenLocked(); + + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->OnScreenLocked(); + + authManager_->authResponseContext_->authType = AUTH_REQUEST_INIT; + std::shared_ptr requestFinishState = std::make_shared(); + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE)); + authManager_->authRequestState_ = requestFinishState; + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_INIT)); + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_JOIN)); + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_JOIN)); + authManager_->authUiStateMgr_ = nullptr; + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE_DONE)); + authManager_->OnScreenLocked(); + + EXPECT_CALL(*requestFinishState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); + authManager_->OnScreenLocked(); + EXPECT_EQ(authManager_->authResponseContext_->state, STATUS_DM_AUTH_DEFAULT); } HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived001, testing::ext::TestSize.Level0) @@ -1029,6 +1074,34 @@ HWTEST_F(DmAuthManagerTest, ProcessSinkMsg_007, testing::ext::TestSize.Level0) authManager_->ProcessSinkMsg(); ASSERT_EQ(authManager_->isFinishOfLocal_, true); } + +HWTEST_F(DmAuthManagerTest, ConvertSrcVersion_001, testing::ext::TestSize.Level0) +{ + std::string version = ""; + std::string edition = "test"; + EXPECT_EQ(authManager_->ConvertSrcVersion(version, edition), "test"); + + edition = ""; + EXPECT_NE(authManager_->ConvertSrcVersion(version, edition), "test"); + + version = "test"; + EXPECT_EQ(authManager_->ConvertSrcVersion(version, edition), "test"); +} + +HWTEST_F(DmAuthManagerTest, GetTaskTimeout_001, testing::ext::TestSize.Level0) +{ + int32_t taskTimeOut = 0; + authManager_->SetAuthType(AUTH_TYPE_CRE); + EXPECT_EQ(authManager_->GetTaskTimeout("test", taskTimeOut), taskTimeOut); + + taskTimeOut = 1000; + + authManager_->SetAuthType(AUTH_TYPE_IMPORT_AUTH_CODE); + EXPECT_EQ(authManager_->GetTaskTimeout("test", taskTimeOut), taskTimeOut); + + authManager_->SetAuthType(AUTH_TYPE_IMPORT_AUTH_CODE); + EXPECT_EQ(authManager_->GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, taskTimeOut), CLONE_AUTHENTICATE_TIMEOUT); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.h b/test/commonunittest/UTTest_dm_auth_manager_first.h index d59bc805d..2a8620a40 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.h +++ b/test/commonunittest/UTTest_dm_auth_manager_first.h @@ -16,9 +16,10 @@ #ifndef OHOS_DM_AUTH_MANAGER_FIRST_TEST_H #define OHOS_DM_AUTH_MANAGER_FIRST_TEST_H +#include +#include #include #include -#include #include "authentication.h" #include "softbus_session.h" @@ -50,6 +51,11 @@ public: std::shared_ptr authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); }; + +class AuthRequestFinishStateMock : public AuthRequestFinishState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); +}; } // namespace DistributedHardware } // namespace OHOS #endif diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp new file mode 100644 index 000000000..5bf4d1165 --- /dev/null +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_auth_manager_third.h" + +#include "nlohmann/json.hpp" + +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_auth_manager.h" +#include "auth_message_processor.h" +#include "device_manager_service_listener.h" +#include "softbus_error_code.h" + +static std::string g_createSimpleMessageReturnDataStr = "{}"; +static bool g_isIdenticalAccountReturnBoolValue = false; + +namespace OHOS { +namespace DistributedHardware { +std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) +{ + return g_createSimpleMessageReturnDataStr; +} + +bool DmAuthManager::IsIdenticalAccount() +{ + return g_isIdenticalAccountReturnBoolValue; +} + +void DmAuthManagerTest::SetUp() +{ + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); + + authManager_->authMessageProcessor_ = std::make_shared(authManager_); + authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); + authManager_->authRequestContext_ = std::make_shared(); + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseState_ = std::make_shared(); + authManager_->hiChainAuthConnector_ = std::make_shared(); + authManager_->softbusConnector_ = std::make_shared(); + authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback( + std::shared_ptr(authManager_)); + authManager_->timer_ = std::make_shared(); +} +void DmAuthManagerTest::TearDown() +{ + g_createSimpleMessageReturnDataStr = "{}"; + g_isIdenticalAccountReturnBoolValue = false; +} +void DmAuthManagerTest::SetUpTestCase() {} +void DmAuthManagerTest::TearDownTestCase() {} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + int32_t sessionId = 0; + authManager_->remoteDeviceId_ = "ProcRespNegotiate001"; + authManager_->ProcRespNegotiate(sessionId); + + jsonObject[TAG_CRYPTO_SUPPORT] = false; + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; + authManager_->ProcRespNegotiate(sessionId); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_SUPPORT] = true; + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->importAuthCode_ = ""; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = false; + authManager_->ProcRespNegotiate(sessionId); + + authManager_->authResponseState_->context_ = std::make_shared(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->ProcRespNegotiate(sessionId); + + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_NAME] = "test"; + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_isIdenticalAccountReturnBoolValue = true; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->ProcRespNegotiate(sessionId); + EXPECT_FALSE(authManager_->authResponseContext_->isOnline); +} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) +{ + nlohmann::json jsonObject; + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + int32_t sessionId = 0; + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_SUPPORT] = true; + jsonObject[TAG_CRYPTO_NAME] = "test"; + jsonObject[TAG_CRYPTO_VERSION] = "test"; + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_isIdenticalAccountReturnBoolValue = false; + authManager_->remoteDeviceId_ = "ProcRespNegotiate002"; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->authResponseState_->context_->cryptoName = jsonObject[TAG_CRYPTO_NAME]; + authManager_->ProcRespNegotiate(sessionId); + EXPECT_FALSE(authManager_->authResponseContext_->isOnline); + + authManager_->authResponseState_->context_ = std::make_shared(); + jsonObject[TAG_CRYPTO_SUPPORT] = true; + jsonObject[TAG_CRYPTO_NAME] = "test"; + jsonObject[TAG_CRYPTO_VERSION] = "test"; + g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_isIdenticalAccountReturnBoolValue = false; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseState_->context_->cryptoSupport = true; + authManager_->authResponseState_->context_->cryptoName = jsonObject[TAG_CRYPTO_NAME]; + authManager_->authResponseState_->context_->cryptoVer = jsonObject[TAG_CRYPTO_VERSION]; + authManager_->ProcRespNegotiate(sessionId); + EXPECT_FALSE(authManager_->authResponseContext_->isOnline); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.h b/test/commonunittest/UTTest_dm_auth_manager_third.h new file mode 100644 index 000000000..2df80f2d9 --- /dev/null +++ b/test/commonunittest/UTTest_dm_auth_manager_third.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_AUTH_MANAGER_THIRD_TEST_H +#define OHOS_DM_AUTH_MANAGER_THIRD_TEST_H + +#include +#include +#include + +#include "authentication.h" +#include "softbus_session.h" +#include "device_manager_service_listener.h" +#include "dm_adapter_manager.h" +#include "dm_constants.h" +#include "softbus_connector.h" +#include "hichain_connector.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "auth_message_processor.h" +#include "dm_timer.h" +#include "dm_auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAuthManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + std::shared_ptr authManager_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 7712f5e7d..17d890776 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -33,6 +33,7 @@ group("unittest") { ":UTTest_dm_anonymous", ":UTTest_dm_auth_manager_first", ":UTTest_dm_auth_manager_second", + ":UTTest_dm_auth_manager_third", ":UTTest_dm_common_event_manager", ":UTTest_dm_credential_manager", ":UTTest_dm_crypto", @@ -1005,6 +1006,15 @@ ohos_unittest("UTTest_dm_auth_manager_first") { "device_info_manager:distributed_device_profile_sdk", "googletest:gmock", ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] } ## UTTest_dm_auth_manager_first }}} @@ -1029,6 +1039,35 @@ ohos_unittest("UTTest_dm_auth_manager_second") { ## UTTest_dm_auth_manager_second }}} +## UnitTest UTTest_dm_auth_manager_third {{{ +ohos_unittest("UTTest_dm_auth_manager_third") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/commonunittest" ] + + sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_third.cpp" ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "googletest:gmock", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] +} + +## UTTest_dm_auth_manager_third }}} + ############################### ## UnitTest UTTest_dm_radar_helper_test {{{ ohos_unittest("UTTest_dm_radar_helper_test") { diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index efab942df..b4d1659a3 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -219,7 +219,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_202, testing::ext::TestSiz DmAccessCallee callee; DeletePermission(); bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } /** @@ -244,7 +244,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSiz DmAccessCallee callee; DeletePermission(); bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } /** -- Gitee From 8bcfa393957319d2dcdedd355403d8503ded0ce4 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Mon, 2 Sep 2024 17:39:20 +0800 Subject: [PATCH 150/520] =?UTF-8?q?=E4=B8=9A=E5=8A=A1=E6=AD=BB=E4=BA=A1?= =?UTF-8?q?=E5=90=8E=E6=B8=85=E7=90=86=E5=8F=91=E7=8E=B0=E8=B5=84=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../service/include/device_manager_service.h | 1 + .../include/discovery/discovery_manager.h | 1 + .../service/src/device_manager_service.cpp | 7 ++++ .../src/discovery/discovery_manager.cpp | 35 +++++++++++++++++++ .../service/src/softbus/softbus_listener.cpp | 4 ++- 5 files changed, 47 insertions(+), 1 deletion(-) diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 68a34459b..0276113b6 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -192,6 +192,7 @@ public: void HandleDeviceTrustedChange(const std::string &msg); int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); + void ClearDiscoveryCache(const std::string &pkgName); private: bool IsDMServiceImplReady(); diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index fd204234e..04c5deef3 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -71,6 +71,7 @@ public: static bool IsCommonDependencyReady(); static bool CloseCommonDependencyObj(); #endif + void ClearDiscoveryCache(const std::string &pkgName); private: void StartDiscoveryTimer(const std::string &pkgName); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 7d8b78ff5..f034ee48a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1882,5 +1882,12 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) } return; } + +void DeviceManagerService::ClearDiscoveryCache(const std::string &pkgName) +{ + LOGI("PkgName %{public}s.", pkgName.c_str()); + CHECK_NULL_VOID(discoveryMgr_); + discoveryMgr_->ClearDiscoveryCache(pkgName); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 5ff9e6f56..285337a8f 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -584,5 +584,40 @@ bool DiscoveryManager::CloseCommonDependencyObj() return true; } #endif + +void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) +{ + LOGI("PkgName %{public}s.", pkgName.c_str()); + uint16_t subscribeId = 0; + { + std::lock_guard autoLock(locks_); + if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { + LOGI("Erase pkgname %{public}s from pkgNameSet.", pkgName.c_str()); + pkgNameSet_.erase(pkgName); + } + if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { + LOGI("Erase pkgname %{public}s from pkgNameSet.", pkgName.c_str()); + subscribeId = discoveryContextMap_[pkgName].subscribeId; + discoveryContextMap_.erase(pkgName); + } + } + { + std::lock_guard capLock(capabilityMapLocks_); + if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { + capabilityMap_.erase(pkgName); + } + } + { + std::lock_guard autoLock(subIdMapLocks_); + if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { + pkgName2SubIdMap_.erase(pkgName); + } + } + CHECK_NULL_VOID(softbusListener_); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); + softbusListener_->StopRefreshSoftbusLNN(subscribeId); + CHECK_NULL_VOID(timer_); + timer_->DeleteTimer(pkgName); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index b20ed4382..a5c80d2f0 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -593,7 +593,9 @@ int32_t SoftbusListener::RegisterSoftbusLnnOpsCbk(const std::string &pkgName, int32_t SoftbusListener::UnRegisterSoftbusLnnOpsCbk(const std::string &pkgName) { std::lock_guard lock(g_lnnCbkMapMutex); - lnnOpsCbkMap.erase(pkgName); + if (lnnOpsCbkMap.find(pkgName) != lnnOpsCbkMap.end()) { + lnnOpsCbkMap.erase(pkgName); + } return DM_OK; } -- Gitee From 65cf05a0c0b1ecf785e56e26d0b331830152834d Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Mon, 2 Sep 2024 17:41:45 +0800 Subject: [PATCH 151/520] =?UTF-8?q?=E4=B8=9A=E5=8A=A1=E6=AD=BB=E4=BA=A1?= =?UTF-8?q?=E5=90=8E=E6=B8=85=E7=90=86=E5=8F=91=E7=8E=B0=E8=B5=84=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- services/service/src/ipc/standard/ipc_server_stub.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 07d01c90c..c74213592 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -334,6 +334,7 @@ void AppDeathRecipient::OnRemoteDied(const wptr &remote) std::string pkgName = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", pkgName.c_str()); IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + DeviceManagerService::GetInstance().ClearDiscoveryCache(pkgName); } } // namespace DistributedHardware } // namespace OHOS -- Gitee From 9eebed5ad56b25f45b87c0eb212d287d37a3cd2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 2 Sep 2024 20:24:21 +0800 Subject: [PATCH 152/520] =?UTF-8?q?=E6=95=B4=E6=94=B9ffrt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../include/notify/device_manager_notify.h | 3 -- .../src/notify/device_manager_notify.cpp | 49 ++++--------------- .../ability/standard/dm_dialog_manager.cpp | 2 +- .../dm_account_common_event.cpp | 4 +- .../dm_publish_common_event.cpp | 4 +- .../dm_screen_common_event.cpp | 4 +- .../service/src/softbus/softbus_listener.cpp | 12 ++--- utils/BUILD.gn | 2 - .../include/threadManager/dm_thread_manager.h | 34 ------------- utils/src/kvadapter/kv_adapter.cpp | 4 +- utils/src/threadManager/dm_thread_manager.cpp | 41 ---------------- 11 files changed, 24 insertions(+), 135 deletions(-) delete mode 100644 utils/include/threadManager/dm_thread_manager.h delete mode 100644 utils/src/threadManager/dm_thread_manager.cpp 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 69672229b..88487ca84 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 @@ -128,9 +128,6 @@ private: std::map> pinHolderCallback_; std::map> devTrustChangeCallback_; std::mutex bindLock_; -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - std::shared_ptr ffrtQueue_; -#endif }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index fac7395f7..b6ed28fd1 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 @@ -43,19 +43,6 @@ void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgN } std::lock_guard autoLock(lock_); dmInitCallback_[pkgName] = dmInitCallback; - -#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - LOGI("FfrtQueue has created!"); - return; - } - ffrtQueue_ = std::make_shared(DEVICE_STATE_INIT_QUEUE, - ffrt::queue_attr().qos(ffrt::qos_default)); - if (ffrtQueue_ == nullptr) { - LOGE("FfrtQueue create failed!"); - return; - } -#endif } void DeviceManagerNotify::UnRegisterDeathRecipientCallback(const std::string &pkgName) @@ -298,9 +285,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoOnline(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoOnline(deviceInfo, tempCbk); }); #else std::thread deviceOnline([=]() { DeviceInfoOnline(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceOnline.native_handle(), DEVICE_ONLINE) != DM_OK) { @@ -332,9 +317,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoOnline(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoOnline(deviceBasicInfo, tempCbk); }); #else std::thread deviceOnline([=]() { DeviceBasicInfoOnline(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceOnline.native_handle(), DEVICE_ONLINE) != DM_OK) { @@ -366,9 +349,7 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); #else std::thread deviceOffline([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceOffline.native_handle(), DEVICE_OFFLINE) != DM_OK) { @@ -400,9 +381,7 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoOffline(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoOffline(deviceBasicInfo, tempCbk); }); #else std::thread deviceOffline([=]() { DeviceBasicInfoOffline(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceOffline.native_handle(), DEVICE_OFFLINE) != DM_OK) { @@ -434,9 +413,7 @@ void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDe return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoChanged(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoChanged(deviceInfo, tempCbk); }); #else std::thread deviceChanged([=]() { DeviceInfoChanged(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceChanged.native_handle(), DEVICEINFO_CHANGE) != DM_OK) { @@ -468,9 +445,7 @@ void DeviceManagerNotify::OnDeviceChanged(const std::string &pkgName, const DmDe return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoChanged(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoChanged(deviceBasicInfo, tempCbk); }); #else std::thread deviceChanged([=]() { DeviceBasicInfoChanged(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceChanged.native_handle(), DEVICEINFO_CHANGE) != DM_OK) { @@ -502,9 +477,7 @@ void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDevi return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceInfoReady(deviceInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceInfoReady(deviceInfo, tempCbk); }); #else std::thread deviceReady([=]() { DeviceInfoReady(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceReady.native_handle(), DEVICE_READY) != DM_OK) { @@ -536,9 +509,7 @@ void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDevi return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceBasicInfoReady(deviceBasicInfo, tempCbk); }); - } + ffrt::submit([=]() { DeviceBasicInfoReady(deviceBasicInfo, tempCbk); }); #else std::thread deviceReady([=]() { DeviceBasicInfoReady(deviceBasicInfo, tempCbk); }); if (pthread_setname_np(deviceReady.native_handle(), DEVICE_READY) != DM_OK) { @@ -1114,9 +1085,7 @@ void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const } DmAuthForm dmAuthForm = static_cast(authForm); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); - } + ffrt::submit([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); #else std::thread deviceTrustChange([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); if (pthread_setname_np(deviceTrustChange.native_handle(), DEVICE_TRUST_CHANGE) != DM_OK) { diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 9ff2a9e0d..4eab5857b 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -115,7 +115,7 @@ void DmDialogManager::ShowPinDialog(const std::string param) abilityName_ = PIN_ABILITY_NAME; pinCode_ = param; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(CONNECT_PIN_DIALOG.c_str(), []() { ConnectExtension(); }); + ff(CONNECT_PIN_DIALOG.c_str(), []() { ConnectExtension(); }); #else std::thread pinDilog([]() { ConnectExtension(); }); int32_t ret = pthread_setname_np(pinDilog.native_handle(), CONNECT_PIN_DIALOG.c_str()); diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index cd885c591..6d547b74f 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -23,7 +23,7 @@ #include "dm_constants.h" #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "dm_thread_manager.h" +#include "ffrt.h" #endif #include "iservice_registry.h" #include "multiple_user_connector.h" @@ -152,7 +152,7 @@ void DmAccountEventSubscriber::OnReceiveEvent(const CommonEventData &data) return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(userId, receiveEvent); }); + ffrt::submit([=]() { callback_(userId, receiveEvent); }); #else std::thread dealThread([=]() { callback_(userId, receiveEvent); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); diff --git a/services/service/src/publishcommonevent/dm_publish_common_event.cpp b/services/service/src/publishcommonevent/dm_publish_common_event.cpp index 859f53a7c..33042506c 100644 --- a/services/service/src/publishcommonevent/dm_publish_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_publish_common_event.cpp @@ -28,7 +28,7 @@ #endif // SUPPORT_WIFI #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "dm_thread_manager.h" +#include "ffrt.h" #endif namespace OHOS { @@ -236,7 +236,7 @@ void DmPublishEventSubscriber::OnReceiveEvent(const CommonEventData &data) #endif // SUPPORT_WIFI #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(bluetoothState_, wifiState_, screenState_); }); + ffrt::submit([=]() { callback_(bluetoothState_, wifiState_, screenState_); }); #else std::thread dealThread([=]() { callback_(bluetoothState_, wifiState_, screenState_); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); diff --git a/services/service/src/publishcommonevent/dm_screen_common_event.cpp b/services/service/src/publishcommonevent/dm_screen_common_event.cpp index fa7867242..e506e3370 100644 --- a/services/service/src/publishcommonevent/dm_screen_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_screen_common_event.cpp @@ -23,7 +23,7 @@ #include "dm_constants.h" #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "dm_thread_manager.h" +#include "ffrt.h" #endif #include "iservice_registry.h" #include "multiple_user_connector.h" @@ -139,7 +139,7 @@ void DmScreenEventSubscriber::OnReceiveEvent(const CommonEventData &data) return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(receiveEvent); }); + ffrt::submit([=]() { callback_(receiveEvent); }); #else std::thread dealThread(callback_, receiveEvent); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index b20ed4382..6778632c6 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -30,7 +30,7 @@ #include "dm_log.h" #include "dm_softbus_cache.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "dm_thread_manager.h" +#include "ffrt.h" #endif #include "parameter.h" #include "system_ability_definition.h" @@ -179,7 +179,7 @@ void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) g_onlinDeviceNum++; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEVICE_ONLINE, [=]() { DeviceOnLine(dmDeviceInfo); }); + ffrt::submit([=]() { DeviceOnLine(dmDeviceInfo); }); #else std::thread deviceOnLine([=]() { DeviceOnLine(dmDeviceInfo); }); int32_t ret = pthread_setname_np(deviceOnLine.native_handle(), DEVICE_ONLINE); @@ -230,7 +230,7 @@ void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info) } LOGI("device offline networkId: %{public}s.", GetAnonyString(dmDeviceInfo.networkId).c_str()); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEVICE_OFFLINE, [=]() { DeviceOffLine(dmDeviceInfo); }); + ffrt::submit([=]() { DeviceOffLine(dmDeviceInfo); }); #else std::thread deviceOffLine([=]() { DeviceOffLine(dmDeviceInfo); }); int32_t ret = pthread_setname_np(deviceOffLine.native_handle(), DEVICE_OFFLINE); @@ -284,7 +284,7 @@ void SoftbusListener::OnSoftbusDeviceInfoChanged(NodeBasicInfoType type, NodeBas dmDeviceInfo.networkType = networkType; SoftbusCache::GetInstance().ChangeDeviceInfo(dmDeviceInfo); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEVICE_NAME_CHANGE, [=]() { DeviceNameChange(dmDeviceInfo); }); + ffrt::submit([=]() { DeviceNameChange(dmDeviceInfo); }); #else std::thread deviceInfoChange([=]() { DeviceNameChange(dmDeviceInfo); }); if (pthread_setname_np(deviceInfoChange.native_handle(), DEVICE_NAME_CHANGE) != DM_OK) { @@ -311,9 +311,9 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms std::string softbusMsg = std::string(msg); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) if (type == TrustChangeType::DEVICE_NOT_TRUSTED) { - ThreadManager::GetInstance().Submit(DEVICE_NOT_TRUST, [=]() { DeviceNotTrust(softbusMsg); }); + ffrt::submit([=]() { DeviceNotTrust(softbusMsg); }); } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { - ThreadManager::GetInstance().Submit(DEVICE_TRUSTED_CHANGE, [=]() { DeviceTrustedChange(softbusMsg); }); + ffrt::submit([=]() { DeviceTrustedChange(softbusMsg); }); } else { LOGE("Invalied trust change type."); } diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 07fd22f58..410446a0e 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -74,7 +74,6 @@ if (defined(ohos_lite)) { "include", "include/crypto", "include/kvadapter", - "include/threadManager", "include/fwkload/standard", "include/appInfo/standard", "include/timer", @@ -102,7 +101,6 @@ if (defined(ohos_lite)) { "src/dm_random.cpp", "src/kvadapter/kv_adapter.cpp", "src/kvadapter/kv_adapter_manager.cpp", - "src/threadManager/dm_thread_manager.cpp", "src/timer/dm_timer.cpp", ] diff --git a/utils/include/threadManager/dm_thread_manager.h b/utils/include/threadManager/dm_thread_manager.h deleted file mode 100644 index a99f2b284..000000000 --- a/utils/include/threadManager/dm_thread_manager.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DM_THREAD_MANAGER_H -#define OHOS_DM_THREAD_MANAGER_H - -#include "dm_single_instance.h" -#include "ffrt.h" - -namespace OHOS { -namespace DistributedHardware { -class ThreadManager { - DM_DECLARE_SINGLE_INSTANCE(ThreadManager); -public: - ffrt::task_handle Submit(const char* threadName, const std::function& threadFunc); - void Wait(const ffrt::task_handle& handle); -private: - std::shared_ptr ffrtQueue_ = nullptr; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_THREAD_MANAGER_H diff --git a/utils/src/kvadapter/kv_adapter.cpp b/utils/src/kvadapter/kv_adapter.cpp index 2082afa97..6b50d2263 100644 --- a/utils/src/kvadapter/kv_adapter.cpp +++ b/utils/src/kvadapter/kv_adapter.cpp @@ -25,7 +25,7 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" -#include "dm_thread_manager.h" +#include "ffrt.h" namespace OHOS { namespace DistributedHardware { @@ -172,7 +172,7 @@ void KVAdapter::OnRemoteDied() LOGI("ReInit, storeId:%{public}s", storeId_.storeId.c_str()); ReInit(); }; - ThreadManager::GetInstance().Submit(KV_REINIT_THREAD.c_str(), reInitTask); + ffrt::submit(reInitTask); } DistributedKv::Status KVAdapter::GetLocalKvStorePtr() diff --git a/utils/src/threadManager/dm_thread_manager.cpp b/utils/src/threadManager/dm_thread_manager.cpp deleted file mode 100644 index 2e60152f4..000000000 --- a/utils/src/threadManager/dm_thread_manager.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "dm_thread_manager.h" -#include "dm_log.h" - -namespace OHOS { -namespace DistributedHardware { -DM_IMPLEMENT_SINGLE_INSTANCE(ThreadManager); -constexpr const char* DEVICE_MANAGER_THREAD_QUEUE = "device_manager_thread_queue"; -ffrt::task_handle ThreadManager::Submit(const char* threadName, const std::function& threadFunc) -{ - if (ffrtQueue_ == nullptr) { - ffrtQueue_ = std::make_shared(DEVICE_MANAGER_THREAD_QUEUE, - ffrt::queue_attr().qos(ffrt::qos_default)); - } - return ffrtQueue_->submit_h(threadFunc, ffrt::task_attr().name(threadName)); -} - -void ThreadManager::Wait(const ffrt::task_handle& handle) -{ - if (ffrtQueue_ == nullptr) { - LOGE("ThreadManager Wait, ffrtQueue is null."); - return; - } - ffrtQueue_->wait(handle); -} -} // namespace DistributedHardware -} // namespace OHOS -- Gitee From 3cab42df11ba4078d6709989a36fbfea894f6a20 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 3 Sep 2024 16:58:37 +0800 Subject: [PATCH 153/520] =?UTF-8?q?=E8=A1=A5=E5=85=85UTTest=5Fdevice=5Fman?= =?UTF-8?q?ager=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 89bb32142..a2233bf3c 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1409,6 +1409,15 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_001, testing::ext::TestSize.Level std::string pkgName; int32_t eventId = 0; std::string event; + std::string msg = ""; + DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); + msg = "hello_openharmony"; + DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); + msg = "NETWORK_ID"; + DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); + std::string commonEventType = "helloworld"; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().ScreenCommonEventCallback(commonEventType); int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); EXPECT_NE(ret, DM_OK); } @@ -1423,6 +1432,16 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_002, testing::ext::TestSize.Level EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); } +HWTEST_F(DeviceManagerServiceTest, NotifyEvent_003, testing::ext::TestSize.Level0) +{ + DeletePermission(); + std::string pkgName; + int32_t eventId = DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT; + std::string event; + int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); + EXPECT_NE(ret, DM_OK); +} + HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_001, testing::ext::TestSize.Level0) { DeviceManagerService::GetInstance().LoadHardwareFwkService(); @@ -1447,6 +1466,20 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_002, testing::ext EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string networkId = "network_id"; + std::string uuid = "13345689"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_NE(ret, DM_OK); + +} + HWTEST_F(DeviceManagerServiceTest, GenerateEncryptedUuid_001, testing::ext::TestSize.Level0) { std::string pkgName; -- Gitee From fe2cf2e54bd69ae522f5ebecfe6c09c522e1a65b Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 3 Sep 2024 18:05:15 +0800 Subject: [PATCH 154/520] =?UTF-8?q?=E8=A1=A5=E5=85=85UTTest=5Fdevice=5Fman?= =?UTF-8?q?ager=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B,=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E5=A4=9A=E4=BD=99=E7=A9=BA=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index a2233bf3c..53315b302 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1477,7 +1477,6 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_NE(ret, DM_OK); - } HWTEST_F(DeviceManagerServiceTest, GenerateEncryptedUuid_001, testing::ext::TestSize.Level0) -- Gitee From 8b227be70dfd946327d6913655c49fcab35759ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 4 Sep 2024 14:13:07 +0800 Subject: [PATCH 155/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../implementation/src/ability/standard/dm_dialog_manager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 4eab5857b..7b6912134 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -27,7 +27,7 @@ #include "parameter.h" #include "dm_single_instance.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "dm_thread_manager.h" +#include "ffrt.h" #endif namespace OHOS { @@ -115,7 +115,7 @@ void DmDialogManager::ShowPinDialog(const std::string param) abilityName_ = PIN_ABILITY_NAME; pinCode_ = param; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ff(CONNECT_PIN_DIALOG.c_str(), []() { ConnectExtension(); }); + ffrt::submit([]() { ConnectExtension(); }); #else std::thread pinDilog([]() { ConnectExtension(); }); int32_t ret = pthread_setname_np(pinDilog.native_handle(), CONNECT_PIN_DIALOG.c_str()); -- Gitee From d43cc0dad712e7656ccfc5f3090aa50daacd8c3c Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 4 Sep 2024 11:48:13 +0800 Subject: [PATCH 156/520] =?UTF-8?q?=E6=B8=85=E7=90=86=E4=B8=8D=E4=B8=80?= =?UTF-8?q?=E8=87=B4=E5=AD=97=E7=AC=A6=E4=B8=B2=20Signed-off-by:=20liuzhon?= =?UTF-8?q?gming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- display/AppScope/app.json | 4 ++-- display/entry/src/main/resources/zh_TW/element/string.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 8b8059ce6..90c74919d 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -4,8 +4,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000020, - "versionName": "1.0.20", + "versionCode": 1000021, + "versionName": "1.0.21", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/resources/zh_TW/element/string.json b/display/entry/src/main/resources/zh_TW/element/string.json index adebbc904..c8117d996 100644 --- a/display/entry/src/main/resources/zh_TW/element/string.json +++ b/display/entry/src/main/resources/zh_TW/element/string.json @@ -26,7 +26,7 @@ }, { "name":"dm_allow_always", - "value":"始終信任" + "value":"永遠信任" }, { "name":"dm_confirm_title_cast", -- Gitee From afde551bb7916c5d816896eab122e17b052d177f Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 5 Sep 2024 10:46:10 +0800 Subject: [PATCH 157/520] =?UTF-8?q?=E5=9B=9E=E9=80=80=E4=B8=A4=E6=AC=A1?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../service/include/pinholder/pin_holder.h | 1 - services/service/src/pinholder/pin_holder.cpp | 28 ++++++++----------- 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index d8f4b6205..206cdd991 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -77,7 +77,6 @@ private: PinHolderState sourceState_; int32_t sessionId_ = -1; bool isRemoteSupported_ = false; - std::atomic isDestroy_; }; } } diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 2fb72d24e..853bf5092 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -331,18 +331,15 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) if (sinkState_ != SINK_CREATE) { jsonObj[TAG_REPLY] = REPLY_FAILED; } else { - if (!isDestroy_.load()) { - jsonObj[TAG_REPLY] = REPLY_SUCCESS; - sinkState_ = SINK_INIT; - sourceState_ = SOURCE_INIT; - listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); - nlohmann::json jsonContent; - jsonContent[TAG_PIN_TYPE] = pinType; - jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); - isDestroy_.store(true); - } + jsonObj[TAG_REPLY] = REPLY_SUCCESS; + sinkState_ = SINK_INIT; + sourceState_ = SOURCE_INIT; + listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); + nlohmann::json jsonContent; + jsonContent[TAG_PIN_TYPE] = pinType; + jsonContent[TAG_PAYLOAD] = payload; + std::string content = jsonContent.dump(); + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); } std::string msg = jsonObj.dump(); @@ -364,14 +361,13 @@ void PinHolder::CloseSession(const std::string &name) nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); - if (listener_ != nullptr && !isDestroy_.load()) { + if (listener_ != nullptr) { listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); - isDestroy_.store(true); } session_->CloseSessionServer(sessionId_); timer_->DeleteAll(); @@ -465,7 +461,6 @@ void PinHolder::GetPeerDeviceId(int32_t sessionId, std::string &udidHash) void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { - isDestroy_.store(false); sessionId_ = sessionId; if (sessionSide == SESSION_SIDE_SERVER) { LOGI("[SOFTBUS]onSesssionOpened success, side is sink. sessionId: %{public}d.", sessionId); @@ -496,14 +491,13 @@ void PinHolder::OnSessionClosed(int32_t sessionId) nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); - if (listener_ != nullptr && !isDestroy_.load()) { + if (listener_ != nullptr) { listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); - isDestroy_.store(true); } if (timer_ != nullptr) { timer_->DeleteAll(); -- Gitee From f17bbe7bee12dedcc4d95f7ba9f005517a4133df Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 5 Sep 2024 11:29:23 +0800 Subject: [PATCH 158/520] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- radar/include/dm_radar_helper.h | 15 ++-- radar/src/dm_radar_helper.cpp | 76 ++++++++++--------- radar/src/lite/dm_radar_helper.cpp | 6 +- .../src/authentication/dm_auth_manager.cpp | 8 +- .../dependency/hichain/hichain_connector.cpp | 1 - .../src/device_manager_service_impl.cpp | 13 ++++ .../service/include/pinholder/pin_holder.h | 1 - services/service/src/pinholder/pin_holder.cpp | 18 +++-- .../service/src/softbus/softbus_listener.cpp | 18 +---- test/commonunittest/dm_radar_helper_test.cpp | 4 +- 10 files changed, 83 insertions(+), 77 deletions(-) diff --git a/radar/include/dm_radar_helper.h b/radar/include/dm_radar_helper.h index f5bc49c29..22d56f2bb 100644 --- a/radar/include/dm_radar_helper.h +++ b/radar/include/dm_radar_helper.h @@ -85,10 +85,11 @@ enum class DeleteTrust : int32_t { enum class PinHolderStage : int32_t { CREATE_PIN_HOLDER = 0x1, - SEND_CREATE_PIN_HOLDER_MSG = 0x2, - RECEIVE_CREATE_PIN_HOLDER_MSG = 0x3, - DESTROY_PIN_HOLDER = 0x4, - RECEIVE_DESTROY_PIN_HOLDER_MSG = 0x5, + SESSION_OPENED = 0x2, + SEND_CREATE_PIN_HOLDER_MSG = 0x3, + RECEIVE_CREATE_PIN_HOLDER_MSG = 0x4, + DESTROY_PIN_HOLDER = 0x5, + RECEIVE_DESTROY_PIN_HOLDER_MSG = 0x6, }; enum class GetTrustDeviceList : int32_t { @@ -161,7 +162,7 @@ public: int32_t channelId, std::string peerUdid, int32_t errCode, int32_t stageRes) = 0; virtual void ReportDestroyPinHolder(std::string hostName, std::string peerUdid, int32_t errCode, int32_t stageRes) = 0; - virtual void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) = 0; + virtual void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) = 0; virtual std::string GetDeviceInfoList(std::vector &deviceInfoList) = 0; virtual std::string GetUdidHashByUdid(std::string udid) = 0; }; @@ -192,14 +193,14 @@ public: int32_t channelId, std::string peerUdid, int32_t errCode, int32_t stageRes) override; void ReportDestroyPinHolder(std::string hostName, std::string peerUdid, int32_t errCode, int32_t stageRes) override; - void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) override; + void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) override; std::string GetDeviceInfoList(std::vector &deviceInfoList) override; std::string GetUdidHashByUdid(std::string udid) override; std::string ConvertHexToString(uint16_t hex); int32_t GetErrCode(int32_t errCode); private: std::string GetAnonyUdid(std::string udid); - std::string GetLocalUdid(); + std::string GetAnonyLocalUdid(); }; extern "C" IDmRadarHelper *CreateDmRadarInstance(); diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index 946a9bf16..bcfd8713f 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -84,8 +84,8 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "COMM_SERV", static_cast(CommServ::USE_SOFTBUS), "PEER_NET_ID", GetAnonyUdid(info.peerNetId)); } else { @@ -100,6 +100,8 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "COMM_SERV", static_cast(CommServ::USE_SOFTBUS), "ERROR_CODE", info.errCode); } @@ -174,8 +176,8 @@ bool DmRadarHelper::ReportAuthStart(const std::string &peerUdid, const std::stri "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_START), "IS_TRUST", static_cast(TrustStatus::NOT_TRUST), - "PEER_UDID", GetUdidHashByUdid(peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid())); + "PEER_UDID", GetAnonyUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid()); if (res != DM_OK) { LOGE("ReportAuthStart error, res:%{public}d", res); return false; @@ -196,8 +198,8 @@ bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "STAGE_RES", info.stageRes, - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "CH_ID", info.channelId, "IS_TRUST", info.isTrust, "COMM_SERV", info.commServ, @@ -214,8 +216,8 @@ bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "BIZ_STATE", info.bizState, "STAGE_RES", info.stageRes, - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "CH_ID", info.channelId, "IS_TRUST", info.isTrust, "COMM_SERV", info.commServ, @@ -241,6 +243,8 @@ bool DmRadarHelper::ReportAuthSessionOpenCb(struct RadarInfo &info) "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "STAGE_RES", info.stageRes, + "PEER_UDID", GetAnonyUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "CH_ID", info.channelId); if (res != DM_OK) { LOGE("ReportAuthSessionOpenCb error, res:%{public}d", res); @@ -335,7 +339,7 @@ bool DmRadarHelper::ReportAuthCreateGroup(struct RadarInfo &info) "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", info.stageRes, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "TO_CALL_PKG", info.toCallPkg); } else { res = HiSysEventWrite( @@ -349,7 +353,7 @@ bool DmRadarHelper::ReportAuthCreateGroup(struct RadarInfo &info) "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, "TO_CALL_PKG", info.toCallPkg, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "ERROR_CODE", info.errCode); } if (res != DM_OK) { @@ -458,8 +462,8 @@ bool DmRadarHelper::ReportAuthAddGroup(struct RadarInfo &info) "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", info.stageRes, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "TO_CALL_PKG", HICHAINNAME); } else { res = HiSysEventWrite( @@ -471,8 +475,8 @@ bool DmRadarHelper::ReportAuthAddGroup(struct RadarInfo &info) "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", info.stageRes, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "TO_CALL_PKG", HICHAINNAME, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "ERROR_CODE", info.errCode); @@ -532,8 +536,8 @@ bool DmRadarHelper::ReportNetworkOnline(struct RadarInfo &info) "BIZ_STAGE", static_cast(NetworkStage::NETWORK_ONLINE), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "PEER_NET_ID", GetAnonyUdid(info.peerNetId), "IS_TRUST", info.isTrust); if (res != DM_OK) { @@ -555,8 +559,8 @@ bool DmRadarHelper::ReportNetworkOffline(struct RadarInfo &info) "BIZ_STAGE", static_cast(NetworkStage::NETWORK_OFFLINE), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "PEER_NET_ID", GetAnonyUdid(info.peerNetId)); if (res != DM_OK) { LOGE("ReportNetworkOffline error, res:%{public}d", res); @@ -578,8 +582,8 @@ bool DmRadarHelper::ReportDeleteTrustRelation(struct RadarInfo &info) "BIZ_STAGE", static_cast(DeleteTrust::DELETE_TRUST), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), - "PEER_UDID", GetUdidHashByUdid(info.peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.peerUdid), "PEER_NET_ID", GetAnonyUdid(info.peerNetId), "TO_CALL_PKG", info.toCallPkg); if (res != DM_OK) { @@ -606,8 +610,8 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_START), "CH_ID", channelId, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportDeleteTrustRelation error, res:%{public}d", res); @@ -626,8 +630,8 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "CH_ID", channelId, - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME, "ERROR_CODE", errCode); if (res != DM_OK) { @@ -653,8 +657,8 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportDeleteTrustRelation error, res:%{public}d", res); @@ -672,8 +676,8 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(GetLocalUdid()), - "PEER_UDID", GetUdidHashByUdid(peerUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME, "ERROR_CODE", errCode); if (res != DM_OK) { @@ -684,7 +688,7 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, return; } -void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) +void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) { int32_t res = DM_OK; if (bizStage == static_cast(PinHolderStage::RECEIVE_DESTROY_PIN_HOLDER_MSG)) { @@ -698,6 +702,8 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f "BIZ_STAGE", bizStage, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportSendOrReceiveHolderMsg error, res:%{public}d", res); @@ -713,6 +719,8 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), "BIZ_STAGE", bizStage, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(peerUdid), "TO_CALL_PKG", SOFTBUSNAME); if (res != DM_OK) { LOGE("ReportSendOrReceiveHolderMsg error, res:%{public}d", res); @@ -736,7 +744,7 @@ bool DmRadarHelper::ReportGetTrustDeviceList(struct RadarInfo &info) "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "DISCOVERY_DEVICE_LIST", info.discoverDevList); } else { res = HiSysEventWrite( @@ -749,7 +757,7 @@ bool DmRadarHelper::ReportGetTrustDeviceList(struct RadarInfo &info) "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), - "LOCAL_UDID", GetUdidHashByUdid(info.localUdid), + "LOCAL_UDID", GetAnonyLocalUdid(), "DISCOVERY_DEVICE_LIST", info.discoverDevList, "ERROR_CODE", info.errCode); } @@ -784,7 +792,7 @@ std::string DmRadarHelper::GetDeviceInfoList(std::vector &deviceIn cJSON_Delete(deviceInfoJson); return ""; } - std::string udidHash = GetUdidHashByUdid(std::string(deviceInfoList[i].deviceId)); + std::string udidHash = GetAnonyUdid(std::string(deviceInfoList[i].deviceId)); cJSON_AddStringToObject(object, "PEER_UDID", udidHash.c_str()); std::string peerNetId = GetAnonyUdid(deviceInfoList[i].networkId); cJSON_AddStringToObject(object, "PEER_NET_ID", peerNetId.c_str()); @@ -822,11 +830,11 @@ std::string DmRadarHelper::GetAnonyUdid(std::string udid) return udid.substr(0, SUBSTR_UDID_LENGTH) + "**" + udid.substr(udid.length() - SUBSTR_UDID_LENGTH); } -std::string DmRadarHelper::GetLocalUdid() +std::string DmRadarHelper::GetAnonyLocalUdid() { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - return std::string(localDeviceId); + return GetAnonyUdid(std::string(localDeviceId)); } int32_t DmRadarHelper::GetErrCode(int32_t errCode) diff --git a/radar/src/lite/dm_radar_helper.cpp b/radar/src/lite/dm_radar_helper.cpp index 2106be41e..df7c6d21b 100644 --- a/radar/src/lite/dm_radar_helper.cpp +++ b/radar/src/lite/dm_radar_helper.cpp @@ -134,7 +134,7 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, return; } -void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName) +void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) { return; } @@ -182,11 +182,11 @@ std::string DmRadarHelper::GetAnonyUdid(std::string udid) return udid.substr(0, SUBSTR_UDID_LENGTH) + "**" + udid.substr(udid.length() - SUBSTR_UDID_LENGTH); } -std::string DmRadarHelper::GetLocalUdid() +std::string DmRadarHelper::GetAnonyLocalUdid() { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - return std::string(localDeviceId); + return GetAnonyUdid(std::string(localDeviceId)); } int32_t DmRadarHelper::GetErrCode(int32_t errCode) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 90b893d64..053c3736b 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -279,13 +279,10 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st return ERR_DM_FAILED; } } - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); struct RadarInfo info = { .funcName = "UnAuthenticateDevice", .toCallPkg = HICHAINNAME, .hostName = pkgName, - .localUdid = localDeviceId, .peerUdid = udid, }; if (!DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info)) { @@ -665,8 +662,6 @@ void DmAuthManager::HandleAuthenticateTimeout(std::string name) int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) { int32_t sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); struct RadarInfo info = { .funcName = "EstablishAuthChannel", .stageRes = (sessionId > 0) ? @@ -677,8 +672,7 @@ int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) .peerSessName = DM_SESSION_NAME, .isTrust = static_cast(TrustStatus::NOT_TRUST), .commServ = static_cast(CommServ::USE_SOFTBUS), - .localUdid = localDeviceId, - .peerUdid = deviceId, + .peerUdid = peerTargetId_.deviceId, .channelId = sessionId, .errCode = sessionId, }; diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index fb44191f6..e762946e9 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -162,7 +162,6 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou static_cast(StageRes::STAGE_FAIL) : static_cast(StageRes::STAGE_IDLE), .bizState = (ret != 0) ? static_cast(BizState::BIZ_STATE_END) : static_cast(BizState::BIZ_STATE_START), - .localUdid = std::string(localDeviceId), .errCode = DmRadarHelper::GetInstance().GetErrCode(ERR_DM_CREATE_GROUP_FAILED), }; if (!DmRadarHelper::GetInstance().ReportAuthCreateGroup(info)) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 02f5af337..7ebcad06a 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -22,6 +22,7 @@ #include "dm_crypto.h" #include "dm_distributed_hardware_load.h" #include "dm_log.h" +#include "dm_radar_helper.h" #include "multiple_user_connector.h" #include "app_manager.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -310,6 +311,18 @@ std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string & int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) { + std::string peerUdid = ""; + softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); + struct RadarInfo info = { + .funcName = "OnSessionOpened", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .isTrust = static_cast(TrustStatus::NOT_TRUST), + .peerUdid = peerUdid, + .channelId = sessionId, + }; + if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) { + LOGE("ReportAuthSessionOpenCb failed"); + } return SoftbusSession::OnSessionOpened(sessionId, result); } diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index 206cdd991..b1aa7c149 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -21,7 +21,6 @@ #include "pin_holder_session.h" #include "pinholder_session_callback.h" -#include #include #include diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 853bf5092..2114f58dd 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -116,8 +116,8 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, sessionId_ = session_->OpenSessionServer(targetId); int32_t stageRes = sessionId_ > 0 ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); - DmRadarHelper::GetInstance().ReportCreatePinHolder(registerPkgName_, - sessionId_, targetId.deviceId, sessionId_, stageRes); + DmRadarHelper::GetInstance().ReportCreatePinHolder( + registerPkgName_, sessionId_, targetId.deviceId, sessionId_, stageRes); if (sessionId_ < 0) { LOGE("[SOFTBUS]open session error, sessionId: %{public}d.", sessionId_); listener_->OnCreateResult(registerPkgName_, sessionId_); @@ -204,7 +204,8 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() MSG_TYPE_CREATE_PIN_HOLDER, pinType_); int32_t ret = session_->SendData(sessionId_, message); int32_t bizStage = static_cast(PinHolderStage::SEND_CREATE_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("CreateGeneratePinHolderMsg")); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, + std::string("CreateGeneratePinHolderMsg"), ""); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); listener_->OnCreateResult(registerPkgName_, ret); @@ -248,7 +249,7 @@ void PinHolder::ProcessCreateMsg(const std::string &message) std::string payload = jsonObject[TAG_PAYLOAD].get(); isRemoteSupported_ = jsonObject.contains(TAG_DM_VERSION); int32_t bizStage = static_cast(PinHolderStage::RECEIVE_CREATE_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessCreateMsg")); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessCreateMsg"), ""); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; if (sinkState_ != SINK_INIT) { @@ -325,7 +326,7 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) DmPinType pinType = static_cast(jsonObject[TAG_PIN_TYPE].get()); std::string payload = jsonObject[TAG_PAYLOAD].get(); int32_t bizStage = static_cast(PinHolderStage::RECEIVE_DESTROY_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessDestroyMsg")); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, std::string("ProcessDestroyMsg"), ""); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; if (sinkState_ != SINK_CREATE) { @@ -461,6 +462,13 @@ void PinHolder::GetPeerDeviceId(int32_t sessionId, std::string &udidHash) void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { + char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; + int32_t ret = ::GetPeerDeviceId(sessionId, &peerDeviceId[0], DEVICE_UUID_LENGTH); + if (ret != DM_OK) { + LOGE("[SOFTBUS]GetPeerDeviceId failed for session: %{public}d.", sessionId); + } + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(static_cast(PinHolderStage::SESSION_OPENED), + std::string("OnSessionOpened"), std::string(peerDeviceId)); sessionId_ = sessionId; if (sessionSide == SESSION_SIDE_SERVER) { LOGI("[SOFTBUS]onSesssionOpened success, side is sink. sessionId: %{public}d.", sessionId); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a5c80d2f0..d87a67086 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -34,6 +34,7 @@ #endif #include "parameter.h" #include "system_ability_definition.h" +#include "softbus_adapter.cpp" namespace OHOS { namespace DistributedHardware { @@ -74,17 +75,6 @@ int32_t g_onlinDeviceNum = 0; static int OnSessionOpened(int sessionId, int result) { - struct RadarInfo info = { - .funcName = "OnSessionOpened", - .stageRes = static_cast(StageRes::STAGE_SUCC), - .isTrust = static_cast(TrustStatus::NOT_TRUST), - .channelId = sessionId, - }; - if (SoftbusListener::IsDmRadarHelperReady() && SoftbusListener::GetDmRadarHelperObj() != nullptr) { - if (!SoftbusListener::GetDmRadarHelperObj()->ReportAuthSessionOpenCb(info)) { - LOGE("ReportAuthSessionOpenCb failed"); - } - } return DeviceManagerService::GetInstance().OnSessionOpened(sessionId, result); } @@ -189,8 +179,6 @@ void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) deviceOnLine.detach(); #endif { - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string peerUdid; GetUdidByNetworkId(info->networkId, peerUdid); struct RadarInfo radarInfo = { @@ -199,7 +187,6 @@ void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) .bizState = static_cast(BizState::BIZ_STATE_START), .isTrust = static_cast(TrustStatus::IS_TRUST), .peerNetId = info->networkId, - .localUdid = std::string(localDeviceId), .peerUdid = peerUdid, }; if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { @@ -240,8 +227,6 @@ void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info) deviceOffLine.detach(); #endif { - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string peerUdid; GetUdidByNetworkId(info->networkId, peerUdid); struct RadarInfo radarInfo = { @@ -249,7 +234,6 @@ void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info) .stageRes = static_cast(StageRes::STAGE_SUCC), .bizState = static_cast(BizState::BIZ_STATE_END), .peerNetId = info->networkId, - .localUdid = std::string(localDeviceId), .peerUdid = peerUdid, }; if (IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { diff --git a/test/commonunittest/dm_radar_helper_test.cpp b/test/commonunittest/dm_radar_helper_test.cpp index 79596bd68..4be878cef 100644 --- a/test/commonunittest/dm_radar_helper_test.cpp +++ b/test/commonunittest/dm_radar_helper_test.cpp @@ -238,10 +238,10 @@ HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_001, testing::ext::TestSize DmRadarHelper::GetInstance().ReportDestroyPinHolder(str, str, 0, stageRes); int32_t bizStage = static_cast(PinHolderStage::RECEIVE_DESTROY_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str, ""); bizStage = static_cast(PinHolderStage::RECEIVE_CREATE_PIN_HOLDER_MSG); - DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str); + DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str, ""); EXPECT_EQ(res, true); } HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_002, testing::ext::TestSize.Level0) -- Gitee From 5b7b4198bb04a07eb433b8b7991a4b59ce3ab1f5 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 5 Sep 2024 11:55:09 +0800 Subject: [PATCH 159/520] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- services/implementation/src/authentication/dm_auth_manager.cpp | 2 ++ services/service/src/softbus/softbus_listener.cpp | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 053c3736b..067463558 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -279,6 +279,8 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st return ERR_DM_FAILED; } } + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); struct RadarInfo info = { .funcName = "UnAuthenticateDevice", .toCallPkg = HICHAINNAME, diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index d87a67086..926845e09 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -34,7 +34,6 @@ #endif #include "parameter.h" #include "system_ability_definition.h" -#include "softbus_adapter.cpp" namespace OHOS { namespace DistributedHardware { -- Gitee From f9d511fa6fe69f6f87a47ece56e7813297945abb Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 5 Sep 2024 19:44:48 +0800 Subject: [PATCH 160/520] =?UTF-8?q?ut=20=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- test/softbusunittest/UTTest_softbus_listener.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 15b00afc3..db63c88ec 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -466,7 +466,7 @@ HWTEST_F(SoftbusListenerTest, OnSessionClosed_001, testing::ext::TestSize.Level0 if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, OnBytesReceived_001, testing::ext::TestSize.Level0) @@ -477,7 +477,7 @@ HWTEST_F(SoftbusListenerTest, OnBytesReceived_001, testing::ext::TestSize.Level0 if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, OnPinHolderSessionOpened_001, testing::ext::TestSize.Level0) @@ -497,7 +497,7 @@ HWTEST_F(SoftbusListenerTest, OnPinHolderSessionClosed_001, testing::ext::TestSi if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, OnPinHolderBytesReceived_001, testing::ext::TestSize.Level0) @@ -508,7 +508,7 @@ HWTEST_F(SoftbusListenerTest, OnPinHolderBytesReceived_001, testing::ext::TestSi if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, GetTrustedDeviceList_001, testing::ext::TestSize.Level0) -- Gitee From 461e01a83b1d83eb933b226b7e54e991e7b3c281 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Thu, 5 Sep 2024 20:38:18 +0800 Subject: [PATCH 161/520] =?UTF-8?q?=E5=86=85=E5=AD=98=E6=B3=84=E9=9C=B2?= =?UTF-8?q?=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../src/dependency/hichain/hichain_auth_connector.cpp | 5 +++++ .../src/dependency/hichain/mine_hichain_connector.cpp | 3 +++ .../src/dependency/softbus/softbus_connector.cpp | 6 ++++++ 3 files changed, 14 insertions(+) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index c7887c985..f3f28c6fb 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -167,6 +167,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); + free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode generate return data jsonStr error."); return ERR_DM_FAILED; @@ -200,6 +201,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); + free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode query return data jsonStr error."); return false; @@ -231,6 +233,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); + free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode query return data jsonStr error."); return ERR_DM_FAILED; @@ -263,6 +266,7 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); + free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode import return data jsonStr error."); return ERR_DM_FAILED; @@ -294,6 +298,7 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); + free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode import return data jsonStr error."); return false; diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index 44e54a941..c5d37fd50 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -143,6 +143,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) LOGE("failed to delete hichain credential and group with ret:%{public}d.", retValue); return ERR_DM_FAILED; } + g_deviceGroupManager->destroyInfo(&returnInfo); #endif return DM_OK; } @@ -263,9 +264,11 @@ int MineHiChainConnector::ImportCredential(std::string reqJsonStr, std::string & } if (CreateGroup(reqJsonStr) != DM_OK) { DeleteCredentialAndGroup(); + g_deviceGroupManager->destroyInfo(&returnInfo); LOGE("fail to import hichain credential bacause create group unsuccessfully."); return ERR_DM_HICHAIN_GROUP_CREATE_FAILED; } + g_deviceGroupManager->destroyInfo(&returnInfo); #endif LOGI("import device credential info successfully."); return DM_OK; diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 89dae5299..3b9307bc6 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -639,9 +639,11 @@ std::string SoftbusConnector::GetNetworkIdByDeviceId(const std::string &deviceId LOGE("[SOFTBUS]GetNodeKeyInfo failed."); } if (reinterpret_cast(mUdid) == deviceId) { + FreeNodeInfo(nodeInfo); return static_cast(nodeBasicInfo->networkId); } } + FreeNodeInfo(nodeInfo); return ""; } @@ -714,10 +716,12 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) std::string udid = reinterpret_cast(mUdid); if (udid == targetDeviceId) { LOGI("The device is online."); + FreeNodeInfo(nodeInfo); return true; } } LOGI("The device is not online."); + FreeNodeInfo(nodeInfo); return false; } @@ -734,6 +738,7 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(deviceId, reinterpret_cast(deviceIdHash)) != DM_OK) { LOGE("get deviceIdHash by deviceId: %{public}s failed.", GetAnonyString(deviceId).c_str()); + FreeNodeInfo(nodeInfo); return info; } for (int32_t i = 0; i < deviceCount; ++i) { @@ -742,6 +747,7 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device if (GetNodeKeyInfo(DM_PKG_NAME, nodeBasicInfo->networkId, NodeDeviceInfoKey::NODE_KEY_UDID, mUdid, sizeof(mUdid)) != DM_OK) { LOGE("[SOFTBUS]GetNodeKeyInfo failed."); + FreeNodeInfo(nodeInfo); return info; } std::string udid = reinterpret_cast(mUdid); -- Gitee From 81c29fbc2f2839c278ea5cf9554daa06df099104 Mon Sep 17 00:00:00 2001 From: wangzhaohao Date: Thu, 5 Sep 2024 21:23:33 +0800 Subject: [PATCH 162/520] =?UTF-8?q?=E6=95=B4=E6=94=B9=E8=8E=B7=E5=8F=96app?= =?UTF-8?q?Id=E7=9A=84=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangzhaohao --- utils/BUILD.gn | 2 + utils/include/appInfo/standard/app_manager.h | 3 ++ utils/src/appInfo/standard/app_manager.cpp | 57 +++++++++++++++++--- 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 07fd22f58..18f3092b8 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -130,12 +130,14 @@ if (defined(ohos_lite)) { "ipc:ipc_core", "ipc:ipc_single", "openssl:libcrypto_shared", + "os_account:os_account_innerkits", "samgr:samgr_proxy", ] public_external_deps = [ "json:nlohmann_json_static", "kv_store:distributeddata_inner", + "bundle_framework:appexecfwk_core", ] if (support_jsapi) { diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 3671f0d74..ede8c28cf 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -19,7 +19,9 @@ #include #include #include +#include "bundle_mgr_interface.h" #include "dm_single_instance.h" +#include "event_handler.h" namespace OHOS { namespace DistributedHardware { @@ -32,6 +34,7 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); private: + bool GetBundleManagerProxy(sptr &bundleManager); std::mutex appIdMapLock_; std::map appIdMap_; }; diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 951e8e5ae..1b73092e7 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -19,7 +19,11 @@ #include "dm_constants.h" #include "dm_log.h" #include "accesstoken_kit.h" +#include "if_system_ability_manager.h" #include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "os_account_manager.h" +#include "system_ability_definition.h" using namespace OHOS::Security::AccessToken; @@ -32,16 +36,35 @@ const std::string AppManager::GetAppId() std::string appId = ""; AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) { - LOGE("The caller is not token_hap."); + LOGI("The caller is not token_hap."); return appId; } - HapTokenInfo tokenInfo; - int32_t result = AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); - if (result != RET_SUCCESS) { - LOGE("GetHapTokenInfo failed ret is %{public}d.", result); + sptr bundleManager = nullptr; + if (!GetBundleManagerProxy(bundleManager)) { + LOGE("get bundleManager failed."); return appId; } - appId = tokenInfo.appID; + if (bundleManager == nullptr) { + LOGE("bundleManager is nullptr."); + return appId; + } + int userId; + ErrCode result = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); + if (result != ERR_OK) { + LOGE("GetAppIdByCallingUid QueryActiveOsAccountIds failed."); + return appId; + } + std::string BundleName; + bundleManager->GetNameForUid(IPCSkeleton::GetCallingUid(), BundleName); + AppExecFwk::BundleInfo bundleInfo; + int ret = bundleManager->GetBundleInfoV9( + BundleName, static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO), + bundleInfo, userId); + if (ret != 0) { + LOGE(" GetBundleInfoV9 failed %{public}d.", ret); + return appId; + } + appId = bundleInfo.appId; return appId; } @@ -91,5 +114,27 @@ int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &a appId = appIdMap_[pkgName]; return DM_OK; } + +bool AppManager::GetBundleManagerProxy(sptr &bundleManager) +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + LOGE("GetBundleManagerProxy Failed to get system ability mgr."); + return false; + } + sptr remoteObject = + systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + LOGE("GetBundleManagerProxy Failed to get bundle manager service."); + return false; + } + bundleManager = iface_cast(remoteObject); + if (bundleManager == nullptr) { + LOGE("bundleManager is nullptr"); + return false; + } + return true; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 312ccd0531892f10e149fcefee5aa875ead7fccd Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Thu, 5 Sep 2024 21:31:11 +0800 Subject: [PATCH 163/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- services/service/src/ipc/standard/ipc_cmd_parser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 879035341..15edf7343 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1465,7 +1465,7 @@ ON_IPC_SET_REQUEST(REMOTE_DEVICE_TRUST_CHANGE, std::shared_ptr pBaseReq, return ERR_DM_FAILED; } std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = data.ReadString(); + std::string pkgName = pReq->GetPkgName(); std::string deviceId = pReq->GetDeviceId(); int32_t authForm = pReq->GetAuthForm(); if (!data.WriteString(pkgName)) { -- Gitee From 7731f73d7773251dbfff95b50cc3b43593c948f4 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Thu, 5 Sep 2024 21:41:46 +0800 Subject: [PATCH 164/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- services/service/src/device_manager_service.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f034ee48a..fa51f7f7f 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1849,7 +1849,6 @@ void DeviceManagerService::SendServiceUnBindBroadCast(const std::vector Date: Thu, 5 Sep 2024 21:53:23 +0800 Subject: [PATCH 165/520] fix codecheck Signed-off-by: wangzhaohao --- utils/BUILD.gn | 2 +- utils/src/appInfo/standard/app_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 18f3092b8..746380f8d 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -135,9 +135,9 @@ if (defined(ohos_lite)) { ] public_external_deps = [ + "bundle_framework:appexecfwk_core", "json:nlohmann_json_static", "kv_store:distributeddata_inner", - "bundle_framework:appexecfwk_core", ] if (support_jsapi) { diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 1b73092e7..a745954ba 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -117,7 +117,7 @@ int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &a bool AppManager::GetBundleManagerProxy(sptr &bundleManager) { - sptr systemAbilityManager = + sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemAbilityManager == nullptr) { LOGE("GetBundleManagerProxy Failed to get system ability mgr."); -- Gitee From a76b888f5c651e959e23a425930da953067303c4 Mon Sep 17 00:00:00 2001 From: wangzhaohao Date: Fri, 6 Sep 2024 10:42:47 +0800 Subject: [PATCH 166/520] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangzhaohao --- services/service/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index ef19386c7..12b52c98e 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -198,6 +198,7 @@ if (defined(ohos_lite)) { "ability_base:want", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_core", -- Gitee From 11a388d81701139874381d7e2615c54ee5f9518c Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Fri, 6 Sep 2024 10:53:26 +0800 Subject: [PATCH 167/520] =?UTF-8?q?=E5=86=85=E5=AD=98=E6=B3=84=E6=BC=8F?= =?UTF-8?q?=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../src/dependency/hichain/hichain_auth_connector.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index f3f28c6fb..c7887c985 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -167,7 +167,6 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); - free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode generate return data jsonStr error."); return ERR_DM_FAILED; @@ -201,7 +200,6 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); - free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode query return data jsonStr error."); return false; @@ -233,7 +231,6 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); - free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode query return data jsonStr error."); return ERR_DM_FAILED; @@ -266,7 +263,6 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); - free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode import return data jsonStr error."); return ERR_DM_FAILED; @@ -298,7 +294,6 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 } std::string returnDataStr = static_cast(returnData); nlohmann::json jsonObject = nlohmann::json::parse(returnDataStr, nullptr, false); - free(returnData); if (jsonObject.is_discarded()) { LOGE("Decode import return data jsonStr error."); return false; -- Gitee From f0183ce904b85e079518af4f964c6a24e1b92893 Mon Sep 17 00:00:00 2001 From: wangzhaohao Date: Fri, 6 Sep 2024 16:29:32 +0800 Subject: [PATCH 168/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wangzhaohao --- utils/include/appInfo/standard/app_manager.h | 4 +++- utils/src/appInfo/standard/app_manager.cpp | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index ede8c28cf..2ee9069b7 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -19,10 +19,12 @@ #include #include #include + #include "bundle_mgr_interface.h" -#include "dm_single_instance.h" #include "event_handler.h" +#include "dm_single_instance.h" + namespace OHOS { namespace DistributedHardware { class AppManager { diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index a745954ba..0d6eddab4 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -15,9 +15,6 @@ #include "app_manager.h" -#include "dm_anonymous.h" -#include "dm_constants.h" -#include "dm_log.h" #include "accesstoken_kit.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" @@ -25,6 +22,10 @@ #include "os_account_manager.h" #include "system_ability_definition.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + using namespace OHOS::Security::AccessToken; namespace OHOS { -- Gitee From ce35b6f1ab97cdc607c9775b5ce6ef0954aada78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 7 Sep 2024 11:28:00 +0800 Subject: [PATCH 169/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/src/notify/device_manager_notify.cpp | 2 -- .../src/publishcommonevent/dm_account_common_event.cpp | 2 ++ .../src/publishcommonevent/dm_publish_common_event.cpp | 2 ++ .../src/publishcommonevent/dm_screen_common_event.cpp | 2 ++ services/service/src/softbus/softbus_listener.cpp | 5 +++-- 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index b6ed28fd1..cec26a318 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 @@ -30,8 +30,6 @@ constexpr const char* DEVICE_OFFLINE = "deviceOffline"; constexpr const char* DEVICEINFO_CHANGE = "deviceInfoChange"; constexpr const char* DEVICE_READY = "deviceReady"; constexpr const char* DEVICE_TRUST_CHANGE = "deviceTrustChange"; -#else -constexpr const char* DEVICE_STATE_INIT_QUEUE = "deviceStateInitQueue"; #endif void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 6d547b74f..50ca53d73 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -34,7 +34,9 @@ namespace DistributedHardware { using OHOS::EventFwk::MatchingSkills; using OHOS::EventFwk::CommonEventManager; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEAL_THREAD = "account_common_event"; +#endif constexpr int32_t MAX_TRY_TIMES = 3; std::vector DmAccountEventSubscriber::GetSubscriberEventNameVec() const diff --git a/services/service/src/publishcommonevent/dm_publish_common_event.cpp b/services/service/src/publishcommonevent/dm_publish_common_event.cpp index 33042506c..4c9af611d 100644 --- a/services/service/src/publishcommonevent/dm_publish_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_publish_common_event.cpp @@ -36,7 +36,9 @@ namespace DistributedHardware { using OHOS::EventFwk::MatchingSkills; using OHOS::EventFwk::CommonEventManager; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEAL_THREAD = "publish_common_event"; +#endif constexpr int32_t MAX_TRY_TIMES = 3; std::vector DmPublishEventSubscriber::GetSubscriberEventNameVec() const diff --git a/services/service/src/publishcommonevent/dm_screen_common_event.cpp b/services/service/src/publishcommonevent/dm_screen_common_event.cpp index e506e3370..943cbcffd 100644 --- a/services/service/src/publishcommonevent/dm_screen_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_screen_common_event.cpp @@ -34,7 +34,9 @@ namespace DistributedHardware { using OHOS::EventFwk::MatchingSkills; using OHOS::EventFwk::CommonEventManager; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEAL_THREAD = "screen_lock"; +#endif constexpr int32_t MAX_TRY_TIMES = 3; std::vector DmScreenEventSubscriber::GetSubscriberEventNameVec() const diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 6778632c6..c056e1442 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -42,12 +42,13 @@ const int32_t SOFTBUS_CHECK_INTERVAL = 100000; // 100ms const int32_t SOFTBUS_SUBSCRIBE_ID_MASK = 0x0000FFFF; const int32_t MAX_CACHED_DISCOVERED_DEVICE_SIZE = 100; const int32_t MAX_SOFTBUS_MSG_LEN = 2000; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEVICE_ONLINE = "deviceOnLine"; constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; -constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; -constexpr const char* DEVICE_TRUSTED_CHANGE = "deviceTrustedChange"; +#endif +constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; constexpr static uint8_t BYTE_MASK = 0x0F; constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2; -- Gitee From 428c0dfde3060b3facf7648f0eb09df58ff20021 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 7 Sep 2024 18:35:28 +0800 Subject: [PATCH 170/520] =?UTF-8?q?UT=E8=A1=A5=E5=85=852?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/BUILD.gn | 12 ++++ test/unittest/UTTest_dm_service_load.cpp | 65 +++++++++++++++++ test/unittest/UTTest_dm_service_load.h | 42 +++++++++++ .../unittest/UTTest_ipc_cmd_parser_client.cpp | 72 +++++++++++++++++++ 4 files changed, 191 insertions(+) create mode 100644 test/unittest/UTTest_dm_service_load.cpp create mode 100644 test/unittest/UTTest_dm_service_load.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 17d890776..d306aef99 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -48,6 +48,7 @@ group("unittest") { ":UTTest_dm_publish_manager", ":UTTest_dm_radar_helper_test", ":UTTest_dm_timer", + ":UTTest_dm_service_load", ":UTTest_hichain_auth_connector", ":UTTest_hichain_connector", ":UTTest_ipc_client_manager", @@ -585,6 +586,17 @@ ohos_unittest("UTTest_dm_timer") { ## UnitTest UTTest_dm_timer }}} +## UnitTest UTTest_dm_service_load {{{ +ohos_unittest("UTTest_dm_service_load") { + module_out_path = module_out_path + + sources = [ "UTTest_dm_service_load.cpp" ] + + deps = [ ":device_manager_test_common" ] +} + +## UnitTest UTTest_dm_service_load }}} + ## UnitTest UTTest_ipc_client_manager {{{ ohos_unittest("UTTest_ipc_client_manager") { module_out_path = module_out_path diff --git a/test/unittest/UTTest_dm_service_load.cpp b/test/unittest/UTTest_dm_service_load.cpp new file mode 100644 index 000000000..8bc760ed4 --- /dev/null +++ b/test/unittest/UTTest_dm_service_load.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_service_load.h" + +#include + +#include "dm_constants.h" +#include "dm_service_load.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +void DmServiceLoadTest::SetUp() +{ +} + +void DmServiceLoadTest::TearDown() +{ +} + +void DmServiceLoadTest::SetUpTestCase() +{ +} + +void DmServiceLoadTest::TearDownTestCase() +{ +} + +namespace { +HWTEST_F(DmServiceLoadTest, LoadDMService_001, testing::ext::TestSize.Level0) +{ + int32_t ret = DmServiceLoad::GetInstance().LoadDMService(); + ASSERT_EQ(ret, DM_OK); + ret = DmServiceLoad::GetInstance().LoadDMService(); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmServiceLoadTest, SetLoadFinish_001, testing::ext::TestSize.Level0) +{ + DmServiceLoad::GetInstance().SetLoadFinish(); + int32_t systemAbilityId = 1000; + sptr remoteObject = nullptr; + DMLoadCallbackTest dmLoadCallback; + dmLoadCallback.OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject); + dmLoadCallback.OnLoadSystemAbilityFail(systemAbilityId); + ASSERT_EQ(DmServiceLoad::GetInstance().isDMServiceLoading_, false); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_service_load.h b/test/unittest/UTTest_dm_service_load.h new file mode 100644 index 000000000..8787b50dc --- /dev/null +++ b/test/unittest/UTTest_dm_service_load.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SERVICE_LOAD_TEST_H +#define OHOS_DM_SERVICE_LOAD_TEST_H + +#include +#include + +#include "dm_service_load.h" + +namespace OHOS { +namespace DistributedHardware { +class DmServiceLoadTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +class DMLoadCallbackTest : public DMLoadCallback { +public: + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const sptr &remoteObject) {} + void OnLoadSystemAbilityFail(int32_t systemAbilityId) {} +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_SERVICE_LOAD_TEST_H diff --git a/test/unittest/UTTest_ipc_cmd_parser_client.cpp b/test/unittest/UTTest_ipc_cmd_parser_client.cpp index 4101bb690..e4bb68919 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_client.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_client.cpp @@ -280,6 +280,42 @@ HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_028, testing::ext::TestSize.Le ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); } +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_029, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SET_DN_POLICY; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_030, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SET_DN_POLICY; + ASSERT_EQ(TestReadResponseRspNotNull(cmdCode), DM_OK); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_031, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SHIFT_LNN_GEAR; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_032, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_SAME_ACCOUNT; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_033, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_ACCESS_CONTROL; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + +HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_034, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = CHECK_API_PERMISSION; + ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); +} + HWTEST_F(IpcCmdParserClientTest, SetIpcRequestFunc_002, testing::ext::TestSize.Level0) { int32_t cmdCode = GET_NETWORKTYPE_BY_NETWORK; @@ -505,6 +541,23 @@ HWTEST_F(IpcCmdParserClientTest, SetIpcRequestFunc_014, testing::ext::TestSize.L ASSERT_EQ(DM_OK, ret); } +HWTEST_F(IpcCmdParserClientTest, SetIpcRequestFunc_015, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SET_DN_POLICY; + MessageParcel data; + std::shared_ptr req = std::make_shared(); + std::string pkgName = "ohos.dm.test"; + std::string policy = "DM_POLICY_STRATEGY_FOR_BLE:100"; + req->SetPkgName(pkgName); + req->SetFirstParam(policy); + int ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(DM_OK, ret); +} + HWTEST_F(IpcCmdParserClientTest, OnIpcCmdFunc_001, testing::ext::TestSize.Level0) { int32_t cmdCode = SERVER_DEVICE_DISCOVERY; @@ -663,6 +716,25 @@ HWTEST_F(IpcCmdParserClientTest, OnIpcCmdFunc_008, testing::ext::TestSize.Level0 } ASSERT_EQ(ret, DM_OK); } + +HWTEST_F(IpcCmdParserClientTest, OnIpcCmdFunc_009, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = REMOTE_DEVICE_TRUST_CHANGE; + int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; + MessageParcel data; + MessageParcel reply; + std::string pkgName = "ohos.dm.test"; + std::string deviceId = "xxx"; + int32_t authForm = 1; + data.WriteString(pkgName); + data.WriteString(deviceId); + data.WriteInt32(authForm); + OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); + if (ptr) { + ret = ptr(data, reply); + } + ASSERT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 4115aec0d1a809d3ef016a80d44274c4139340ab Mon Sep 17 00:00:00 2001 From: pwx1285814 Date: Sat, 7 Sep 2024 18:37:17 +0800 Subject: [PATCH 171/520] =?UTF-8?q?=E8=A1=A5=E5=85=85services/implementati?= =?UTF-8?q?on/src/authentication/dm=5Fauth=5Fmanager.cpp=20UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: pwx1285814 Change-Id: Iebbfa0cb81ccba316779ff2b624ba19d9e2dd39a --- .../UTTest_dm_auth_manager_first.cpp | 321 ++++++++++++++---- .../UTTest_dm_auth_manager_first.h | 10 + .../UTTest_dm_auth_manager_second.cpp | 212 +++++------- .../UTTest_dm_auth_manager_second.h | 28 +- test/unittest/BUILD.gn | 1 + 5 files changed, 377 insertions(+), 195 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 0aa9a9879..57f0ca81b 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -15,20 +15,33 @@ #include "UTTest_dm_auth_manager_first.h" -#include "nlohmann/json.hpp" - #include "auth_message_processor.h" #include "common_event_support.h" #include "device_manager_service_listener.h" #include "dm_auth_manager.h" #include "dm_constants.h" #include "dm_log.h" +#include "dm_radar_helper.h" +#include "nlohmann/json.hpp" #include "softbus_error_code.h" +static bool g_reportAuthOpenSessionReturnBoolValue = false; +static bool g_reportAuthConfirmBoxReturnBoolValue = false; + namespace OHOS { namespace DistributedHardware { const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; +bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) +{ + return g_reportAuthOpenSessionReturnBoolValue; +} + +bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) +{ + return g_reportAuthConfirmBoxReturnBoolValue; +} + class SoftbusStateCallbackTest : public ISoftbusStateCallback { public: SoftbusStateCallbackTest() {} @@ -91,39 +104,96 @@ HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_003, testing::ext::TestSiz ASSERT_TRUE(authManager_->authRequestState_ != nullptr); } +HWTEST_F(DmAuthManagerTest, HandleAuthenticateTimeout_004, testing::ext::TestSize.Level0) +{ + std::string name = "test"; + authManager_->authRequestContext_->reason = DM_OK; + std::shared_ptr requestInitState = std::make_shared(); + EXPECT_CALL(*requestInitState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE)); + authManager_->authRequestState_ = requestInitState; + authManager_->HandleAuthenticateTimeout(name); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_TIME_OUT); + + std::shared_ptr authResponseInitState = std::make_shared(); + EXPECT_CALL(*authResponseInitState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); + authManager_->authResponseState_ = authResponseInitState; + authManager_->HandleAuthenticateTimeout(name); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_TIME_OUT); + + authManager_->authResponseState_ = nullptr; + authManager_->HandleAuthenticateTimeout(name); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_TIME_OUT); +} + HWTEST_F(DmAuthManagerTest, EstablishAuthChannel_001, testing::ext::TestSize.Level0) { - std::shared_ptr sessionSession = std::shared_ptr(); - std::shared_ptr authRequestContext = std::make_shared(); std::string deviceId1; authManager_->AbilityNegotiate(); + g_reportAuthOpenSessionReturnBoolValue = false; int32_t ret = authManager_->EstablishAuthChannel(deviceId1); ASSERT_EQ(ret, DM_OK); } +HWTEST_F(DmAuthManagerTest, EstablishAuthChannel_002, testing::ext::TestSize.Level0) +{ + std::string deviceId; + authManager_->authResponseContext_ = nullptr; + authManager_->authRequestContext_ = nullptr; + authManager_->authRequestState_ = nullptr; + g_reportAuthOpenSessionReturnBoolValue = true; + int32_t ret = authManager_->EstablishAuthChannel(deviceId); + g_reportAuthOpenSessionReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + HWTEST_F(DmAuthManagerTest, StartAuthProcess_001, testing::ext::TestSize.Level0) { std::shared_ptr authResponseState = std::make_shared(); authManager_->SetAuthResponseState(authResponseState); int32_t action = 0; - authManager_->StartAuthProcess(action); - bool ret = authManager_->authRequestContext_->deviceName.empty(); - ASSERT_EQ(ret, true); + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = DEVICE; + int32_t ret = authManager_->StartAuthProcess(action); + ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, StartAuthProcess_002, testing::ext::TestSize.Level0) { - std::shared_ptr authResponseState = std::make_shared(); - authManager_->authResponseState_ = std::make_shared(); + std::shared_ptr authResponseState = std::make_shared(); authManager_->SetAuthResponseState(authResponseState); - authManager_->authResponseContext_->sessionId = 111; - authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authManager_); - int32_t action = 1; + int32_t action = 0; + g_reportAuthConfirmBoxReturnBoolValue = true; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = APP + 1; int32_t ret = authManager_->StartAuthProcess(action); + g_reportAuthConfirmBoxReturnBoolValue = false; ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, StartAuthProcess_003, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = std::make_shared(); + authManager_->SetAuthResponseState(authResponseState); + int32_t action = 0; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; + int32_t ret = authManager_->StartAuthProcess(action); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, StartAuthProcess_004, testing::ext::TestSize.Level0) +{ + std::shared_ptr authResponseState = std::make_shared(); + authManager_->SetAuthResponseState(authResponseState); + int32_t action = 0; + authManager_->remoteVersion_ = "4.1.5.0"; + int32_t ret = authManager_->StartAuthProcess(action); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, StartAuthProcess_005, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; int32_t action = 1; @@ -428,6 +498,52 @@ HWTEST_F(DmAuthManagerTest, AuthenticateDevice_003, testing::ext::TestSize.Level ASSERT_EQ(ret, DM_OK); } +HWTEST_F(DmAuthManagerTest, UnAuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "UnAuthenticateDevice_001"; + int32_t bindLevel = DEVICE; + int32_t ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + pkgName = "com.ohos.test"; + authManager_->isAuthenticateDevice_ = false; + ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + authManager_->authRequestState_ = nullptr; + authManager_->authResponseContext_ = nullptr; + ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + bindLevel = 0; + ret = authManager_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, UnBindDevice_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "UnAuthenticateDevice_001"; + int32_t bindLevel = DEVICE; + int32_t ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + pkgName = "com.ohos.test"; + authManager_->isAuthenticateDevice_ = false; + ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + authManager_->authRequestState_ = nullptr; + authManager_->authResponseContext_ = nullptr; + ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); + + bindLevel = 0; + ret = authManager_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, DM_OK); +} + HWTEST_F(DmAuthManagerTest, GenerateGroupName_001, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; @@ -476,6 +592,38 @@ HWTEST_F(DmAuthManagerTest, GetIsCryptoSupport_003, testing::ext::TestSize.Level ASSERT_EQ(ret, false); } +HWTEST_F(DmAuthManagerTest, GetIsCryptoSupport_004, testing::ext::TestSize.Level0) +{ + authManager_->isCryptoSupport_ = true; + authManager_->authRequestState_ = nullptr; + std::shared_ptr authResponseInitState = std::make_shared(); + EXPECT_CALL(*authResponseInitState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); + authManager_->authResponseState_ = authResponseInitState; + bool ret = authManager_->GetIsCryptoSupport(); + ASSERT_TRUE(ret); + + EXPECT_CALL(*authResponseInitState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE_DONE)); + ret = authManager_->GetIsCryptoSupport(); + ASSERT_FALSE(ret); + + std::shared_ptr requestFinishState = std::make_shared(); + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE)); + authManager_->authRequestState_ = requestFinishState; + ret = authManager_->GetIsCryptoSupport(); + ASSERT_FALSE(ret); + + EXPECT_CALL(*requestFinishState, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE_DONE)); + ret = authManager_->GetIsCryptoSupport(); + ASSERT_FALSE(ret); + + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_INIT)); + ret = authManager_->GetIsCryptoSupport(); + ASSERT_TRUE(ret); +} + HWTEST_F(DmAuthManagerTest, OnUserOperation_001, testing::ext::TestSize.Level0) { int32_t action = 0; @@ -620,68 +768,68 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceTransmit004, testing::ext::TestSize.Level0 HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish001, testing::ext::TestSize.Level0) { - authManager_->authRequestState_ = std::make_shared(); - authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} - -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish002, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); + authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->confirmOperation = 0; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH; authManager_->authResponseContext_->haveCredential = true; - authManager_->authResponseContext_->bindLevel = 3; + authManager_->authResponseContext_->bindLevel = APP; authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish003, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->confirmOperation = 6; - authManager_->authResponseContext_->haveCredential = true; - authManager_->authResponseContext_->bindLevel = 3; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + authManager_->authResponseContext_->hostPkgName = ""; authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + + authManager_->authResponseContext_->bindLevel = SERVICE; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish004, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->confirmOperation = 6; authManager_->authResponseContext_->haveCredential = false; - authManager_->authResponseContext_->bindLevel = 3; + authManager_->authResponseContext_->bindLevel = APP; authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + + authManager_->authResponseContext_->hostPkgName = ""; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + + authManager_->authResponseContext_->bindLevel = SERVICE; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + authManager_->SrcAuthDeviceFinish(); + EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); } -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish005, testing::ext::TestSize.Level0) +HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish002, testing::ext::TestSize.Level0) { - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authUiStateMgr_ = std::make_shared(listener); + authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH; authManager_->authResponseContext_->haveCredential = true; + authManager_->authResponseContext_->bindLevel = APP; + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); -} + EXPECT_EQ(authManager_->authRequestContext_->reason, DM_OK); -HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish006, testing::ext::TestSize.Level0) -{ - authManager_->authRequestState_ = std::make_shared(); - authManager_->softbusConnector_->RegisterSoftbusStateCallback(std::make_shared()); - authManager_->authResponseContext_->isOnline = false; + authManager_->authRequestContext_->reason = ERR_DM_FAILED; authManager_->authResponseContext_->haveCredential = false; authManager_->SrcAuthDeviceFinish(); - ASSERT_EQ(authManager_->isAuthDevice_, false); + EXPECT_EQ(authManager_->authRequestContext_->reason, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, SinkAuthDeviceFinish001, testing::ext::TestSize.Level0) @@ -728,7 +876,6 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceFinish003, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, AuthDeviceError001, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = nullptr; - authManager_->authResponseState_ = std::make_shared(); int64_t requestId = 0; int32_t errorCode = -1; authManager_->AuthDeviceError(requestId, errorCode); @@ -738,7 +885,7 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceError001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, AuthDeviceError002, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = std::make_shared(); - authManager_->authResponseState_ = nullptr; + authManager_->authResponseState_ = std::make_shared(); authManager_->authResponseContext_->authType = 5; int64_t requestId = 0; int32_t errorCode = -1; @@ -750,7 +897,7 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceError003, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = std::make_shared(); authManager_->authResponseState_ = nullptr; - authManager_->authResponseContext_->authType = 6; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->authResponseContext_->requestId = 2; int64_t requestId = 0; int32_t errorCode = -1; @@ -758,6 +905,47 @@ HWTEST_F(DmAuthManagerTest, AuthDeviceError003, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isAuthDevice_, false); } +HWTEST_F(DmAuthManagerTest, AuthDeviceError004, testing::ext::TestSize.Level0) +{ + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->requestId = 3; + authManager_->authTimes_ = 3; + int64_t requestId = 0; + int32_t errorCode = ERR_DM_FAILED; + authManager_->AuthDeviceError(requestId, errorCode); + ASSERT_EQ(authManager_->authResponseContext_->state, AuthState::AUTH_REQUEST_JOIN); +} + +HWTEST_F(DmAuthManagerTest, AuthDeviceError005, testing::ext::TestSize.Level0) +{ + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->requestId = 3; + authManager_->authTimes_ = 0; + int64_t requestId = authManager_->authResponseContext_->requestId + 1; + int32_t errorCode = DM_OK; + uint32_t sessionKeyLen = 0; + authManager_->AuthDeviceError(requestId, errorCode); + authManager_->AuthDeviceSessionKey(requestId, nullptr, sessionKeyLen); + ASSERT_EQ(authManager_->isAuthDevice_, false); +} + +HWTEST_F(DmAuthManagerTest, AuthDeviceError006, testing::ext::TestSize.Level0) +{ + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseState_ = nullptr; + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->requestId = 3; + authManager_->authTimes_ = 0; + int64_t requestId = authManager_->authResponseContext_->requestId; + int32_t errorCode = DM_OK; + authManager_->AuthDeviceError(requestId, errorCode); + ASSERT_EQ(authManager_->isAuthDevice_, false); +} + HWTEST_F(DmAuthManagerTest, AuthDeviceSessionKey001, testing::ext::TestSize.Level0) { authManager_->authRequestState_ = std::make_shared(); @@ -782,6 +970,20 @@ HWTEST_F(DmAuthManagerTest, CompatiblePutAcl001, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isAuthDevice_, false); } +HWTEST_F(DmAuthManagerTest, CompatiblePutAcl002, testing::ext::TestSize.Level0) +{ + authManager_->action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + authManager_->CompatiblePutAcl(); + ASSERT_EQ(authManager_->isAuthDevice_, false); +} + +HWTEST_F(DmAuthManagerTest, CompatiblePutAcl003, testing::ext::TestSize.Level0) +{ + authManager_->action_ = USER_OPERATION_TYPE_ALLOW_AUTH; + authManager_->CompatiblePutAcl(); + ASSERT_EQ(authManager_->isAuthDevice_, false); +} + HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt001, testing::ext::TestSize.Level0) { int32_t sessionId = 0; @@ -837,8 +1039,7 @@ HWTEST_F(DmAuthManagerTest, OnScreenLocked001, testing::ext::TestSize.Level0) .WillRepeatedly(testing::Return(AuthState::AUTH_REQUEST_NEGOTIATE_DONE)); authManager_->OnScreenLocked(); - EXPECT_CALL(*requestFinishState, GetStateType()) - .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); + EXPECT_CALL(*requestFinishState, GetStateType()).WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_FINISH)); authManager_->OnScreenLocked(); EXPECT_EQ(authManager_->authResponseContext_->state, STATUS_DM_AUTH_DEFAULT); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.h b/test/commonunittest/UTTest_dm_auth_manager_first.h index 2a8620a40..7963c5dd7 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.h +++ b/test/commonunittest/UTTest_dm_auth_manager_first.h @@ -56,6 +56,16 @@ class AuthRequestFinishStateMock : public AuthRequestFinishState { public: MOCK_METHOD(int32_t, GetStateType, (), (override)); }; + +class AuthRequestInitStateMock : public AuthRequestInitState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); +}; + +class AuthResponseInitStateMock : public AuthResponseInitState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); +}; } // namespace DistributedHardware } // namespace OHOS #endif diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 47341d14f..3342521d6 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -15,20 +15,25 @@ #include "UTTest_dm_auth_manager_second.h" -#include "nlohmann/json.hpp" - -#include "dm_log.h" -#include "dm_crypto.h" -#include "dm_constants.h" -#include "dm_auth_manager.h" #include "auth_message_processor.h" #include "device_manager_service_listener.h" +#include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "nlohmann/json.hpp" #include "softbus_error_code.h" namespace OHOS { namespace DistributedHardware { void DmAuthManagerTest::SetUp() { + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainConnector = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); authManager_->authMessageProcessor_ = std::make_shared(authManager_); authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); authManager_->authRequestContext_ = std::make_shared(); @@ -37,19 +42,16 @@ void DmAuthManagerTest::SetUp() authManager_->authResponseState_ = std::make_shared(); authManager_->hiChainAuthConnector_ = std::make_shared(); authManager_->softbusConnector_ = std::make_shared(); - authManager_->softbusConnector_->GetSoftbusSession()-> - RegisterSessionCallback(std::shared_ptr(authManager_)); + authManager_->softbusConnector_->GetSoftbusSession()->RegisterSessionCallback( + std::shared_ptr(authManager_)); authManager_->timer_ = std::make_shared(); } void DmAuthManagerTest::TearDown() { + authManager_ = nullptr; } -void DmAuthManagerTest::SetUpTestCase() -{ -} -void DmAuthManagerTest::TearDownTestCase() -{ -} +void DmAuthManagerTest::SetUpTestCase() {} +void DmAuthManagerTest::TearDownTestCase() {} namespace { HWTEST_F(DmAuthManagerTest, OnDataReceived_001, testing::ext::TestSize.Level0) @@ -210,6 +212,33 @@ HWTEST_F(DmAuthManagerTest, OnMemberJoin_008, testing::ext::TestSize.Level0) ASSERT_EQ(authManager_->isFinishOfLocal_, true); } +HWTEST_F(DmAuthManagerTest, OnMemberJoin_009, testing::ext::TestSize.Level0) +{ + int64_t requestId = 0; + int32_t status = DM_OK; + authManager_->authRequestState_ = nullptr; + authManager_->authTimes_ = 1; + std::shared_ptr authResponseInitStateMock = + std::make_shared(); + EXPECT_CALL(*authResponseInitStateMock, GetStateType()) + .WillRepeatedly(testing::Return(AuthState::AUTH_RESPONSE_CREDENTIAL)); + authManager_->authResponseState_ = authResponseInitStateMock; + authManager_->authResponseContext_->isFinish = true; + authManager_->authResponseContext_->requestId = 0; + authManager_->OnMemberJoin(requestId, status); + ASSERT_TRUE(authManager_->authResponseContext_->isFinish); + + authManager_->authResponseContext_->isFinish = true; + authManager_->authResponseContext_->requestId = 1; + authManager_->OnMemberJoin(requestId, status); + ASSERT_FALSE(authManager_->authResponseContext_->isFinish); + + authManager_->authResponseContext_->isFinish = true; + status = ERR_DM_FAILED; + authManager_->OnMemberJoin(requestId, status); + ASSERT_FALSE(authManager_->authResponseContext_->isFinish); +} + HWTEST_F(DmAuthManagerTest, HandleMemberJoinImportAuthCode_001, testing::ext::TestSize.Level0) { int64_t requestId = 1; @@ -504,8 +533,8 @@ HWTEST_F(DmAuthManagerTest, GetConnectAddr_002, testing::ext::TestSize.Level0) std::string deviceId = "deviceId"; std::shared_ptr infoPtr = std::make_shared(); infoPtr->addrNum = 1; - authManager_->softbusConnector_->discoveryDeviceInfoMap_.insert(std::pair>(deviceId, infoPtr)); + authManager_->softbusConnector_->discoveryDeviceInfoMap_.insert( + std::pair>(deviceId, infoPtr)); auto ret = authManager_->GetConnectAddr(deviceId); ASSERT_EQ(ret.empty(), false); } @@ -675,7 +704,7 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_001, testing::ext::TestSize.Leve HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_002, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->authType = 5; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->importAuthCode_ = ""; authManager_->importPkgName_ = ""; authManager_->ShowStartAuthDialog(); @@ -684,7 +713,7 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_002, testing::ext::TestSize.Leve HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_003, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->authType = 5; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->importAuthCode_ = "123456"; authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; @@ -696,23 +725,29 @@ HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_003, testing::ext::TestSize.Leve HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog_004, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->authType = 5; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->importAuthCode_ = "123456"; authManager_->importPkgName_ = "hostPkgName"; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; - authManager_->authResponseContext_->dmVersion = ""; - authManager_->authResponseContext_->bindLevel = 0; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; authManager_->ShowStartAuthDialog(); - authManager_->authResponseContext_->dmVersion = "5.0.1"; - authManager_->authResponseContext_->bindLevel = 0; + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = APP + 1; authManager_->ShowStartAuthDialog(); - authManager_->authResponseContext_->dmVersion = ""; - authManager_->authResponseContext_->bindLevel = 1; + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; authManager_->ShowStartAuthDialog(); - authManager_->authResponseContext_->dmVersion = "5.0.1"; - authManager_->authResponseContext_->bindLevel = 1; + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); + + authManager_->remoteVersion_ = "4.1.5.0"; authManager_->ShowStartAuthDialog(); - ASSERT_EQ(authManager_->authResponseContext_->bindLevel, 1); + EXPECT_NE(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); } HWTEST_F(DmAuthManagerTest, ProcessPincode_001, testing::ext::TestSize.Level0) @@ -735,24 +770,31 @@ HWTEST_F(DmAuthManagerTest, ProcessPincode_002, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, ProcessPincode_003, testing::ext::TestSize.Level0) { - int32_t pinCode = 123456; - authManager_->authResponseContext_->dmVersion = ""; - authManager_->authResponseContext_->bindLevel = 0; + int32_t pinCode = -1; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->authUiStateMgr_ = nullptr; + authManager_->importAuthCode_ = "123456"; + authManager_->importPkgName_ = "hostPkgName"; + authManager_->authResponseContext_->hostPkgName = "hostPkgName"; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = DEVICE; + authManager_->authResponseContext_->targetDeviceName = "ShowStartAuthDialog_004"; int32_t ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, ERR_DM_FAILED); - authManager_->authResponseContext_->dmVersion = "5.0.1"; - authManager_->authResponseContext_->bindLevel = 0; + EXPECT_NE(ret, DM_OK); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = APP + 1; ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, ERR_DM_FAILED); - authManager_->authResponseContext_->dmVersion = ""; - authManager_->authResponseContext_->bindLevel = 1; + EXPECT_NE(ret, DM_OK); + + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, ERR_DM_FAILED); - authManager_->authResponseContext_->dmVersion = "5.0.1"; - authManager_->authResponseContext_->bindLevel = 1; + EXPECT_NE(ret, DM_OK); + + authManager_->remoteVersion_ = "4.1.5.0"; ret = authManager_->ProcessPincode(pinCode); - ASSERT_EQ(ret, ERR_DM_FAILED); + EXPECT_NE(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, AuthDevice_001, testing::ext::TestSize.Level0) @@ -1383,93 +1425,21 @@ HWTEST_F(DmAuthManagerTest, HandleSessionHeartbeat_001, testing::ext::TestSize.L HWTEST_F(DmAuthManagerTest, CheckTrustState_001, testing::ext::TestSize.Level0) { authManager_->authResponseContext_->isOnline = true; - authManager_->authResponseContext_->authType = 5; - authManager_->authResponseContext_->importAuthCode = ""; - authManager_->importAuthCode_ = ""; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_->importAuthCode = Crypto::Sha256(authManager_->importAuthCode_); int32_t ret = authManager_->CheckTrustState(); ASSERT_NE(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, CheckTrustState_002, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = true; - int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = false; - authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; - int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, CheckTrustState_004, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = false; - authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; - authManager_->authResponseContext_->authType = 5; - authManager_->authResponseContext_->isAuthCodeReady = false; - int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); -} - -HWTEST_F(DmAuthManagerTest, CheckTrustState_005, testing::ext::TestSize.Level0) -{ - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = false; - authManager_->authResponseContext_->reply = 1; - authManager_->authResponseContext_->authType = 1; - authManager_->authResponseContext_->isAuthCodeReady = true; - int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(DmAuthManagerTest, CheckTrustState_006, testing::ext::TestSize.Level0) -{ - std::string udid = ""; - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->authType = 6; - authManager_->authResponseContext_->importAuthCode = "importAuthCode"; - authManager_->importAuthCode_ = "importAuthCode_"; - authManager_->authResponseContext_->isIdenticalAccount = false; - authManager_->authResponseContext_->reply = 1; - authManager_->authResponseContext_->authType = 1; - authManager_->authResponseContext_->isAuthCodeReady = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->importAuthCode_ = "test"; + authManager_->authResponseContext_->importAuthCode = "test"; int32_t ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); - authManager_->importAuthCode_ = Crypto::Sha256("importAuthCode_"); - ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); - authManager_->authResponseContext_->isOnline = false; - authManager_->authResponseContext_->isIdenticalAccount = true; - ret = authManager_->CheckTrustState(); - ASSERT_EQ(ret, DM_OK); - authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; - ret = authManager_->CheckTrustState(); - authManager_->OnScreenLocked(); - authManager_->HandleDeviceNotTrust(udid); - udid = "udidTest"; - authManager_->HandleDeviceNotTrust(udid); - authManager_->authRequestState_ = nullptr; - authManager_->OnScreenLocked(); - ASSERT_EQ(ret, DM_OK); + ASSERT_NE(ret, DM_OK); } } // namespace } // namespace DistributedHardware diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.h b/test/commonunittest/UTTest_dm_auth_manager_second.h index d74d49337..5b1dde490 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.h +++ b/test/commonunittest/UTTest_dm_auth_manager_second.h @@ -16,22 +16,23 @@ #ifndef OHOS_DM_AUTH_MANAGER_SECOND_TEST_H #define OHOS_DM_AUTH_MANAGER_SECOND_TEST_H +#include +#include #include #include -#include +#include "auth_message_processor.h" +#include "auth_request_state.h" +#include "auth_response_state.h" #include "authentication.h" -#include "softbus_session.h" #include "device_manager_service_listener.h" #include "dm_adapter_manager.h" +#include "dm_auth_manager.h" #include "dm_constants.h" -#include "softbus_connector.h" -#include "hichain_connector.h" -#include "auth_request_state.h" -#include "auth_response_state.h" -#include "auth_message_processor.h" #include "dm_timer.h" -#include "dm_auth_manager.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" namespace OHOS { namespace DistributedHardware { @@ -42,13 +43,12 @@ public: void SetUp(); void TearDown(); - std::shared_ptr softbusConnector = std::make_shared(); - std::shared_ptr listener = std::make_shared(); - std::shared_ptr hiChainConnector = std::make_shared(); - std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager_; +}; - std::shared_ptr authManager_ = - std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); +class AuthResponseInitStateMock : public AuthResponseInitState { +public: + MOCK_METHOD(int32_t, GetStateType, (), (override)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 17d890776..c068fae32 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1030,6 +1030,7 @@ ohos_unittest("UTTest_dm_auth_manager_second") { deps = [ ":device_manager_test_common" ] external_deps = [ + "ability_runtime:ability_connect_callback_stub", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", -- Gitee From 27a30188a0e2acea1616154dfc0bd0abfe8e41fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 7 Sep 2024 19:40:09 +0800 Subject: [PATCH 172/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9gn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index d306aef99..a298c6380 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -47,8 +47,8 @@ group("unittest") { ":UTTest_dm_pin_holder", ":UTTest_dm_publish_manager", ":UTTest_dm_radar_helper_test", - ":UTTest_dm_timer", ":UTTest_dm_service_load", + ":UTTest_dm_timer", ":UTTest_hichain_auth_connector", ":UTTest_hichain_connector", ":UTTest_ipc_client_manager", -- Gitee From 04c3e09cc37c4aee6b62dcc032140f046f4a8429 Mon Sep 17 00:00:00 2001 From: pwx1285814 Date: Mon, 9 Sep 2024 09:16:32 +0800 Subject: [PATCH 173/520] =?UTF-8?q?=E8=A1=A5=E5=85=85services/implementati?= =?UTF-8?q?on/src/authentication/dm=5Fauth=5Fmanager.cpp=20UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: pwx1285814 --- .../UTTest_dm_auth_manager_third.cpp | 357 +++++++++++++++++- .../UTTest_dm_auth_manager_third.h | 9 + test/unittest/BUILD.gn | 1 + 3 files changed, 361 insertions(+), 6 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index 5bf4d1165..e760738ff 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -15,17 +15,31 @@ #include "UTTest_dm_auth_manager_third.h" -#include "nlohmann/json.hpp" - -#include "dm_log.h" -#include "dm_constants.h" -#include "dm_auth_manager.h" #include "auth_message_processor.h" #include "device_manager_service_listener.h" +#include "deviceprofile_connector.h" +#include "dm_auth_manager.h" +#include "dm_constants.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" +#include "dm_radar_helper.h" +#include "multiple_user_connector.h" +#include "nlohmann/json.hpp" #include "softbus_error_code.h" -static std::string g_createSimpleMessageReturnDataStr = "{}"; +static bool g_checkIsOnlineReturnBoolValue = false; +static bool g_checkSrcDevIdInAclForDevBindReturnBoolValue = false; +static bool g_isDevicesInP2PGroupReturnBoolValue = false; static bool g_isIdenticalAccountReturnBoolValue = false; +static bool g_isLocked = false; +static bool g_reportAuthConfirmBoxReturnBoolValue = false; +static bool g_reportAuthInputPinBoxReturnBoolValue = false; +static int32_t g_bindType = INVALIED_TYPE; +static int32_t g_leftAclNumber = 0; +static int32_t g_trustNumber = 0; +static std::string g_accountId = ""; +static std::string g_createSimpleMessageReturnDataStr = "{}"; +static std::string g_peerUdidHash = ""; namespace OHOS { namespace DistributedHardware { @@ -39,6 +53,60 @@ bool DmAuthManager::IsIdenticalAccount() return g_isIdenticalAccountReturnBoolValue; } +void DmAuthManager::GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash) +{ + peerUdidHash = g_peerUdidHash; +} + +bool DmAuthManager::IsScreenLocked() +{ + return g_isLocked; +} + +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +{ + return g_checkIsOnlineReturnBoolValue; +} + +DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string &pkgName, + const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel) +{ + DmOfflineParam offlineParam; + offlineParam.bindType = g_bindType; + offlineParam.leftAclNumber = g_leftAclNumber; + return offlineParam; +} + +bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) +{ + return g_reportAuthConfirmBoxReturnBoolValue; +} + +bool DmRadarHelper::ReportAuthInputPinBox(struct RadarInfo &info) +{ + return g_reportAuthInputPinBoxReturnBoolValue; +} + +int32_t DeviceProfileConnector::GetTrustNumber(const std::string &deviceId) +{ + return g_trustNumber; +} + +std::string MultipleUserConnector::GetOhosAccountId(void) +{ + return g_accountId; +} + +bool HiChainConnector::IsDevicesInP2PGroup(const std::string &hostDevice, const std::string &peerDevice) +{ + return g_isDevicesInP2PGroupReturnBoolValue; +} + +bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) +{ + return g_checkSrcDevIdInAclForDevBindReturnBoolValue; +} + void DmAuthManagerTest::SetUp() { std::shared_ptr softbusConnector = std::make_shared(); @@ -61,8 +129,11 @@ void DmAuthManagerTest::SetUp() } void DmAuthManagerTest::TearDown() { + g_bindType = INVALIED_TYPE; g_createSimpleMessageReturnDataStr = "{}"; g_isIdenticalAccountReturnBoolValue = false; + g_leftAclNumber = 0; + g_peerUdidHash = ""; } void DmAuthManagerTest::SetUpTestCase() {} void DmAuthManagerTest::TearDownTestCase() {} @@ -147,5 +218,279 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) authManager_->ProcRespNegotiate(sessionId); EXPECT_FALSE(authManager_->authResponseContext_->isOnline); } + +HWTEST_F(DmAuthManagerTest, DeleteAcl001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string localUdid = "localUdid"; + std::string remoteUdid = "remoteUdid"; + int32_t sessionId = 0; + int32_t bindLevel = APP; + g_bindType = INVALIED_TYPE; + int32_t ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, ERR_DM_FAILED); + + bindLevel = APP; + g_bindType = APP_PEER_TO_PEER_TYPE; + g_leftAclNumber = 1; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + g_leftAclNumber = 0; + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + bindLevel = DEVICE; + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + g_leftAclNumber = 1; + g_peerUdidHash = "test"; + authManager_->DeleteOffLineTimer(sessionId); + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, DM_OK); + + authManager_->softbusConnector_ = nullptr; + authManager_->DeleteOffLineTimer(sessionId); + bindLevel = 0; + ret = authManager_->DeleteAcl(pkgName, localUdid, remoteUdid, bindLevel); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DmAuthManagerTest, AuthenticateFinish001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_ = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + authManager_->authUiStateMgr_ = std::make_shared(listener); + authManager_->authResponseState_ = nullptr; + authManager_->remoteVersion_ = "4.1.5.2"; + authManager_->authResponseContext_->bindLevel = INVALIED_TYPE; + authManager_->authResponseContext_->isFinish = true; + authManager_->authRequestState_ = std::make_shared(); + g_checkIsOnlineReturnBoolValue = true; + g_trustNumber = 1; + authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->isFinish = false; + g_trustNumber = 1; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + g_checkIsOnlineReturnBoolValue = false; + g_trustNumber = 1; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authResponseContext_->bindLevel = APP_PEER_TO_PEER_TYPE; + g_trustNumber = 1; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + authManager_->authResponseContext_ = std::make_shared(); + authManager_->remoteVersion_ = "4.1.5.0"; + g_trustNumber = 2; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); + + g_trustNumber = 0; + authManager_->AuthenticateFinish(); + ASSERT_EQ(authManager_->authMessageProcessor_, nullptr); +} + +HWTEST_F(DmAuthManagerTest, ShowStartAuthDialog001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authRequestState_ = nullptr; + authManager_->authResponseState_ = nullptr; + g_isLocked = true; + authManager_->ShowStartAuthDialog(); + ASSERT_EQ(authManager_->authResponseContext_->state, STATUS_DM_AUTH_DEFAULT); + + g_isLocked = false; + authManager_->authResponseContext_->targetDeviceName = "test"; + authManager_->ShowStartAuthDialog(); + ASSERT_EQ(authManager_->authResponseContext_->targetDeviceName, DmDialogManager::GetInstance().targetDeviceName_); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation001, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation002, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation003, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, OnUserOperation004, testing::ext::TestSize.Level0) +{ + int32_t action = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + std::string params = "12345"; + g_reportAuthConfirmBoxReturnBoolValue = false; + authManager_->authResponseContext_ = std::make_shared(); + g_reportAuthInputPinBoxReturnBoolValue = true; + int32_t ret = authManager_->OnUserOperation(action, params); + g_reportAuthInputPinBoxReturnBoolValue = false; + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt001, testing::ext::TestSize.Level0) +{ + int32_t sessionId = 0; + g_accountId = "test"; + authManager_->authResponseContext_->localAccountId = "test"; + authManager_->authenticationMap_.clear(); + authManager_->authResponseContext_->hostPkgName = "test"; + authManager_->importPkgName_ = "test"; + authManager_->importAuthCode_ = "12345"; + authManager_->ProcRespNegotiateExt(sessionId); + ASSERT_EQ(authManager_->authResponseContext_->reply, ERR_DM_UNSUPPORTED_AUTH_TYPE); + g_accountId = ""; +} + +HWTEST_F(DmAuthManagerTest, ProcRespNegotiateExt002, testing::ext::TestSize.Level0) +{ + authManager_->authenticationMap_.clear(); + authManager_->authResponseContext_->hostPkgName = "test"; + authManager_->authResponseContext_->localAccountId = "test"; + authManager_->importAuthCode_ = "12345"; + authManager_->importPkgName_ = "test"; + g_accountId = "ohosAnonymousUid"; + int32_t sessionId = 0; + authManager_->ProcRespNegotiateExt(sessionId); + ASSERT_EQ(authManager_->authResponseContext_->reply, ERR_DM_UNSUPPORTED_AUTH_TYPE); + g_accountId = ""; +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->importAuthCode_ = ""; + g_isIdenticalAccountReturnBoolValue = true; + int32_t ret = authManager_->CheckTrustState(); + g_isIdenticalAccountReturnBoolValue = false; + ASSERT_EQ(ret, 1); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_002, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + g_checkSrcDevIdInAclForDevBindReturnBoolValue = false; + g_isDevicesInP2PGroupReturnBoolValue = true; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + g_isDevicesInP2PGroupReturnBoolValue = false; + ASSERT_EQ(ret, 1); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + g_checkSrcDevIdInAclForDevBindReturnBoolValue = true; + g_isDevicesInP2PGroupReturnBoolValue = true; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + g_isDevicesInP2PGroupReturnBoolValue = false; + ASSERT_EQ(ret, 1); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_004, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_005, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_006, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = AUTH_TYPE_IMPORT_AUTH_CODE; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_007, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->authType = AUTH_TYPE_UNKNOW; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->authResponseContext_->isAuthCodeReady = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = AUTH_TYPE_IMPORT_AUTH_CODE; + g_isDevicesInP2PGroupReturnBoolValue = false; + g_isIdenticalAccountReturnBoolValue = false; + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, DM_OK); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.h b/test/commonunittest/UTTest_dm_auth_manager_third.h index 2df80f2d9..e2875d6d8 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.h +++ b/test/commonunittest/UTTest_dm_auth_manager_third.h @@ -44,6 +44,15 @@ public: std::shared_ptr authManager_; }; + +class SoftbusStateCallbackMock : public ISoftbusStateCallback { +public: + SoftbusStateCallbackMock() {} + virtual ~SoftbusStateCallbackMock() {} + void OnDeviceOnline(std::string deviceId, int32_t authForm) {} + void OnDeviceOffline(std::string deviceId) {} + void DeleteOffLineTimer(std::string udidHash) {} +}; } // namespace DistributedHardware } // namespace OHOS #endif diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 17d890776..b33ab4188 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1050,6 +1050,7 @@ ohos_unittest("UTTest_dm_auth_manager_third") { deps = [ ":device_manager_test_common" ] external_deps = [ + "ability_runtime:ability_connect_callback_stub", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", -- Gitee From 4aebfbbcac1491feeb476627c152121ecdd064b1 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Fri, 6 Sep 2024 14:24:33 +0800 Subject: [PATCH 174/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0UT=20Signed-off-by:?= =?UTF-8?q?=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/unittest/BUILD.gn | 77 ++++++ .../UTTest_dm_account_common_event.cpp | 106 ++++++++ .../unittest/UTTest_dm_account_common_event.h | 36 +++ .../UTTest_dm_publish_common_event.cpp | 115 ++++++++ .../unittest/UTTest_dm_publish_common_event.h | 36 +++ .../UTTest_dm_screen_common_event.cpp | 69 +++++ test/unittest/UTTest_dm_screen_common_event.h | 36 +++ .../unittest/UTTest_relationship_sync_mgr.cpp | 245 ++++++++++++++++++ test/unittest/UTTest_relationship_sync_mgr.h | 36 +++ 9 files changed, 756 insertions(+) create mode 100644 test/unittest/UTTest_dm_account_common_event.cpp create mode 100644 test/unittest/UTTest_dm_account_common_event.h create mode 100644 test/unittest/UTTest_dm_publish_common_event.cpp create mode 100644 test/unittest/UTTest_dm_publish_common_event.h create mode 100644 test/unittest/UTTest_dm_screen_common_event.cpp create mode 100644 test/unittest/UTTest_dm_screen_common_event.h create mode 100644 test/unittest/UTTest_relationship_sync_mgr.cpp create mode 100644 test/unittest/UTTest_relationship_sync_mgr.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 17d890776..7085a56b3 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -29,6 +29,7 @@ group("unittest") { ":UTTest_device_manager_service_listener", ":UTTest_discovery_filter", ":UTTest_discovery_manager", + ":UTTest_dm_account_common_event", ":UTTest_dm_adapter_manager", ":UTTest_dm_anonymous", ":UTTest_dm_auth_manager_first", @@ -45,8 +46,10 @@ group("unittest") { ":UTTest_dm_distributed_hardware_load", ":UTTest_dm_import_auth_code", ":UTTest_dm_pin_holder", + ":UTTest_dm_publish_common_event", ":UTTest_dm_publish_manager", ":UTTest_dm_radar_helper_test", + ":UTTest_dm_screen_common_event", ":UTTest_dm_timer", ":UTTest_hichain_auth_connector", ":UTTest_hichain_connector", @@ -67,6 +70,7 @@ group("unittest") { ":UTTest_permission_manager", ":UTTest_pin_auth", ":UTTest_pin_auth_ui", + ":UTTest_relationship_sync_mgr", ":UTTest_softbus_connector", ":UTTest_softbus_listener", ":UTTest_softbus_publish", @@ -1223,6 +1227,79 @@ ohos_unittest("UTTest_dm_crypto") { ## UnitTest UTTest_dm_crypto }}} +## UnitTest UTTest_dm_account_common_event {{{ +ohos_unittest("UTTest_dm_account_common_event") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_dm_account_common_event.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [] +} + +## UnitTest UTTest_dm_account_common_event }}} + +## UnitTest UTTest_dm_publish_common_event {{{ +ohos_unittest("UTTest_dm_publish_common_event") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_dm_publish_common_event.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "bluetooth:btframework", + "wifi:wifi_sdk", + ] +} + +## UnitTest UTTest_dm_publish_common_event }}} + +## UnitTest UTTest_dm_screen_common_event {{{ +ohos_unittest("UTTest_dm_screen_common_event") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_dm_screen_common_event.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "bluetooth:btframework", + "wifi:wifi_sdk", + ] +} + +## UnitTest UTTest_dm_screen_common_event }}} + +## UnitTest UTTest_relationship_sync_mgr {{{ +ohos_unittest("UTTest_relationship_sync_mgr") { + module_out_path = module_out_path + + include_dirs = [ "${devicemanager_path}/test/unittest" ] + + sources = + [ "${devicemanager_path}/test/unittest/UTTest_relationship_sync_mgr.cpp" ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ "cJSON:cjson" ] +} + +## UnitTest UTTest_relationship_sync_mgr }}} + ## UnitTest UTTest_dm_publish_manager {{{ ohos_unittest("UTTest_dm_publish_manager") { module_out_path = module_out_path diff --git a/test/unittest/UTTest_dm_account_common_event.cpp b/test/unittest/UTTest_dm_account_common_event.cpp new file mode 100644 index 000000000..6544244dd --- /dev/null +++ b/test/unittest/UTTest_dm_account_common_event.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "UTTest_dm_account_common_event.h" + +#include "common_event_support.h" +#include "dm_account_common_event.h" +#include "dm_constants.h" +#include "matching_skills.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +void DmAccountCommonEventManagerTest::SetUp() +{ +} + +void DmAccountCommonEventManagerTest::TearDown() +{ +} + +void DmAccountCommonEventManagerTest::SetUpTestCase() +{ +} + +void DmAccountCommonEventManagerTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(DmAccountCommonEventManagerTest, SubscribeAccountCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr accountCommonEventManager + = std::make_shared(); + std::vector commonEventVec; + bool ret = accountCommonEventManager->SubscribeAccountCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); + commonEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + ret = accountCommonEventManager->SubscribeAccountCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); +} + +HWTEST_F(DmAccountCommonEventManagerTest, UnSubscribeAccountCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr accountCommonEventManager + = std::make_shared(); + bool ret = accountCommonEventManager->UnsubscribeAccountCommonEvent(); + ASSERT_EQ(ret, false); + accountCommonEventManager->eventValidFlag_ = true; + ret = accountCommonEventManager->UnsubscribeAccountCommonEvent(); + ASSERT_EQ(ret, true); +} + +HWTEST_F(DmAccountCommonEventManagerTest, OnReceiveEvent_001, testing::ext::TestSize.Level0) +{ + AAFwk::Want want; + EventFwk::CommonEventData data; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + data.SetWant(want); + data.SetCode(0); + + std::vector changeEventVec; + changeEventVec.push_back("changeEvent"); + std::string strEvent = "test"; + std::vector strEventVec; + strEventVec.push_back(strEvent); + AccountEventCallback callback = nullptr; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(strEvent); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + + std::shared_ptr accountCommonEventManager + = std::make_shared(); + accountCommonEventManager->subscriber_ + = std::make_shared(subscriberInfo, callback, strEventVec); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED); + data.SetWant(want); + data.SetCode(1); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + data.SetWant(want); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN); + data.SetWant(want); + accountCommonEventManager->subscriber_->OnReceiveEvent(data); + EXPECT_NE(accountCommonEventManager->subscriber_->GetSubscriberEventNameVec(), changeEventVec); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_account_common_event.h b/test/unittest/UTTest_dm_account_common_event.h new file mode 100644 index 000000000..c92821250 --- /dev/null +++ b/test/unittest/UTTest_dm_account_common_event.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_IPC_CLIENT_MANAGER_TEST_H +#define OHOS_IPC_CLIENT_MANAGER_TEST_H + +#include +#include + +#include "dm_account_common_event.h" + +namespace OHOS { +namespace DistributedHardware { +class DmAccountCommonEventManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_IPC_CLIENT_MANAGER_TEST_H diff --git a/test/unittest/UTTest_dm_publish_common_event.cpp b/test/unittest/UTTest_dm_publish_common_event.cpp new file mode 100644 index 000000000..da45aabb9 --- /dev/null +++ b/test/unittest/UTTest_dm_publish_common_event.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_publish_common_event.h" + +#include "bluetooth_def.h" +#include "common_event_support.h" +#include "dm_constants.h" +#include "dm_publish_common_event.h" +#include "matching_skills.h" +#include "system_ability_definition.h" +#include "wifi_msg.h" + +namespace OHOS { +namespace DistributedHardware { +void DmPublishCommonEventManagerTest::SetUp() +{ +} + +void DmPublishCommonEventManagerTest::TearDown() +{ +} + +void DmPublishCommonEventManagerTest::SetUpTestCase() +{ +} + +void DmPublishCommonEventManagerTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(DmPublishCommonEventManagerTest, SubscribePublishCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr publshCommonEventManager + = std::make_shared(); + std::vector publishCommonEventVec; + bool ret = publshCommonEventManager->SubscribePublishCommonEvent(publishCommonEventVec, nullptr); + ASSERT_EQ(ret, false); + publishCommonEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + ret = publshCommonEventManager->SubscribePublishCommonEvent(publishCommonEventVec, nullptr); + ASSERT_EQ(ret, false); +} + +HWTEST_F(DmPublishCommonEventManagerTest, UnsubscribePublishCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr publshCommonEventManager + = std::make_shared(); + bool ret = publshCommonEventManager->UnsubscribePublishCommonEvent(); + ASSERT_EQ(ret, false); + publshCommonEventManager->eventValidFlag_ = true; + ret = publshCommonEventManager->UnsubscribePublishCommonEvent(); + ASSERT_EQ(ret, true); +} + +HWTEST_F(DmPublishCommonEventManagerTest, OnReceiveEvent_001, testing::ext::TestSize.Level0) +{ + AAFwk::Want want; + EventFwk::CommonEventData data; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + data.SetWant(want); + data.SetCode(0); + std::vector changeEventVec; + changeEventVec.push_back(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + std::string strEvent = "test"; + std::vector strEventVec; + strEventVec.push_back(strEvent); + PublishEventCallback callback = nullptr; + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(strEvent); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + + std::shared_ptr publshCommonEventManager + = std::make_shared(); + publshCommonEventManager->subscriber_ + = std::make_shared(subscriberInfo, callback, strEventVec); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE); + data.SetWant(want); + data.SetCode(static_cast(Bluetooth::BTStateID::STATE_TURN_ON)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + data.SetCode(static_cast(Bluetooth::BTStateID::STATE_TURN_OFF)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + data.SetCode(-1); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_WIFI_POWER_STATE); + data.SetWant(want); + data.SetCode(static_cast(OHOS::Wifi::WifiState::ENABLED)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + data.SetCode(static_cast(OHOS::Wifi::WifiState::DISABLED)); + publshCommonEventManager->subscriber_->OnReceiveEvent(data); + + EXPECT_NE(publshCommonEventManager->subscriber_->GetSubscriberEventNameVec(), changeEventVec); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_publish_common_event.h b/test/unittest/UTTest_dm_publish_common_event.h new file mode 100644 index 000000000..947f02d32 --- /dev/null +++ b/test/unittest/UTTest_dm_publish_common_event.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_PUBLISH_COMMON_EVENT_TEST_H +#define OHOS_DM_PUBLISH_COMMON_EVENT_TEST_H + +#include +#include + +#include "dm_publish_common_event.h" + +namespace OHOS { +namespace DistributedHardware { +class DmPublishCommonEventManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_PUBLISH_COMMON_EVENT_TEST_H diff --git a/test/unittest/UTTest_dm_screen_common_event.cpp b/test/unittest/UTTest_dm_screen_common_event.cpp new file mode 100644 index 000000000..a728f55ad --- /dev/null +++ b/test/unittest/UTTest_dm_screen_common_event.cpp @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_screen_common_event.h" + +#include "bluetooth_def.h" +#include "common_event_support.h" +#include "dm_constants.h" +#include "dm_screen_common_event.h" +#include "matching_skills.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +void DmScreenCommonEventManagerTest::SetUp() +{ +} + +void DmScreenCommonEventManagerTest::TearDown() +{ +} + +void DmScreenCommonEventManagerTest::SetUpTestCase() +{ +} + +void DmScreenCommonEventManagerTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(DmScreenCommonEventManagerTest, SubscribeScreenCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr screenCommonEventManager + = std::make_shared(); + std::vector commonEventVec; + bool ret = screenCommonEventManager->SubscribeScreenCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); + commonEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + ret = screenCommonEventManager->SubscribeScreenCommonEvent(commonEventVec, nullptr); + ASSERT_EQ(ret, false); +} + +HWTEST_F(DmScreenCommonEventManagerTest, UnSubscribeScreenCommonEvent_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr screenCommonEventManager + = std::make_shared(); + bool ret = screenCommonEventManager->UnsubscribeScreenCommonEvent(); + ASSERT_EQ(ret, false); + screenCommonEventManager->eventValidFlag_ = true; + ret = screenCommonEventManager->UnsubscribeScreenCommonEvent(); + ASSERT_EQ(ret, true); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_dm_screen_common_event.h b/test/unittest/UTTest_dm_screen_common_event.h new file mode 100644 index 000000000..b1a7b5201 --- /dev/null +++ b/test/unittest/UTTest_dm_screen_common_event.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SCREEN_COMMON_EVENT_TEST_H +#define OHOS_DM_SCREEN_COMMON_EVENT_TEST_H + +#include +#include + +#include "dm_screen_common_event.h" + +namespace OHOS { +namespace DistributedHardware { +class DmScreenCommonEventManagerTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DM_SCREEN_COMMON_EVENT_TEST_H diff --git a/test/unittest/UTTest_relationship_sync_mgr.cpp b/test/unittest/UTTest_relationship_sync_mgr.cpp new file mode 100644 index 000000000..3fb543097 --- /dev/null +++ b/test/unittest/UTTest_relationship_sync_mgr.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_relationship_sync_mgr.h" + +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +void ReleationShipSyncMgrTest::SetUp() +{ +} + +void ReleationShipSyncMgrTest::TearDown() +{ +} + +void ReleationShipSyncMgrTest::SetUpTestCase() +{ +} + +void ReleationShipSyncMgrTest::TearDownTestCase() +{ +} + +namespace { + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_001, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = UINT32_MAX; + msg.peerUdids = peerUdids; + msg.accountId = "1"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_002, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_003, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::ACCOUNT_LOGOUT; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_NE(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_004, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEVICE_UNBIND; + msg.userId = UINT32_MAX; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_005, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEVICE_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_NE(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_006, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = UINT32_MAX; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_007, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + msg.tokenId = UINT64_MAX; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_008, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + msg.tokenId = 1; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_NE(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, SyncTrustRelationShip_009, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SERVICE_UNBIND; + msg.userId = 1; + msg.peerUdids = peerUdids; + msg.accountId = "1111111"; + msg.accountName = "1"; + msg.tokenId = 1; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + msg.type = RelationShipChangeType::DEL_USER; + broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + msg.type = RelationShipChangeType::APP_UNINSTALL; + broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + msg.type = RelationShipChangeType::TYPE_MAX; + broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + ASSERT_EQ(broadCastMsg, ""); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_001, testing::ext::TestSize.Level0) +{ + std::string msg = ""; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_002, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "xx": "xx" + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_003, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "TYPE": "xx" + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_004, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "TYPE": 0 + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + msg = R"( + { + "TYPE": 1 + } + )"; + relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + msg = R"( + { + "TYPE": 2 + } + )"; + relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + msg = R"( + { + "TYPE": 3 + } + )"; + relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} + +HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_005, testing::ext::TestSize.Level0) +{ + std::string msg = R"( + { + "TYPE": 0, + "VALUE": "" + } + )"; + RelationShipChangeMsg relationShipMsg = + ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); +} +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_relationship_sync_mgr.h b/test/unittest/UTTest_relationship_sync_mgr.h new file mode 100644 index 000000000..1b81d0ae0 --- /dev/null +++ b/test/unittest/UTTest_relationship_sync_mgr.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_RELEATION_SHIP_SYNC_MGR_TEST_H +#define OHOS_RELEATION_SHIP_SYNC_MGR_TEST_H + +#include +#include + +#include "relationship_sync_mgr.h" + +namespace OHOS { +namespace DistributedHardware { +class ReleationShipSyncMgrTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_RELEATION_SHIP_SYNC_MGR_TEST_H -- Gitee From 351998d167efbd0f7ba8827451c6c761f95bbc2b Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Mon, 9 Sep 2024 11:31:58 +0800 Subject: [PATCH 175/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0uuid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../model/ipc_notify_devicetrustchange_req.h | 20 +++++++++++++------ .../include/device_manager_callback.h | 2 +- .../include/notify/device_manager_notify.h | 5 +++-- .../src/ipc/standard/ipc_cmd_parser.cpp | 5 +++-- .../src/notify/device_manager_notify.cpp | 15 +++++++------- .../src/device_manager_service_impl.cpp | 7 +++++-- .../include/device_manager_service_listener.h | 2 +- .../idevice_manager_service_listener.h | 2 +- .../src/device_manager_service_listener.cpp | 9 ++++++--- .../src/ipc/standard/ipc_cmd_parser.cpp | 11 +++++++--- .../softbuscache/include/dm_softbus_cache.h | 1 + .../softbuscache/src/dm_softbus_cache.cpp | 14 +++++++++++++ test/unittest/UTTest_dm_pin_holder.h | 5 +++-- 13 files changed, 68 insertions(+), 30 deletions(-) diff --git a/common/include/ipc/model/ipc_notify_devicetrustchange_req.h b/common/include/ipc/model/ipc_notify_devicetrustchange_req.h index ba4428035..4af68e552 100644 --- a/common/include/ipc/model/ipc_notify_devicetrustchange_req.h +++ b/common/include/ipc/model/ipc_notify_devicetrustchange_req.h @@ -30,18 +30,26 @@ public: { authForm_ = authForm; } - const std::string &GetDeviceId() const + const std::string &GetUdid() const { - return deviceId_; + return udid_; } - void SetDeviceId(const std::string &deviceId) + void SetUdid(const std::string &udid) { - deviceId_ = deviceId; + udid_ = udid; + } + const std::string &GetUuid() const + { + return uuid_; + } + void SetUuid(const std::string &uuid) + { + uuid_ = uuid; } - private: int32_t authForm_; - std::string deviceId_; + std::string udid_; + std::string uuid_; }; } // 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 e84d0f387..97ea9ff54 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -138,7 +138,7 @@ public: virtual ~DevTrustChangeCallback() { } - virtual void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) = 0; + virtual void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 69672229b..993dc7240 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 @@ -81,7 +81,7 @@ public: std::shared_ptr tempCbk); static void DeviceBasicInfoReady(const DmDeviceBasicInfo &deviceBasicInfo, std::shared_ptr tempCbk); - static void DeviceTrustChange(const std::string &deviceId, DmAuthForm authForm, + static void DeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm, std::shared_ptr tempCbk); public: void OnRemoteDied(); @@ -110,7 +110,8 @@ public: void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content); std::map> GetDmInitCallback(); - void OnDeviceTrustChange(const std::string &pkgName, const std::string &deviceId, int32_t authForm); + void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, + int32_t authForm); private: #if !defined(__LITEOS_M__) std::mutex lock_; 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 f58038277..ac5faf4d4 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 @@ -1639,9 +1639,10 @@ ON_IPC_READ_RESPONSE(SHIFT_LNN_GEAR, MessageParcel &reply, std::shared_ptr(INVALID_TYPE) || authForm > static_cast(ACROSS_ACCOUNT)) { LOGE("Invalid parameter, pkgName is empty."); @@ -1115,10 +1116,10 @@ void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const DmAuthForm dmAuthForm = static_cast(authForm); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) if (ffrtQueue_ != nullptr) { - ffrtQueue_->submit([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); + ffrtQueue_->submit([=]() { DeviceTrustChange(udid, uuid, dmAuthForm, tempCbk); }); } #else - std::thread deviceTrustChange([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); + std::thread deviceTrustChange([=]() { DeviceTrustChange(udid, uuid, dmAuthForm, tempCbk); }); if (pthread_setname_np(deviceTrustChange.native_handle(), DEVICE_TRUST_CHANGE) != DM_OK) { LOGE("deviceTrustChange set name failed."); } @@ -1126,14 +1127,14 @@ void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const #endif } -void DeviceManagerNotify::DeviceTrustChange(const std::string &deviceId, DmAuthForm authForm, +void DeviceManagerNotify::DeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm, std::shared_ptr tempCbk) { if (tempCbk == nullptr) { LOGE("Callback ptr is nullptr."); return; } - tempCbk->OnDeviceTrustChange(deviceId, authForm); + tempCbk->OnDeviceTrustChange(udid, uuid, authForm); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 7ebcad06a..63e33140a 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -17,14 +17,15 @@ #include +#include "app_manager.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_distributed_hardware_load.h" #include "dm_log.h" #include "dm_radar_helper.h" +#include "dm_softbus_cache.h" #include "multiple_user_connector.h" -#include "app_manager.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_common_event_manager.h" #include "parameter.h" @@ -745,7 +746,9 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co CHECK_NULL_VOID(authMgr_); authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); CHECK_NULL_VOID(listener_); - listener_->OnDeviceTrustChange(remoteUdid, ConvertBindTypeToAuthForm(bindType)); + std::string uuid = ""; + SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); + listener_->OnDeviceTrustChange(remoteUdid, uuid, ConvertBindTypeToAuthForm(bindType)); } DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 403d25a5e..32cf8fa70 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -71,7 +71,7 @@ public: void OnDestroyResult(const std::string &pkgName, int32_t result) override; void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content) override; - void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override; + void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index bce45fe33..9730ce596 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -150,7 +150,7 @@ public: * @tc.desc: Set the pkgname that not offline * @tc.type: FUNC */ - virtual void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) = 0; + virtual void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 04613a802..cf88485d7 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -478,15 +478,18 @@ int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoy(const std::string &p } #endif -void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) +void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, const std::string &uuid, + DmAuthForm authForm) { - LOGI("DeviceId %{public}s, authForm %{public}d.", GetAnonyString(deviceId).c_str(), authForm); + LOGI("udid %{public}s, uuid %{public}s, authForm %{public}d.", GetAnonyString(udid).c_str(), + GetAnonyString(uuid).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); for (const auto &it : PkgNameVec) { pReq->SetPkgName(it); - pReq->SetDeviceId(deviceId); + pReq->SetUdid(udid); + pReq->SetUuid(uuid); pReq->SetAuthForm(authForm); ipcServerListener_.SendRequest(REMOTE_DEVICE_TRUST_CHANGE, pReq, pRsp); } diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 15edf7343..68f584bbe 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1466,14 +1466,19 @@ ON_IPC_SET_REQUEST(REMOTE_DEVICE_TRUST_CHANGE, std::shared_ptr pBaseReq, } std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); - std::string deviceId = pReq->GetDeviceId(); + std::string udid = pReq->GetUdid(); + std::string uuid = pReq->GetUuid(); int32_t authForm = pReq->GetAuthForm(); if (!data.WriteString(pkgName)) { LOGE("write pkgName failed"); return ERR_DM_IPC_WRITE_FAILED; } - if (!data.WriteString(deviceId)) { - LOGE("write deviceId failed"); + if (!data.WriteString(udid)) { + LOGE("write udid failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(uuid)) { + LOGE("write uuid code failed"); return ERR_DM_IPC_WRITE_FAILED; } if (!data.WriteInt32(authForm)) { diff --git a/services/softbuscache/include/dm_softbus_cache.h b/services/softbuscache/include/dm_softbus_cache.h index e3c2a6d8b..028bbcf41 100644 --- a/services/softbuscache/include/dm_softbus_cache.h +++ b/services/softbuscache/include/dm_softbus_cache.h @@ -46,6 +46,7 @@ public: int32_t GetDevInfoByNetworkId(const std::string &networkId, DmDeviceInfo &nodeInfo); void UpDataLocalDevInfo(); int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid); + int32_t GetUuidByUdid(const std::string &udid, std::string &uuid); private: int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index de4b171fb..3a4e11ea9 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -387,5 +387,19 @@ int32_t SoftbusCache::GetUdidByUdidHash(const std::string &udidHash, std::string } return ERR_DM_FAILED; } + +int32_t SoftbusCache::GetUuidByUdid(const std::string &udid, std::string &uuid) +{ + LOGI("udid %{public}s.", GetAnonyString(udid).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + if (deviceInfo_.find(udid) != deviceInfo_.end()) { + uuid = deviceInfo_[udid].first; + LOGI("success uuid %{public}s.", GetAnonyString(uuid).c_str()); + return DM_OK; + } + } + return ERR_DM_FAILED; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 6ac958aa4..8101bbcd1 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -180,9 +180,10 @@ public: (void)content; } - void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override + void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override { - (void)deviceId; + (void)udid; + (void)uuid; (void)authForm; } }; -- Gitee From 614b4de5c0d87d6e75d9deaaeacc8b81fe4dbdf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 9 Sep 2024 16:10:28 +0800 Subject: [PATCH 176/520] =?UTF-8?q?=E8=A1=A5=E5=85=85ut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/commonunittest/UTTest_dm_anonymous.cpp | 43 +++++-- .../UTTest_softbus_listener.cpp | 25 ++-- .../UTTest_softbus_publish.cpp | 9 +- test/unittest/BUILD.gn | 8 ++ test/unittest/UTTest_device_manager_impl.h | 8 ++ .../UTTest_device_manager_impl_three.cpp | 95 +++++++++++++++ .../unittest/UTTest_device_manager_notify.cpp | 93 +++----------- .../UTTest_device_manager_notify_two.cpp | 9 -- .../UTTest_device_manager_service.cpp | 2 +- .../UTTest_device_manager_service_impl.cpp | 115 ++++++++++++++++++ .../UTTest_device_manager_service_two.cpp | 2 +- 11 files changed, 295 insertions(+), 114 deletions(-) diff --git a/test/commonunittest/UTTest_dm_anonymous.cpp b/test/commonunittest/UTTest_dm_anonymous.cpp index 547b4d927..c9bf7d64d 100644 --- a/test/commonunittest/UTTest_dm_anonymous.cpp +++ b/test/commonunittest/UTTest_dm_anonymous.cpp @@ -394,18 +394,47 @@ HWTEST_F(DmAnonymousTest, IsBool_002, testing::ext::TestSize.Level0) */ HWTEST_F(DmAnonymousTest, ConvertCharArray2String_001, testing::ext::TestSize.Level0) { + constexpr uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; char *srcData = nullptr; uint32_t srcLen = 0; std::string ret = ConvertCharArray2String(srcData, srcLen); EXPECT_EQ(ret, ""); - srcLen = 40 * 1024 * 1024 * 2; - char *srcData1 = new char[srcLen](); - if (srcData1 == nullptr) { - return; - } - ret = ConvertCharArray2String(srcData1, srcLen); + ret = ConvertCharArray2String(srcData, MAX_MESSAGE_LEN + 1); + EXPECT_EQ(ret, ""); + char srcData2[20] = {"1234"}; + ret = ConvertCharArray2String(srcData2, MAX_MESSAGE_LEN + 1); + EXPECT_EQ(ret, ""); + uint32_t srcLen2 = 20; + ret = ConvertCharArray2String(srcData2, srcLen); + EXPECT_EQ(ret, ""); + ret = ConvertCharArray2String(srcData, srcLen2); EXPECT_EQ(ret, ""); - delete[] srcData1; + ret = ConvertCharArray2String(srcData2, srcLen2); + EXPECT_EQ(ret, "1234"); +} + +HWTEST_F(DmAnonymousTest, StringToInt_001, testing::ext::TestSize.Level0) +{ + std::string str = "12344"; + int32_t base = 10; + int32_t ret = StringToInt(str, base); + EXPECT_EQ(ret, 12344); +} + +HWTEST_F(DmAnonymousTest, StringToInt_002, testing::ext::TestSize.Level0) +{ + std::string str; + int32_t base = 10; + int32_t ret = StringToInt(str, base); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DmAnonymousTest, StringToInt64_001, testing::ext::TestSize.Level0) +{ + std::string str; + int32_t base = 10; + int64_t ret = StringToInt64(str, base); + EXPECT_EQ(ret, 0); } } // namespace } // namespace DistributedHardware diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index db63c88ec..66aa4b18e 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -712,17 +712,22 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener = std::make_shared(); } int32_t ret = softbusListener->StopRefreshSoftbusLNN(subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); -} - -HWTEST_F(SoftbusListenerTest, OnLocalDevInfoChange_001, testing::ext::TestSize.Level0) -{ - char *msg = nullptr; - if (softbusListener == nullptr) { - softbusListener = std::make_shared(); - } softbusListener->OnLocalDevInfoChange(); - EXPECT_EQ(msg, nullptr); + std::string msg = "123"; + softbusListener->DeviceNotTrust(msg); + NodeBasicInfo *info = nullptr; + softbusListener->OnSoftbusDeviceOffline(info); + TrustChangeType type = TrustChangeType::DEVICE_NOT_TRUSTED; + const uint32_t msgLen = 100; + char msg1[msgLen] = {0}; + softbusListener->OnDeviceTrustedChange(type, msg1, msgLen); + char *msg2 = nullptr; + softbusListener->OnDeviceTrustedChange(type, msg2, msgLen); + const uint32_t msgLen2 = MAX_SOFTBUS_MSG_LEN + 1; + softbusListener->OnDeviceTrustedChange(type, msg1, msgLen2); + softbusListener->OnDeviceTrustedChange(type, msg2, msgLen2); + softbusListener->SendAclChangedBroadcast(msg); + EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } } // namespace } // namespace DistributedHardware diff --git a/test/softbusunittest/UTTest_softbus_publish.cpp b/test/softbusunittest/UTTest_softbus_publish.cpp index d305d2ed0..8e4e695af 100644 --- a/test/softbusunittest/UTTest_softbus_publish.cpp +++ b/test/softbusunittest/UTTest_softbus_publish.cpp @@ -37,17 +37,12 @@ void SoftbusPublishTest::TearDownTestCase() } namespace { -HWTEST_F(SoftbusPublishTest, OnSoftbusPublishResult_001, testing::ext::TestSize.Level0) -{ - int publishId = 1; - SoftbusPublish::OnSoftbusPublishResult(publishId, PUBLISH_LNN_SUCCESS); - EXPECT_EQ(publishId, 1); -} - HWTEST_F(SoftbusPublishTest, PublishSoftbusLNN_001, testing::ext::TestSize.Level0) { SoftbusPublish spftbusPublish; int32_t ret = spftbusPublish.PublishSoftbusLNN(); + int publishId = 1; + SoftbusPublish::OnSoftbusPublishResult(publishId, PUBLISH_LNN_SUCCESS); EXPECT_EQ(ret, ERR_DM_PUBLISH_FAILED); } } // namespace diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index d4b54f2f4..85c5ccb1e 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -726,6 +726,14 @@ ohos_unittest("UTTest_device_manager_impl") { "ffrt:libffrt", "googletest:gmock", ] + + cflags = [ + "-Wall", + "-Werror", + "-g3", + "-Dprivate=public", + "-Dprotected=public", + ] } ## UnitTest UTTest_device_manager_impl }}} diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index cef907dcd..004e76270 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -101,6 +101,14 @@ public: void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override {} }; + +class DevTrustChangeCallbackTest : public DevTrustChangeCallback { +public: + virtual ~DevTrustChangeCallbackTest() + { + } + void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override {}; +}; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index cbdd95cfe..79b56a2b7 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1175,6 +1175,101 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } + +HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_301, testing::ext::TestSize.Level0) +{ + std::string packName; + uint64_t tokenId = 123; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(tokenId, packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_302, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.test"; + uint64_t tokenId = 123; + std::shared_ptr callback = std::make_shared(); + DeviceManagerImpl::GetInstance().InitDeviceManager(packName, callback); + DeviceManagerImpl::GetInstance().subscribIdMap_[tokenId] = 12345; + DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); + DeviceManagerImpl::GetInstance().subscribIdMap_.erase(tokenId); + int32_t ret = DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); + ASSERT_EQ(ret, ERR_DM_STOP_DISCOVERY); + DeviceManagerImpl::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, RegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string packName; + int32_t ret = DeviceManagerImpl::GetInstance().RegisterUiStateCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string packName; + DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + int32_t ret = DeviceManagerImpl::GetInstance().UnRegisterUiStateCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, StopAdvertising_301, testing::ext::TestSize.Level0) +{ + std::string packName; + std::map advertiseParam; + int32_t ret = DeviceManager::GetInstance().StopAdvertising(packName, advertiseParam); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, CheckAccessToTarget_301, testing::ext::TestSize.Level0) +{ + uint64_t tokenId = 123; + std::string targetId; + int32_t ret = DeviceManager::GetInstance().CheckAccessToTarget(tokenId, targetId); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_302, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_303, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, RegDevTrustChangeCallback_304, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, GetErrCode_301, testing::ext::TestSize.Level0) +{ + int32_t errCode = ERR_DM_TIME_OUT; + int32_t ret = DeviceManager::GetInstance().GetErrCode(errCode); + ASSERT_EQ(ret, 96929745); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_notify.cpp b/test/unittest/UTTest_device_manager_notify.cpp index 61d242b4e..e9f5422f7 100644 --- a/test/unittest/UTTest_device_manager_notify.cpp +++ b/test/unittest/UTTest_device_manager_notify.cpp @@ -182,7 +182,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_005, testing::e // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null - int count = 0; std::shared_ptr dmInitCallback = nullptr; // 2. set checkMap null std::shared_ptr checkMap = nullptr; @@ -191,11 +190,7 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_005, testing::e // 4. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().dmInitCallback_[pkgName]; // 5. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -205,16 +200,11 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_005, testing::e HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_006, testing::ext::TestSize.Level0) { std::string pkgName; - int count = 0; std::shared_ptr dmInitCallback = nullptr; std::shared_ptr checkMap = nullptr; DeviceManagerNotify::GetInstance().RegisterDeathRecipientCallback(pkgName, dmInitCallback); checkMap = DeviceManagerNotify::GetInstance().dmInitCallback_[pkgName]; - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -237,7 +227,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeathRecipientCallback_001, testing: // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null - int count = 0; std::shared_ptr dmInitCallback = std::make_shared(count); // 2. set checkMap null std::shared_ptr checkMap = nullptr; @@ -363,7 +352,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeathRecipientCallback_004, testing: // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null - int count = 0; std::shared_ptr dmInitCallback = std::make_shared(count); // 2. set checkMap null std::shared_ptr checkMap = nullptr; @@ -380,10 +368,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeathRecipientCallback_004, testing: // 8. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().dmInitCallback_[pkgName]; // 9. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -580,10 +564,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeviceStateCallback_005, testing::ext: // 5. Get checkMap from DeviceManagerNotify with testpkcName checkMap = DeviceManagerNotify::GetInstance().deviceStateCallback_[testPkgName]; // 6. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -745,11 +725,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeviceStateCallback_004, testing::ex // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().deviceStateCallback_[pkgName]; // 8 check checkMap null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -951,23 +927,16 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDiscoveryCallback_005, testing::ext::T { // 1. set pkgName com.ohos.test std::string pkgName = "com.ohos.test"; - int count = 0; // set dmInitCallback not null std::shared_ptr callback = std::make_shared(count); uint16_t subscribeId = 0; // 2. set checkMap null std::shared_ptr checkMap = nullptr; - // 3. set testpkcName com.ohos.test1 - std::string testPkgName = "com.ohos.test1"; // 4. call DeviceManagerNotifyTest RegisterDiscoverCallback with parameter DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); // 5. Get checkMap from DeviceManagerNotify with testpkcName checkMap = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName][subscribeId]; // 6. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -978,7 +947,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDiscoveryCallback_005, testing::ext::T HWTEST_F(DeviceManagerNotifyTest, RegisterDiscoveryCallback_006, testing::ext::TestSize.Level0) { std::string pkgName; - int count = 0; std::shared_ptr callback = std::make_shared(count); uint16_t subscribeId = 0; DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); @@ -1156,11 +1124,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDiscoveryCallback_004, testing::ext: // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName][subscribeId]; // 8 check checkMap null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -1381,10 +1345,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterAuthenticateCallback_005, testing::ext // 5. Get checkMap from DeviceManagerNotify with testpkcName checkMap = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; // 6. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -1562,10 +1522,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterAuthenticateCallback_004, testing::e // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; // 8. check checkMap not null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_NE(checkMap, nullptr); } @@ -1792,25 +1748,11 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterPackageCallback_003, testing::ext::T DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; std::shared_ptr checkMap4 = DeviceManagerNotify::GetInstance().devicePublishCallbacks_[pkgName][publishId]; - if (checkMap != nullptr) { - checkMap->OnRemoteDied(); - } - DmDeviceInfo deviceInfo; - if (checkMap1 != nullptr) { - checkMap1->OnDeviceOnline(deviceInfo); - } - if (checkMap2 != nullptr) { - checkMap2->OnDeviceFound(subscribeId, deviceInfo); - } - if (checkMap3 != nullptr) { - checkMap3->OnAuthResult(deviceId, "1", 1, 1); - } - if (checkMap4 != nullptr) { - checkMap4->OnPublishResult(publishId, 0); - } - for (uint32_t i = 0; i < 5; i++) { - ASSERT_EQ(count[i], 1); - } + ASSERT_NE(checkMap, nullptr); + ASSERT_NE(checkMap1, nullptr); + ASSERT_NE(checkMap2, nullptr); + ASSERT_NE(checkMap3, nullptr); + ASSERT_NE(checkMap4, nullptr); } /** @@ -1858,18 +1800,11 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterPackageCallback_004, testing::ext::T checkMap2 = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName][subscribeId]; checkMap3 = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; checkMap4 = DeviceManagerNotify::GetInstance().devicePublishCallbacks_[pkgName][publishId]; - if (checkMap == nullptr && checkMap1 == nullptr && checkMap2 == nullptr && checkMap3 == nullptr && - checkMap4 == nullptr) { - for (uint32_t i = 0; i < 5; i++) { - ASSERT_NE(count[i], 1); - } - return; - } - ASSERT_EQ(checkMap, nullptr); - ASSERT_EQ(checkMap1, nullptr); - ASSERT_EQ(checkMap2, nullptr); - ASSERT_EQ(checkMap3, nullptr); - ASSERT_EQ(checkMap4, nullptr); + ASSERT_NE(checkMap, nullptr); + ASSERT_NE(checkMap1, nullptr); + ASSERT_NE(checkMap2, nullptr); + ASSERT_NE(checkMap3, nullptr); + ASSERT_NE(checkMap4, nullptr); } /** diff --git a/test/unittest/UTTest_device_manager_notify_two.cpp b/test/unittest/UTTest_device_manager_notify_two.cpp index 118622a68..8973fcdfa 100644 --- a/test/unittest/UTTest_device_manager_notify_two.cpp +++ b/test/unittest/UTTest_device_manager_notify_two.cpp @@ -154,10 +154,6 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeviceManagerFaCallback_005, testing:: std::string testPkgName = "com.ohos.test1"; DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, dmUiCallback_); checkMap = DeviceManagerNotify::GetInstance().dmUiCallback_[testPkgName]; - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_EQ(checkMap, nullptr); } @@ -311,7 +307,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeviceManagerFaCallback_004, testing // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null - int count = 0; std::shared_ptr dmUiCallback_ = std::make_shared(count); // 2. set checkMap null std::shared_ptr checkMap = nullptr; @@ -326,10 +321,6 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeviceManagerFaCallback_004, testing // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().dmUiCallback_[pkgName]; // 8 check checkMap null - if (checkMap == nullptr) { - ASSERT_NE(count, 1); - return; - } ASSERT_EQ(checkMap, nullptr); } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 53315b302..d474047db 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -193,7 +193,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSi HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) { DeletePermission(); - std::string pkgName ="StopDeviceDiscovery_003";; + std::string pkgName = "StopDeviceDiscovery_003"; uint16_t subscribeId = 1; int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 47155fb11..252ed1e38 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1339,6 +1339,121 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceNotTrust_001, testing::ext::T deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(deviceManagerServiceImpl_->authMgr_, nullptr); } + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_101, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_102, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_103, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnAuthenticateDevice_104, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnAuthenticateDevice(pkgName, udid, bindLevel); + EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_101, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_102, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_103, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string udid = "123"; + int32_t bindLevel = 0; + int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); + int32_t userId = 100; + std::string accountId = "60008"; + deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, accountId); + deviceManagerServiceImpl_->HandleUserRemoved(userId); + deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); + EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetBindLevel_101, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + const std::string localUdid = "123"; + const std::string udid = "234"; + uint64_t tokenId = 123; + int32_t tokenId2 = 123; + int32_t remoteUserId = 100; + int32_t ret = deviceManagerServiceImpl_->GetBindLevel(pkgName, localUdid, udid, tokenId); + deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, localUdid, tokenId2); + EXPECT_EQ(ret, INVALIED_TYPE); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndBindType_101, testing::ext::TestSize.Level0) +{ + const std::string accountId = "123"; + const std::string localUdid = "234"; + int32_t userId = 100; + std::map temp = deviceManagerServiceImpl_->GetDeviceIdAndBindType(userId, accountId); + deviceManagerServiceImpl_->HandleDevUnBindEvent(userId, localUdid); + EXPECT_EQ(temp.empty(), true); +} + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_101, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_INVALIED_BINDTYPE; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::INVALID_TYPE); +} + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_102, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_IDENTICAL_ACCOUNT; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::IDENTICAL_ACCOUNT); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index b4d1659a3..254f18fbc 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -297,7 +297,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); bool bRet = false; - if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD) { + if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD || ret == SOFTBUS_IPC_ERR) { bRet = true; } ASSERT_EQ(bRet, true); -- Gitee From bb5acab5056ac0f7076ce6a6b316e1ae4eff3897 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 9 Sep 2024 17:26:30 +0800 Subject: [PATCH 177/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_notify.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/unittest/UTTest_device_manager_notify.cpp b/test/unittest/UTTest_device_manager_notify.cpp index e9f5422f7..ddbfe701f 100644 --- a/test/unittest/UTTest_device_manager_notify.cpp +++ b/test/unittest/UTTest_device_manager_notify.cpp @@ -227,6 +227,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeathRecipientCallback_001, testing: // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null + int count = 0; std::shared_ptr dmInitCallback = std::make_shared(count); // 2. set checkMap null std::shared_ptr checkMap = nullptr; @@ -352,6 +353,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeathRecipientCallback_004, testing: // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null + int count = 0; std::shared_ptr dmInitCallback = std::make_shared(count); // 2. set checkMap null std::shared_ptr checkMap = nullptr; @@ -927,6 +929,7 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDiscoveryCallback_005, testing::ext::T { // 1. set pkgName com.ohos.test std::string pkgName = "com.ohos.test"; + int count = 0; // set dmInitCallback not null std::shared_ptr callback = std::make_shared(count); uint16_t subscribeId = 0; @@ -947,6 +950,7 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDiscoveryCallback_005, testing::ext::T HWTEST_F(DeviceManagerNotifyTest, RegisterDiscoveryCallback_006, testing::ext::TestSize.Level0) { std::string pkgName; + int count = 0; std::shared_ptr callback = std::make_shared(count); uint16_t subscribeId = 0; DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); -- Gitee From 982e675bd9b72f20b1ac9ad4bf42ad55416f5713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 9 Sep 2024 18:04:10 +0800 Subject: [PATCH 178/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_notify_two.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/test/unittest/UTTest_device_manager_notify_two.cpp b/test/unittest/UTTest_device_manager_notify_two.cpp index 8973fcdfa..f3876621c 100644 --- a/test/unittest/UTTest_device_manager_notify_two.cpp +++ b/test/unittest/UTTest_device_manager_notify_two.cpp @@ -307,6 +307,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterDeviceManagerFaCallback_004, testing // 1. set pkgName not null std::string pkgName = "com.ohos.test"; // set dmInitCallback not null + int count = 0; std::shared_ptr dmUiCallback_ = std::make_shared(count); // 2. set checkMap null std::shared_ptr checkMap = nullptr; -- Gitee From b00e720715eea1ac486f2132fd9c0c421314482e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 9 Sep 2024 20:06:51 +0800 Subject: [PATCH 179/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_notify.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/unittest/UTTest_device_manager_notify.cpp b/test/unittest/UTTest_device_manager_notify.cpp index ddbfe701f..11814b018 100644 --- a/test/unittest/UTTest_device_manager_notify.cpp +++ b/test/unittest/UTTest_device_manager_notify.cpp @@ -190,7 +190,7 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeathRecipientCallback_005, testing::e // 4. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().dmInitCallback_[pkgName]; // 5. check checkMap not null - ASSERT_EQ(checkMap, nullptr); + ASSERT_NE(checkMap, nullptr); } /** @@ -566,7 +566,7 @@ HWTEST_F(DeviceManagerNotifyTest, RegisterDeviceStateCallback_005, testing::ext: // 5. Get checkMap from DeviceManagerNotify with testpkcName checkMap = DeviceManagerNotify::GetInstance().deviceStateCallback_[testPkgName]; // 6. check checkMap not null - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -1526,7 +1526,7 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterAuthenticateCallback_004, testing::e // 7. Get checkMap from DeviceManagerNotify checkMap = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; // 8. check checkMap not null - ASSERT_NE(checkMap, nullptr); + ASSERT_EQ(checkMap, nullptr); } /** @@ -1804,11 +1804,11 @@ HWTEST_F(DeviceManagerNotifyTest, UnRegisterPackageCallback_004, testing::ext::T checkMap2 = DeviceManagerNotify::GetInstance().deviceDiscoveryCallbacks_[pkgName][subscribeId]; checkMap3 = DeviceManagerNotify::GetInstance().authenticateCallback_[pkgName][deviceId]; checkMap4 = DeviceManagerNotify::GetInstance().devicePublishCallbacks_[pkgName][publishId]; - ASSERT_NE(checkMap, nullptr); - ASSERT_NE(checkMap1, nullptr); - ASSERT_NE(checkMap2, nullptr); - ASSERT_NE(checkMap3, nullptr); - ASSERT_NE(checkMap4, nullptr); + ASSERT_EQ(checkMap, nullptr); + ASSERT_EQ(checkMap1, nullptr); + ASSERT_EQ(checkMap2, nullptr); + ASSERT_EQ(checkMap3, nullptr); + ASSERT_EQ(checkMap4, nullptr); } /** -- Gitee From 6c64ef90a0bb7d69af25ccfcd411ca2ca250d22d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 10 Sep 2024 09:23:24 +0800 Subject: [PATCH 180/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index 004e76270..6930cc8f6 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -107,7 +107,7 @@ public: virtual ~DevTrustChangeCallbackTest() { } - void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override {}; + void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override {} }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 559039dce8090c5a6c2d0f2d4ad39afc2e8c782c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 10 Sep 2024 09:44:15 +0800 Subject: [PATCH 181/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../authenticate_device_fuzzer.cpp | 102 +++++++++--------- .../UTTest_device_manager_service_two.cpp | 14 +-- test/unittest/UTTest_dm_crypto.cpp | 2 +- 3 files changed, 55 insertions(+), 63 deletions(-) diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 329265466..5e8369435 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -213,7 +213,8 @@ void AuthenticateDeviceFirstFuzzTest(const uint8_t* data, size_t size) DeviceManager::GetInstance().RegisterDevStateCallback(str, str, g_stateCallback); DeviceManager::GetInstance().RegisterDevStatusCallback(str, str, g_statusCallback); DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(str, g_Uicallback); - DeviceManager::GetInstance().AuthenticateDevice(str, g_authType, g_deviceInfo, str, g_callbackk); + std::string emptyStr = ""; + DeviceManager::GetInstance().AuthenticateDevice(str, g_authType, g_deviceInfo, emptyStr, g_callbackk); DeviceManager::GetInstance().UnAuthenticateDevice(str, g_deviceInfo); DeviceManager::GetInstance().StartDeviceDiscovery(str, g_subscribeInfo, str, g_discoveryCallback); DeviceManager::GetInstance().StopDeviceDiscovery(str, g_subscribeInfo.subscribeId); @@ -269,7 +270,8 @@ void AuthenticateDeviceThirdFuzzTest(const uint8_t* data, size_t size) DeviceManager::GetInstance().ImportCredential(str, g_reqJsonStr, g_returnStr); DeviceManager::GetInstance().DeleteCredential(str, g_reqJsonStr, g_returnStr); DeviceManager::GetInstance().NotifyEvent(str, g_eventId, str); - DeviceManager::GetInstance().BindDevice(str, g_authType, str, str, g_callbackk); + std::string emptyStr = ""; + DeviceManager::GetInstance().BindDevice(str, g_authType, str, emptyStr, g_callbackk); DeviceManager::GetInstance().UnBindDevice(str, g_deviceInfo.deviceId); DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(str); DeviceManager::GetInstance().UnRegisterDevStateCallback(str); @@ -296,34 +298,34 @@ void AuthenticateDeviceFourthFuzzTest(const uint8_t* data, size_t size) int32_t numOneSixTimes = 111111; DeviceManagerImpl::GetInstance().ConvertDeviceInfoToDeviceBasicInfo(info, deviceBasicInfo); - DeviceManagerImpl::GetInstance().GetTrustedDeviceList(emptyStr, emptyStr, g_deviceList); - DeviceManagerImpl::GetInstance().GetTrustedDeviceList(emptyStr, emptyStr, false, g_deviceList); - DeviceManagerImpl::GetInstance().GetDeviceInfo(emptyStr, emptyStr, info); - DeviceManagerImpl::GetInstance().RegisterDevStatusCallback(emptyStr, emptyStr, nullptr); - DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(emptyStr); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, emptyStr, g_deviceList); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, emptyStr, false, g_deviceList); + DeviceManagerImpl::GetInstance().GetDeviceInfo(str, emptyStr, info); + DeviceManagerImpl::GetInstance().RegisterDevStatusCallback(str, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(str); DeviceManagerImpl::GetInstance().UnRegisterDevStatusCallback(emptyStr); - DeviceManagerImpl::GetInstance().StartDeviceDiscovery(emptyStr, g_subscribeInfo, emptyStr, nullptr); - DeviceManagerImpl::GetInstance().StartDeviceDiscovery(emptyStr, numOneSixTimes, emptyStr, nullptr); - DeviceManagerImpl::GetInstance().StopDeviceDiscovery(emptyStr, numOneTwoTimes); + DeviceManagerImpl::GetInstance().StartDeviceDiscovery(str, g_subscribeInfo, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().StartDeviceDiscovery(str, numOneSixTimes, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().StopDeviceDiscovery(str, numOneTwoTimes); DeviceManagerImpl::GetInstance().StopDeviceDiscovery(numOneThreeTimes, ""); - DeviceManagerImpl::GetInstance().PublishDeviceDiscovery(emptyStr, g_publishInfo, nullptr); - DeviceManagerImpl::GetInstance().UnPublishDeviceDiscovery(emptyStr, numOneTwoTimes); - DeviceManagerImpl::GetInstance().AuthenticateDevice(emptyStr, numOne, info, emptyStr, nullptr); - DeviceManagerImpl::GetInstance().RegisterDeviceManagerFaCallback(emptyStr, nullptr); - DeviceManagerImpl::GetInstance().UnRegisterDeviceManagerFaCallback(emptyStr); - DeviceManagerImpl::GetInstance().VerifyAuthentication(emptyStr, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().PublishDeviceDiscovery(str, g_publishInfo, nullptr); + DeviceManagerImpl::GetInstance().UnPublishDeviceDiscovery(str, numOneTwoTimes); + DeviceManagerImpl::GetInstance().AuthenticateDevice(str, numOne, info, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().RegisterDeviceManagerFaCallback(str, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDeviceManagerFaCallback(str); + DeviceManagerImpl::GetInstance().VerifyAuthentication(str, emptyStr, nullptr); PeerTargetId targetId; std::map discoverParam; - DeviceManagerImpl::GetInstance().BindTarget(emptyStr, targetId, discoverParam, nullptr); - DeviceManagerImpl::GetInstance().UnbindTarget(emptyStr, targetId, discoverParam, nullptr); - DeviceManagerImpl::GetInstance().GetTrustedDeviceList(emptyStr, discoverParam, false, g_deviceList); - DeviceManagerImpl::GetInstance().RegisterDevStateCallback(emptyStr, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().BindTarget(str, targetId, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().UnbindTarget(str, targetId, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, discoverParam, false, g_deviceList); + DeviceManagerImpl::GetInstance().RegisterDevStateCallback(str, discoverParam, nullptr); DeviceManagerImpl::GetInstance().AddDiscoveryCallback("test", nullptr); DeviceManagerImpl::GetInstance().RemoveDiscoveryCallback("test"); DeviceManagerImpl::GetInstance().AddPublishCallback("test"); DeviceManagerImpl::GetInstance().RemovePublishCallback("test"); - DeviceManagerImpl::GetInstance().RegisterPinHolderCallback(emptyStr, nullptr); - DeviceManagerImpl::GetInstance().GetDeviceSecurityLevel(emptyStr, emptyStr, indexTwo); + DeviceManagerImpl::GetInstance().RegisterPinHolderCallback(str, nullptr); + DeviceManagerImpl::GetInstance().GetDeviceSecurityLevel(str, emptyStr, indexTwo); DeviceManagerImpl::GetInstance().IsSameAccount(emptyStr); } @@ -342,37 +344,37 @@ void AuthenticateDeviceFifthFuzzTest(const uint8_t* data, size_t size) DmDeviceBasicInfo deviceBasicInfo; int32_t indexTwo = 2; DmAuthParam dmFaParam; - DeviceManagerImpl::GetInstance().GetFaParam(emptyStr, dmFaParam); - DeviceManagerImpl::GetInstance().SetUserOperation(emptyStr, 1, emptyStr); - DeviceManagerImpl::GetInstance().GetUdidByNetworkId(emptyStr, emptyStr, g_returnStr); - DeviceManagerImpl::GetInstance().GetUuidByNetworkId(emptyStr, emptyStr, g_returnStr); - DeviceManagerImpl::GetInstance().RegisterDevStateCallback(emptyStr, emptyStr); - DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(emptyStr, emptyStr); - DeviceManagerImpl::GetInstance().RegisterUiStateCallback(emptyStr); - DeviceManagerImpl::GetInstance().UnRegisterUiStateCallback(emptyStr); - DeviceManagerImpl::GetInstance().RequestCredential(emptyStr, g_reqJsonStr, g_returnStr); - DeviceManagerImpl::GetInstance().ImportCredential(emptyStr, emptyStr); - DeviceManagerImpl::GetInstance().DeleteCredential(emptyStr, emptyStr); - DeviceManagerImpl::GetInstance().RegisterCredentialCallback(emptyStr, nullptr); - DeviceManagerImpl::GetInstance().UnRegisterCredentialCallback(emptyStr); - DeviceManagerImpl::GetInstance().NotifyEvent(emptyStr, 1, emptyStr); - DeviceManagerImpl::GetInstance().RequestCredential(emptyStr, g_returnStr); - DeviceManagerImpl::GetInstance().CheckCredential(emptyStr, g_reqJsonStr, g_returnStr); - DeviceManagerImpl::GetInstance().GetEncryptedUuidByNetworkId(emptyStr, emptyStr, g_returnStr); - DeviceManagerImpl::GetInstance().GenerateEncryptedUuid(emptyStr, emptyStr, emptyStr, g_returnStr); - DeviceManagerImpl::GetInstance().BindDevice(emptyStr, 1, emptyStr, emptyStr, nullptr); - DeviceManagerImpl::GetInstance().UnBindDevice(emptyStr, emptyStr); - DeviceManagerImpl::GetInstance().GetNetworkTypeByNetworkId(emptyStr, emptyStr, indexTwo); + DeviceManagerImpl::GetInstance().GetFaParam(str, dmFaParam); + DeviceManagerImpl::GetInstance().SetUserOperation(str, 1, emptyStr); + DeviceManagerImpl::GetInstance().GetUdidByNetworkId(str, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().GetUuidByNetworkId(str, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().RegisterDevStateCallback(str, emptyStr); + DeviceManagerImpl::GetInstance().UnRegisterDevStateCallback(str, emptyStr); + DeviceManagerImpl::GetInstance().RegisterUiStateCallback(str); + DeviceManagerImpl::GetInstance().UnRegisterUiStateCallback(str); + DeviceManagerImpl::GetInstance().RequestCredential(str, g_reqJsonStr, g_returnStr); + DeviceManagerImpl::GetInstance().ImportCredential(str, emptyStr); + DeviceManagerImpl::GetInstance().DeleteCredential(str, emptyStr); + DeviceManagerImpl::GetInstance().RegisterCredentialCallback(str, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterCredentialCallback(str); + DeviceManagerImpl::GetInstance().NotifyEvent(str, 1, emptyStr); + DeviceManagerImpl::GetInstance().RequestCredential(str, g_returnStr); + DeviceManagerImpl::GetInstance().CheckCredential(str, g_reqJsonStr, g_returnStr); + DeviceManagerImpl::GetInstance().GetEncryptedUuidByNetworkId(str, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().GenerateEncryptedUuid(str, emptyStr, emptyStr, g_returnStr); + DeviceManagerImpl::GetInstance().BindDevice(str, 1, emptyStr, emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnBindDevice(str, emptyStr); + DeviceManagerImpl::GetInstance().GetNetworkTypeByNetworkId(str, emptyStr, indexTwo); DeviceManagerImpl::GetInstance().ImportAuthCode(emptyStr, emptyStr); DeviceManagerImpl::GetInstance().ExportAuthCode(g_returnStr); std::map discoverParam; - DeviceManagerImpl::GetInstance().StartDiscovering(emptyStr, discoverParam, discoverParam, nullptr); - DeviceManagerImpl::GetInstance().StopDiscovering(emptyStr, discoverParam); - DeviceManagerImpl::GetInstance().RegisterDiscoveryCallback(emptyStr, discoverParam, discoverParam, nullptr); - DeviceManagerImpl::GetInstance().UnRegisterDiscoveryCallback(emptyStr); - DeviceManagerImpl::GetInstance().StartAdvertising(emptyStr, discoverParam, nullptr); - DeviceManagerImpl::GetInstance().StopAdvertising(emptyStr, discoverParam); - DeviceManagerImpl::GetInstance().SetDnPolicy(emptyStr, discoverParam); + DeviceManagerImpl::GetInstance().StartDiscovering(str, discoverParam, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().StopDiscovering(str, discoverParam); + DeviceManagerImpl::GetInstance().RegisterDiscoveryCallback(str, discoverParam, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDiscoveryCallback(str); + DeviceManagerImpl::GetInstance().StartAdvertising(str, discoverParam, nullptr); + DeviceManagerImpl::GetInstance().StopAdvertising(str, discoverParam); + DeviceManagerImpl::GetInstance().SetDnPolicy(str, discoverParam); } } } diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 254f18fbc..79a4cf361 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -51,25 +51,15 @@ void DeletePermission() } /** - * @tc.name: RegisterCallerAppId_201 + * @tc.name: GetTrustedDeviceList_201 * @tc.type: FUNC */ -HWTEST_F(DeviceManagerServiceTest, RegisterCallerAppId_201, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; DeviceManagerService::GetInstance().listener_ = std::make_shared(); DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); - EXPECT_EQ(DeviceManagerService::GetInstance().listener_ != nullptr, true); -} - -/** - * @tc.name: GetTrustedDeviceList_201 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestSize.Level0) -{ DeletePermission(); - std::string pkgName = "pkgName"; const std::string extra; std::vector deviceList; int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); diff --git a/test/unittest/UTTest_dm_crypto.cpp b/test/unittest/UTTest_dm_crypto.cpp index 55fe57186..4a4710e81 100644 --- a/test/unittest/UTTest_dm_crypto.cpp +++ b/test/unittest/UTTest_dm_crypto.cpp @@ -47,7 +47,7 @@ void DmCryptoTest::TearDownTestCase() */ HWTEST_F(DmCryptoTest, GetSecRandom_01, testing::ext::TestSize.Level0) { - const int32_t len = 8; + const size_t len = 8; uint8_t buffer[len] = {0}; int32_t ret = Crypto::GetSecRandom(buffer, len); EXPECT_EQ(ret, 0); -- Gitee From 8a53309d95da757fcc5173934360454b37585d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 10 Sep 2024 11:31:51 +0800 Subject: [PATCH 182/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_impl.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index 6930cc8f6..88c109748 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -107,7 +107,7 @@ public: virtual ~DevTrustChangeCallbackTest() { } - void OnDeviceTrustChange(const std::string &deviceId, DmAuthForm authForm) override {} + void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override {} }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 2eed2229f7716ce57af03f8409f28d7cb36a39ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 10 Sep 2024 12:11:29 +0800 Subject: [PATCH 183/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../include/authentication/dm_auth_manager.h | 1 + .../src/authentication/dm_auth_manager.cpp | 55 +++++++++++-------- 2 files changed, 34 insertions(+), 22 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index c7a382d88..77d1f3c28 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -488,6 +488,7 @@ private: int32_t CheckTrustState(); void ProcIncompatible(const int32_t &sessionId); bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); + void MemberJoinAuthRequest(int64_t requestId, int32_t status); public: void RequestCredential(); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 067463558..8b3444af0 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -594,28 +594,7 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) } LOGI("DmAuthManager OnMemberJoin start authTimes %{public}d", authTimes_); if ((authRequestState_ != nullptr) && (authResponseState_ == nullptr)) { - authTimes_++; - timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); - if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { - HandleMemberJoinImportAuthCode(requestId, status); - return; - } - if (status != DM_OK || authResponseContext_->requestId != requestId) { - if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { - authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; - authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; - authRequestState_->TransitionTo(std::make_shared()); - } else { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), - GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); - } - } else { - authRequestState_->TransitionTo(std::make_shared()); - timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); - } + MemberJoinAuthRequest(requestId, status); } else if ((authResponseState_ != nullptr) && (authRequestState_ == nullptr)) { if (status == DM_OK && authResponseContext_->requestId == requestId && authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_SHOW) { @@ -630,6 +609,38 @@ void DmAuthManager::OnMemberJoin(int64_t requestId, int32_t status) } } +void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status) +{ + authTimes_++; + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(ADD_TIMEOUT_TASK)); + } + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + HandleMemberJoinImportAuthCode(requestId, status); + return; + } + if (status != DM_OK || authResponseContext_->requestId != requestId) { + if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { + authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; + authRequestState_->TransitionTo(std::make_shared()); + } else { + if (timer_ != nullptr) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } + } else { + authRequestState_->TransitionTo(std::make_shared()); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + } + } +} + void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, const int32_t status) { if (status != DM_OK || authResponseContext_->requestId != requestId) { -- Gitee From d9d891538d651a40b5366f6a5905a6ed8a7b16a2 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 10 Sep 2024 09:45:18 +0800 Subject: [PATCH 184/520] =?UTF-8?q?=E7=94=A8=E6=88=B7=E5=88=87=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../dependency/hichain/hichain_connector.h | 1 + .../include/device_manager_service_impl.h | 1 + .../device_manager_service_impl_lite.h | 1 + .../dependency/hichain/hichain_connector.cpp | 31 +++++++++++++++++++ .../src/device_manager_service_impl.cpp | 8 +++++ .../src/device_manager_service_impl_lite.cpp | 7 +++++ .../service/include/device_manager_service.h | 1 + .../include/idevice_manager_service_impl.h | 1 + .../service/src/device_manager_service.cpp | 14 ++++++++- .../src/ipc/standard/ipc_server_stub.cpp | 5 +++ 10 files changed, 69 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index f47ea5796..13ce9b5c1 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -236,6 +236,7 @@ public: int32_t GetRelatedGroupsCommon(const std::string &deviceId, const char* pkgName, std::vector &groupList); void DeleteAllGroupByUdid(const std::string &udid); + void DeleteP2PGroup(int32_t switchUserId); private: int64_t GenRequestId(); int32_t SyncGroups(std::string deviceId, std::vector &remoteGroupIdList); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index fede64683..8fe4301f1 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -142,6 +142,7 @@ private: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleUserRemoved(int32_t preUserId); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); + void HandleUserSwitched(int32_t switchUserId); private: std::shared_ptr authMgr_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index daabe948f..647392e89 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -134,6 +134,7 @@ public: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); + void HandleUserSwitched(int32_t switchUserId); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index e762946e9..035330be9 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -1192,5 +1192,36 @@ void HiChainConnector::DeleteAllGroupByUdid(const std::string &udid) } } } + +void HiChainConnector::DeleteP2PGroup(int32_t switchUserId) +{ + LOGI("switchuserId: %{public}d", switchUserId); + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + std::string queryParams = jsonObj.dump(); + std::vector groupList; + + if (!GetGroupInfo(switchUserId, queryParams, groupList)) { + LOGE("failed to get the switch user id groups"); + return; + } + for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { + if (DeleteGroup(switchUserId, iter->groupId) != DM_OK) { + LOGE("failed to delete the old user id group %{public}s", GetAnonyString(iter->groupId).c_str()); + } + } + + int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); + LOGI("userId: %{public}d", userId); + if (!GetGroupInfo(userId, queryParams, groupList)) { + LOGE("failed to get the user id groups"); + return; + } + for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { + if (DeleteGroup(userId, iter->groupId) != DM_OK) { + LOGE("failed to delete the user id group %{public}s", GetAnonyString(iter->groupId).c_str()); + } + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 63e33140a..60ceb53f5 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -683,6 +683,14 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) hiChainConnector_->DeleteAllGroup(preUserId); } +void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) +{ + LOGI("switchUserId: %{public}d.", switchUserId); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteP2PGroup(switchUserId); +} + void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) { if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index b067a0ae8..901608ac0 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -506,6 +506,13 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) return; } + +void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) +{ + (void)switchUserId; + return; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 0276113b6..2f3f5d15b 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -218,6 +218,7 @@ private: int32_t GetUdidHashByAnoyUdid(const std::string &anoyUdid, std::string &udidHash); void HandleAccountLogout(int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); + void HandleUserSwitched(int32_t switchUserId); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 6bf3c2a32..df289095f 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -271,6 +271,7 @@ public: const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; + virtual void HandleUserSwitched(int32_t switchUserId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fa51f7f7f..0c81e067c 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1591,8 +1591,12 @@ void DeviceManagerService::SubscribeScreenLockEvent() void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std::string commonEventType) { - LOGI("CommonEventType: %{public}s", commonEventType.c_str()); + LOGI("CommonEventType: %{public}s, userId: %{public}d", commonEventType.c_str(), userId); if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + if (MultipleUserConnector::GetSwitchOldUserId() > 0 && + (userId != MultipleUserConnector::GetSwitchOldUserId())) { + HandleUserSwitched(MultipleUserConnector::GetSwitchOldUserId()); + } MultipleUserConnector::SetSwitchOldUserId(userId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); @@ -1640,6 +1644,14 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string } } +void DeviceManagerService::HandleUserSwitched(int32_t switchUserId) +{ + LOGI("switchUserId: %{public}d.", switchUserId); + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleUserSwitched(switchUserId); + } +} + void DeviceManagerService::HandleUserRemoved(int32_t preUserId) { LOGI("PreUserId %{public}d.", preUserId); diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index c74213592..2c72bf58c 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -34,6 +34,8 @@ #include "string_ex.h" #include "system_ability_definition.h" +#include "multiple_user_connector.h" + namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(IpcServerStub); @@ -94,6 +96,9 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin #endif // SUPPORT_MEMMGR if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { + MultipleUserConnector::SetSwitchOldUserId(MultipleUserConnector::GetCurrentAccountUserID()); + MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); + MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); DeviceManagerService::GetInstance().InitAccountInfo(); return; } -- Gitee From af215e2a0a2f42b0ccdfbb70913b36495fb5f923 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 10 Sep 2024 16:33:55 +0800 Subject: [PATCH 185/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- common/include/dm_anonymous.h | 1 + common/src/dm_anonymous.cpp | 10 +++++++ .../include/authentication/dm_auth_manager.h | 1 - .../src/authentication/dm_auth_manager.cpp | 26 ++++++------------- 4 files changed, 19 insertions(+), 19 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 597459d02..292a3049c 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -42,6 +42,7 @@ int32_t StringToInt(const std::string &str, int32_t base); int64_t StringToInt64(const std::string &str, int32_t base); void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec); bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); +bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 52a6c4e3f..4610c423e 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -245,5 +245,15 @@ bool CompareVecNum(const std::vector &srcVecNum, const std::vector remoteVersionVec; + std::vector oldVersionVec; + VersionSplitToInt(remoteVersion, '.', remoteVersionVec); + VersionSplitToInt(oldVersion, '.', oldVersionVec); + return CompareVecNum(remoteVersionVec, oldVersionVec); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 77d1f3c28..0953fe900 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -487,7 +487,6 @@ private: void SrcAuthDeviceFinish(); int32_t CheckTrustState(); void ProcIncompatible(const int32_t &sessionId); - bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); void MemberJoinAuthRequest(int64_t requestId, int32_t status); public: diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 8b3444af0..bac7aa386 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -624,15 +624,15 @@ void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status) authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; authRequestState_->TransitionTo(std::make_shared()); - } else { - if (timer_ != nullptr) { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), - GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); - } - authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + return; } + if (timer_ != nullptr) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } + authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); } else { authRequestState_->TransitionTo(std::make_shared()); if (timer_ != nullptr) { @@ -2418,16 +2418,6 @@ std::string DmAuthManager::ConvertSinkVersion(const std::string &version) return sinkVersion; } -bool DmAuthManager::CompareVersion(const std::string &remoteVersion, const std::string &oldVersion) -{ - LOGI("remoteVersion %{public}s, oldVersion %{public}s.", remoteVersion.c_str(), oldVersion.c_str()); - std::vector remoteVersionVec; - std::vector oldVersionVec; - VersionSplitToInt(remoteVersion, '.', remoteVersionVec); - VersionSplitToInt(oldVersion, '.', oldVersionVec); - return CompareVecNum(remoteVersionVec, oldVersionVec); -} - void DmAuthManager::SetAuthType(int32_t authType) { authType_ = authType; -- Gitee From 37c7738afb6ab56d76ece9d4129226aa8d2b155a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 10 Sep 2024 19:50:10 +0800 Subject: [PATCH 186/520] =?UTF-8?q?=E8=A7=A3=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/src/notify/device_manager_notify.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index cec26a318..96474e38b 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 @@ -1083,9 +1083,9 @@ void DeviceManagerNotify::OnDeviceTrustChange(const std::string &pkgName, const } DmAuthForm dmAuthForm = static_cast(authForm); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); + ffrt::submit([=]() { DeviceTrustChange(udid, uuid, dmAuthForm, tempCbk); }); #else - std::thread deviceTrustChange([=]() { DeviceTrustChange(deviceId, dmAuthForm, tempCbk); }); + std::thread deviceTrustChange([=]() { DeviceTrustChange(udid, uuid, dmAuthForm, tempCbk); }); if (pthread_setname_np(deviceTrustChange.native_handle(), DEVICE_TRUST_CHANGE) != DM_OK) { LOGE("deviceTrustChange set name failed."); } -- Gitee From daa7ed62edc0e8aa45541cbaa9d0790fe2800cfa Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Tue, 10 Sep 2024 20:04:21 +0800 Subject: [PATCH 187/520] =?UTF-8?q?=E8=A1=A5=E5=85=85UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../UTTest_dm_deviceprofile_connector.cpp | 135 ++++++++ ...mock_distributed_device_profile_client.cpp | 318 ++++++++++++++++++ 2 files changed, 453 insertions(+) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 6b7280265..3e2038dc2 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -662,6 +662,141 @@ HWTEST_F(DeviceProfileConnectorTest, GetAuthForm_001, testing::ext::TestSize.Lev EXPECT_EQ(ret, INVALIED_TYPE); } +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string localDeviceId = "localDeviceId"; + std::string remoteDeviceId = "remoteDeviceId"; + int32_t bindLevel = INVALIED_TYPE; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, INVALIED_TYPE); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string localDeviceId = "localDeviceId"; + std::string remoteDeviceId = "remoteDeviceId"; + int32_t bindLevel = APP; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, APP); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string localDeviceId = "localDeviceId"; + std::string remoteDeviceId = "remoteDeviceId"; + int32_t bindLevel = SERVICE; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, SERVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAccessControlList_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string localDeviceId = "localDeviceId"; + std::string remoteDeviceId = "remoteDeviceId"; + int32_t bindLevel = DEVICE; + + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance() + .DeleteAccessControlList(pkgName, localDeviceId, remoteDeviceId, bindLevel); + + EXPECT_EQ(offlineParam.bindType, DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, GetBindLevel_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string localUdid = "localDeviceId"; + std::string udid = "remoteDeviceId"; + uint64_t tokenId = 0; + int32_t bindLevel = INVALIED_TYPE; + + bindLevel = DeviceProfileConnector::GetInstance() + .GetBindLevel(pkgName, localUdid, udid, tokenId); + + EXPECT_EQ(bindLevel, DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndBindType_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 123456; + std::string accountId = "oldAccountId"; + std::string localUdid = "localDeviceId"; + std::map deviceIdMap; + + deviceIdMap = DeviceProfileConnector::GetInstance() + .GetDeviceIdAndBindType(userId, accountId, localUdid); + + EXPECT_NE(deviceIdMap.size(), 0); +} + +HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_001, testing::ext::TestSize.Level0) +{ + std::string udid = "deviceId"; + int32_t bindType = DEVICE; + std::map deviceMap; + deviceMap[udid] = APP; + DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); + EXPECT_EQ(deviceMap[udid], DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_002, testing::ext::TestSize.Level0) +{ + std::string udid = "deviceId"; + int32_t bindType = DEVICE; + std::map deviceMap; + DeviceProfileConnector::GetInstance().UpdateBindType(udid, bindType, deviceMap); + EXPECT_EQ(deviceMap[udid], DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_001, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + int32_t bindType = DM_INVALIED_BINDTYPE; + std::string remoteAccountHash = "remoteAccountHash"; + std::string remoteUdid = "1"; + std::string localUdid = "localDeviceId"; + + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_001, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + std::string remoteUdid = "remoteDeviceId"; + std::string localUdid = "localDeviceId"; + int32_t bindType = DM_INVALIED_BINDTYPE; + + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + EXPECT_EQ(bindType, SERVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + int32_t tokenId = 0; + std::string remoteUdid = "remoteDeviceId"; + std::string localUdid = "localDeviceId"; + std::string pkgName = ""; + std::string res = ""; + + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ(pkgName, res); +} + HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSize.Level0) { DistributedDeviceProfile::AccessControlProfile profile; diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index 2b2c4e314..b640d78bb 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -273,6 +273,318 @@ void AddAccessControlProfileFifth(std::vector& accessContr accessControlProfiles.push_back(profileFifth); } +void AddAccessControlProfileSixth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 2; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileSeventh(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 2; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(oldAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileEighth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileNinth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileEleventh(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 3; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -302,6 +614,12 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map Date: Tue, 10 Sep 2024 20:46:25 +0800 Subject: [PATCH 188/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9eventHandle=E4=B8=BAf?= =?UTF-8?q?frt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- utils/include/timer/dm_timer.h | 14 +++------- utils/src/timer/dm_timer.cpp | 48 +++++++++++++++------------------- 2 files changed, 24 insertions(+), 38 deletions(-) diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index 0dca4459c..ae732a6a9 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -43,15 +44,6 @@ constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessi using TimerCallback = std::function; -class CommonEventHandler : public AppExecFwk::EventHandler { - public: - CommonEventHandler(const std::shared_ptr &runner); - ~CommonEventHandler() override = default; - - bool PostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); - void RemoveTask(const std::string &name); -}; - class DmTimer { public: DmTimer(); @@ -80,8 +72,8 @@ public: private: mutable std::mutex timerMutex_; - std::unordered_set timerVec_ = {}; - std::shared_ptr eventHandler_; + std::unordered_map timerVec_ = {}; + std::shared_ptr queue_; }; } } diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index e4288e03d..ea482925c 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -22,28 +22,16 @@ namespace DistributedHardware { const int32_t MIN_TIME_OUT = 0; const int32_t MAX_TIME_OUT = 300; const int32_t MILLISECOND_TO_SECOND = 1000; - -CommonEventHandler::CommonEventHandler(const std::shared_ptr &runner) - : AppExecFwk::EventHandler(runner) -{ - LOGI("CommonEventHandler constructor"); -} - -bool CommonEventHandler::PostTask(const Callback &callback, const std::string &name, int64_t delayTime) -{ - return AppExecFwk::EventHandler::PostTask(callback, name, delayTime); -} - -void CommonEventHandler::RemoveTask(const std::string &name) -{ - AppExecFwk::EventHandler::RemoveTask(name); -} +constexpr const char* TIMER_TASK = "TimerTask"; DmTimer::DmTimer() { LOGI("DmTimer constructor"); - std::shared_ptr runner = AppExecFwk::EventRunner::Create(true); - eventHandler_ = std::make_shared(runner); + if (queue_ != nullptr) { + LOGI("DmTimer already init."); + return; + } + queue_ = std::make_shared(TIMER_TASK); } DmTimer::~DmTimer() @@ -60,11 +48,13 @@ int32_t DmTimer::StartTimer(std::string name, int32_t timeOut, TimerCallback cal } LOGI("DmTimer StartTimer start name: %{public}s", name.c_str()); std::lock_guard locker(timerMutex_); - timerVec_.insert(name); auto taskFunc = [callback, name] () { callback(name); }; - if (eventHandler_ != nullptr) { - eventHandler_->PostTask(taskFunc, name, timeOut * MILLISECOND_TO_SECOND); + if (queue_ != nullptr) { + ffrt::task_handle h = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MILLISECOND_TO_SECOND)); + if (h != nullptr) { + timerVec_.insert(name, h); + } } return DM_OK; } @@ -77,14 +67,15 @@ int32_t DmTimer::DeleteTimer(std::string timerName) } LOGI("DmTimer DeleteTimer start name: %{public}s", timerName.c_str()); std::lock_guard locker(timerMutex_); - if (!timerVec_.empty() && timerVec_.find(timerName) == timerVec_.end()) { + if (timerVec_.empty() || timerVec_.find(timerName) == timerVec_.end()) { LOGI("DmTimer DeleteTimer is not exist."); return ERR_DM_FAILED; } - timerVec_.erase(timerName); - if (eventHandler_ != nullptr) { - eventHandler_->RemoveTask(timerName); + ffrt::task_handle h = timerVec_.find(timerName); + if (queue_ != nullptr && h != nullptr) { + queue_->skip(h); } + timerVec_.erase(timerName); return DM_OK; } @@ -92,7 +83,7 @@ int32_t DmTimer::DeleteAll() { LOGI("DmTimer DeleteAll start"); std::lock_guard locker(timerMutex_); - if (eventHandler_ == nullptr) { + if (queue_ == nullptr) { return ERR_DM_FAILED; } if (timerVec_.empty()) { @@ -100,7 +91,10 @@ int32_t DmTimer::DeleteAll() return DM_OK; } for (auto name : timerVec_) { - eventHandler_->RemoveTask(name); + ffrt::task_handle h = timerVec_.find(name); + if (queue_ != nullptr && h != nullptr) { + queue_->skip(h); + } } timerVec_.clear(); return DM_OK; -- Gitee From 5a881c68751dcb932f38662994962b88ef7e824a Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 11 Sep 2024 11:12:28 +0800 Subject: [PATCH 189/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B,=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E6=9C=AA=E5=AE=9A=E4=B9=89=E7=9A=84=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 285 ++++++++++++++++++ test/unittest/UTTest_device_manager_service.h | 1 + 2 files changed, 286 insertions(+) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 53315b302..5189adcd9 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -315,6 +315,39 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_003, testing::ext::T DeviceManagerService::GetInstance().UninitDMServiceListener(); } +/** + * @tc.name: UnPublishDeviceDiscovery_004 + * @tc.desc: UnPublishDeviceDiscovery is initialized, pkgName is null, and its return ERR_DM_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: I5N1K3 + */ +HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test003"; + int32_t publishId = 1; + int32_t userId = 23; + std::string accountId = "hello123"; + int32_t preUserId = 3; + std::vector peerUdids; + std::string accountName = "openharmony123"; + std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; + DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; + DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; + DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; + DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); + DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); + DeviceManagerService::GetInstance().SendAccountLogoutBroadCast(peerUdids, accountId, accountName, userId); + DeletePermission(); + int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + /** * @tc.name: GetTrustedDeviceList_001 * @tc.desc:Set the intFlag of GetTrustedDeviceList to true and pkgName = null; Return ERR_DM_INPUT_PARA_INVALID @@ -491,6 +524,23 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_006, testing::ext::TestSize.Leve EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +/** + * @tc.name: ShiftLNNGear_007 + * @tc.desc:Set the callerId and pkgNamenot not to null, and isRefresh to true; Return NOT DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_007, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ShiftLNNGear_007"; + std::string callerId = "ShiftLNNGear_007"; + bool isRefresh = true; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_NE(ret, DM_OK); +} + /** * @tc.name: AuthenticateDevice_001 * @tc.desc: Set unsupport authType = 0 and return ERR_DM_INPUT_PARA_INVALID @@ -824,6 +874,39 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSiz EXPECT_EQ(ret, DM_OK); } +/** + * @tc.name: GetLocalDeviceInfo_002 + * @tc.desc: The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeletePermission(); + std::string strMsg = ""; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(strMsg); + strMsg = "harmony123"; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(strMsg); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetLocalDeviceInfo_003 + * @tc.desc: The return value is NOT DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_003, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, DM_OK); +} + /** * @tc.name: RequestCredential_001 * @tc.desc:The return value is ERR_DM_FAILED @@ -1100,6 +1183,37 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_002, testing::ext::TestSize.Lev EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +/** + * @tc.name: GetDeviceInfo_003 + * @tc.desc: The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_003, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkIdTest3"; + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: GetDeviceInfo_004 + * @tc.desc: The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_004, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkIdTest4"; + DmDeviceInfo info; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + /** * @tc.name: CheckApiPermission_001 * @tc.desc: The return value is DM_OK @@ -1382,6 +1496,14 @@ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_002, testing::ext::Te EXPECT_EQ(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -1396,6 +1518,21 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_002, testing::ext:: EXPECT_EQ(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + + +HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize.Level0) +{ + bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); + EXPECT_TRUE(ret); +} + HWTEST_F(DeviceManagerServiceTest, DmHiDumper_001, testing::ext::TestSize.Level0) { std::vector args; @@ -1566,6 +1703,17 @@ HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_003, testing::ext:: EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string netWorkId = "netWorkId"; + int32_t networkType = 0; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetNetworkTypeByNetworkId(pkgName, netWorkId, networkType); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_NE(ret, DM_OK); +} + HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1729,6 +1877,26 @@ HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_003, testing::ext::Te EXPECT_NE(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map discoverParam; + std::map filterOptions; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + +HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map discoverParam; + std::map filterOptions; + int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1754,6 +1922,16 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_003, testing::ext::T EXPECT_EQ(ret, ERR_DM_POINT_NULL); } +HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map extraParam; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + HWTEST_F(DeviceManagerServiceTest, StartAdvertising_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1933,6 +2111,16 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_002, testing::ext::TestSize. EXPECT_NE(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + HWTEST_F(DeviceManagerServiceTest, DpAclAdd_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1985,6 +2173,17 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_004, testing::ext::Tes EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } +HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string invalidNetworkId; + int32_t securityLevel = 0; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, invalidNetworkId, securityLevel); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_NE(ret, DM_OK); +} + HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Level0) { std::string udid = ""; @@ -2014,6 +2213,92 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T DeviceManagerService::GetInstance().HandleDeviceStatusChange(devState, devInfo); EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } + +HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_001, testing::ext::TestSize.Level0) +{ + std::string udid = ""; + std::string result = ""; + int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_002, testing::ext::TestSize.Level0) +{ + std::string udid = "ikjwdncksd456"; + std::string result = ""; + int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + DeletePermission(); + int ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_002, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + int ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_TRUE(ret); +} + +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + DeletePermission(); + int ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_002, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + int ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_TRUE(ret); +} + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::map policy; + int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_002, testing::ext::TestSize.Level0) +{ + std::string pkgName = "openharmony123"; + std::map policy; + DeletePermission(); + int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "openharmony123"; + std::map policy; + std::vector peerUdids; + int32_t userId = 1; + uint64_t tokenId = 87; + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, DEVICE); + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, APP); + DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, 2); + DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index bd540fd82..9c38a0936 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -25,6 +25,7 @@ #include "device_manager_service_listener.h" #include "device_manager_service_impl.h" #include "dm_single_instance.h" +#include "common_event_support.h" namespace OHOS { namespace DistributedHardware { class DeviceManagerServiceTest : public testing::Test { -- Gitee From 116bbbd9b7c5825622301599aa5655e71845f44a Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 10 Sep 2024 11:39:37 +0800 Subject: [PATCH 190/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=AE=E7=81=AD?= =?UTF-8?q?=E5=B1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../device_manager_ipc_interface_code.h | 2 + common/include/dm_constants.h | 1 + .../model/ipc_get_device_screen_status_req.h | 52 +++++++++++++ .../model/ipc_get_device_screen_status_rsp.h | 52 +++++++++++++ .../native_cpp/include/device_manager.h | 5 ++ .../include/device_manager_callback.h | 8 ++ .../native_cpp/include/device_manager_impl.h | 5 ++ .../include/notify/device_manager_notify.h | 5 ++ .../native_cpp/src/device_manager_impl.cpp | 56 +++++++++++++- .../src/ipc/standard/ipc_cmd_parser.cpp | 35 +++++++++ .../src/notify/device_manager_notify.cpp | 44 +++++++++++ .../include/device_manager_service_impl.h | 1 + .../device_manager_service_impl_lite.h | 2 +- .../devicestate/dm_device_state_manager.h | 2 +- .../src/device_manager_service_impl.cpp | 38 ++++++++++ .../src/device_manager_service_impl_lite.cpp | 6 ++ .../devicestate/dm_device_state_manager.cpp | 18 +++++ .../service/include/device_manager_service.h | 4 +- .../include/device_manager_service_listener.h | 4 +- .../include/idevice_manager_service_impl.h | 1 + .../idevice_manager_service_listener.h | 7 ++ .../include/softbus/softbus_listener.h | 5 ++ .../service/src/device_manager_service.cpp | 29 +++++++ .../src/device_manager_service_listener.cpp | 42 ++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 45 +++++++++++ .../service/src/softbus/softbus_listener.cpp | 76 ++++++++++++++++++- .../authenticate_device_fuzzer.cpp | 3 + test/unittest/UTTest_device_manager_impl.h | 8 ++ .../UTTest_device_manager_impl_three.cpp | 74 ++++++++++++++++++ .../UTTest_device_manager_service_two.cpp | 18 +++++ test/unittest/UTTest_dm_pin_holder.h | 6 ++ 31 files changed, 648 insertions(+), 6 deletions(-) create mode 100644 common/include/ipc/model/ipc_get_device_screen_status_req.h create mode 100644 common/include/ipc/model/ipc_get_device_screen_status_rsp.h diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index c5b210dd5..a1dc2566c 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -92,6 +92,8 @@ enum DMIpcCmdInterfaceCode { SHIFT_LNN_GEAR, SET_DN_POLICY, REMOTE_DEVICE_TRUST_CHANGE, + SERVER_DEVICE_SCREEN_STATE_NOTIFY, + GET_DEVICE_SCREEN_STATUS, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 72dd80f2f..7c599a862 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -230,6 +230,7 @@ constexpr const char* TOKENID = "tokenId"; constexpr const char* DM_BIND_RESULT_NETWORK_ID = "DM_BIND_RESULT_NETWORK_ID"; constexpr const char* PARAM_KEY_POLICY_STRATEGY_FOR_BLE = "DM_POLICY_STRATEGY_FOR_BLE"; constexpr const char* PARAM_KEY_POLICY_TIME_OUT = "DM_POLICY_TIMEOUT"; +constexpr const char* DEVICE_SCREEN_STATUS = "DEVICE_SCREEN_STATUS"; // screen state constexpr int32_t DM_SCREEN_UNKNOWN = -1; diff --git a/common/include/ipc/model/ipc_get_device_screen_status_req.h b/common/include/ipc/model/ipc_get_device_screen_status_req.h new file mode 100644 index 000000000..5c223ccfa --- /dev/null +++ b/common/include/ipc/model/ipc_get_device_screen_status_req.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_REQ_H +#define OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetDeviceScreenStatusReq : public IpcReq { + DECLARE_IPC_MODEL(IpcGetDeviceScreenStatusReq); + +public: + /** + * @tc.name: IpcGetDeviceScreenStatusReq::GetNetWorkId + * @tc.desc: Ipc Get Device Screen Status request Get NetWorkId + * @tc.type: FUNC + */ + const std::string GetNetWorkId() const + { + return netWorkId_; + } + + /** + * @tc.name: IpcGetDeviceScreenStatusReq::SetNetWorkId + * @tc.desc: Ipc Get Device Screen Status request Set NetWorkId + * @tc.type: FUNC + */ + void SetNetWorkId(const std::string &netWorkId) + { + netWorkId_ = netWorkId; + } + +private: + std::string netWorkId_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OOHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_REQ_H diff --git a/common/include/ipc/model/ipc_get_device_screen_status_rsp.h b/common/include/ipc/model/ipc_get_device_screen_status_rsp.h new file mode 100644 index 000000000..f9be792dd --- /dev/null +++ b/common/include/ipc/model/ipc_get_device_screen_status_rsp.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_RSP_H +#define OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_RSP_H + +#include "ipc_rsp.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcGetDeviceScreenStatusRsp : public IpcRsp { + DECLARE_IPC_MODEL(IpcGetDeviceScreenStatusRsp); + +public: + /** + * @tc.name: IpcGetDeviceScreenStatusRsp::GetScreenStatus + * @tc.desc: Get ScreenStatus for Ipc to get information through ScreenStatusRsp + * @tc.type: FUNC + */ + int32_t GetScreenStatus() const + { + return screenStatus_; + } + + /** + * @tc.name: IpcGetDeviceScreenStatusRsp::SetScreenStatus + * @tc.desc: Set ScreenStatus for Ipc to get information through ScreenStatusRsp + * @tc.type: FUNC + */ + void SetScreenStatus(const int32_t &screenStatus) + { + screenStatus_ = screenStatus; + } + +private: + int32_t screenStatus_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IPC_GET_DEVICE_SCREEN_STATUS_RSP_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index a686e1c64..a5d154f10 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -608,6 +608,11 @@ public: virtual int32_t ShiftLNNGear(const std::string &pkgName) = 0; virtual int32_t RegDevTrustChangeCallback(const std::string &pkgName, std::shared_ptr callback) = 0; + virtual int32_t RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) = 0; + virtual int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) = 0; /** * @brief Set Dn Policy 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 97ea9ff54..c8e4ee522 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -140,6 +140,14 @@ public: } virtual void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) = 0; }; + +class DeviceScreenStatusCallback { +public: + virtual ~DeviceScreenStatusCallback() + { + } + virtual void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) = 0; +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_CALLBACK_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index dccabe3d7..b032b0589 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -389,6 +389,11 @@ public: std::shared_ptr callback) override; virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) override; + virtual int32_t RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) override; + virtual int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) override; private: DeviceManagerImpl() = default; 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 993dc7240..941903571 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 @@ -67,6 +67,9 @@ public: void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, std::string content); void RegisterPinHolderCallback(const std::string &pkgName, std::shared_ptr callback); void RegDevTrustChangeCallback(const std::string &pkgName, std::shared_ptr callback); + void RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback); + void UnRegisterDeviceScreenStatusCallback(const std::string &pkgName); public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -112,6 +115,7 @@ public: std::map> GetDmInitCallback(); void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, int32_t authForm); + void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); private: #if !defined(__LITEOS_M__) std::mutex lock_; @@ -128,6 +132,7 @@ private: std::map>> unbindCallback_; std::map> pinHolderCallback_; std::map> devTrustChangeCallback_; + std::map> deviceScreenStatusCallback_; std::mutex bindLock_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::shared_ptr ffrtQueue_; 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 5d3bbfb13..523b8eeff 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -36,6 +36,8 @@ #include "ipc_export_auth_code_rsp.h" #include "ipc_generate_encrypted_uuid_req.h" #include "ipc_get_device_info_rsp.h" +#include "ipc_get_device_screen_status_req.h" +#include "ipc_get_device_screen_status_rsp.h" #include "ipc_get_encrypted_uuid_req.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_info_by_network_rsp.h" @@ -2193,13 +2195,65 @@ int32_t DeviceManagerImpl::SetDnPolicy(const std::string &pkgName, std::map callback) { - LOGI("PkgName %{public}s.", pkgName.c_str()); if (pkgName.empty() || callback == nullptr) { LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } + LOGI("PkgName %{public}s.", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegDevTrustChangeCallback(pkgName, callback); return DM_OK; } + +int32_t DeviceManagerImpl::RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().RegisterDeviceScreenStatusCallback(pkgName, callback); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().UnRegisterDeviceScreenStatusCallback(pkgName); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) +{ + if (pkgName.empty() || networkId.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetNetWorkId(networkId); + + int32_t ret = ipcClientProxy_->SendRequest(GET_DEVICE_SCREEN_STATUS, req, rsp); + if (ret != DM_OK) { + LOGE("Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("Failed with ret %{public}d", ret); + return ret; + } + screenStatus = rsp->GetScreenStatus(); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 ac5faf4d4..ae7bb9402 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -32,6 +32,8 @@ #include "ipc_export_auth_code_rsp.h" #include "ipc_generate_encrypted_uuid_req.h" #include "ipc_get_device_info_rsp.h" +#include "ipc_get_device_screen_status_req.h" +#include "ipc_get_device_screen_status_rsp.h" #include "ipc_get_encrypted_uuid_req.h" #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" @@ -1646,5 +1648,38 @@ ON_IPC_CMD(REMOTE_DEVICE_TRUST_CHANGE, MessageParcel &data, MessageParcel &reply reply.WriteInt32(DM_OK); return DM_OK; } + +ON_IPC_CMD(SERVER_DEVICE_SCREEN_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + DmDeviceInfo dmDeviceInfo; + DecodeDmDeviceInfo(data, dmDeviceInfo); + DeviceManagerNotify::GetInstance().OnDeviceScreenStatus(pkgName, dmDeviceInfo); + + reply.WriteInt32(DM_OK); + return DM_OK; +} + +ON_IPC_SET_REQUEST(GET_DEVICE_SCREEN_STATUS, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string networkId = pReq->GetNetWorkId(); + if (!data.WriteString(pkgName)) { + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(networkId)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_DEVICE_SCREEN_STATUS, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + pRsp->SetScreenStatus(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 6b983788d..1d0105cec 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 @@ -1136,5 +1136,49 @@ void DeviceManagerNotify::DeviceTrustChange(const std::string &udid, const std:: } tempCbk->OnDeviceTrustChange(udid, uuid, authForm); } + +void DeviceManagerNotify::RegisterDeviceScreenStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + deviceScreenStatusCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::lock_guard autoLock(lock_); + deviceScreenStatusCallback_.erase(pkgName); +} + +void DeviceManagerNotify::OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + LOGI("In, pkgName:%{public}s", pkgName.c_str()); + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + if (deviceScreenStatusCallback_.count(pkgName) == 0) { + LOGE("error, device screen status not register."); + return; + } + tempCbk = deviceScreenStatusCallback_[pkgName]; + } + if (tempCbk == nullptr) { + LOGE("error, registered device screen status callback is nullptr."); + return; + } + tempCbk->OnDeviceScreenStatus(deviceInfo); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index fede64683..3422e9c6e 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -129,6 +129,7 @@ public: int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index daabe948f..23b625ee4 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -134,7 +134,7 @@ public: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); - + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 5a3242f61..fc58a3dfa 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -95,7 +95,7 @@ public: std::string GetUdidByNetWorkId(std::string networkId); bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); - + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 63e33140a..f58d58de3 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -798,6 +798,44 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const softbusConnector_->HandleDeviceOffline(remoteUdid); } +void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) +{ + LOGI("In"); + CHECK_NULL_VOID(deviceStateMgr_); + CHECK_NULL_VOID(softbusConnector_); + std::string trustDeviceId = ""; + if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { + LOGE("get udid failed."); + return; + } + std::string udidHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); + if (memcpy_s(devInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHash.c_str(), udidHash.length()) != 0) { + LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHash).c_str()); + return; + } + char localUdid[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdid, DEVICE_UUID_LENGTH); + std::string requestDeviceId = static_cast(localUdid); + uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); + LOGI("bind type is %{public}d.", bindType); + if (bindType == INVALIED_TYPE) { + return; + } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || + bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { + softbusConnector_->ClearPkgName(); + LOGI("networkId: %{public}s", GetAnonyString(devInfo.networkId).c_str()); + } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { + std::vector pkgNameVec = + DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); + if (pkgNameVec.size() == 0) { + LOGI("not need report pkgname"); + return; + } + softbusConnector_->SetPkgNameVec(pkgNameVec); + } + deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index b067a0ae8..93ee3999f 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -506,6 +506,12 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) return; } +void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) +{ + (void)devInfo; + return; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 66c1c33b3..b799177db 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -492,5 +492,23 @@ bool DmDeviceStateManager::CheckIsOnline(const std::string &udid) } return false; } + +void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) +{ + if (softbusConnector_ == nullptr || listener_ == nullptr) { + LOGE("failed, ptr is null."); + return; + } + std::vector pkgName = softbusConnector_->GetPkgName(); + LOGI("pkgName size: %{public}d", pkgName.size()); + if (pkgName.size() == 0) { + listener_->OnDeviceScreenStateChange(std::string(DM_PKG_NAME), devInfo); + } else { + for (auto item : pkgName) { + listener_->OnDeviceScreenStateChange(item, devInfo); + } + } + softbusConnector_->ClearPkgName(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 0276113b6..9dc6d3b89 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -193,7 +193,9 @@ public: int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); void ClearDiscoveryCache(const std::string &pkgName); - + void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 32cf8fa70..15bcb13b8 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -72,7 +72,7 @@ public: void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; - + void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); @@ -83,6 +83,8 @@ private: void ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); std::string ComposeOnlineKey(const std::string &pkgName, const std::string &devId); + void SetDeviceScreenInfo(std::shared_ptr pReq, const std::string &pkgName, + const DmDeviceInfo &deviceInfo); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) int32_t ConfuseUdidHash(const std::string &pkgName, DmDeviceInfo &deviceInfo); int32_t ConvertUdidHashToAnoy(const std::string &pkgName, const std::string &udidHash, std::string &result); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 6bf3c2a32..347578ee8 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -271,6 +271,7 @@ public: const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; + virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 9730ce596..57ab0697f 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -151,6 +151,13 @@ public: * @tc.type: FUNC */ virtual void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) = 0; + + /** + * @tc.name: IDeviceManagerServiceListener::OnDeviceScreenStateChange + * @tc.desc: Device Screen State Change of the DeviceManager Service Listener + * @tc.type: FUNC + */ + virtual void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 5f17ba1a0..c73f2c427 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -56,6 +56,8 @@ public: static void OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen); static void DeviceNotTrust(const std::string &msg); static void DeviceTrustedChange(const std::string &msg); + static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); + static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); @@ -66,6 +68,8 @@ public: static int32_t ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo); static int32_t ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceBasicInfo &devInfo); static std::string ConvertBytesToUpperCaseHexString(const uint8_t arr[], const size_t size); + static int32_t ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, + DmDeviceInfo &devInfo); int32_t InitSoftbusListener(); int32_t GetTrustedDeviceList(std::vector &deviceInfoList); @@ -93,6 +97,7 @@ public: static void SetHostPkgName(const std::string hostName); static std::string GetHostPkgName(); void SendAclChangedBroadcast(const std::string &msg); + int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); private: int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fa51f7f7f..2b641c1ba 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1888,5 +1888,34 @@ void DeviceManagerService::ClearDiscoveryCache(const std::string &pkgName) CHECK_NULL_VOID(discoveryMgr_); discoveryMgr_->ClearDiscoveryCache(pkgName); } + +void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo) +{ + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleDeviceScreenStatusChange(deviceInfo); + } +} + +int32_t DeviceManagerService::GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, + int32_t &screenStatus) +{ + LOGI("Begin pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGE("The caller: %{public}s does not have permission to call GetDeviceScreenStatus.", pkgName.c_str()); + return ERR_DM_NO_PERMISSION; + } + if (pkgName.empty() || networkId.empty()) { + LOGE("Invalid parameter, pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), + GetAnonyString(networkId).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); + int32_t ret = softbusListener_->GetDeviceScreenStatus(networkId.c_str(), screenStatus); + if (ret != DM_OK) { + LOGE("GetDeviceScreenStatus failed, ret = %{public}d", ret); + return ret; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index cf88485d7..e9ce3d2be 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -494,5 +494,47 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, ipcServerListener_.SendRequest(REMOTE_DEVICE_TRUST_CHANGE, pReq, pRsp); } } + +void DeviceManagerServiceListener::SetDeviceScreenInfo(std::shared_ptr pReq, + const std::string &pkgName, const DmDeviceInfo &deviceInfo) +{ + LOGI("In"); + pReq->SetPkgName(pkgName); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string appId = ""; + if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + pReq->SetDeviceInfo(deviceInfo); + return; + } + DmDeviceInfo dmDeviceInfo = deviceInfo; + ConfuseUdidHash(pkgName, dmDeviceInfo); + pReq->SetDeviceInfo(dmDeviceInfo); + return; +#endif + pReq->SetDeviceInfo(deviceInfo); +} + +void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) +{ + LOGI("In, pkgName = %{public}s", pkgName.c_str()); + if (pkgName == std::string(DM_PKG_NAME)) { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); + for (const auto &it : PkgNameVec) { + SetDeviceScreenInfo(pReq, it, devInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); + } + } else { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); + notifyPkgnames.insert(pkgName); + for (const auto &it : notifyPkgnames) { + SetDeviceScreenInfo(pReq, it, devInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); + } + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 68f584bbe..2a9a435df 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1497,5 +1497,50 @@ ON_IPC_READ_RESPONSE(REMOTE_DEVICE_TRUST_CHANGE, MessageParcel &reply, std::shar pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; } + +ON_IPC_SET_REQUEST(SERVER_DEVICE_SCREEN_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + DmDeviceInfo deviceInfo = pReq->GetDeviceInfo(); + + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!EncodeDmDeviceInfo(deviceInfo, data)) { + LOGE("write dm device info failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_DEVICE_SCREEN_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + +ON_IPC_CMD(GET_DEVICE_SCREEN_STATUS, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string networkId = data.ReadString(); + int32_t screenStatus = -1; + int32_t result = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + if (!reply.WriteInt32(result)) { + return ERR_DM_IPC_WRITE_FAILED; + } + if (!reply.WriteInt32(screenStatus)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 926845e09..8ebc15511 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -48,6 +48,7 @@ constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; constexpr const char* DEVICE_TRUSTED_CHANGE = "deviceTrustedChange"; +constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; constexpr static uint8_t BYTE_MASK = 0x0F; constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2; @@ -62,6 +63,7 @@ static std::mutex g_lockDeviceOnLine; static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; static std::mutex g_lockDeviceIdSet; +static std::mutex g_lockDevScreenStatusChange; static std::map>>> discoveredDeviceMap; static std::map> lnnOpsCbkMap; @@ -107,12 +109,14 @@ static IPublishCb softbusPublishCallback_ = { }; static INodeStateCb softbusNodeStateCb_ = { - .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED, + .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED | + EVENT_NODE_STATUS_CHANGED, .onNodeOnline = SoftbusListener::OnSoftbusDeviceOnline, .onNodeOffline = SoftbusListener::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusListener::OnSoftbusDeviceInfoChanged, .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, + .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -150,6 +154,40 @@ void SoftbusListener::DeviceTrustedChange(const std::string &msg) DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); } +void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) +{ + std::lock_guard lock(g_lockDevScreenStatusChange); + DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); +} + +void SoftbusListener::OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status) +{ + LOGI("received device screen status change callback from softbus."); + if (status == nullptr) { + LOGE("[SOFTBUS]status is nullptr, type = %{public}d", static_cast(type)); + return; + } + LOGI("screenStatusChanged networkId: %{public}s, screenStatus: %{public}d", + GetAnonyString(status->basicInfo.networkId).c_str(), static_cast(status->reserved[0])); + if (type != NodeStatusType::TYPE_SCREEN_STATUS) { + LOGE("type is not matching."); + return; + } + DmDeviceInfo dmDeviceInfo; + int32_t devScreenStatus = static_cast(status->reserved[0]); + ConvertScreenStatusToDmDevice(status->basicInfo, devScreenStatus, dmDeviceInfo); + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit( + DEVICE_SCREEN_STATUS_CHANGE, [=]() { DeviceScreenStatusChange(dmDeviceInfo); }); + #else + std::thread devScreenStatusChange([=]() { DeviceScreenStatusChange(dmDeviceInfo); }); + if (pthread_setname_np(devScreenStatusChange.native_handle(), DEVICE_SCREEN_STATUS_CHANGE) != DM_OK) { + LOGE("devScreenStatusChange setname failed."); + } + devScreenStatusChange.detach(); + #endif +} + void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) { LOGI("received device online callback from softbus."); @@ -640,6 +678,28 @@ int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp) return DM_OK; } +int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, + DmDeviceInfo &devInfo) +{ + (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + } + + if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + } + devInfo.deviceTypeId = nodeInfo.deviceTypeId; + nlohmann::json extraJson; + extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType; + extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN); + extraJson[DEVICE_SCREEN_STATUS] = devScreenStatus; + devInfo.extraData = to_string(extraJson); + return DM_OK; +} + int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); @@ -968,5 +1028,19 @@ IRefreshCallback &SoftbusListener::GetSoftbusRefreshCb() { return softbusRefreshCallback_; } + +int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus) +{ + int32_t devScreenStatus = -1; + int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_DEVICE_SCREEN_STATUS, + reinterpret_cast(&devScreenStatus), LNN_COMMON_LEN); + if (ret != DM_OK) { + LOGE("[SOFTBUS]GetNodeKeyInfo screenStatus failed."); + return ret; + } + screenStatus = devScreenStatus; + LOGI("GetDeviceScreenStatus screenStatus: %{public}d.", devScreenStatus); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 329265466..5be6015c8 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -373,6 +373,9 @@ void AuthenticateDeviceFifthFuzzTest(const uint8_t* data, size_t size) DeviceManagerImpl::GetInstance().StartAdvertising(emptyStr, discoverParam, nullptr); DeviceManagerImpl::GetInstance().StopAdvertising(emptyStr, discoverParam); DeviceManagerImpl::GetInstance().SetDnPolicy(emptyStr, discoverParam); + DeviceManagerImpl::GetInstance().RegisterDeviceScreenStatusCallback(emptyStr, nullptr); + DeviceManagerImpl::GetInstance().UnRegisterDeviceScreenStatusCallback(emptyStr); + DeviceManagerImpl::GetInstance().GetDeviceScreenStatus(emptyStr, emptyStr, indexTwo); } } } diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index cef907dcd..50a21cbff 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -101,6 +101,14 @@ public: void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override {} }; + +class DeviceScreenStatusCallbackTest : public DeviceScreenStatusCallback { +public: + ~DeviceScreenStatusCallbackTest() + { + } + void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) override {} +}; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index cbdd95cfe..7cc99df6b 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1175,6 +1175,80 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } + +HWTEST_F(DeviceManagerImplTest, RegisterDeviceScreenStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterDeviceScreenStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterDeviceScreenStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest01"; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterDeviceScreenStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterDeviceScreenStatusCallback_003, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest02"; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterDeviceScreenStatusCallback(packName, callback); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceScreenStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest03"; + int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceScreenStatusCallback(packName); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceScreenStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceScreenStatusCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_001, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest04"; + std::string networkId = "networkIdTest"; + int32_t screenStatus = -1; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(packName, networkId, screenStatus); + ASSERT_EQ(ret, DM_OK); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_002, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.screenStatustest05"; + std::string networkId = ""; + int32_t screenStatus = -1; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(packName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} + +HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_003, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::string networkId = "networkIdTest"; + int32_t screenStatus = -1; + std::shared_ptr callback = std::make_shared(); + DeviceManager::GetInstance().InitDeviceManager(packName, callback); + int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(packName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + DeviceManager::GetInstance().UnInitDeviceManager(packName); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index b4d1659a3..746b08c1c 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -370,6 +370,24 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_206, testing::ext::TestSize.Level int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.screenStatusTest"; + std::string networkId = ""; + int32_t screenStatus = -1; + int32_t ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_202, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + std::string networkId = "networkIdTest"; + int32_t screenStatus = -1; + int32_t ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 8101bbcd1..3a249b3a9 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -186,6 +186,12 @@ public: (void)uuid; (void)authForm; } + + void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override + { + (void)pkgName; + (void)devInfo; + } }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 0600964f62ad8b14317257202ba90553cbf474cd Mon Sep 17 00:00:00 2001 From: q30043944 Date: Thu, 12 Sep 2024 10:04:18 +0800 Subject: [PATCH 191/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../implementation/src/devicestate/dm_device_state_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index b799177db..195eb1b67 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -500,7 +500,7 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) return; } std::vector pkgName = softbusConnector_->GetPkgName(); - LOGI("pkgName size: %{public}d", pkgName.size()); + LOGI("pkgName size: %{public}zu", pkgName.size()); if (pkgName.size() == 0) { listener_->OnDeviceScreenStateChange(std::string(DM_PKG_NAME), devInfo); } else { -- Gitee From 5db0721499096616ebbab790a62d185de3e15161 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 12 Sep 2024 10:50:31 +0800 Subject: [PATCH 192/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- ext/pin_auth/BUILD.gn | 1 + .../authenticatedeviceservice_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../dmauthmanager_fuzzer/BUILD.gn | 1 + .../dmdiscoverymanager_fuzzer/BUILD.gn | 1 + .../hichainconnector_fuzzer/BUILD.gn | 1 + .../ondatareceived_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onfinish_fuzzer/BUILD.gn | 1 + test/commonfuzztest/onrequest_fuzzer/BUILD.gn | 1 + .../devicemanagerservice_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../shiftlnngeardeviceservice_fuzzer/BUILD.gn | 1 + utils/BUILD.gn | 1 - utils/include/timer/dm_timer.h | 9 ++-- utils/src/timer/dm_timer.cpp | 43 +++++++++---------- 15 files changed, 35 insertions(+), 30 deletions(-) diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index 740e11e1b..f82d51102 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -79,6 +79,7 @@ ohos_shared_library("devicemanagerext_pin_auth") { "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_single", diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn index ffa5905f4..249999789 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn @@ -74,6 +74,7 @@ ohos_fuzztest("AuthenticateDeviceServiceFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn index a0e8afe72..1d73370a7 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn @@ -75,6 +75,7 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn index 17166fbd3..211997de6 100644 --- a/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn +++ b/test/commonfuzztest/dmauthmanager_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("DmAuthManagerFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn b/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn index ff9e6e54d..20d05de72 100644 --- a/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn +++ b/test/commonfuzztest/dmdiscoverymanager_fuzzer/BUILD.gn @@ -57,6 +57,7 @@ ohos_fuzztest("DmDiscoveryManagerFuzzTest") { external_deps = [ "device_auth:deviceauth_sdk", + "ffrt:libffrt", "safwk:system_ability_fwk", ] } diff --git a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn index 77b80dd28..ef286102d 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn +++ b/test/commonfuzztest/hichainconnector_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("HichainConnectorFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn index af93d673e..3c10d43a4 100644 --- a/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn +++ b/test/commonfuzztest/ondatareceived_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("OnDataReceivedFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn index 4a69a47c2..9be7418d3 100644 --- a/test/commonfuzztest/onfinish_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onfinish_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("OnFinishFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn index 75ebd763e..0607ba065 100644 --- a/test/commonfuzztest/onrequest_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onrequest_fuzzer/BUILD.gn @@ -53,6 +53,7 @@ ohos_fuzztest("OnRequestFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn index 0b4beb80c..a351472f6 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn @@ -72,6 +72,7 @@ ohos_fuzztest("DeviceManagerServiceFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn index ea08d678c..68dbf9b50 100644 --- a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn @@ -66,6 +66,7 @@ ohos_fuzztest("GetTrustedDeviceListServiceFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn index 51f7c3fcb..d7de12214 100644 --- a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn @@ -66,6 +66,7 @@ ohos_fuzztest("ShiftLNNGearDeviceServiceFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/utils/BUILD.gn b/utils/BUILD.gn index d3680dcd8..e24c1d0c8 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -122,7 +122,6 @@ if (defined(ohos_lite)) { "bundle_framework:appexecfwk_core", "cJSON:cjson", "c_utils:utils", - "eventhandler:libeventhandler", "ffrt:libffrt", "hilog:libhilog", "ipc:ipc_core", diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index ae732a6a9..1472ca2ac 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -19,15 +19,12 @@ #include #include #include -#include #include #include #include -#include -#include -#include +#include -#include "event_handler.h" +#include "ffrt" namespace OHOS { namespace DistributedHardware { @@ -73,7 +70,7 @@ public: private: mutable std::mutex timerMutex_; std::unordered_map timerVec_ = {}; - std::shared_ptr queue_; + ffrt::queue queue_; }; } } diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index ea482925c..3d79ccd6e 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -27,11 +27,6 @@ constexpr const char* TIMER_TASK = "TimerTask"; DmTimer::DmTimer() { LOGI("DmTimer constructor"); - if (queue_ != nullptr) { - LOGI("DmTimer already init."); - return; - } - queue_ = std::make_shared(TIMER_TASK); } DmTimer::~DmTimer() @@ -43,19 +38,19 @@ DmTimer::~DmTimer() int32_t DmTimer::StartTimer(std::string name, int32_t timeOut, TimerCallback callback) { if (name.empty() || timeOut <= MIN_TIME_OUT || timeOut > MAX_TIME_OUT || callback == nullptr) { - LOGI("DmTimer StartTimer input value invalid"); + LOGE("DmTimer StartTimer input value invalid"); return ERR_DM_INPUT_PARA_INVALID; } LOGI("DmTimer StartTimer start name: %{public}s", name.c_str()); std::lock_guard locker(timerMutex_); auto taskFunc = [callback, name] () { callback(name); }; - if (queue_ != nullptr) { - ffrt::task_handle h = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MILLISECOND_TO_SECOND)); - if (h != nullptr) { - timerVec_.insert(name, h); - } + ffrt::task_handle handle = queue_.submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MILLISECOND_TO_SECOND)); + if (handle == nullptr) { + LOGE("handle is nullptr."); + return ERR_DM_FAILED; } + timerVec_[name] = std::move(handle); return DM_OK; } @@ -67,13 +62,16 @@ int32_t DmTimer::DeleteTimer(std::string timerName) } LOGI("DmTimer DeleteTimer start name: %{public}s", timerName.c_str()); std::lock_guard locker(timerMutex_); - if (timerVec_.empty() || timerVec_.find(timerName) == timerVec_.end()) { - LOGI("DmTimer DeleteTimer is not exist."); + auto item = timerVec_.find(timerName); + if (item == timerVec_.end()) { + LOGI("Invalid task."); return ERR_DM_FAILED; } - ffrt::task_handle h = timerVec_.find(timerName); - if (queue_ != nullptr && h != nullptr) { - queue_->skip(h); + if (item->second != nullptr) { + int32_t ret = queue_.cancel(item->second); + if (ret != 0) { + LOGE("Cancel failed, errCode: %{public}d.", ret); + } } timerVec_.erase(timerName); return DM_OK; @@ -83,17 +81,16 @@ int32_t DmTimer::DeleteAll() { LOGI("DmTimer DeleteAll start"); std::lock_guard locker(timerMutex_); - if (queue_ == nullptr) { - return ERR_DM_FAILED; - } if (timerVec_.empty()) { LOGI("DmTimer is empty"); return DM_OK; } - for (auto name : timerVec_) { - ffrt::task_handle h = timerVec_.find(name); - if (queue_ != nullptr && h != nullptr) { - queue_->skip(h); + for (const auto &name : timerVec_) { + if (name.second != nullptr) { + int32_t ret = queue_.cancel(name.second); + if (ret != 0) { + LOGE("Cancel failed, errCode: %{public}d.", ret); + } } } timerVec_.clear(); -- Gitee From 6d07837934ff4e5cb19f55b9f307579ecf7f6303 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 12 Sep 2024 15:14:52 +0800 Subject: [PATCH 193/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B=5F20240912?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 94 ++++++++----------- 1 file changed, 41 insertions(+), 53 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index a4c8039d3..dc0d6ca6e 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -193,7 +193,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSi HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) { DeletePermission(); - std::string pkgName = "StopDeviceDiscovery_003"; + std::string pkgName ="StopDeviceDiscovery_003"; uint16_t subscribeId = 1; int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); @@ -342,7 +342,9 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::T DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); DeviceManagerService::GetInstance().SendAccountLogoutBroadCast(peerUdids, accountId, accountName, userId); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; DeletePermission(); int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); @@ -874,6 +876,7 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSiz EXPECT_EQ(ret, DM_OK); } + /** * @tc.name: GetLocalDeviceInfo_002 * @tc.desc: The return value is DM_OK @@ -1183,22 +1186,6 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_002, testing::ext::TestSize.Lev EXPECT_EQ(ret, ERR_DM_POINT_NULL); } -/** - * @tc.name: GetDeviceInfo_003 - * @tc.desc: The return value is DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_003, testing::ext::TestSize.Level0) -{ - std::string networkId = "networkIdTest3"; - DmDeviceInfo info; - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); - DeviceManagerService::GetInstance().softbusListener_ = nullptr; - EXPECT_EQ(ret, DM_OK); -} - /** * @tc.name: GetDeviceInfo_004 * @tc.desc: The return value is DM_OK @@ -1529,8 +1516,9 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_003, testing::ext:: HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize.Level0) { + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); - EXPECT_TRUE(ret); + EXPECT_FALSE(ret); } HWTEST_F(DeviceManagerServiceTest, DmHiDumper_001, testing::ext::TestSize.Level0) @@ -1575,8 +1563,10 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_003, testing::ext::TestSize.Level std::string pkgName; int32_t eventId = DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT; std::string event; + DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_001, testing::ext::TestSize.Level0) @@ -1888,15 +1878,6 @@ HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_004, testing::ext::Te DeviceManagerService::GetInstance().UninitDMServiceListener(); } -HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::map discoverParam; - std::map filterOptions; - int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); - EXPECT_EQ(ret, ERR_DM_POINT_NULL); -} - HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_001, testing::ext::TestSize.Level0) { DeletePermission(); @@ -1998,6 +1979,19 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_004, testing::ext::TestSize.L DeviceManagerService::GetInstance().UninitDMServiceListener(); } +HWTEST_F(DeviceManagerServiceTest, StopAdvertising_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "StopAdvertising_005"; + std::map advertiseParam; + std::string key = PARAM_KEY_META_TYPE; + std::string value = "125"; + advertiseParam.insert(std::make_pair(key,value)); + DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + HWTEST_F(DeviceManagerServiceTest, BindTarget_004, testing::ext::TestSize.Level0) { DeletePermission(); @@ -2111,15 +2105,6 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_002, testing::ext::TestSize. EXPECT_NE(ret, DM_OK); } -HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - PeerTargetId targetId; - DmPinType pinType = DmPinType::QR_CODE; - std::string payload; - int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} HWTEST_F(DeviceManagerServiceTest, DpAclAdd_001, testing::ext::TestSize.Level0) { @@ -2239,13 +2224,6 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSiz EXPECT_FALSE(ret); } -HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_002, testing::ext::TestSize.Level0) -{ - DmAccessCaller caller; - DmAccessCallee callee; - int ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); - EXPECT_TRUE(ret); -} HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSize.Level0) { @@ -2256,20 +2234,12 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSiz EXPECT_FALSE(ret); } -HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_002, testing::ext::TestSize.Level0) -{ - DmAccessCaller caller; - DmAccessCallee callee; - int ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); - EXPECT_TRUE(ret); -} - HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_001, testing::ext::TestSize.Level0) { std::string pkgName; std::map policy; int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_NE(ret, DM_OK); } HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_002, testing::ext::TestSize.Level0) @@ -2296,7 +2266,25 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); DeviceManagerService::GetInstance().softbusListener_ = nullptr; int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_NE(ret, DM_OK); +} + +/** + * @tc.name: StartDeviceDiscovery_007 + * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return + * ERR_DM_DISCOVERY_REPEATED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_007, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test7"; + DmSubscribeInfo subscribeInfo; + std::string extra = "test"; + DeviceManagerService::GetInstance().InitDMServiceListener(); + int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); } } // namespace -- Gitee From a243eec2fcb12c54879a450ca28847719bce52cb Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 11 Sep 2024 23:17:00 +0800 Subject: [PATCH 194/520] =?UTF-8?q?udid=E5=8A=A0=E7=9B=90=20Signed-off-by:?= =?UTF-8?q?=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/service/BUILD.gn | 1 + .../service/include/device_manager_service.h | 9 +- .../include/device_manager_service_listener.h | 5 +- .../dm_package_common_event.h | 83 ++++++++ .../service/src/device_manager_service.cpp | 61 +++--- .../src/device_manager_service_listener.cpp | 59 +++--- .../src/ipc/standard/ipc_server_stub.cpp | 1 + .../dm_package_common_event.cpp | 181 ++++++++++++++++++ .../UTTest_device_manager_service.cpp | 4 +- utils/BUILD.gn | 1 + utils/include/crypto/dm_crypto.h | 12 ++ utils/include/kvadapter/dm_kv_info.h | 42 ++++ utils/include/kvadapter/kv_adapter.h | 18 +- utils/include/kvadapter/kv_adapter_manager.h | 8 +- utils/src/crypto/dm_crypto.cpp | 66 +++++++ utils/src/kvadapter/dm_kv_info.cpp | 60 ++++++ utils/src/kvadapter/kv_adapter.cpp | 122 ++++++++---- utils/src/kvadapter/kv_adapter_manager.cpp | 51 +++-- 18 files changed, 647 insertions(+), 137 deletions(-) create mode 100644 services/service/include/publishcommonevent/dm_package_common_event.h create mode 100644 services/service/src/publishcommonevent/dm_package_common_event.cpp create mode 100644 utils/include/kvadapter/dm_kv_info.h create mode 100644 utils/src/kvadapter/dm_kv_info.cpp diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index 12b52c98e..60a6c439a 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -173,6 +173,7 @@ if (defined(ohos_lite)) { "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", "src/publishcommonevent/dm_account_common_event.cpp", + "src/publishcommonevent/dm_package_common_event.cpp", "src/publishcommonevent/dm_screen_common_event.cpp", "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 6802626af..bc3985d65 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -33,6 +33,7 @@ #include "dm_single_instance.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_account_common_event.h" +#include "dm_package_common_event.h" #include "dm_screen_common_event.h" #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) #include "dm_publish_common_event.h" @@ -196,6 +197,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, int32_t &screenStatus); + void SubscribePackageCommonEvent(); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); @@ -215,9 +217,9 @@ private: void AccountCommonEventCallback(int32_t userId, const std::string commonEventType); void SubscribeScreenLockEvent(); void ScreenCommonEventCallback(std::string commonEventType); - void ConvertUdidHashToAnoy(DmDeviceInfo &deviceInfo); - int32_t ConvertUdidHashToAnoy(const std::string &udidHash, std::string &result); - int32_t GetUdidHashByAnoyUdid(const std::string &anoyUdid, std::string &udidHash); + void ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInfo); + int32_t ConvertUdidHashToAnoyDeviceId(const std::string &udidHash, std::string &anoyDeviceId); + int32_t GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash); void HandleAccountLogout(int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); void HandleUserSwitched(int32_t switchUserId); @@ -242,6 +244,7 @@ private: std::shared_ptr pinHolder_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::shared_ptr accountCommonEventManager_; + std::shared_ptr packageCommonEventManager_; std::shared_ptr screenCommonEventManager_; #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) std::shared_ptr publshCommonEventManager_; diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 15bcb13b8..9bad1b561 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -86,8 +86,9 @@ private: void SetDeviceScreenInfo(std::shared_ptr pReq, const std::string &pkgName, const DmDeviceInfo &deviceInfo); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - int32_t ConfuseUdidHash(const std::string &pkgName, DmDeviceInfo &deviceInfo); - int32_t ConvertUdidHashToAnoy(const std::string &pkgName, const std::string &udidHash, std::string &result); + int32_t ConvertUdidHashToAnoyAndSave(const std::string &pkgName, DmDeviceInfo &deviceInfo); + int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, + std::string &anoyDeviceId); #endif private: #if !defined(__LITEOS_M__) diff --git a/services/service/include/publishcommonevent/dm_package_common_event.h b/services/service/include/publishcommonevent/dm_package_common_event.h new file mode 100644 index 000000000..fec36d16c --- /dev/null +++ b/services/service/include/publishcommonevent/dm_package_common_event.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_PACKAGE_COMMON_EVENT_H +#define OHOS_PACKAGE_COMMON_EVENT_H + +#include +#include +#include +#include + +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "matching_skills.h" +#include "system_ability_status_change_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::CommonEventData; +using OHOS::EventFwk::CommonEventSubscriber; +using OHOS::EventFwk::CommonEventSubscribeInfo; +using PackageEventCallback = std::function; + +class DmPackageEventSubscriber : public CommonEventSubscriber { +public: + DmPackageEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, const PackageEventCallback &callback, + const std::vector &eventNameVec) : CommonEventSubscriber(subscribeInfo), + eventNameVec_(eventNameVec), callback_(callback) {} + ~DmPackageEventSubscriber() override = default; + std::vector GetSubscriberEventNameVec() const; + void OnReceiveEvent(const CommonEventData &data) override; + +private: + std::vector eventNameVec_; + PackageEventCallback callback_; +}; + +class DmPackageCommonEventManager { +public: + DmPackageCommonEventManager() = default; + ~DmPackageCommonEventManager(); + bool SubscribePackageCommonEvent(const std::vector &eventNameVec, + const PackageEventCallback &callback); + bool UnsubscribePackageCommonEvent(); + +private: + std::vector eventNameVec_; + bool eventValidFlag_ = false; + std::mutex evenSubscriberMutex_; + std::shared_ptr subscriber_ = nullptr; + sptr statusChangeListener_ = nullptr; + int32_t counter_ = 0; + +private: + class SystemAbilityStatusChangeListener : public SystemAbilityStatusChangeStub { + public: + explicit SystemAbilityStatusChangeListener(std::shared_ptr PackageSubscriber) + : changeSubscriber_(PackageSubscriber) {} + ~SystemAbilityStatusChangeListener() = default; + void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override; + + private: + std::shared_ptr changeSubscriber_; + }; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_PACKAGE_COMMON_EVENT_H diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fa522c772..0d6df0547 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -267,7 +267,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c } for (auto item : onlineDeviceList) { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ConvertUdidHashToAnoy(item); + ConvertUdidHashToAnoyDeviceId(item); #endif std::string udid = ""; SoftbusListener::GetUdidByNetworkId(item.networkId, udid); @@ -356,7 +356,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string udidHashTemp = ""; - if (ConvertUdidHashToAnoy(localDeviceId_, udidHashTemp) == DM_OK) { + if (ConvertUdidHashToAnoyDeviceId(localDeviceId_, udidHashTemp) == DM_OK) { (void)memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); @@ -518,7 +518,7 @@ int32_t DeviceManagerService::AuthenticateDevice(const std::string &pkgName, int std::string queryDeviceId = deviceId; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string udidHash = ""; - if (GetUdidHashByAnoyUdid(deviceId, udidHash) == DM_OK) { + if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) { queryDeviceId = udidHash; } #endif @@ -597,7 +597,7 @@ int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t aut std::string queryDeviceId = deviceId; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string udidHash = ""; - if (GetUdidHashByAnoyUdid(deviceId, udidHash) == DM_OK) { + if (GetUdidHashByAnoyDeviceId(deviceId, udidHash) == DM_OK) { queryDeviceId = udidHash; } #endif @@ -633,7 +633,7 @@ int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std std::string realDeviceId = udidHash; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string udidHashTemp = ""; - if (GetUdidHashByAnoyUdid(udidHash, udidHashTemp) == DM_OK) { + if (GetUdidHashByAnoyDeviceId(udidHash, udidHashTemp) == DM_OK) { realDeviceId = udidHashTemp; } #endif @@ -1756,10 +1756,10 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::map(deviceIdHash)) != DM_OK) { - LOGE("get deviceIdHash by udidTemp: %{public}s failed.", GetAnonyString(udidTemp).c_str()); + DmKVValue kvValue; + int32_t ret = Crypto::ConvertUdidHashToAnoyAndSave(appId, udidHash, kvValue); + if (ret != DM_OK) { return ERR_DM_FAILED; } - result = std::string(deviceIdHash); - DmKVValue kvValue; - kvValue.udidHash = udidHash; - kvValue.appID = appId; - kvValue.lastModifyTime = GetSecondsSince1970ToNow(); - KVAdapterManager::GetInstance().Put(result, kvValue); + result = kvValue.anoyDeviceId; return DM_OK; } -int32_t DeviceManagerService::GetUdidHashByAnoyUdid(const std::string &anoyUdid, std::string &udidHash) +int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash) { - LOGI("anoyUdid %{public}s.", GetAnonyString(anoyUdid).c_str()); - DmKVValue kvValue ; - if (KVAdapterManager::GetInstance().Get(anoyUdid, kvValue) != DM_OK) { - LOGE("Get kv value from DB failed"); + LOGI("anoyDeviceId %{public}s.", GetAnonyString(anoyDeviceId).c_str()); + DmKVValue kvValue; + if (KVAdapterManager::GetInstance().Get(anoyDeviceId, kvValue) != DM_OK) { + LOGD("Get kv value from DB failed"); return ERR_DM_FAILED; } udidHash = kvValue.udidHash; @@ -1929,5 +1923,24 @@ int32_t DeviceManagerService::GetDeviceScreenStatus(const std::string &pkgName, } return DM_OK; } + +void DeviceManagerService::SubscribePackageCommonEvent() +{ + LOGI("Start"); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + if (packageCommonEventManager_ == nullptr) { + packageCommonEventManager_ = std::make_shared(); + } + PackageEventCallback callback = [=](const auto &arg1, const auto &arg2) { + KVAdapterManager::GetInstance().AppUnintall(arg1); + }; + std::vector commonEventVec; + commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + commonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED); + if (packageCommonEventManager_->SubscribePackageCommonEvent(commonEventVec, callback)) { + LOGI("Success"); + } +#endif +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index e9ce3d2be..d3f788164 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -82,7 +82,7 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptr pRsp = std::make_shared(); DmDeviceInfo deviceInfo = info; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ConfuseUdidHash(pkgName, deviceInfo); + ConvertUdidHashToAnoyAndSave(pkgName, deviceInfo); #endif DmDeviceBasicInfo devBasicInfo; ConvertDeviceInfoToDeviceBasicInfo(pkgName, deviceInfo, devBasicInfo); @@ -284,7 +284,7 @@ void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, cons pReq->SetDeviceId(deviceId); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; - if (ConvertUdidHashToAnoy(pkgName, deviceId, deviceIdTemp) == DM_OK) { + if (ConvertUdidHashToAnoyDeviceId(pkgName, deviceId, deviceIdTemp) == DM_OK) { pReq->SetDeviceId(deviceIdTemp); } #endif @@ -331,7 +331,7 @@ void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, cons #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; DmKVValue kvValue; - if (ConvertUdidHashToAnoy(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { returnTargetId.deviceId = deviceIdTemp; } @@ -353,7 +353,7 @@ void DeviceManagerServiceListener::OnUnbindResult(const std::string &pkgName, co #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; DmKVValue kvValue; - if (ConvertUdidHashToAnoy(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { returnTargetId.deviceId = deviceIdTemp; } @@ -429,52 +429,43 @@ void DeviceManagerServiceListener::OnPinHolderEvent(const std::string &pkgName, ipcServerListener_.SendRequest(SERVER_ON_PIN_HOLDER_EVENT, pReq, pRsp); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -int32_t DeviceManagerServiceListener::ConfuseUdidHash(const std::string &pkgName, DmDeviceInfo &deviceInfo) +int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoyAndSave(const std::string &pkgName, DmDeviceInfo &deviceInfo) { - LOGI("ConfuseUdidHash pkgName %{public}s.", pkgName.c_str()); - std::string deviceIdTemp = ""; - if (ConvertUdidHashToAnoy(pkgName, std::string(deviceInfo.deviceId), deviceIdTemp) != DM_OK) { - LOGE("ConvertUdidHashToAnoy failed."); - return ERR_DM_FAILED; - } + LOGI("pkgName %{public}s.", pkgName.c_str()); std::string appId = ""; - AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId); - if (appId.empty()) { - LOGE("GetAppIdByPkgName failed."); + if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + LOGD("GetAppIdByPkgName failed"); return ERR_DM_FAILED; } - DmKVValue kvValue; - kvValue.udidHash = std::string(deviceInfo.deviceId); - kvValue.appID = appId; - kvValue.lastModifyTime = GetSecondsSince1970ToNow(); + int32_t ret = Crypto::ConvertUdidHashToAnoyAndSave(appId, std::string(deviceInfo.deviceId), kvValue); + if (ret != DM_OK) { + return ERR_DM_FAILED; + } (void)memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); - if (memcpy_s(deviceInfo.deviceId, sizeof(deviceInfo.deviceId), deviceIdTemp.c_str(), - std::min(sizeof(deviceInfo.deviceId), deviceIdTemp.length())) != DM_OK) { - LOGE("ConfuseUdidHash copy deviceId data failed."); + if (memcpy_s(deviceInfo.deviceId, sizeof(deviceInfo.deviceId), kvValue.anoyDeviceId.c_str(), + std::min(sizeof(deviceInfo.deviceId), kvValue.anoyDeviceId.length())) != DM_OK) { + LOGE("copy deviceId data failed."); return ERR_DM_FAILED; } - KVAdapterManager::GetInstance().Put(deviceIdTemp, kvValue); return DM_OK; } -int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoy(const std::string &pkgName, - const std::string &udidHash, std::string &result) +int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, + const std::string &udidHash, std::string &anoyDeviceId) { LOGI("pkgName %{public}s, udidHash %{public}s.", pkgName.c_str(), GetAnonyString(udidHash).c_str()); std::string appId = ""; if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { - LOGE("GetAppIdByPkgName failed"); + LOGD("GetAppIdByPkgName failed"); return ERR_DM_FAILED; } - std::string udidTemp = udidHash + appId; - char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetUdidHash(udidTemp, reinterpret_cast(deviceIdHash)) != DM_OK) { - LOGE("get deviceIdHash by udidTemp: %{public}s failed.", GetAnonyString(udidTemp).c_str()); - return ERR_DM_FAILED; + DmKVValue kvValue; + int32_t ret = Crypto::ConvertUdidHashToAnoyDeviceId(appId, udidHash, kvValue); + if (ret == DM_OK) { + anoyDeviceId = kvValue.anoyDeviceId; } - result = std::string(deviceIdHash); - return DM_OK; + return ret; } #endif @@ -507,7 +498,7 @@ void DeviceManagerServiceListener::SetDeviceScreenInfo(std::shared_ptrSetDeviceInfo(dmDeviceInfo); return; #endif diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 2c72bf58c..40a4db53d 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -71,6 +71,7 @@ void IpcServerStub::OnStart() #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); #endif + DeviceManagerService::GetInstance().SubscribePackageCommonEvent(); } void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) diff --git a/services/service/src/publishcommonevent/dm_package_common_event.cpp b/services/service/src/publishcommonevent/dm_package_common_event.cpp new file mode 100644 index 000000000..54272d6f9 --- /dev/null +++ b/services/service/src/publishcommonevent/dm_package_common_event.cpp @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_package_common_event.h" + +#include +#include + +#include "common_event_support.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_thread_manager.h" +#endif +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::MatchingSkills; +using OHOS::EventFwk::CommonEventManager; + +constexpr const char* DEAL_THREAD = "package_common_event"; +const std::string APP_ID = "appId"; +constexpr int32_t MAX_TRY_TIMES = 3; + +std::vector DmPackageEventSubscriber::GetSubscriberEventNameVec() const +{ + return eventNameVec_; +} + +DmPackageCommonEventManager::~DmPackageCommonEventManager() +{ + DmPackageCommonEventManager::UnsubscribePackageCommonEvent(); +} + +bool DmPackageCommonEventManager::SubscribePackageCommonEvent(const std::vector &eventNameVec, + const PackageEventCallback &callback) +{ + if (eventNameVec.empty() || callback == nullptr) { + LOGE("eventNameVec is empty or callback is nullptr."); + return false; + } + std::lock_guard locker(evenSubscriberMutex_); + if (eventValidFlag_) { + LOGE("failed to subscribe package commom eventName size: %{public}zu", eventNameVec.size()); + return false; + } + + MatchingSkills matchingSkills; + for (auto &item : eventNameVec) { + matchingSkills.AddEvent(item); + } + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + subscriber_ = std::make_shared(subscriberInfo, callback, eventNameVec); + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + subscriber_ = nullptr; + return false; + } + statusChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener(subscriber_); + if (statusChangeListener_ == nullptr) { + LOGE("statusChangeListener_ is nullptr"); + subscriber_ = nullptr; + return false; + } + while (counter_ != MAX_TRY_TIMES) { + if (samgrProxy->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_) == ERR_OK) { + LOGI("SubscribePackageEvent success."); + counter_ = 0; + break; + } + if (++counter_ == MAX_TRY_TIMES) { + LOGI("SubscribePackageEvent failed."); + } + sleep(1); + } + eventNameVec_ = eventNameVec; + eventValidFlag_ = true; + LOGI("success to subscribe package commom event name size: %{public}zu", eventNameVec.size()); + return true; +} + +bool DmPackageCommonEventManager::UnsubscribePackageCommonEvent() +{ + std::lock_guard locker(evenSubscriberMutex_); + if (!eventValidFlag_) { + LOGE("failed to unsubscribe package commom event name size: %{public}zu because event is invalid.", + eventNameVec_.size()); + return false; + } + if (subscriber_ != nullptr) { + LOGI("start to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + if (!CommonEventManager::UnSubscribeCommonEvent(subscriber_)) { + LOGE("failed to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + return false; + } + LOGI("success to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + subscriber_ = nullptr; + } + if (statusChangeListener_ != nullptr) { + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + return false; + } + int32_t ret = samgrProxy->UnSubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_); + if (ret != ERR_OK) { + LOGE("failed to unsubscribe system ability COMMON_EVENT_SERVICE_ID ret:%{public}d", ret); + return false; + } + statusChangeListener_ = nullptr; + } + + LOGI("success to unsubscribe package commom event name size: %{public}zu", eventNameVec_.size()); + eventValidFlag_ = false; + return true; +} + +void DmPackageEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + std::string receiveEvent = data.GetWant().GetAction(); + std::string appId = data.GetWant().GetStringParam(APP_ID); + LOGI("Received package event: %{public}s", receiveEvent.c_str()); + + if (receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED && + receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + LOGE("Invalied package type event."); + return; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(appId, receiveEvent); }); +#else + std::thread dealThread([=]() { callback_(appId, receiveEvent); }); + int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); + if (ret != DM_OK) { + LOGE("dealThread setname failed."); + } + dealThread.detach(); +#endif +} + +void DmPackageCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is added with said: %{public}d.", systemAbilityId); + if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { + return; + } + if (changeSubscriber_ == nullptr) { + LOGE("failed to subscribe package commom event because changeSubscriber_ is nullptr."); + return; + } + std::vector eventNameVec = changeSubscriber_->GetSubscriberEventNameVec(); + LOGI("start to subscribe package commom eventName: %{public}zu", eventNameVec.size()); + if (!CommonEventManager::SubscribeCommonEvent(changeSubscriber_)) { + LOGE("failed to subscribe package commom event: %{public}zu", eventNameVec.size()); + } +} + +void DmPackageCommonEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is removed with said: %{public}d.", systemAbilityId); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index a4c8039d3..ae519109a 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2218,7 +2218,7 @@ HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_001, testing::ext::Test { std::string udid = ""; std::string result = ""; - int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); + int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udid, result); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -2226,7 +2226,7 @@ HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_002, testing::ext::Test { std::string udid = "ikjwdncksd456"; std::string result = ""; - int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); + int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udid, result); EXPECT_EQ(ret, ERR_DM_FAILED); } diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 746380f8d..860559a9a 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -100,6 +100,7 @@ if (defined(ohos_lite)) { "src/appInfo/standard/app_manager.cpp", "src/crypto/dm_crypto.cpp", "src/dm_random.cpp", + "src/kvadapter/dm_kv_info.cpp", "src/kvadapter/kv_adapter.cpp", "src/kvadapter/kv_adapter_manager.cpp", "src/threadManager/dm_thread_manager.cpp", diff --git a/utils/include/crypto/dm_crypto.h b/utils/include/crypto/dm_crypto.h index 93c9ff3f8..52d6f2bad 100644 --- a/utils/include/crypto/dm_crypto.h +++ b/utils/include/crypto/dm_crypto.h @@ -16,6 +16,9 @@ #ifndef OHOS_DM_CRYPTO_H #define OHOS_DM_CRYPTO_H #include +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_kv_info.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -31,6 +34,15 @@ public: static std::string GetSecSalt(); static std::string GetHashWithSalt(const std::string &text, const std::string &salt); static int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + static int32_t ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue); + static int32_t ConvertUdidHashToAnoyDeviceId(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue); + static int32_t GetAnoyDeviceInfo(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue); + static int32_t ConvertUdidHashToAnoyGenerate(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue); +#endif }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/kvadapter/dm_kv_info.h b/utils/include/kvadapter/dm_kv_info.h new file mode 100644 index 000000000..fd96cffcb --- /dev/null +++ b/utils/include/kvadapter/dm_kv_info.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_KV_INFO_H +#define OHOS_DM_KV_INFO_H + +#include + +namespace OHOS { +namespace DistributedHardware { +const std::string DB_KEY_DELIMITER = "###"; +const std::string UDID_HASH_KEY = "udidHash"; +const std::string APP_ID_KEY = "appID"; +const std::string ANOY_DEVICE_ID_KEY = "anoyDeviceId"; +const std::string SALT_KEY = "salt"; +const std::string LAST_MODIFY_TIME_KEY = "lastModifyTime"; + +typedef struct DmKVValue { + std::string udidHash; + std::string appID; + std::string anoyDeviceId; + std::string salt; + int64_t lastModifyTime; + explicit DmKVValue() : udidHash(""), appID(""), anoyDeviceId(""), salt(""), lastModifyTime(0) {} +} DmKVValue; +void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result); +void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue); +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_KV_INFO_H diff --git a/utils/include/kvadapter/kv_adapter.h b/utils/include/kvadapter/kv_adapter.h index 055bfa644..0e116398e 100644 --- a/utils/include/kvadapter/kv_adapter.h +++ b/utils/include/kvadapter/kv_adapter.h @@ -24,21 +24,13 @@ #include #include +#include "dm_kv_info.h" #include "distributed_kv_data_manager.h" #include "kvstore_death_recipient.h" #include "kvstore_observer.h" namespace OHOS { namespace DistributedHardware { -typedef struct DmKVValue { - std::string udidHash; - std::string appID; - std::string udid; - int64_t lastModifyTime; - explicit DmKVValue() : udidHash(""), appID(""), udid(""), lastModifyTime(0) {} -} DmKVValue; -void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result); -void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue); class KVAdapter : public DistributedKv::KvStoreDeathRecipient, public std::enable_shared_from_this { public: KVAdapter() = default; @@ -46,9 +38,11 @@ public: int32_t Init(); void UnInit(); int32_t ReInit(); - int32_t Put(const std::string& key, const std::string& value); - int32_t Get(const std::string& key, std::string& value); - + int32_t Put(const std::string &key, const std::string &value); + int32_t Get(const std::string &key, std::string &value); + int32_t DeleteKvStore(); + int32_t DeleteByAppId(const std::string &appId, const std::string &prefix); + int32_t DeleteBatch(const std::vector &keys); void OnRemoteDied() override; private: diff --git a/utils/include/kvadapter/kv_adapter_manager.h b/utils/include/kvadapter/kv_adapter_manager.h index aec0bd5da..8dacc074c 100644 --- a/utils/include/kvadapter/kv_adapter_manager.h +++ b/utils/include/kvadapter/kv_adapter_manager.h @@ -34,21 +34,21 @@ public: int32_t Init(); void UnInit(); void ReInit(); - int32_t Put(const std::string& key, const DmKVValue& value); - int32_t Get(const std::string& key, DmKVValue& value); + int32_t PutByAnoyDeviceId(const std::string &key, const DmKVValue &value); + int32_t Get(const std::string &key, DmKVValue &value); int32_t DeleteAgedEntry(); + int32_t AppUnintall(const std::string &appId); private: KVAdapterManager() = default; ~KVAdapterManager() = default; inline bool IsTimeOut(int64_t sourceTime, int64_t targetTime, int64_t timeOut); - inline std::string AddPrefix(const std::string& key); private: std::shared_ptr deathRecipient_ = nullptr; std::shared_ptr kvAdapter_ = nullptr; std::mutex idCacheMapMtx_; - std::map> idCacheMap_; + std::map idCacheMap_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/crypto/dm_crypto.cpp b/utils/src/crypto/dm_crypto.cpp index 7a7e51d79..59bf08e3c 100644 --- a/utils/src/crypto/dm_crypto.cpp +++ b/utils/src/crypto/dm_crypto.cpp @@ -14,6 +14,10 @@ */ #include "dm_crypto.h" #include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "datetime_ex.h" +#include "kv_adapter_manager.h" +#endif #include #include @@ -37,6 +41,9 @@ constexpr int SHORT_DEVICE_ID_HASH_LENGTH = 16; constexpr int32_t SALT_LENGTH = 8; const std::string SALT_DEFAULT = "salt_defsalt_def"; constexpr int SHORT_ACCOUNTID_ID_HASH_LENGTH = 6; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#define DM_MAX_DEVICE_ID_LEN (97) +#endif uint32_t HexifyLen(uint32_t len) { @@ -214,5 +221,64 @@ int32_t Crypto::GetAccountIdHash(const std::string &accountId, unsigned char *ac } return DM_OK; } + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +int32_t Crypto::ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + if (GetAnoyDeviceInfo(appId, udidHash, kvValue) == DM_OK) { + kvValue.lastModifyTime = GetSecondsSince1970ToNow(); + KVAdapterManager::GetInstance().PutByAnoyDeviceId(kvValue.anoyDeviceId, kvValue); + return DM_OK; + } + int32_t ret = ConvertUdidHashToAnoyGenerate(appId, udidHash, kvValue); + if (ret != DM_OK) { + LOGE("failed"); + return ERR_DM_FAILED; + } + KVAdapterManager::GetInstance().PutByAnoyDeviceId(kvValue.anoyDeviceId, kvValue); + return DM_OK; +} + +int32_t Crypto::ConvertUdidHashToAnoyDeviceId(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + LOGI("start."); + if (GetAnoyDeviceInfo(appId, udidHash, kvValue) == DM_OK) { + return DM_OK; + } + return ConvertUdidHashToAnoyGenerate(appId, udidHash, kvValue); +} + +int32_t Crypto::GetAnoyDeviceInfo(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue) +{ + LOGI("start"); + std::string udidPrefix = appId + DB_KEY_DELIMITER + udidHash; + if (KVAdapterManager::GetInstance().Get(udidPrefix, kvValue) != DM_OK) { + LOGI("Get kv value from DB failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t Crypto::ConvertUdidHashToAnoyGenerate(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + LOGI("start."); + std::string salt = GetSecSalt(); + std::string udidTemp = appId + DB_KEY_DELIMITER + udidHash + DB_KEY_DELIMITER + salt; + char anoyDeviceId[DM_MAX_DEVICE_ID_LEN] = {0}; + if (GetUdidHash(udidTemp, reinterpret_cast(anoyDeviceId)) != DM_OK) { + LOGE("get anoyDeviceId by udidTemp failed."); + return ERR_DM_FAILED; + } + kvValue.udidHash = udidHash; + kvValue.anoyDeviceId = std::string(anoyDeviceId); + kvValue.appID = appId; + kvValue.salt = salt; + kvValue.lastModifyTime = GetSecondsSince1970ToNow(); + return DM_OK; +} +#endif } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/kvadapter/dm_kv_info.cpp b/utils/src/kvadapter/dm_kv_info.cpp new file mode 100644 index 000000000..2a251d6fa --- /dev/null +++ b/utils/src/kvadapter/dm_kv_info.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dm_kv_info.h" + +#include "cJSON.h" +#include "dm_anonymous.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { +void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) +{ + nlohmann::json jsonObj; + jsonObj[UDID_HASH_KEY] = kvValue.udidHash; + jsonObj[APP_ID_KEY] = kvValue.appID; + jsonObj[ANOY_DEVICE_ID_KEY] = kvValue.anoyDeviceId; + jsonObj[SALT_KEY] = kvValue.salt; + jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; + result = jsonObj.dump(); +} + +void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) +{ + if (result.empty()) { + return; + } + nlohmann::json resultJson = nlohmann::json::parse(result, nullptr, false); + if (resultJson.is_discarded()) { + return; + } + if (IsString(resultJson, UDID_HASH_KEY)) { + kvValue.udidHash = resultJson[UDID_HASH_KEY].get(); + } + if (IsString(resultJson, APP_ID_KEY)) { + kvValue.appID = resultJson[APP_ID_KEY].get(); + } + if (IsString(resultJson, ANOY_DEVICE_ID_KEY)) { + kvValue.anoyDeviceId = resultJson[ANOY_DEVICE_ID_KEY].get(); + } + if (IsString(resultJson, SALT_KEY)) { + kvValue.salt = resultJson[SALT_KEY].get(); + } + if (IsInt64(resultJson, LAST_MODIFY_TIME_KEY)) { + kvValue.lastModifyTime = resultJson[LAST_MODIFY_TIME_KEY].get(); + } +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/utils/src/kvadapter/kv_adapter.cpp b/utils/src/kvadapter/kv_adapter.cpp index 2082afa97..6b135f474 100644 --- a/utils/src/kvadapter/kv_adapter.cpp +++ b/utils/src/kvadapter/kv_adapter.cpp @@ -35,48 +35,12 @@ namespace { const std::string STORE_ID = "dm_kv_store"; const std::string DATABASE_DIR = "/data/service/el1/public/database/distributed_device_manager_service"; const std::string KV_REINIT_THREAD = "reinit_kv_store"; - const std::string UDID_HASH_KEY = "udidHash"; - const std::string APP_ID_KEY = "appID"; - const std::string UDID_ID_KEY = "udid"; - const std::string LAST_MODIFY_TIME_KEY = "lastModifyTime"; + constexpr uint32_t MAX_BATCH_SIZE = 128; constexpr int32_t MAX_STRING_LEN = 4096; constexpr int32_t MAX_INIT_RETRY_TIMES = 20; constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms } -void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) -{ - nlohmann::json jsonObj; - jsonObj[UDID_HASH_KEY] = kvValue.udidHash; - jsonObj[APP_ID_KEY] = kvValue.appID; - jsonObj[UDID_ID_KEY] = kvValue.udid; - jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; - result = jsonObj.dump(); -} - -void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) -{ - if (result.empty()) { - return; - } - nlohmann::json resultJson = nlohmann::json::parse(result, nullptr, false); - if (resultJson.is_discarded()) { - return; - } - if (IsString(resultJson, UDID_HASH_KEY)) { - kvValue.udidHash = resultJson[UDID_HASH_KEY].get(); - } - if (IsString(resultJson, APP_ID_KEY)) { - kvValue.appID = resultJson[APP_ID_KEY].get(); - } - if (IsString(resultJson, UDID_ID_KEY)) { - kvValue.udid = resultJson[UDID_ID_KEY].get(); - } - if (IsString(resultJson, LAST_MODIFY_TIME_KEY)) { - kvValue.lastModifyTime = resultJson[LAST_MODIFY_TIME_KEY].get(); - } -} - int32_t KVAdapter::Init() { LOGI("Init local DB, dataType: %{public}d", static_cast(dataType_)); @@ -96,7 +60,13 @@ int32_t KVAdapter::Init() isInited_.store(true); return DM_OK; } - LOGD("CheckKvStore, left times: %{public}d", tryTimes); + LOGE("CheckKvStore, left times: %{public}d, status: %{public}d", tryTimes, status); + if (status == DistributedKv::Status::STORE_META_CHANGED || + status == DistributedKv::Status::SECURITY_LEVEL_ERROR || + status == DistributedKv::Status::CRYPT_ERROR) { + LOGE("init db error, remove and rebuild it"); + DeleteKvStore(); + } usleep(INIT_RETRY_SLEEP_INTERVAL); tryTimes--; } @@ -124,7 +94,7 @@ int32_t KVAdapter::ReInit() return Init(); } -int32_t KVAdapter::Put(const std::string& key, const std::string& value) +int32_t KVAdapter::Put(const std::string &key, const std::string &value) { if (key.empty() || key.size() > MAX_STRING_LEN || value.empty() || value.size() > MAX_STRING_LEN) { LOGE("Param is invalid!"); @@ -146,7 +116,7 @@ int32_t KVAdapter::Put(const std::string& key, const std::string& value) return DM_OK; } -int32_t KVAdapter::Get(const std::string& key, std::string& value) +int32_t KVAdapter::Get(const std::string &key, std::string &value) { LOGI("Get data by key: %{public}s", GetAnonyString(key).c_str()); DistributedKv::Key kvKey(key); @@ -201,5 +171,77 @@ void KVAdapter::UnregisterKvStoreDeathListener() LOGI("UnRegister death listener"); kvDataMgr_.UnRegisterKvStoreServiceDeathRecipient(shared_from_this()); } + +int32_t KVAdapter::DeleteKvStore() +{ + LOGI("Delete KvStore!"); + kvDataMgr_.CloseKvStore(appId_, storeId_); + kvDataMgr_.DeleteKvStore(appId_, storeId_, DATABASE_DIR); + return DM_OK; +} + +int32_t KVAdapter::DeleteByAppId(const std::string &appId, const std::string &prefix) +{ + if (appId.empty()) { + LOGE("appId is empty"); + return ERR_DM_FAILED; + } + std::vector localEntries; + { + std::lock_guard lock(kvAdapterMutex_); + if (kvStorePtr_ == nullptr) { + LOGE("kvStoragePtr_ is null"); + return ERR_DM_POINT_NULL; + } + if (kvStorePtr_->GetEntries(prefix + appId, localEntries) != DistributedKv::Status::SUCCESS) { + LOGE("Get entrys from DB failed."); + return ERR_DM_FAILED; + } + } + std::vector delKeys; + for (const auto &entry : localEntries) { + delKeys.emplace_back(entry.key.ToString()); + DmKVValue kvValue; + ConvertJsonToDmKVValue(entry.value.ToString(), kvValue); + delKeys.emplace_back(prefix + kvValue.anoyDeviceId); + } + return DeleteBatch(delKeys); +} + +int32_t KVAdapter::DeleteBatch(const std::vector &keys) +{ + if (keys.empty()) { + LOGE("keys size(%{public}zu) is invalid!", keys.size()); + return ERR_DM_FAILED; + } + uint32_t keysSize = static_cast(keys.size()); + std::vector> delKeyBatches; + for (uint32_t i = 0; i < keysSize; i += MAX_BATCH_SIZE) { + uint32_t end = (i + MAX_BATCH_SIZE) > keysSize ? keysSize : (i + MAX_BATCH_SIZE); + auto batch = std::vector(keys.begin() + i, keys.begin() + end); + std::vector delKeys; + for (auto item : batch) { + DistributedKv::Key key(item); + delKeys.emplace_back(key); + } + delKeyBatches.emplace_back(delKeys); + } + + { + std::lock_guard lock(kvAdapterMutex_); + if (kvStorePtr_ == nullptr) { + LOGE("kvStorePtr is nullptr!"); + return ERR_DM_POINT_NULL; + } + for (auto delKeys : delKeyBatches) { + DistributedKv::Status status = kvStorePtr_->DeleteBatch(delKeys); + if (status != DistributedKv::Status::SUCCESS) { + LOGE("DeleteBatch failed!"); + return ERR_DM_FAILED; + } + } + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/kvadapter/kv_adapter_manager.cpp b/utils/src/kvadapter/kv_adapter_manager.cpp index 75b9d02a8..617b2e450 100644 --- a/utils/src/kvadapter/kv_adapter_manager.cpp +++ b/utils/src/kvadapter/kv_adapter_manager.cpp @@ -27,7 +27,7 @@ namespace OHOS { namespace DistributedHardware { namespace { -const std::string DM_KV_STORE_PREFIX = "DM_"; +const std::string DM_KV_STORE_PREFIX = "DM2_"; constexpr int64_t DM_KV_STORE_REFRESH_TIME = 24 * 60 * 60; // one day constexpr int64_t MAX_SUPPORTED_EXIST_TIME = 3 * 24 * 60 * 60; // 3days } @@ -60,36 +60,40 @@ void KVAdapterManager::ReInit() kvAdapter_->ReInit(); } -int32_t KVAdapterManager::Put(const std::string& key, const DmKVValue& value) +int32_t KVAdapterManager::PutByAnoyDeviceId(const std::string &key, const DmKVValue &value) { - std::string dmKey = AddPrefix(key); + std::string dmKey = DM_KV_STORE_PREFIX + key; std::lock_guard lock(idCacheMapMtx_); auto idIter = idCacheMap_.find(dmKey); - if (idIter != idCacheMap_.end() && !IsTimeOut(idIter->second.second, value.lastModifyTime, + if (idIter != idCacheMap_.end() && !IsTimeOut(idIter->second.lastModifyTime, value.lastModifyTime, DM_KV_STORE_REFRESH_TIME)) { LOGD("Kv value is existed"); return DM_OK; } + idCacheMap_[dmKey] = value; + std::string prefixKey = DM_KV_STORE_PREFIX + value.appID + DB_KEY_DELIMITER + value.udidHash; + idCacheMap_[prefixKey] = value; std::string valueStr = ""; ConvertDmKVValueToJson(value, valueStr); - idCacheMap_[dmKey].first = value.udidHash; - idCacheMap_[dmKey].second = value.lastModifyTime; CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); if (kvAdapter_->Put(dmKey, valueStr) != DM_OK) { - LOGE("Insert value to DB failed"); + LOGE("Insert value to DB for dmKey failed"); + return ERR_DM_FAILED; + } + if (kvAdapter_->Put(prefixKey, valueStr) != DM_OK) { + LOGE("Insert value to DB for prefixKey failed"); return ERR_DM_FAILED; } return DM_OK; } -int32_t KVAdapterManager::Get(const std::string& key, DmKVValue& value) +int32_t KVAdapterManager::Get(const std::string &key, DmKVValue &value) { - std::string dmKey = AddPrefix(key); + std::string dmKey = DM_KV_STORE_PREFIX + key; std::lock_guard lock(idCacheMapMtx_); auto idIter = idCacheMap_.find(dmKey); if (idIter != idCacheMap_.end()) { - value.udidHash = idIter->second.first; - value.lastModifyTime = idIter->second.second; + value = idIter->second; return DM_OK; } CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); @@ -99,8 +103,9 @@ int32_t KVAdapterManager::Get(const std::string& key, DmKVValue& value) return ERR_DM_FAILED; } ConvertJsonToDmKVValue(valueStr, value); - idCacheMap_[dmKey].first = value.udidHash; - idCacheMap_[dmKey].second = value.lastModifyTime; + idCacheMap_[dmKey] = value; + std::string prefixKey = DM_KV_STORE_PREFIX + value.appID + DB_KEY_DELIMITER + value.udidHash; + idCacheMap_[prefixKey] = value; return DM_OK; } @@ -109,7 +114,7 @@ int32_t KVAdapterManager::DeleteAgedEntry() int64_t nowTime = GetSecondsSince1970ToNow(); std::lock_guard lock(idCacheMapMtx_); for (auto it = idCacheMap_.begin(); it != idCacheMap_.end();) { - if (IsTimeOut(it->second.second, nowTime, MAX_SUPPORTED_EXIST_TIME)) { + if (IsTimeOut(it->second.lastModifyTime, nowTime, MAX_SUPPORTED_EXIST_TIME)) { it = idCacheMap_.erase(it); } else { ++it; @@ -123,9 +128,23 @@ inline bool KVAdapterManager::IsTimeOut(int64_t sourceTime, int64_t targetTime, return targetTime - sourceTime >= timeOut ? true : false; } -inline std::string KVAdapterManager::AddPrefix(const std::string& key) +int32_t KVAdapterManager::AppUnintall(const std::string &appId) { - return DM_KV_STORE_PREFIX + key; + LOGI("appId %{public}s.", GetAnonyString(appId).c_str()); + std::lock_guard lock(idCacheMapMtx_); + for (auto it = idCacheMap_.begin(); it != idCacheMap_.end();) { + if (it->second.appID == appId) { + it = idCacheMap_.erase(it); + } else { + ++it; + } + } + CHECK_NULL_RETURN(kvAdapter_, ERR_DM_POINT_NULL); + if (kvAdapter_->DeleteByAppId(appId, DM_KV_STORE_PREFIX) != DM_OK) { + LOGE("DeleteByAppId failed"); + return ERR_DM_FAILED; + } + return DM_OK; } } // namespace DistributedHardware } // namespace OHOS -- Gitee From 03c4276248f679e7a7f6ac0459b2c4cf85b8cb80 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 12 Sep 2024 18:35:32 +0800 Subject: [PATCH 195/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B=5F20240912?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- 1.patch | 365 ++++++++++++++++++ .../UTTest_device_manager_service.cpp | 34 -- 2 files changed, 365 insertions(+), 34 deletions(-) create mode 100644 1.patch diff --git a/1.patch b/1.patch new file mode 100644 index 000000000..f39edba0d --- /dev/null +++ b/1.patch @@ -0,0 +1,365 @@ +diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp +index d474047d..4467b825 100644 +--- a/test/unittest/UTTest_device_manager_service.cpp ++++ b/test/unittest/UTTest_device_manager_service.cpp +@@ -193,7 +193,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSi + HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) + { + DeletePermission(); +- std::string pkgName = "StopDeviceDiscovery_003"; ++ std::string pkgName ="StopDeviceDiscovery_003"; + uint16_t subscribeId = 1; + int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +@@ -315,6 +315,41 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_003, testing::ext::T + DeviceManagerService::GetInstance().UninitDMServiceListener(); + } + ++/** ++ * @tc.name: UnPublishDeviceDiscovery_004 ++ * @tc.desc: UnPublishDeviceDiscovery is initialized, pkgName is null, and its return ERR_DM_INPUT_PARA_INVALID ++ * @tc.type: FUNC ++ * @tc.require: I5N1K3 ++ */ ++HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "com.ohos.test003"; ++ int32_t publishId = 1; ++ int32_t userId = 23; ++ std::string accountId = "hello123"; ++ int32_t preUserId = 3; ++ std::vector peerUdids; ++ std::string accountName = "openharmony123"; ++ std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; ++ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); ++ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; ++ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); ++ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; ++ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); ++ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; ++ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); ++ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; ++ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); ++ DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); ++ DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); ++ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); ++ DeviceManagerService::GetInstance().SendAccountLogoutBroadCast(peerUdids, accountId, accountName, userId); ++ DeviceManagerService::GetInstance().softbusListener_ = nullptr; ++ DeletePermission(); ++ int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); ++ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); ++} ++ + /** + * @tc.name: GetTrustedDeviceList_001 + * @tc.desc:Set the intFlag of GetTrustedDeviceList to true and pkgName = null; Return ERR_DM_INPUT_PARA_INVALID +@@ -491,6 +526,23 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_006, testing::ext::TestSize.Leve + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + } + ++/** ++ * @tc.name: ShiftLNNGear_007 ++ * @tc.desc:Set the callerId and pkgNamenot not to null, and isRefresh to true; Return NOT DM_OK ++ * @tc.type: FUNC ++ * @tc.require: AR000GHSJK ++ */ ++HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_007, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "ShiftLNNGear_007"; ++ std::string callerId = "ShiftLNNGear_007"; ++ bool isRefresh = true; ++ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); ++ int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); ++ DeviceManagerService::GetInstance().softbusListener_ = nullptr; ++ EXPECT_NE(ret, DM_OK); ++} ++ + /** + * @tc.name: AuthenticateDevice_001 + * @tc.desc: Set unsupport authType = 0 and return ERR_DM_INPUT_PARA_INVALID +@@ -824,6 +876,7 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSiz + EXPECT_EQ(ret, DM_OK); + } + ++ + /** + * @tc.name: RequestCredential_001 + * @tc.desc:The return value is ERR_DM_FAILED +@@ -1100,6 +1153,21 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_002, testing::ext::TestSize.Lev + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + } + ++/** ++ * @tc.name: GetDeviceInfo_004 ++ * @tc.desc: The return value is DM_OK ++ * @tc.type: FUNC ++ * @tc.require: AR000GHSJK ++ */ ++HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_004, testing::ext::TestSize.Level0) ++{ ++ std::string networkId = "networkIdTest4"; ++ DmDeviceInfo info; ++ DeletePermission(); ++ int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); ++ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); ++} ++ + /** + * @tc.name: CheckApiPermission_001 + * @tc.desc: The return value is DM_OK +@@ -1382,6 +1450,14 @@ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_002, testing::ext::Te + EXPECT_EQ(ret, DM_OK); + } + ++HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_003, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "pkgName"; ++ DeletePermission(); ++ int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); ++ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); ++} ++ + HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_001, testing::ext::TestSize.Level0) + { + std::string pkgName; +@@ -1396,6 +1472,22 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_002, testing::ext:: + EXPECT_EQ(ret, DM_OK); + } + ++HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_003, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "pkgName"; ++ DeletePermission(); ++ int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); ++ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); ++} ++ ++ ++HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize.Level0) ++{ ++ DeviceManagerService::GetInstance().isImplsoLoaded_ = false; ++ bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); ++ EXPECT_FALSE(ret); ++} ++ + HWTEST_F(DeviceManagerServiceTest, DmHiDumper_001, testing::ext::TestSize.Level0) + { + std::vector args; +@@ -1438,8 +1530,10 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_003, testing::ext::TestSize.Level + std::string pkgName; + int32_t eventId = DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT; + std::string event; ++ DeviceManagerService::GetInstance().InitDMServiceListener(); + int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); + EXPECT_NE(ret, DM_OK); ++ DeviceManagerService::GetInstance().UninitDMServiceListener(); + } + + HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_001, testing::ext::TestSize.Level0) +@@ -1566,6 +1660,17 @@ HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_003, testing::ext:: + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + } + ++HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_004, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "pkgName"; ++ std::string netWorkId = "netWorkId"; ++ int32_t networkType = 0; ++ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); ++ int32_t ret = DeviceManagerService::GetInstance().GetNetworkTypeByNetworkId(pkgName, netWorkId, networkType); ++ DeviceManagerService::GetInstance().softbusListener_ = nullptr; ++ EXPECT_NE(ret, DM_OK); ++} ++ + HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_001, testing::ext::TestSize.Level0) + { + DeletePermission(); +@@ -1729,6 +1834,17 @@ HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_003, testing::ext::Te + EXPECT_NE(ret, DM_OK); + } + ++HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_004, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "pkgName"; ++ std::map discoverParam; ++ std::map filterOptions; ++ DeviceManagerService::GetInstance().InitDMServiceListener(); ++ int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); ++ EXPECT_NE(ret, DM_OK); ++ DeviceManagerService::GetInstance().UninitDMServiceListener(); ++} ++ + HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_001, testing::ext::TestSize.Level0) + { + DeletePermission(); +@@ -1754,6 +1870,16 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_003, testing::ext::T + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + } + ++HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "pkgName"; ++ std::map extraParam; ++ DeviceManagerService::GetInstance().InitDMServiceListener(); ++ int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); ++ EXPECT_NE(ret, DM_OK); ++ DeviceManagerService::GetInstance().UninitDMServiceListener(); ++} ++ + HWTEST_F(DeviceManagerServiceTest, StartAdvertising_001, testing::ext::TestSize.Level0) + { + DeletePermission(); +@@ -1820,6 +1946,19 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_004, testing::ext::TestSize.L + DeviceManagerService::GetInstance().UninitDMServiceListener(); + } + ++HWTEST_F(DeviceManagerServiceTest, StopAdvertising_005, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "StopAdvertising_005"; ++ std::map advertiseParam; ++ std::string key = PARAM_KEY_META_TYPE; ++ std::string value = "125"; ++ advertiseParam.insert(std::make_pair(key,value)); ++ DeviceManagerService::GetInstance().InitDMServiceListener(); ++ int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); ++ EXPECT_NE(ret, DM_OK); ++ DeviceManagerService::GetInstance().UninitDMServiceListener(); ++} ++ + HWTEST_F(DeviceManagerServiceTest, BindTarget_004, testing::ext::TestSize.Level0) + { + DeletePermission(); +@@ -1933,6 +2072,7 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_002, testing::ext::TestSize. + EXPECT_NE(ret, DM_OK); + } + ++ + HWTEST_F(DeviceManagerServiceTest, DpAclAdd_001, testing::ext::TestSize.Level0) + { + DeletePermission(); +@@ -1985,6 +2125,17 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_004, testing::ext::Tes + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + } + ++HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_005, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "com.ohos.test"; ++ std::string invalidNetworkId; ++ int32_t securityLevel = 0; ++ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); ++ int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, invalidNetworkId, securityLevel); ++ DeviceManagerService::GetInstance().softbusListener_ = nullptr; ++ EXPECT_NE(ret, DM_OK); ++} ++ + HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Level0) + { + std::string udid = ""; +@@ -2014,6 +2165,95 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T + DeviceManagerService::GetInstance().HandleDeviceStatusChange(devState, devInfo); + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); + } ++ ++HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_001, testing::ext::TestSize.Level0) ++{ ++ std::string udid = ""; ++ std::string result = ""; ++ int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); ++ EXPECT_EQ(ret, ERR_DM_FAILED); ++} ++ ++HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_002, testing::ext::TestSize.Level0) ++{ ++ std::string udid = "ikjwdncksd456"; ++ std::string result = ""; ++ int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); ++ EXPECT_EQ(ret, ERR_DM_FAILED); ++} ++ ++HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) ++{ ++ DmAccessCaller caller; ++ DmAccessCallee callee; ++ DeletePermission(); ++ int ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); ++ EXPECT_FALSE(ret); ++} ++ ++ ++HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSize.Level0) ++{ ++ DmAccessCaller caller; ++ DmAccessCallee callee; ++ DeletePermission(); ++ int ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); ++ EXPECT_FALSE(ret); ++} ++ ++HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_001, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName; ++ std::map policy; ++ int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); ++ EXPECT_NE(ret, DM_OK); ++} ++ ++HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_002, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "openharmony123"; ++ std::map policy; ++ DeletePermission(); ++ int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); ++ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); ++} ++ ++HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "openharmony123"; ++ std::map policy; ++ std::vector peerUdids; ++ int32_t userId = 1; ++ uint64_t tokenId = 87; ++ DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, DEVICE); ++ DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, APP); ++ DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, 2); ++ DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); ++ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); ++ DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); ++ DeviceManagerService::GetInstance().softbusListener_ = nullptr; ++ int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); ++ EXPECT_NE(ret, DM_OK); ++} ++ ++/** ++ * @tc.name: StartDeviceDiscovery_007 ++ * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return ++ * ERR_DM_DISCOVERY_REPEATED ++ * @tc.type: FUNC ++ * @tc.require: AR000GHSJK ++ */ ++HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_007, testing::ext::TestSize.Level0) ++{ ++ std::string pkgName = "com.ohos.test7"; ++ DmSubscribeInfo subscribeInfo; ++ std::string extra = "test"; ++ DeviceManagerService::GetInstance().InitDMServiceListener(); ++ int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); ++ EXPECT_NE(ret, DM_OK); ++ DeviceManagerService::GetInstance().UninitDMServiceListener(); ++} ++ + } // namespace + } // namespace DistributedHardware + } // namespace OHOS +diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h +index bd540fd8..9c38a093 100644 +--- a/test/unittest/UTTest_device_manager_service.h ++++ b/test/unittest/UTTest_device_manager_service.h +@@ -25,6 +25,7 @@ + #include "device_manager_service_listener.h" + #include "device_manager_service_impl.h" + #include "dm_single_instance.h" ++#include "common_event_support.h" + namespace OHOS { + namespace DistributedHardware { + class DeviceManagerServiceTest : public testing::Test { diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index dc0d6ca6e..350a37b93 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -876,40 +876,6 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSiz EXPECT_EQ(ret, DM_OK); } - -/** - * @tc.name: GetLocalDeviceInfo_002 - * @tc.desc: The return value is DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSize.Level0) -{ - DmDeviceInfo info; - DeletePermission(); - std::string strMsg = ""; - DeviceManagerService::GetInstance().HandleDeviceTrustedChange(strMsg); - strMsg = "harmony123"; - DeviceManagerService::GetInstance().HandleDeviceTrustedChange(strMsg); - int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); - EXPECT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GetLocalDeviceInfo_003 - * @tc.desc: The return value is NOT DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_003, testing::ext::TestSize.Level0) -{ - DmDeviceInfo info; - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); - DeviceManagerService::GetInstance().softbusListener_ = nullptr; - EXPECT_EQ(ret, DM_OK); -} - /** * @tc.name: RequestCredential_001 * @tc.desc:The return value is ERR_DM_FAILED -- Gitee From e96010730c1b368976057c15776e9512b60f5d7c Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 12 Sep 2024 18:52:11 +0800 Subject: [PATCH 196/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B=5F20240912?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- 1.patch | 365 ------------------ .../UTTest_device_manager_service.cpp | 2 +- 2 files changed, 1 insertion(+), 366 deletions(-) delete mode 100644 1.patch diff --git a/1.patch b/1.patch deleted file mode 100644 index f39edba0d..000000000 --- a/1.patch +++ /dev/null @@ -1,365 +0,0 @@ -diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp -index d474047d..4467b825 100644 ---- a/test/unittest/UTTest_device_manager_service.cpp -+++ b/test/unittest/UTTest_device_manager_service.cpp -@@ -193,7 +193,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSi - HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) - { - DeletePermission(); -- std::string pkgName = "StopDeviceDiscovery_003"; -+ std::string pkgName ="StopDeviceDiscovery_003"; - uint16_t subscribeId = 1; - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -@@ -315,6 +315,41 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_003, testing::ext::T - DeviceManagerService::GetInstance().UninitDMServiceListener(); - } - -+/** -+ * @tc.name: UnPublishDeviceDiscovery_004 -+ * @tc.desc: UnPublishDeviceDiscovery is initialized, pkgName is null, and its return ERR_DM_INPUT_PARA_INVALID -+ * @tc.type: FUNC -+ * @tc.require: I5N1K3 -+ */ -+HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "com.ohos.test003"; -+ int32_t publishId = 1; -+ int32_t userId = 23; -+ std::string accountId = "hello123"; -+ int32_t preUserId = 3; -+ std::vector peerUdids; -+ std::string accountName = "openharmony123"; -+ std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; -+ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); -+ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; -+ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); -+ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; -+ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); -+ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; -+ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); -+ commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; -+ DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); -+ DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); -+ DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); -+ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); -+ DeviceManagerService::GetInstance().SendAccountLogoutBroadCast(peerUdids, accountId, accountName, userId); -+ DeviceManagerService::GetInstance().softbusListener_ = nullptr; -+ DeletePermission(); -+ int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); -+ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -+} -+ - /** - * @tc.name: GetTrustedDeviceList_001 - * @tc.desc:Set the intFlag of GetTrustedDeviceList to true and pkgName = null; Return ERR_DM_INPUT_PARA_INVALID -@@ -491,6 +526,23 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_006, testing::ext::TestSize.Leve - EXPECT_EQ(ret, ERR_DM_POINT_NULL); - } - -+/** -+ * @tc.name: ShiftLNNGear_007 -+ * @tc.desc:Set the callerId and pkgNamenot not to null, and isRefresh to true; Return NOT DM_OK -+ * @tc.type: FUNC -+ * @tc.require: AR000GHSJK -+ */ -+HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_007, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "ShiftLNNGear_007"; -+ std::string callerId = "ShiftLNNGear_007"; -+ bool isRefresh = true; -+ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); -+ int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); -+ DeviceManagerService::GetInstance().softbusListener_ = nullptr; -+ EXPECT_NE(ret, DM_OK); -+} -+ - /** - * @tc.name: AuthenticateDevice_001 - * @tc.desc: Set unsupport authType = 0 and return ERR_DM_INPUT_PARA_INVALID -@@ -824,6 +876,7 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_001, testing::ext::TestSiz - EXPECT_EQ(ret, DM_OK); - } - -+ - /** - * @tc.name: RequestCredential_001 - * @tc.desc:The return value is ERR_DM_FAILED -@@ -1100,6 +1153,21 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_002, testing::ext::TestSize.Lev - EXPECT_EQ(ret, ERR_DM_POINT_NULL); - } - -+/** -+ * @tc.name: GetDeviceInfo_004 -+ * @tc.desc: The return value is DM_OK -+ * @tc.type: FUNC -+ * @tc.require: AR000GHSJK -+ */ -+HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_004, testing::ext::TestSize.Level0) -+{ -+ std::string networkId = "networkIdTest4"; -+ DmDeviceInfo info; -+ DeletePermission(); -+ int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); -+ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -+} -+ - /** - * @tc.name: CheckApiPermission_001 - * @tc.desc: The return value is DM_OK -@@ -1382,6 +1450,14 @@ HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_002, testing::ext::Te - EXPECT_EQ(ret, DM_OK); - } - -+HWTEST_F(DeviceManagerServiceTest, RegisterUiStateCallback_003, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "pkgName"; -+ DeletePermission(); -+ int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); -+ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -+} -+ - HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_001, testing::ext::TestSize.Level0) - { - std::string pkgName; -@@ -1396,6 +1472,22 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_002, testing::ext:: - EXPECT_EQ(ret, DM_OK); - } - -+HWTEST_F(DeviceManagerServiceTest, UnRegisterUiStateCallback_003, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "pkgName"; -+ DeletePermission(); -+ int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); -+ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -+} -+ -+ -+HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_001, testing::ext::TestSize.Level0) -+{ -+ DeviceManagerService::GetInstance().isImplsoLoaded_ = false; -+ bool ret = DeviceManagerService::GetInstance().IsDMImplSoLoaded(); -+ EXPECT_FALSE(ret); -+} -+ - HWTEST_F(DeviceManagerServiceTest, DmHiDumper_001, testing::ext::TestSize.Level0) - { - std::vector args; -@@ -1438,8 +1530,10 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_003, testing::ext::TestSize.Level - std::string pkgName; - int32_t eventId = DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT; - std::string event; -+ DeviceManagerService::GetInstance().InitDMServiceListener(); - int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); - EXPECT_NE(ret, DM_OK); -+ DeviceManagerService::GetInstance().UninitDMServiceListener(); - } - - HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_001, testing::ext::TestSize.Level0) -@@ -1566,6 +1660,17 @@ HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_003, testing::ext:: - EXPECT_EQ(ret, ERR_DM_POINT_NULL); - } - -+HWTEST_F(DeviceManagerServiceTest, GetNetworkTypeByNetworkId_004, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "pkgName"; -+ std::string netWorkId = "netWorkId"; -+ int32_t networkType = 0; -+ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); -+ int32_t ret = DeviceManagerService::GetInstance().GetNetworkTypeByNetworkId(pkgName, netWorkId, networkType); -+ DeviceManagerService::GetInstance().softbusListener_ = nullptr; -+ EXPECT_NE(ret, DM_OK); -+} -+ - HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_001, testing::ext::TestSize.Level0) - { - DeletePermission(); -@@ -1729,6 +1834,17 @@ HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_003, testing::ext::Te - EXPECT_NE(ret, DM_OK); - } - -+HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_004, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "pkgName"; -+ std::map discoverParam; -+ std::map filterOptions; -+ DeviceManagerService::GetInstance().InitDMServiceListener(); -+ int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); -+ EXPECT_NE(ret, DM_OK); -+ DeviceManagerService::GetInstance().UninitDMServiceListener(); -+} -+ - HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_001, testing::ext::TestSize.Level0) - { - DeletePermission(); -@@ -1754,6 +1870,16 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_003, testing::ext::T - EXPECT_EQ(ret, ERR_DM_POINT_NULL); - } - -+HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "pkgName"; -+ std::map extraParam; -+ DeviceManagerService::GetInstance().InitDMServiceListener(); -+ int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); -+ EXPECT_NE(ret, DM_OK); -+ DeviceManagerService::GetInstance().UninitDMServiceListener(); -+} -+ - HWTEST_F(DeviceManagerServiceTest, StartAdvertising_001, testing::ext::TestSize.Level0) - { - DeletePermission(); -@@ -1820,6 +1946,19 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_004, testing::ext::TestSize.L - DeviceManagerService::GetInstance().UninitDMServiceListener(); - } - -+HWTEST_F(DeviceManagerServiceTest, StopAdvertising_005, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "StopAdvertising_005"; -+ std::map advertiseParam; -+ std::string key = PARAM_KEY_META_TYPE; -+ std::string value = "125"; -+ advertiseParam.insert(std::make_pair(key,value)); -+ DeviceManagerService::GetInstance().InitDMServiceListener(); -+ int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); -+ EXPECT_NE(ret, DM_OK); -+ DeviceManagerService::GetInstance().UninitDMServiceListener(); -+} -+ - HWTEST_F(DeviceManagerServiceTest, BindTarget_004, testing::ext::TestSize.Level0) - { - DeletePermission(); -@@ -1933,6 +2072,7 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_002, testing::ext::TestSize. - EXPECT_NE(ret, DM_OK); - } - -+ - HWTEST_F(DeviceManagerServiceTest, DpAclAdd_001, testing::ext::TestSize.Level0) - { - DeletePermission(); -@@ -1985,6 +2125,17 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_004, testing::ext::Tes - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); - } - -+HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_005, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "com.ohos.test"; -+ std::string invalidNetworkId; -+ int32_t securityLevel = 0; -+ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); -+ int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, invalidNetworkId, securityLevel); -+ DeviceManagerService::GetInstance().softbusListener_ = nullptr; -+ EXPECT_NE(ret, DM_OK); -+} -+ - HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Level0) - { - std::string udid = ""; -@@ -2014,6 +2165,95 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T - DeviceManagerService::GetInstance().HandleDeviceStatusChange(devState, devInfo); - EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); - } -+ -+HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_001, testing::ext::TestSize.Level0) -+{ -+ std::string udid = ""; -+ std::string result = ""; -+ int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); -+ EXPECT_EQ(ret, ERR_DM_FAILED); -+} -+ -+HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_002, testing::ext::TestSize.Level0) -+{ -+ std::string udid = "ikjwdncksd456"; -+ std::string result = ""; -+ int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoy(udid, result); -+ EXPECT_EQ(ret, ERR_DM_FAILED); -+} -+ -+HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) -+{ -+ DmAccessCaller caller; -+ DmAccessCallee callee; -+ DeletePermission(); -+ int ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); -+ EXPECT_FALSE(ret); -+} -+ -+ -+HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSize.Level0) -+{ -+ DmAccessCaller caller; -+ DmAccessCallee callee; -+ DeletePermission(); -+ int ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); -+ EXPECT_FALSE(ret); -+} -+ -+HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_001, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName; -+ std::map policy; -+ int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); -+ EXPECT_NE(ret, DM_OK); -+} -+ -+HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_002, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "openharmony123"; -+ std::map policy; -+ DeletePermission(); -+ int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); -+ EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -+} -+ -+HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "openharmony123"; -+ std::map policy; -+ std::vector peerUdids; -+ int32_t userId = 1; -+ uint64_t tokenId = 87; -+ DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, DEVICE); -+ DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, APP); -+ DeviceManagerService::GetInstance().SendUnBindBroadCast(peerUdids, userId, tokenId, 2); -+ DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); -+ DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); -+ DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); -+ DeviceManagerService::GetInstance().softbusListener_ = nullptr; -+ int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); -+ EXPECT_NE(ret, DM_OK); -+} -+ -+/** -+ * @tc.name: StartDeviceDiscovery_007 -+ * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return -+ * ERR_DM_DISCOVERY_REPEATED -+ * @tc.type: FUNC -+ * @tc.require: AR000GHSJK -+ */ -+HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_007, testing::ext::TestSize.Level0) -+{ -+ std::string pkgName = "com.ohos.test7"; -+ DmSubscribeInfo subscribeInfo; -+ std::string extra = "test"; -+ DeviceManagerService::GetInstance().InitDMServiceListener(); -+ int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); -+ EXPECT_NE(ret, DM_OK); -+ DeviceManagerService::GetInstance().UninitDMServiceListener(); -+} -+ - } // namespace - } // namespace DistributedHardware - } // namespace OHOS -diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h -index bd540fd8..9c38a093 100644 ---- a/test/unittest/UTTest_device_manager_service.h -+++ b/test/unittest/UTTest_device_manager_service.h -@@ -25,6 +25,7 @@ - #include "device_manager_service_listener.h" - #include "device_manager_service_impl.h" - #include "dm_single_instance.h" -+#include "common_event_support.h" - namespace OHOS { - namespace DistributedHardware { - class DeviceManagerServiceTest : public testing::Test { diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 350a37b93..dfc783e95 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1951,7 +1951,7 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_005, testing::ext::TestSize.L std::map advertiseParam; std::string key = PARAM_KEY_META_TYPE; std::string value = "125"; - advertiseParam.insert(std::make_pair(key,value)); + advertiseParam.insert(std::make_pair(key, value)); DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); EXPECT_NE(ret, DM_OK); -- Gitee From 72f8917d57e41a30217d463f23cccf302e079e67 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 13 Sep 2024 09:24:47 +0800 Subject: [PATCH 197/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=9B=B7=E8=BE=BE?= =?UTF-8?q?=E7=82=B9=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- interfaces/inner_kits/native_cpp/BUILD.gn | 8 + .../native_cpp/include/ipc/ipc_client_proxy.h | 4 +- .../native_cpp/src/device_manager_impl.cpp | 112 ++++++++- radar/include/dm_radar_helper.h | 34 ++- radar/src/dm_radar_helper.cpp | 231 +++++++++++++----- radar/src/lite/dm_radar_helper.cpp | 22 +- .../service/src/softbus/softbus_listener.cpp | 15 -- test/commonunittest/dm_radar_helper_test.cpp | 16 +- 8 files changed, 341 insertions(+), 101 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index b76f69b84..75b8714a6 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -76,6 +76,7 @@ if (defined(ohos_lite)) { "${common_path}/include/ipc", "${common_path}/include/ipc/lite", "${common_path}/include/ipc/model", + "${devicemanager_path}/radar/include", "${interfaces_path}/c/ipc/include", "${interfaces_path}/ipc_core/include", "${samgr_lite_path}/kits/samgr", @@ -136,6 +137,8 @@ if (defined(ohos_lite)) { "${common_path}/include/ipc/standard", "${common_path}/include/dfx", "${common_path}/include/dfx/standard", + "${devicemanager_path}/radar/include", + "${utils_path}/include/crypto", ] } @@ -153,6 +156,8 @@ if (defined(ohos_lite)) { "${common_path}/src/dfx/standard/dm_hitrace.cpp", "${common_path}/src/dm_anonymous.cpp", "${common_path}/src/ipc/standard/ipc_cmd_register.cpp", + "${devicemanager_path}/radar/src/dm_radar_helper.cpp", + "${utils_path}/src/crypto/dm_crypto.cpp", "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", @@ -177,15 +182,18 @@ if (defined(ohos_lite)) { external_deps = [ "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", + "cJSON:cjson", "c_utils:utils", "ffrt:libffrt", "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", + "init:libbegetutil", "ipc:ipc_core", "ipc:ipc_napi", "ipc:ipc_single", "ipc:libdbinder", + "openssl:libcrypto_shared", "samgr:samgr_proxy", ] diff --git a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h index 6d84dda2e..690650918 100644 --- a/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h +++ b/interfaces/inner_kits/native_cpp/include/ipc/ipc_client_proxy.h @@ -20,11 +20,11 @@ #include #include "ipc_client.h" -namespace OHOS::DistributedHardware { class IpcReq; } -namespace OHOS::DistributedHardware { class IpcRsp; } namespace OHOS { namespace DistributedHardware { +class IpcReq; +class IpcRsp; class IpcClientProxy : public IpcClient { DECLARE_IPC_INTERFACE(IpcClientProxy); diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 523b8eeff..afc4b5923 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -25,6 +25,7 @@ #include "dm_hisysevent.h" #include "dm_hitrace.h" #include "dm_log.h" +#include "dm_radar_helper.h" #include "ipc_acl_profile_req.h" #include "ipc_authenticate_device_req.h" #include "ipc_bind_device_req.h" @@ -118,6 +119,7 @@ DeviceManagerImpl &DeviceManagerImpl::GetInstance() int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::shared_ptr dmInitCallback) { if (pkgName.empty() || dmInitCallback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "InitDeviceManager", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::InitDeviceManager error: Invalid parameter, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } @@ -134,10 +136,12 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh usleep(USLEEP_TIME_MS); retryNum++; if (retryNum == SERVICE_INIT_TRY_MAX_NUM) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "InitDeviceManager", ERR_DM_NOT_INIT); LOGE("InitDeviceManager error, wait for device manager service starting timeout."); return ERR_DM_NOT_INIT; } } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "InitDeviceManager", ret); if (ret != DM_OK) { LOGE("InitDeviceManager error, proxy init failed ret: %{public}d", ret); SysEventWrite(std::string(DM_INIT_DEVICE_MANAGER_FAILED), DM_HISYEVENT_FAULT, @@ -156,12 +160,14 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnInitDeviceManager", ERR_DM_INPUT_PARA_INVALID); LOGE("UnInitDeviceManager Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); int32_t ret = ipcClientProxy_->UnInit(pkgName); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnInitDeviceManager", ret); if (ret != DM_OK) { LOGE("UnInitDeviceManager error, proxy unInit failed ret: %{public}d", ret); return ERR_DM_FAILED; @@ -195,6 +201,8 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons std::vector &deviceList) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList( + pkgName, "GetTrustedDeviceList", deviceList, ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -206,18 +214,21 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons req->SetExtra(extra); int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGE("DeviceManagerImpl::GetTrustedDeviceList error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGI("GetTrustedDeviceList error, failed ret: %{public}d", ret); return ret; } deviceList = rsp->GetDeviceVec(); LOGI("Completed, device size %{public}zu", deviceList.size()); + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, DM_OK); return DM_OK; } @@ -225,6 +236,8 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons bool isRefresh, std::vector &deviceList) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList( + pkgName, "GetTrustedDeviceList", deviceList, ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -238,17 +251,20 @@ int32_t DeviceManagerImpl::GetTrustedDeviceList(const std::string &pkgName, cons req->SetRefresh(isRefresh); int32_t ret = ipcClientProxy_->SendRequest(GET_TRUST_DEVICE_LIST, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGE("DeviceManagerImpl::GetTrustedDeviceList error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, ret); LOGE("GetTrustedDeviceList error, failed ret: %{public}d", ret); return ret; } deviceList = rsp->GetDeviceVec(); LOGI("Completed, device size %{public}zu", deviceList.size()); + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceList, DM_OK); return DM_OK; } @@ -259,6 +275,7 @@ int32_t DeviceManagerImpl::GetAvailableDeviceList(const std::string &pkgName, std::vector deviceListTemp; std::string extra = ""; int32_t ret = GetTrustedDeviceList(pkgName, extra, false, deviceListTemp); + DmRadarHelper::GetInstance().ReportGetTrustDeviceList(pkgName, "GetTrustedDeviceList", deviceListTemp, ret); if (ret != DM_OK) { LOGE("DeviceManagerImpl::GetTrustedDeviceList error."); return ret; @@ -276,6 +293,8 @@ int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, const std:: DmDeviceInfo &deviceInfo) { if (pkgName.empty() || networkId.empty()) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo( + pkgName, "GetDeviceInfo", deviceInfo, ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName: %{public}s, netWorkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; @@ -288,12 +307,14 @@ int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, const std:: req->SetNetWorkId(networkId); int32_t ret = ipcClientProxy_->SendRequest(GET_DEVICE_INFO, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceInfo", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceInfo error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceInfo", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceInfo error, failed ret: %{public}d", ret); return ret; } @@ -301,6 +322,7 @@ int32_t DeviceManagerImpl::GetDeviceInfo(const std::string &pkgName, const std:: deviceInfo = rsp->GetDeviceInfo(); LOGI("Completed, networKId = %{public}s deviceName = %{public}s", GetAnonyString(req->GetNetWorkId()).c_str(), GetAnonyString(deviceInfo.deviceName).c_str()); + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceInfo", deviceInfo, DM_OK); return DM_OK; } @@ -313,12 +335,14 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDevi req->SetPkgName(pkgName); int32_t ret = ipcClientProxy_->SendRequest(GET_LOCAL_DEVICE_INFO, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceInfo", info, ret); LOGE("DeviceManagerImpl::GetLocalDeviceInfo error, Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceInfo", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceInfo error, failed ret: %{public}d", ret); SysEventWrite(std::string(GET_LOCAL_DEVICE_INFO_FAILED), DM_HISYEVENT_BEHAVIOR, std::string(GET_LOCAL_DEVICE_INFO_FAILED_MSG)); @@ -330,6 +354,7 @@ int32_t DeviceManagerImpl::GetLocalDeviceInfo(const std::string &pkgName, DmDevi LOGI("Completed"); SysEventWrite(std::string(GET_LOCAL_DEVICE_INFO_SUCCESS), DM_HISYEVENT_BEHAVIOR, std::string(GET_LOCAL_DEVICE_INFO_SUCCESS_MSG)); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceInfo", info, DM_OK); return DM_OK; } @@ -337,6 +362,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterDevStateCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } @@ -344,6 +370,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ERR_DM_INIT_FAILED); LOGE("Get SystemAbilityManager Failed"); return ERR_DM_INIT_FAILED; } @@ -353,11 +380,13 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, } int32_t ret = CheckApiPermission(SYSTEM_CORE); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ret); LOGE("System SA not have permission, ret: %{public}d.", ret); return ret; } #endif DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -366,11 +395,14 @@ int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegisterDevStatusCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterDevStatusCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterDeviceStatusCallback(pkgName, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStatusCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -378,11 +410,14 @@ int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDevStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("UnRegisterDevStateCallback Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDevStateCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -390,11 +425,14 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName int32_t DeviceManagerImpl::UnRegisterDevStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDevStatusCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("UnRegisterDevStatusCallback Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterDeviceStatusCallback(pkgName); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDevStatusCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -553,6 +591,7 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", ERR_DM_INPUT_PARA_INVALID); LOGE("PublishDeviceDiscovery error: pkgName %{public}s invalid para", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } @@ -566,6 +605,7 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co req->SetPublishInfo(publishInfo); int32_t ret = ipcClientProxy_->SendRequest(PUBLISH_DEVICE_DISCOVER, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", ret); LOGE("PublishDeviceDiscovery error: Send Request failed ret: %{public}d", ret); DeviceManagerNotify::GetInstance().UnRegisterPublishCallback(pkgName, publishInfo.publishId); return ERR_DM_IPC_SEND_REQUEST_FAILED; @@ -573,10 +613,11 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", ret); LOGE("PublishDeviceDiscovery error: Failed with ret %{public}d", ret); return ret; } - + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "PublishDeviceDiscovery", DM_OK); LOGI("Completed"); return DM_OK; } @@ -584,6 +625,7 @@ int32_t DeviceManagerImpl::PublishDeviceDiscovery(const std::string &pkgName, co int32_t DeviceManagerImpl::UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -595,17 +637,20 @@ int32_t DeviceManagerImpl::UnPublishDeviceDiscovery(const std::string &pkgName, req->SetPublishId(publishId); int32_t ret = ipcClientProxy_->SendRequest(UNPUBLISH_DEVICE_DISCOVER, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", ret); LOGE("UnPublishDeviceDiscovery error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", ret); LOGE("UnPublishDeviceDiscovery error: Failed with ret %{public}d", ret); return ret; } DeviceManagerNotify::GetInstance().UnRegisterPublishCallback(pkgName, publishId); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnPublishDeviceDiscovery", DM_OK); LOGI("Completed"); return DM_OK; } @@ -692,6 +737,8 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pk std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegisterDeviceManagerFaCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterDeviceManagerFaCallback error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } @@ -699,6 +746,7 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pk LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegisterDeviceManagerFaCallback(pkgName, callback); RegisterUiStateCallback(pkgName); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDeviceManagerFaCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -706,6 +754,8 @@ int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pk int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDeviceManagerFaCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -713,6 +763,7 @@ int32_t DeviceManagerImpl::UnRegisterDeviceManagerFaCallback(const std::string & LOGI("Start, pkgName: %{public}s", pkgName.c_str()); DeviceManagerNotify::GetInstance().UnRegisterDeviceManagerFaCallback(pkgName); UnRegisterUiStateCallback(pkgName); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDeviceManagerFaCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -844,6 +895,7 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName int32_t DeviceManagerImpl::RegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -855,21 +907,26 @@ int32_t DeviceManagerImpl::RegisterUiStateCallback(const std::string &pkgName) int32_t ret = ipcClientProxy_->SendRequest(REGISTER_UI_STATE_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", ret); LOGI("RegisterUiStateCallback Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", ret); LOGE("RegisterUiStateCallback Failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterUiStateCallback", DM_OK); return DM_OK; } int32_t DeviceManagerImpl::UnRegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterUiStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -880,15 +937,18 @@ int32_t DeviceManagerImpl::UnRegisterUiStateCallback(const std::string &pkgName) int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_UI_STATE_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterUiStateCallback", ret); LOGI("UnRegisterUiStateCallback Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterUiStateCallback", ret); LOGE("UnRegisterUiStateCallback Failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterUiStateCallback", DM_OK); return DM_OK; } @@ -1050,11 +1110,13 @@ int32_t DeviceManagerImpl::UnRegisterCredentialCallback(const std::string &pkgNa int32_t DeviceManagerImpl::NotifyEvent(const std::string &pkgName, const int32_t eventId, const std::string &event) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ERR_DM_INPUT_PARA_INVALID); LOGE("NotifyEvent error: pkgName empty"); return ERR_DM_INPUT_PARA_INVALID; } if ((eventId <= DM_NOTIFY_EVENT_START) || (eventId >= DM_NOTIFY_EVENT_BUTT)) { LOGE("NotifyEvent eventId invalid"); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ERR_DM_INPUT_PARA_INVALID); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); @@ -1066,15 +1128,18 @@ int32_t DeviceManagerImpl::NotifyEvent(const std::string &pkgName, const int32_t int32_t ret = ipcClientProxy_->SendRequest(NOTIFY_EVENT, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ret); LOGI("NotifyEvent Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", ret); LOGE("NotifyEvent failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "NotifyEvent", DM_OK); LOGI("Completed"); return DM_OK; } @@ -1294,11 +1359,13 @@ int32_t DeviceManagerImpl::GetLocalDeviceNetWorkId(const std::string &pkgName, s DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceNetWorkId", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } networkId = std::string(info.networkId); LOGI("End, networkId : %{public}s", GetAnonyString(networkId).c_str()); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceNetWorkId", info, DM_OK); return DM_OK; } @@ -1308,11 +1375,13 @@ int32_t DeviceManagerImpl::GetLocalDeviceId(const std::string &pkgName, std::str DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceId", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } deviceId = std::string(info.deviceId); LOGI("End, deviceId : %{public}s", GetAnonyString(deviceId).c_str()); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceId", info, DM_OK); return DM_OK; } @@ -1322,11 +1391,13 @@ int32_t DeviceManagerImpl::GetLocalDeviceName(const std::string &pkgName, std::s DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceName", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } deviceName = std::string(info.deviceName); LOGI("End, deviceName : %{public}s", GetAnonyString(deviceName).c_str()); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceName", info, DM_OK); return DM_OK; } @@ -1336,11 +1407,13 @@ int32_t DeviceManagerImpl::GetLocalDeviceType(const std::string &pkgName, int32 DmDeviceInfo info; int32_t ret = GetLocalDeviceInfo(pkgName, info); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceType", info, ret); LOGI("DeviceManagerImpl::GetLocalDeviceNetWorkId failed."); return ret; } deviceType = info.deviceTypeId; LOGI("End, deviceType : %{public}d", deviceType); + DmRadarHelper::GetInstance().ReportGetLocalDevInfo(pkgName, "GetLocalDeviceType", info, DM_OK); return DM_OK; } @@ -1350,12 +1423,14 @@ int32_t DeviceManagerImpl::GetDeviceName(const std::string &pkgName, const std:: DmDeviceInfo deviceInfo; int32_t ret = GetDeviceInfo(pkgName, networkId, deviceInfo); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceName", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceName error, failed ret: %{public}d", ret); return ret; } deviceName = std::string(deviceInfo.deviceName); LOGI("End, pkgName : %{public}s, networkId : %{public}s, deviceName = %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str(), GetAnonyString(deviceName).c_str()); + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceName", deviceInfo, DM_OK); return DM_OK; } @@ -1364,12 +1439,14 @@ int32_t DeviceManagerImpl::GetDeviceType(const std::string &pkgName, const std:: DmDeviceInfo deviceInfo; int32_t ret = GetDeviceInfo(pkgName, networkId, deviceInfo); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceType", deviceInfo, ret); LOGE("DeviceManagerImpl::GetDeviceType error, failed ret: %{public}d", ret); return ret; } deviceType = deviceInfo.deviceTypeId; LOGI("End, pkgName : %{public}s, networkId : %{public}s, deviceType = %{public}d", pkgName.c_str(), GetAnonyString(networkId).c_str(), deviceType); + DmRadarHelper::GetInstance().ReportGetDeviceInfo(pkgName, "GetDeviceType", deviceInfo, DM_OK); return DM_OK; } @@ -1645,6 +1722,8 @@ int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgName) { if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDiscoveryCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::UnRegisterDiscoveryCallback failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } @@ -1652,6 +1731,8 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); if (subscribeId == DM_INVALID_FLAG_ID) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "UnRegisterDiscoveryCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::UnRegisterDiscoveryCallback failed: cannot find pkgName in cache map."); return ERR_DM_INPUT_PARA_INVALID; } @@ -1665,14 +1746,17 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam req->SetFirstParam(extraParaStr); int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_DISCOVERY_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -1836,10 +1920,12 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, { (void)extraParam; if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::RegisterDeviceStateCallback failed: input pkgName or callback is empty."); return ERR_DM_INPUT_PARA_INVALID; } DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } @@ -1866,6 +1952,7 @@ uint16_t DeviceManagerImpl::AddDiscoveryCallback(const std::string &pkgName, } } DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "AddDiscoveryCallback", DM_OK); return subscribeId; } @@ -1880,6 +1967,7 @@ uint16_t DeviceManagerImpl::RemoveDiscoveryCallback(const std::string &pkgName) } } DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RemoveDiscoveryCallback", DM_OK); return subscribeId; } @@ -1895,6 +1983,7 @@ int32_t DeviceManagerImpl::AddPublishCallback(const std::string &pkgName) pkgName2PubIdMap_[pkgName] = publishId; } } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "AddPublishCallback", DM_OK); return publishId; } @@ -1908,7 +1997,7 @@ int32_t DeviceManagerImpl::RemovePublishCallback(const std::string &pkgName) pkgName2PubIdMap_.erase(pkgName); } } - + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RemovePublishCallback", DM_OK); return publishId; } @@ -1916,6 +2005,8 @@ int32_t DeviceManagerImpl::RegisterPinHolderCallback(const std::string &pkgName, std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegisterPinHolderCallback", ERR_DM_INPUT_PARA_INVALID); LOGE("RegisterPinHolderCallback error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } @@ -1926,14 +2017,17 @@ int32_t DeviceManagerImpl::RegisterPinHolderCallback(const std::string &pkgName, int32_t ret = ipcClientProxy_->SendRequest(REGISTER_PIN_HOLDER_CALLBACK, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterPinHolderCallback", ret); LOGI("RegisterPinHolderCallback Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterPinHolderCallback", ret); LOGE("RegisterPinHolderCallback Failed with ret %{public}d", ret); return ret; } + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterPinHolderCallback", DM_OK); return DM_OK; } @@ -2025,6 +2119,7 @@ int32_t DeviceManagerImpl::GetDeviceSecurityLevel(const std::string &pkgName, co int32_t &securityLevel) { if (pkgName.empty() || networkId.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", ERR_DM_INPUT_PARA_INVALID); LOGE("DeviceManagerImpl::GetDeviceSecurityLevel error: pkgName: %{public}s, networkId: %{public}s", pkgName.c_str(), GetAnonyString(networkId).c_str()); return ERR_DM_INPUT_PARA_INVALID; @@ -2039,16 +2134,19 @@ int32_t DeviceManagerImpl::GetDeviceSecurityLevel(const std::string &pkgName, co int32_t ret = ipcClientProxy_->SendRequest(GET_SECURITY_LEVEL, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", ret); LOGE("GetDeviceSecurityLevel Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", ret); LOGE("GetDeviceSecurityLevel Failed with ret %{public}d", ret); return ret; } securityLevel = rsp->GetSecurityLevel(); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "GetDeviceSecurityLevel", DM_OK); return DM_OK; } @@ -2152,15 +2250,18 @@ int32_t DeviceManagerImpl::ShiftLNNGear(const std::string &pkgName) req->SetPkgName(pkgName); int32_t ret = ipcClientProxy_->SendRequest(SHIFT_LNN_GEAR, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "ShiftLNNGear", ret); LOGE("ShiftLNNGear error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "ShiftLNNGear", ret); LOGE("ShiftLNNGear error: Failed with ret %{public}d", ret); return ret; } LOGI("Completed"); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "ShiftLNNGear", DM_OK); return DM_OK; } @@ -2168,6 +2269,7 @@ int32_t DeviceManagerImpl::SetDnPolicy(const std::string &pkgName, std::mapSetFirstParam(strategy); int32_t ret = ipcClientProxy_->SendRequest(SET_DN_POLICY, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "SetDnPolicy", ret); LOGE("Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "SetDnPolicy", ret); LOGE("Failed with ret %{public}d", ret); return ret; } LOGI("Completed"); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "SetDnPolicy", DM_OK); return DM_OK; } @@ -2197,10 +2302,13 @@ int32_t DeviceManagerImpl::RegDevTrustChangeCallback(const std::string &pkgName, { if (pkgName.empty() || callback == nullptr) { LOGE("Error: Invalid para"); + DmRadarHelper::GetInstance().ReportDmBehavior( + pkgName, "RegDevTrustChangeCallback", ERR_DM_INPUT_PARA_INVALID); return ERR_DM_INPUT_PARA_INVALID; } LOGI("PkgName %{public}s.", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegDevTrustChangeCallback(pkgName, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegDevTrustChangeCallback", DM_OK); return DM_OK; } diff --git a/radar/include/dm_radar_helper.h b/radar/include/dm_radar_helper.h index 22d56f2bb..ef308589f 100644 --- a/radar/include/dm_radar_helper.h +++ b/radar/include/dm_radar_helper.h @@ -35,12 +35,20 @@ const std::string DM_AUTHCATION_BEHAVIOR = "DM_AUTHCATION_BEHAVIOR"; constexpr int32_t SUBSYS_DISTRIBUTEDHARDWARE_DM = 204; constexpr int32_t INVALID_UDID_LENGTH = 10; constexpr int32_t SUBSTR_UDID_LENGTH = 5; -enum class BizScene : int32_t { +constexpr int32_t DEFAULT_STAGE = 1; +enum class DiscoverScene : int32_t { DM_DISCOVER = 0x1, - DM_AUTHCATION = 0x2, - DM_NETWORK = 0x3, - DM_DELET_TRUST_RELATION = 0x4, - DM_PIN_HOLDER = 0x5, + DM_GET_TRUST_DEVICE_LIST = 0x2, + DM_GET_LOCAL_DEVICE_INFO = 0x3, + DM_GET_DEVICE_INFO = 0x4, + DM_BEHAVIOR = 0x5, +}; + +enum class AuthScene : int32_t { + DM_AUTHCATION = 0x1, + DM_NETWORK = 0x2, + DM_DELET_TRUST_RELATION = 0x3, + DM_PIN_HOLDER = 0x4, }; enum class StageRes : int32_t { @@ -157,12 +165,18 @@ public: virtual bool ReportNetworkOnline(struct RadarInfo &info) = 0; virtual bool ReportNetworkOffline(struct RadarInfo &info) = 0; virtual bool ReportDeleteTrustRelation(struct RadarInfo &info) = 0; - virtual bool ReportGetTrustDeviceList(struct RadarInfo &info) = 0; + virtual void ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) = 0; virtual void ReportCreatePinHolder(std::string hostName, int32_t channelId, std::string peerUdid, int32_t errCode, int32_t stageRes) = 0; virtual void ReportDestroyPinHolder(std::string hostName, std::string peerUdid, int32_t errCode, int32_t stageRes) = 0; virtual void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) = 0; + virtual void ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) = 0; + virtual void ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) = 0; + virtual void ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) = 0; virtual std::string GetDeviceInfoList(std::vector &deviceInfoList) = 0; virtual std::string GetUdidHashByUdid(std::string udid) = 0; }; @@ -188,12 +202,18 @@ public: bool ReportNetworkOnline(struct RadarInfo &info) override; bool ReportNetworkOffline(struct RadarInfo &info) override; bool ReportDeleteTrustRelation(struct RadarInfo &info) override; - bool ReportGetTrustDeviceList(struct RadarInfo &info) override; + void ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) override; void ReportCreatePinHolder(std::string hostName, int32_t channelId, std::string peerUdid, int32_t errCode, int32_t stageRes) override; void ReportDestroyPinHolder(std::string hostName, std::string peerUdid, int32_t errCode, int32_t stageRes) override; void ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string funcName, std::string peerUdid) override; + void ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) override; + void ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) override; + void ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) override; std::string GetDeviceInfoList(std::vector &deviceInfoList) override; std::string GetUdidHashByUdid(std::string udid) override; std::string ConvertHexToString(uint16_t hex); diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index bcfd8713f..eaa01cf8d 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -42,7 +42,7 @@ bool DmRadarHelper::ReportDiscoverRegCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -55,7 +55,7 @@ bool DmRadarHelper::ReportDiscoverRegCallback(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -81,7 +81,7 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", SOFTBUSNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "PEER_UDID", GetAnonyUdid(info.peerUdid), @@ -96,7 +96,7 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", SOFTBUSNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -124,7 +124,7 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -136,7 +136,7 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END)); @@ -148,7 +148,7 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -171,7 +171,7 @@ bool DmRadarHelper::ReportAuthStart(const std::string &peerUdid, const std::stri "ORG_PKG", ORGPKGNAME, "FUNC", "AuthenticateDevice", "HOST_PKG", pkgName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_START), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_START), @@ -195,7 +195,7 @@ bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "STAGE_RES", info.stageRes, "PEER_UDID", GetAnonyUdid(info.peerUdid), @@ -212,7 +212,7 @@ bool DmRadarHelper::ReportAuthOpenSession(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "BIZ_STATE", info.bizState, "STAGE_RES", info.stageRes, @@ -240,7 +240,7 @@ bool DmRadarHelper::ReportAuthSessionOpenCb(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_OPEN_SESSION), "STAGE_RES", info.stageRes, "PEER_UDID", GetAnonyUdid(info.peerUdid), @@ -261,7 +261,7 @@ bool DmRadarHelper::ReportAuthSendRequest(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_SEND_REQUEST), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "TO_CALL_PKG", SOFTBUSNAME, @@ -283,7 +283,7 @@ bool DmRadarHelper::ReportAuthPullAuthBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_AUTH_BOX), "STAGE_RES", info.stageRes); if (res != DM_OK) { @@ -303,7 +303,7 @@ bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_AUTH_BOX), "STAGE_RES", info.stageRes); } else { @@ -313,7 +313,7 @@ bool DmRadarHelper::ReportAuthConfirmBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_AUTH_BOX), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -336,7 +336,7 @@ bool DmRadarHelper::ReportAuthCreateGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", info.stageRes, "LOCAL_UDID", GetAnonyLocalUdid(), @@ -348,7 +348,7 @@ bool DmRadarHelper::ReportAuthCreateGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -373,7 +373,7 @@ bool DmRadarHelper::ReportAuthCreateGroupCb(std::string funcName, int32_t stageR HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", stageRes, "HOST_PKG", HICHAINNAME); @@ -384,7 +384,7 @@ bool DmRadarHelper::ReportAuthCreateGroupCb(std::string funcName, int32_t stageR HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_CREATE_HICHAIN_GROUP), "STAGE_RES", stageRes, "HOST_PKG", HICHAINNAME, @@ -406,7 +406,7 @@ bool DmRadarHelper::ReportAuthPullPinBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_PIN_BOX_START), "STAGE_RES", info.stageRes); if (res != DM_OK) { @@ -426,7 +426,7 @@ bool DmRadarHelper::ReportAuthInputPinBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_PIN_INPUT_BOX_END), "STAGE_RES", info.stageRes); } else { @@ -436,7 +436,7 @@ bool DmRadarHelper::ReportAuthInputPinBox(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_PULL_PIN_INPUT_BOX_END), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -459,7 +459,7 @@ bool DmRadarHelper::ReportAuthAddGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", info.stageRes, "LOCAL_UDID", GetAnonyLocalUdid(), @@ -472,7 +472,7 @@ bool DmRadarHelper::ReportAuthAddGroup(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", info.stageRes, "LOCAL_UDID", GetAnonyLocalUdid(), @@ -498,7 +498,7 @@ bool DmRadarHelper::ReportAuthAddGroupCb(std::string funcName, int32_t stageRes) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", stageRes, "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -510,7 +510,7 @@ bool DmRadarHelper::ReportAuthAddGroupCb(std::string funcName, int32_t stageRes) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_AUTHCATION), + "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_ADD_HICHAIN_GROUP), "STAGE_RES", stageRes, "HOST_PKG", HICHAINNAME, @@ -532,7 +532,7 @@ bool DmRadarHelper::ReportNetworkOnline(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_NETWORK), + "BIZ_SCENE", static_cast(AuthScene::DM_NETWORK), "BIZ_STAGE", static_cast(NetworkStage::NETWORK_ONLINE), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -555,7 +555,7 @@ bool DmRadarHelper::ReportNetworkOffline(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_NETWORK), + "BIZ_SCENE", static_cast(AuthScene::DM_NETWORK), "BIZ_STAGE", static_cast(NetworkStage::NETWORK_OFFLINE), "STAGE_RES", info.stageRes, "BIZ_STATE", info.bizState, @@ -578,7 +578,7 @@ bool DmRadarHelper::ReportDeleteTrustRelation(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, - "BIZ_SCENE", static_cast(BizScene::DM_DELET_TRUST_RELATION), + "BIZ_SCENE", static_cast(AuthScene::DM_DELET_TRUST_RELATION), "BIZ_STAGE", static_cast(DeleteTrust::DELETE_TRUST), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -605,7 +605,7 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "CreatePinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::CREATE_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_START), @@ -625,7 +625,7 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "CreatePinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::CREATE_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -654,7 +654,7 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "DestroyPinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "LOCAL_UDID", GetAnonyLocalUdid(), @@ -672,7 +672,7 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "DestroyPinHolder", - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -698,7 +698,7 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", bizStage, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), @@ -716,7 +716,7 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", funcName, - "BIZ_SCENE", static_cast(BizScene::DM_PIN_HOLDER), + "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", bizStage, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "LOCAL_UDID", GetAnonyLocalUdid(), @@ -730,42 +730,162 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f return; } -bool DmRadarHelper::ReportGetTrustDeviceList(struct RadarInfo &info) +void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) { int32_t res = DM_OK; - if (info.stageRes == static_cast(StageRes::STAGE_SUCC)) { + std::string discoverDevList = GetDeviceInfoList(deviceInfoList); + if (errCode == DM_OK) { + if (deviceInfoList.size() > 0) { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_TRUST_DEVICE_LIST), + "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "DISCOVERY_DEVICE_LIST", discoverDevList); + } + } else { res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, - DM_AUTHCATION_BEHAVIOR, + DM_DISCOVER_BEHAVIOR, HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, - "FUNC", "GetTrustedDeviceList", - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_TRUST_DEVICE_LIST), "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), - "STAGE_RES", info.stageRes, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "LOCAL_UDID", GetAnonyLocalUdid(), - "DISCOVERY_DEVICE_LIST", info.discoverDevList); + "DISCOVERY_DEVICE_LIST", discoverDevList, + "ERROR_CODE", GetErrCode(errCode)); + } + return; +} + +void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) +{ + int32_t res = DM_OK; + if (errCode == DM_OK) { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_BEHAVIOR), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid()); } else { res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, - DM_AUTHCATION_BEHAVIOR, + DM_DISCOVER_BEHAVIOR, HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, - "FUNC", "GetTrustedDeviceList", - "BIZ_SCENE", static_cast(BizScene::DM_DISCOVER), - "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), - "STAGE_RES", info.stageRes, + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_BEHAVIOR), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "LOCAL_UDID", GetAnonyLocalUdid(), - "DISCOVERY_DEVICE_LIST", info.discoverDevList, - "ERROR_CODE", info.errCode); + "ERROR_CODE", GetErrCode(errCode)); } - if (res != DM_OK) { - LOGE("ReportDeleteTrustRelation error, res:%{public}d", res); - return false; + return; +} + +void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) +{ + int32_t res = DM_OK; + static std::string localCallerName = ""; + if (localCallerName != hostName) { + localCallerName = hostName; + if (errCode == DM_OK) { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_LOCAL_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "LOCAL_NET_ID", GetAnonyUdid(info.networkId)); + } else { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_LOCAL_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "LOCAL_NET_ID", GetAnonyUdid(info.networkId), + "ERROR_CODE", GetErrCode(errCode)); + } } - return true; + return; +} + +void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) +{ + int32_t res = DM_OK; + static std::string callerName = ""; + if (callerName != hostName) { + callerName = hostName; + if (errCode == DM_OK) { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_SUCC), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.deviceId), + "PEER_NET_ID", GetAnonyUdid(info.networkId)); + } else { + res = HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, + DM_DISCOVER_BEHAVIOR, + HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "ORG_PKG", ORGPKGNAME, + "HOST_PKG", hostName, + "FUNC", funcName, + "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_DEVICE_INFO), + "BIZ_STAGE", DEFAULT_STAGE, + "STAGE_RES", static_cast(StageRes::STAGE_FAIL), + "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "LOCAL_UDID", GetAnonyLocalUdid(), + "PEER_UDID", GetAnonyUdid(info.deviceId), + "PEER_NET_ID", GetAnonyUdid(info.networkId), + "ERROR_CODE", GetErrCode(errCode)); + } + } + return; } std::string DmRadarHelper::ConvertHexToString(uint16_t hex) @@ -792,13 +912,8 @@ std::string DmRadarHelper::GetDeviceInfoList(std::vector &deviceIn cJSON_Delete(deviceInfoJson); return ""; } - std::string udidHash = GetAnonyUdid(std::string(deviceInfoList[i].deviceId)); - cJSON_AddStringToObject(object, "PEER_UDID", udidHash.c_str()); - std::string peerNetId = GetAnonyUdid(deviceInfoList[i].networkId); - cJSON_AddStringToObject(object, "PEER_NET_ID", peerNetId.c_str()); std::string devType = ConvertHexToString(deviceInfoList[i].deviceTypeId); cJSON_AddStringToObject(object, "PEER_DEV_TYPE", devType.c_str()); - cJSON_AddStringToObject(object, "PEER_DEV_NAME", deviceInfoList[i].deviceName); cJSON_AddItemToArray(deviceInfoJson, object); } char *deviceInfoStr = cJSON_PrintUnformatted(deviceInfoJson); diff --git a/radar/src/lite/dm_radar_helper.cpp b/radar/src/lite/dm_radar_helper.cpp index df7c6d21b..b6591cc12 100644 --- a/radar/src/lite/dm_radar_helper.cpp +++ b/radar/src/lite/dm_radar_helper.cpp @@ -117,9 +117,10 @@ bool DmRadarHelper::ReportDeleteTrustRelation(struct RadarInfo &info) return true; } -bool DmRadarHelper::ReportGetTrustDeviceList(struct RadarInfo &info) +void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, + std::string funcName, std::vector &deviceInfoList, int32_t errCode) { - return true; + return; } void DmRadarHelper::ReportCreatePinHolder(std::string hostName, @@ -139,6 +140,23 @@ void DmRadarHelper::ReportSendOrReceiveHolderMsg(int32_t bizStage, std::string f return; } +void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) +{ + return; +} + +void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) +{ + return; +} + +void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, + std::string funcName, DmDeviceInfo &info, int32_t errCode) +{ + return; +} + std::string DmRadarHelper::ConvertHexToString(uint16_t hex) { std::stringstream str; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 8ebc15511..bf8420320 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -623,22 +623,7 @@ int32_t SoftbusListener::UnRegisterSoftbusLnnOpsCbk(const std::string &pkgName) int32_t SoftbusListener::GetTrustedDeviceList(std::vector &deviceInfoList) { int32_t ret = SoftbusCache::GetInstance().GetDeviceInfoFromCache(deviceInfoList); - static size_t radarDeviceCount = 0; size_t deviceCount = deviceInfoList.size(); - char localDeviceId[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - struct RadarInfo radarInfo = { - .localUdid = std::string(localDeviceId), - }; - radarInfo.stageRes = static_cast(StageRes::STAGE_SUCC); - if (radarDeviceCount != deviceCount && deviceCount > 0 - && IsDmRadarHelperReady() && GetDmRadarHelperObj() != nullptr) { - radarDeviceCount = deviceCount; - radarInfo.discoverDevList = GetDmRadarHelperObj()->GetDeviceInfoList(deviceInfoList); - if (!GetDmRadarHelperObj()->ReportGetTrustDeviceList(radarInfo)) { - LOGE("ReportGetTrustDeviceList failed"); - } - } LOGI("Success from cache deviceInfoList size is %{public}zu.", deviceCount); return ret; } diff --git a/test/commonunittest/dm_radar_helper_test.cpp b/test/commonunittest/dm_radar_helper_test.cpp index 4be878cef..d6f83ff24 100644 --- a/test/commonunittest/dm_radar_helper_test.cpp +++ b/test/commonunittest/dm_radar_helper_test.cpp @@ -220,13 +220,6 @@ HWTEST_F(DmRadarHelperTest, ReportDeleteTrustRelation_001, testing::ext::TestSiz struct RadarInfo info = { 0 }; info.stageRes = static_cast(StageRes::STAGE_IDLE); bool res = DmRadarHelper::GetInstance().ReportDeleteTrustRelation(info); - EXPECT_EQ(res, true); -} -HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_001, testing::ext::TestSize.Level0) -{ - struct RadarInfo info = { 0 }; - info.stageRes = static_cast(StageRes::STAGE_SUCC); - bool res = DmRadarHelper::GetInstance().ReportGetTrustDeviceList(info); int32_t stageRes = static_cast(StageRes::STAGE_SUCC); std::string str = "test"; @@ -239,16 +232,9 @@ HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_001, testing::ext::TestSize int32_t bizStage = static_cast(PinHolderStage::RECEIVE_DESTROY_PIN_HOLDER_MSG); DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str, ""); - bizStage = static_cast(PinHolderStage::RECEIVE_CREATE_PIN_HOLDER_MSG); DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(bizStage, str, ""); - EXPECT_EQ(res, true); -} -HWTEST_F(DmRadarHelperTest, ReportGetTrustDeviceList_002, testing::ext::TestSize.Level0) -{ - struct RadarInfo info = { 0 }; - info.stageRes = static_cast(StageRes::STAGE_IDLE); - bool res = DmRadarHelper::GetInstance().ReportGetTrustDeviceList(info); + EXPECT_EQ(res, true); } } // namespace DistributedHardware -- Gitee From 238320cbf5e48c2528aa45edfff5babc69f9fa6a Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 13 Sep 2024 10:31:42 +0800 Subject: [PATCH 198/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- interfaces/inner_kits/native_cpp/BUILD.gn | 2 -- radar/BUILD.gn | 5 ----- radar/include/dm_radar_helper.h | 2 -- radar/src/dm_radar_helper.cpp | 15 ++++----------- radar/src/lite/dm_radar_helper.cpp | 23 +---------------------- 5 files changed, 5 insertions(+), 42 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 75b8714a6..3343bcbae 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -138,7 +138,6 @@ if (defined(ohos_lite)) { "${common_path}/include/dfx", "${common_path}/include/dfx/standard", "${devicemanager_path}/radar/include", - "${utils_path}/include/crypto", ] } @@ -157,7 +156,6 @@ if (defined(ohos_lite)) { "${common_path}/src/dm_anonymous.cpp", "${common_path}/src/ipc/standard/ipc_cmd_register.cpp", "${devicemanager_path}/radar/src/dm_radar_helper.cpp", - "${utils_path}/src/crypto/dm_crypto.cpp", "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", diff --git a/radar/BUILD.gn b/radar/BUILD.gn index ebdd6420d..b93d77b96 100644 --- a/radar/BUILD.gn +++ b/radar/BUILD.gn @@ -25,7 +25,6 @@ if (defined(ohos_lite)) { "${common_path}/include", "${innerkits_path}/native_cpp/include", "${c_utils_path}/include", - "${utils_path}/include/crypto", "//third_party/cJSON", ] @@ -38,7 +37,6 @@ if (defined(ohos_lite)) { ] deps = [ - "${utils_path}:devicemanagerutils", "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", "//base/startup/init/interfaces/innerkits:libbegetutil", "//commonlibrary/utils_lite:utils", @@ -52,7 +50,6 @@ if (defined(ohos_lite)) { "include", "${common_path}/include", "${innerkits_path}/native_cpp/include", - "${utils_path}/include/crypto", ] sources = [ "src/dm_radar_helper.cpp" ] @@ -63,8 +60,6 @@ if (defined(ohos_lite)) { "LOG_DOMAIN=0xD004110", ] - deps = [ "${utils_path}:devicemanagerutils" ] - external_deps = [ "cJSON:cjson", "c_utils:utils", diff --git a/radar/include/dm_radar_helper.h b/radar/include/dm_radar_helper.h index ef308589f..91de34ac7 100644 --- a/radar/include/dm_radar_helper.h +++ b/radar/include/dm_radar_helper.h @@ -178,7 +178,6 @@ public: virtual void ReportGetDeviceInfo(std::string hostName, std::string funcName, DmDeviceInfo &info, int32_t errCode) = 0; virtual std::string GetDeviceInfoList(std::vector &deviceInfoList) = 0; - virtual std::string GetUdidHashByUdid(std::string udid) = 0; }; class DmRadarHelper : public IDmRadarHelper { @@ -215,7 +214,6 @@ public: void ReportGetDeviceInfo(std::string hostName, std::string funcName, DmDeviceInfo &info, int32_t errCode) override; std::string GetDeviceInfoList(std::vector &deviceInfoList) override; - std::string GetUdidHashByUdid(std::string udid) override; std::string ConvertHexToString(uint16_t hex); int32_t GetErrCode(int32_t errCode); private: diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index eaa01cf8d..1ad7f4f35 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -24,7 +24,6 @@ #include "hisysevent.h" #include "dm_constants.h" -#include "dm_crypto.h" #include "dm_log.h" #include "parameter.h" @@ -736,7 +735,10 @@ void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, int32_t res = DM_OK; std::string discoverDevList = GetDeviceInfoList(deviceInfoList); if (errCode == DM_OK) { - if (deviceInfoList.size() > 0) { + int32_t deviceCount = deviceInfoList.size(); + static std::string TrustCallerName = ""; + if (deviceCount > 0 && TrustCallerName != hostName) { + TrustCallerName = hostName; res = HiSysEventWrite( OHOS::HiviewDFX::HiSysEvent::Domain::DISTRIBUTED_DEVICE_MANAGER, DM_DISCOVER_BEHAVIOR, @@ -928,15 +930,6 @@ std::string DmRadarHelper::GetDeviceInfoList(std::vector &deviceIn return devInfoStr; } -std::string DmRadarHelper::GetUdidHashByUdid(std::string udid) -{ - char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetUdidHash(udid, reinterpret_cast(udidHash)) != DM_OK) { - return ""; - } - return GetAnonyUdid(std::string(udidHash)); -} - std::string DmRadarHelper::GetAnonyUdid(std::string udid) { if (udid.empty() || udid.length() < INVALID_UDID_LENGTH) { diff --git a/radar/src/lite/dm_radar_helper.cpp b/radar/src/lite/dm_radar_helper.cpp index b6591cc12..091c5d714 100644 --- a/radar/src/lite/dm_radar_helper.cpp +++ b/radar/src/lite/dm_radar_helper.cpp @@ -20,7 +20,6 @@ #include #include #include "dm_constants.h" -#include "dm_crypto.h" #include "dm_log.h" #include "parameter.h" @@ -169,27 +168,7 @@ std::string DmRadarHelper::ConvertHexToString(uint16_t hex) std::string DmRadarHelper::GetDeviceInfoList(std::vector &deviceInfoList) { - cJSON* deviceInfoJson = cJSON_CreateArray(); - for (size_t i = 0; i < deviceInfoList.size(); i++) { - cJSON* object = cJSON_CreateObject(); - std::string udidHash = GetUdidHashByUdid(std::string(deviceInfoList[i].deviceId)); - cJSON_AddStringToObject(object, "PEER_UDID", udidHash.c_str()); - cJSON_AddStringToObject(object, "PEER_NET_ID", deviceInfoList[i].networkId); - std::string devType = ConvertHexToString(deviceInfoList[i].deviceTypeId); - cJSON_AddStringToObject(object, "PEER_DEV_TYPE", devType.c_str()); - cJSON_AddStringToObject(object, "PEER_DEV_NAME", deviceInfoList[i].deviceName); - cJSON_AddItemToArray(deviceInfoJson, object); - } - return std::string(cJSON_PrintUnformatted(deviceInfoJson)); -} - -std::string DmRadarHelper::GetUdidHashByUdid(std::string udid) -{ - char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetUdidHash(udid, reinterpret_cast(udidHash)) != DM_OK) { - return ""; - } - return GetAnonyUdid(std::string(udidHash)); + return ""; } std::string DmRadarHelper::GetAnonyUdid(std::string udid) -- Gitee From 9c71dab35f395b04e0404bc9c5ba837cda2decd4 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 13 Sep 2024 10:49:32 +0800 Subject: [PATCH 199/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=89=93=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index afc4b5923..023c6279a 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2302,13 +2302,13 @@ int32_t DeviceManagerImpl::RegDevTrustChangeCallback(const std::string &pkgName, { if (pkgName.empty() || callback == nullptr) { LOGE("Error: Invalid para"); - DmRadarHelper::GetInstance().ReportDmBehavior( + DmRadarHelper::GetInstance().ReportDmBehavior( pkgName, "RegDevTrustChangeCallback", ERR_DM_INPUT_PARA_INVALID); return ERR_DM_INPUT_PARA_INVALID; } LOGI("PkgName %{public}s.", pkgName.c_str()); DeviceManagerNotify::GetInstance().RegDevTrustChangeCallback(pkgName, callback); - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegDevTrustChangeCallback", DM_OK); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegDevTrustChangeCallback", DM_OK); return DM_OK; } -- Gitee From fe0dff73361f97c12e0630948f3115e8ef7ad088 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 13 Sep 2024 11:51:13 +0800 Subject: [PATCH 200/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- test/softbusunittest/UTTest_softbus_listener.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 66aa4b18e..8adb18538 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -578,11 +578,9 @@ HWTEST_F(SoftbusListenerTest, GetDeviceSecurityLevel_001, testing::ext::TestSize HWTEST_F(SoftbusListenerTest, GetDmRadarHelperObj_001, testing::ext::TestSize.Level0) { - if (softbusListener == nullptr) { - softbusListener = std::make_shared(); - } - auto ret = softbusListener->GetDmRadarHelperObj(); - EXPECT_NE(ret, nullptr); + std::shared_ptr softbusListener_ = std::make_shared(); + auto ret = softbusListener_->GetDmRadarHelperObj(); + EXPECT_EQ(ret, nullptr); } HWTEST_F(SoftbusListenerTest, SetHostPkgName_001, testing::ext::TestSize.Level0) @@ -612,7 +610,7 @@ HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_001, testing::ext::TestSize.Level0 softbusListener = std::make_shared(); } softbusListener->CacheDeviceInfo(deviceId, infoPtr); - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_002, testing::ext::TestSize.Level0) @@ -624,7 +622,7 @@ HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_002, testing::ext::TestSize.Level0 softbusListener = std::make_shared(); } softbusListener->CacheDeviceInfo(deviceId, infoPtr); - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_003, testing::ext::TestSize.Level0) @@ -636,7 +634,7 @@ HWTEST_F(SoftbusListenerTest, CacheDeviceInfo_003, testing::ext::TestSize.Level0 softbusListener = std::make_shared(); } softbusListener->CacheDeviceInfo(deviceId, infoPtr); - EXPECT_EQ(softbusListener->isRadarSoLoad_, true); + EXPECT_EQ(softbusListener->isRadarSoLoad_, false); } HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_001, testing::ext::TestSize.Level0) -- Gitee From bd7e9627ae0273401fad71475036848a8680effc Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 13 Sep 2024 14:04:32 +0800 Subject: [PATCH 201/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B=5F20240913?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index ddba85bc6..7c336872a 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2165,22 +2165,6 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } -HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_001, testing::ext::TestSize.Level0) -{ - std::string udid = ""; - std::string result = ""; - int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udid, result); - EXPECT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoy_002, testing::ext::TestSize.Level0) -{ - std::string udid = "ikjwdncksd456"; - std::string result = ""; - int ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udid, result); - EXPECT_EQ(ret, ERR_DM_FAILED); -} - HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) { DmAccessCaller caller; -- Gitee From 09f19aac43db265db90a982a1272b565cc873241 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 13 Sep 2024 17:54:43 +0800 Subject: [PATCH 202/520] add radar Signed-off-by: gaoqiang_strong --- radar/src/dm_radar_helper.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index 1ad7f4f35..6446d9e04 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -825,6 +825,7 @@ void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), "LOCAL_UDID", GetAnonyLocalUdid(), "LOCAL_NET_ID", GetAnonyUdid(info.networkId)); } else { @@ -839,6 +840,7 @@ void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), "LOCAL_UDID", GetAnonyLocalUdid(), "LOCAL_NET_ID", GetAnonyUdid(info.networkId), "ERROR_CODE", GetErrCode(errCode)); @@ -867,6 +869,7 @@ void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "LOCAL_UDID", GetAnonyLocalUdid(), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), "PEER_UDID", GetAnonyUdid(info.deviceId), "PEER_NET_ID", GetAnonyUdid(info.networkId)); } else { @@ -882,6 +885,7 @@ void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, "STAGE_RES", static_cast(StageRes::STAGE_FAIL), "BIZ_STATE", static_cast(BizState::BIZ_STATE_END), "LOCAL_UDID", GetAnonyLocalUdid(), + "DEV_TYPE", ConvertHexToString(info.deviceTypeId), "PEER_UDID", GetAnonyUdid(info.deviceId), "PEER_NET_ID", GetAnonyUdid(info.networkId), "ERROR_CODE", GetErrCode(errCode)); -- Gitee From 4f3d05880821ab60ba7f43a23e905d7643315f05 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 13 Sep 2024 18:26:18 +0800 Subject: [PATCH 203/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B=5F20240913?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 7c336872a..30cf5f847 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -193,7 +193,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSi HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) { DeletePermission(); - std::string pkgName ="StopDeviceDiscovery_003"; + std::string pkgName = "StopDeviceDiscovery_003"; uint16_t subscribeId = 1; int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -- Gitee From 2929e89566acd0ce6b33ff6200a6e2e3b45701d5 Mon Sep 17 00:00:00 2001 From: dengxiaoyu Date: Sat, 14 Sep 2024 16:25:56 +0800 Subject: [PATCH 204/520] modify inputPin gap Signed-off-by: dengxiaoyu --- .../src/main/ets/pages/InputPinDialog.ets | 98 ++++++++++--------- 1 file changed, 52 insertions(+), 46 deletions(-) diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index 32e505220..d10ab96d5 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -64,7 +64,7 @@ struct InputCustomDialog { this.isPC = Constant.isPC(); let ims = inputMethod.getSetting(); ims.on('imeShow', (info: Array) => { - this.scroller.scrollTo({yOffset: 72, xOffset: 0}); + this.scroller.scrollTo({ yOffset: 72, xOffset: 0 }); }); if (AppStorage.get('targetDeviceName') != null) { this.targetDeviceName = AppStorage.get('targetDeviceName') as string; @@ -76,37 +76,37 @@ struct InputCustomDialog { } deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', (err: Error, dm: deviceManager.DeviceManager) => { - if (err) { - console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); - return; - } - dmClass = dm; - dmClass.on('uiStateChange', (data: Record) => { - console.log('uiStateChange executed, dialog closed' + JSON.stringify(data)); - let tmpStr: Record = JSON.parse(data.param); - let msg: number = tmpStr.uiStateMsg as number; - if (msg === MSG_DOING_AUTH) { - this.errorTips = $r('app.string.dm_authenticating'); - this.errorTipsVisible = Visibility.Visible; - return; - } - if (msg === MSG_CANCEL_PIN_CODE_INPUT) { - this.destruction(); + if (err) { + console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); return; } - if (msg === MSG_PIN_CODE_ERROR) { - if (this.model == MODEL_PASSWORD) { - this.errorTips = $r('app.string.dm_password_error'); - } else { - this.isTimes--; - this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); + dmClass = dm; + dmClass.on('uiStateChange', (data: Record) => { + console.log('uiStateChange executed, dialog closed' + JSON.stringify(data)); + let tmpStr: Record = JSON.parse(data.param); + let msg: number = tmpStr.uiStateMsg as number; + if (msg === MSG_DOING_AUTH) { + this.errorTips = $r('app.string.dm_authenticating'); + this.errorTipsVisible = Visibility.Visible; + return; } - this.password = ''; - this.errorTipsVisible = Visibility.Visible; - this.passwordCircle = ['', '', '', '', '', '']; - } - }) - }); + if (msg === MSG_CANCEL_PIN_CODE_INPUT) { + this.destruction(); + return; + } + if (msg === MSG_PIN_CODE_ERROR) { + if (this.model == MODEL_PASSWORD) { + this.errorTips = $r('app.string.dm_password_error'); + } else { + this.isTimes--; + this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); + } + this.password = ''; + this.errorTipsVisible = Visibility.Visible; + this.passwordCircle = ['', '', '', '', '', '']; + } + }) + }); this.listener.on('change', (mediaQueryResult: mediaquery.MediaQueryResult) => { this.onPortrait(mediaQueryResult); }); @@ -221,7 +221,7 @@ struct InputCustomDialog { List() { ListItem() { Flex({ justifyContent: FlexAlign.Center }) { - ForEach(this.passwordCircle, (item:string) => { + ForEach(this.passwordCircle, (item: string) => { Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text(item) .fontSize($r('sys.float.ohos_id_text_size_headline7')) @@ -237,7 +237,7 @@ struct InputCustomDialog { Column() .width(12) .height(12) - .border({ width: 2, color: $r('sys.color.ohos_id_color_primary'), radius: 12}) + .border({ width: 2, color: $r('sys.color.ohos_id_color_primary'), radius: 12 }) }.width('10%') .height('100%') .visibility(item === '' ? Visibility.Visible : Visibility.None) @@ -245,7 +245,8 @@ struct InputCustomDialog { } } } - TextInput({ placeholder: '', text: this.password}) + + TextInput({ placeholder: '', text: this.password }) .defaultFocus(true) .type(8) .height(60) @@ -270,23 +271,23 @@ struct InputCustomDialog { } } let gThis = this; - setTimeout(()=> { + setTimeout(() => { gThis.passwordOnChange(value); }, 50) console.log(TAG + 'this.password: ' + this.password); }) }.height(48) - .margin({ top: 12, bottom: 16}) + .margin({ top: 12, bottom: 16 }) Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text(this.errorTips) - .fontSize($r('sys.float.ohos_id_text_size_body2')) - .fontWeight(FontWeight.Medium) - .fontColor($r('sys.color.ohos_id_color_warning')) + .fontSize($r('sys.float.ohos_id_text_size_body2')) + .fontWeight(FontWeight.Medium) + .fontColor($r('sys.color.ohos_id_color_warning')) }.visibility(this.errorTipsVisible) .margin({ bottom: 16, - left: $r('sys.float.ohos_id_corner_radius_dialog'), - right: $r('sys.float.ohos_id_corner_radius_dialog') }) + left: $r('sys.float.ohos_id_corner_radius_dialog'), + right: $r('sys.float.ohos_id_corner_radius_dialog') }) Flex({ justifyContent: FlexAlign.Center }) { Button($r('app.string.dm_cancel')) @@ -324,33 +325,38 @@ struct InputCustomDialog { } .scrollable(ScrollDirection.Vertical) .scrollBar(BarState.On) - .constraintSize({ maxHeight: `${this.heightNum}`}) + .constraintSize({ maxHeight: `${this.heightNum}` }) .borderRadius($r('sys.float.ohos_id_corner_radius_dialog')) .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) - .margin({ left: $r('sys.float.ohos_id_dialog_margin_start'), right: $r('sys.float.ohos_id_dialog_margin_end') }) + .margin({ + left: $r('sys.float.ohos_id_dialog_margin_bottom'), + right: $r('sys.float.ohos_id_dialog_margin_bottom') + }) } - }.margin({top: 8, bottom: 20}) + }.margin({ top: 8, bottom: 20 }) } } @Entry @Component struct dialogPlusPage { + @State isPC: boolean = false; dialogController: CustomDialogController = new CustomDialogController({ builder: InputCustomDialog(), autoCancel: false, - alignment: DialogAlignment.Center, + alignment: this.isPC ? DialogAlignment.Center : DialogAlignment.Bottom, , offset: { dx: 0, dy: 0 }, customStyle: true, maskColor: $r('sys.color.ohos_id_color_mask_thin') }); aboutToAppear() { - console.log(TAG + 'aboutToAppear aboutToAppear') + console.log(TAG + 'aboutToAppear aboutToAppear'); + this.isPC = Constant.isPC(); } aboutToDisappear() { - console.log(TAG + 'aboutToDisappear aboutToDisappear') + console.log(TAG + 'aboutToDisappear aboutToDisappear'); if (dmClass != null) { try { dmClass.off('uiStateChange'); @@ -358,7 +364,7 @@ struct dialogPlusPage { } catch (error) { console.log('dmClass release failed'); } - dmClass = null + dmClass = null; } } -- Gitee From ac6439051be14ce2874b374740857e5a55ad47d9 Mon Sep 17 00:00:00 2001 From: dengxiaoyu Date: Sat, 14 Sep 2024 16:43:24 +0800 Subject: [PATCH 205/520] modify inputPin gap Signed-off-by: dengxiaoyu --- display/entry/src/main/ets/pages/InputPinDialog.ets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index d10ab96d5..bf8fb439d 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -344,7 +344,7 @@ struct dialogPlusPage { dialogController: CustomDialogController = new CustomDialogController({ builder: InputCustomDialog(), autoCancel: false, - alignment: this.isPC ? DialogAlignment.Center : DialogAlignment.Bottom, , + alignment: this.isPC ? DialogAlignment.Center : DialogAlignment.Bottom, offset: { dx: 0, dy: 0 }, customStyle: true, maskColor: $r('sys.color.ohos_id_color_mask_thin') -- Gitee From 5ef5fd3c4c88313eb0a5dd33fc406474f0681b21 Mon Sep 17 00:00:00 2001 From: dengxiaoyu Date: Wed, 18 Sep 2024 09:21:43 +0800 Subject: [PATCH 206/520] add inputdialog gap Signed-off-by: dengxiaoyu --- display/AppScope/app.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 90c74919d..c96690240 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -1,11 +1,11 @@ - + { "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000021, - "versionName": "1.0.21", + "versionCode": 1000022, + "versionName": "1.0.22", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, -- Gitee From 283a53e426ab4401f930061f62ca65063b6ce761 Mon Sep 17 00:00:00 2001 From: dengxiaoyu Date: Wed, 18 Sep 2024 09:24:21 +0800 Subject: [PATCH 207/520] add inputdialog gap Signed-off-by: dengxiaoyu --- display/AppScope/app.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index c96690240..606cb31cd 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -1,5 +1,3 @@ - - { "app": { "bundleName": "com.ohos.devicemanagerui", -- Gitee From c921be6c396f3078c720c753c597bb90908d1bfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 18 Sep 2024 10:03:45 +0800 Subject: [PATCH 208/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 5a6e08277..e43a2889b 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -47,10 +47,9 @@ constexpr const char* DEVICE_ONLINE = "deviceOnLine"; constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; +constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; #endif constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; -constexpr const char* DEVICE_TRUSTED_CHANGE = "deviceTrustedChange"; -constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; constexpr static uint8_t BYTE_MASK = 0x0F; constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2; @@ -179,8 +178,7 @@ void SoftbusListener::OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatu int32_t devScreenStatus = static_cast(status->reserved[0]); ConvertScreenStatusToDmDevice(status->basicInfo, devScreenStatus, dmDeviceInfo); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit( - DEVICE_SCREEN_STATUS_CHANGE, [=]() { DeviceScreenStatusChange(dmDeviceInfo); }); + ffrt::submit([=]() { DeviceScreenStatusChange(dmDeviceInfo); }); #else std::thread devScreenStatusChange([=]() { DeviceScreenStatusChange(dmDeviceInfo); }); if (pthread_setname_np(devScreenStatusChange.native_handle(), DEVICE_SCREEN_STATUS_CHANGE) != DM_OK) { -- Gitee From e67133554b947ca5d690a178c831fdaa079b0f74 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Wed, 18 Sep 2024 10:26:26 +0800 Subject: [PATCH 209/520] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- common/include/dm_constants.h | 1 + common/src/dm_anonymous.cpp | 20 +++-- .../native_cpp/src/device_manager_impl.cpp | 41 ++++++--- .../src/ipc/lite/ipc_client_manager.cpp | 4 + .../src/ipc/standard/ipc_cmd_parser.cpp | 4 + .../native_cpp/src/mini/softbus_adapter.c | 30 ++++++- interfaces/kits/js/src/dm_native_event.cpp | 4 +- .../kits/js/src/native_devicemanager_js.cpp | 89 +++++++++++------- .../kits/js4.0/include/dm_native_util.h | 2 +- .../js4.0/include/native_devicemanager_js.h | 3 +- interfaces/kits/js4.0/src/dm_native_event.cpp | 4 + .../js4.0/src/native_devicemanager_js.cpp | 21 ++++- .../authentication/auth_message_processor.cpp | 4 + .../src/authentication/auth_request_state.cpp | 2 +- .../commonevent/dm_common_event_manager.cpp | 3 +- .../dependency/softbus/softbus_connector.cpp | 90 ++++++++++++++----- .../dependency/softbus/softbus_session.cpp | 10 ++- .../service/src/device_manager_service.cpp | 14 ++- .../src/device_manager_service_listener.cpp | 33 ++++--- .../src/discovery/discovery_filter.cpp | 12 +-- .../standard/permission_manager.cpp | 6 +- .../service/src/softbus/softbus_listener.cpp | 88 +++++++++++++----- .../softbuscache/src/dm_softbus_cache.cpp | 24 +++-- test/unittest/UTTest_ipc_client_stub.cpp | 2 +- utils/include/appInfo/lite/app_manager.h | 2 +- utils/include/timer/dm_timer.h | 10 +-- 26 files changed, 376 insertions(+), 147 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 7c599a862..3a933cd29 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -37,6 +37,7 @@ enum { STOP_BIND = 1, /* Transfer to the other end device, not define specification error code */ + ERR_DM_NOT_SYSTEM_APP = 202, ERR_DM_TIME_OUT = -20001, ERR_DM_UNSUPPORTED_AUTH_TYPE = -20018, ERR_DM_AUTH_BUSINESS_BUSY = -20019, diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 4610c423e..6bfd22004 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -20,6 +20,8 @@ namespace OHOS { namespace DistributedHardware { namespace { constexpr uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; +constexpr uint32_t MAX_MAP_LEN = 1000; +constexpr uint32_t MAX_INT_LEN = 20; } std::string GetAnonyString(const std::string &value) @@ -65,15 +67,15 @@ std::string GetAnonyInt32(const int32_t value) bool IsNumberString(const std::string &inputString) { LOGI("IsNumberString for DeviceManagerNapi"); - if (inputString.length() == 0) { - LOGE("inputString is Null"); + if (inputString.length() == 0 || inputString.length() > MAX_INT_LEN) { + LOGE("inputString is Null or inputString length is too long"); return false; } - const int32_t MIN_ASCLL_NUM = 48; - const int32_t MAX_ASCLL_NUM = 57; + const int32_t MIN_ASCII_NUM = 48; + const int32_t MAX_ASCII_NUM = 57; for (size_t i = 0; i < inputString.length(); i++) { int num = (int)inputString[i]; - if (num >= MIN_ASCLL_NUM && num <= MAX_ASCLL_NUM) { + if (num >= MIN_ASCII_NUM && num <= MAX_ASCII_NUM) { continue; } else { return false; @@ -142,6 +144,10 @@ bool IsBool(const nlohmann::json &jsonObj, const std::string &key) std::string ConvertMapToJsonString(const std::map ¶mMap) { std::string jsonStr = ""; + if (paramMap.size() > MAX_MAP_LEN) { + LOGE("invalid paramMap"); + return jsonStr; + } if (!paramMap.empty()) { nlohmann::json jsonObj; for (const auto &it : paramMap) { @@ -157,6 +163,10 @@ void ParseMapFromJsonString(const std::string &jsonStr, std::map MAX_MAP_LEN) { + LOGE("invalid paramMap"); + return; + } nlohmann::json paramJson = nlohmann::json::parse(jsonStr, nullptr, false); if (paramJson.is_discarded()) { return; 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 023c6279a..b9b5ab5cd 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -181,19 +181,34 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) void DeviceManagerImpl::ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { - (void)memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); - } - if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, - std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); - } - if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, - std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); - } + errno_t retValue = DM_OK; + retValue = memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (retValue != DM_OK) { + LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed, ret: %d.", retValue); + return; + } + + retValue = memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))); + if (retValue != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return; + } + + retValue = memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, + std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))); + if (retValue != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + return; + } + + retValue = memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, + std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))); + if (retValue != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + return; + } + deviceBasicInfo.deviceTypeId = info.deviceTypeId; } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp index 8db463b92..e542d7aa1 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp @@ -84,6 +84,10 @@ int32_t IpcClientManager::UnInit(const std::string &pkgName) int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { + if (req == nullptr) { + LOGE("req is null"); + return ERR_DM_INIT_FAILED; + } std::string pkgName = req->GetPkgName(); if (!IsInit(pkgName)) { return ERR_DM_INIT_FAILED; 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 ae7bb9402..d6125cd0e 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 @@ -174,6 +174,10 @@ ON_IPC_READ_RESPONSE(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &reply, std ON_IPC_SET_REQUEST(UNREGISTER_DEVICE_MANAGER_LISTENER, std::shared_ptr pBaseReq, MessageParcel &data) { + if (pBaseReq == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } std::string pkgName = pBaseReq->GetPkgName(); if (!data.WriteString(pkgName)) { LOGE("write papam failed"); diff --git a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c index 56564b020..d850c994e 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c +++ b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c @@ -411,6 +411,10 @@ int GetSoftbusTrustedDeviceList(const char *pkgName, DmDeviceBasicInfo *deviceLi return ERR_DM_SOFTBUS_GET_ALL_DEVICE_INFO; } int minLen = (deviceListLen > *trustListLen ? *trustListLen : deviceListLen); + if (minLen > DM_MAX_DEVICE_SIZE) { + DMLOGE("invalid device len."); + return ERR_DM_INPUT_INVALID_VALUE; + } for (int i = 0; i < minLen; i++) { NodeBasicInfoCopyToDmDevice(&deviceList[i], &nodeInfo[i]); } @@ -739,6 +743,9 @@ static int DeleteSoftbusSemaphoreAndMutex(void) static int FilterDevice(const DmDeviceInfo *dmDeviceInfo) { DMLOGI("FilterDevice start."); + if (dmDeviceInfo == NULL) { + return ERR_DM_FAILED; + } int ret = DM_OK; if (g_discoveryCallbackMap.filterOption.isTrusted != NOT_FILTER && dmDeviceInfo->isLocalExistCredential != g_discoveryCallbackMap.filterOption.isTrusted) { @@ -993,15 +1000,24 @@ static void OnSoftbusDeviceOffline(NodeBasicInfo *deviceInfo) static void NodeBasicInfoCopyToDmDevice(DmDeviceBasicInfo *dmDeviceInfo, const NodeBasicInfo *nodeBasicInfo) { - (void)memset_s(dmDeviceInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - errno_t retValue = strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), nodeBasicInfo->deviceName); + errno_t retValue = memset_s(dmDeviceInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (retValue != EOK) { + LOGE("NodeBasicInfoCopyToDmDevice memset_s failed, ret: %d.", retValue); + return; + } + + retValue = strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), nodeBasicInfo->deviceName); if (retValue != EOK) { DMLOGE("failed to copy device name with ret: %d.", retValue); + return; } + retValue = strcpy_s(dmDeviceInfo->networkId, sizeof(dmDeviceInfo->networkId), nodeBasicInfo->networkId); if (retValue != EOK) { DMLOGE("failed to copy networkId with ret: %d.", retValue); + return; } + GetDeviceIdByNetworkId(nodeBasicInfo->networkId, dmDeviceInfo->deviceId); dmDeviceInfo->deviceTypeId = nodeBasicInfo->deviceTypeId; } @@ -1009,14 +1025,20 @@ static void NodeBasicInfoCopyToDmDevice(DmDeviceBasicInfo *dmDeviceInfo, const N static void DeviceInfoCopyToDmDevice(DmDeviceInfo *dmDeviceInfo, const DeviceInfo *deviceInfo) { const size_t arrayStartPosition = 0; - (void)memset_s(dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - errno_t retValue = strcpy_s(dmDeviceInfo->deviceId, sizeof(dmDeviceInfo->deviceId), deviceInfo->devId); + errno_t retValue = memset_s(dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (retValue != EOK) { + DMLOGE("failed to memset device id with ret: %d.", retValue); + return; + } + retValue = strcpy_s(dmDeviceInfo->deviceId, sizeof(dmDeviceInfo->deviceId), deviceInfo->devId); if (retValue != EOK) { DMLOGE("failed to copy device id with ret: %d.", retValue); + return; } retValue = strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), deviceInfo->devName); if (retValue != EOK) { DMLOGE("failed to copy device name with ret: %d.", retValue); + return; } dmDeviceInfo->credible = deviceInfo->isOnline; dmDeviceInfo->deviceTypeId = deviceInfo->devType; diff --git a/interfaces/kits/js/src/dm_native_event.cpp b/interfaces/kits/js/src/dm_native_event.cpp index d0c3f9bb9..dc76ab079 100644 --- a/interfaces/kits/js/src/dm_native_event.cpp +++ b/interfaces/kits/js/src/dm_native_event.cpp @@ -30,7 +30,9 @@ DmNativeEvent::~DmNativeEvent() { for (auto iter = eventMap_.begin(); iter != eventMap_.end(); iter++) { auto listener = iter->second; - napi_delete_reference(env_, listener->handlerRef); + if (listener != nullptr) { + napi_delete_reference(env_, listener->handlerRef); + } } eventMap_.clear(); napi_delete_reference(env_, thisVarRef_); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 111711b17..6242094d2 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -56,6 +56,7 @@ const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7; const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_DDMP = 0; const int32_t DM_NAPI_SUBSCRIBE_CAPABILITY_OSD = 1; +constexpr int32_t DM_MAX_DEVICE_SIZE = 100; napi_ref deviceTypeEnumConstructor_ = nullptr; napi_ref deviceStateChangeActionEnumConstructor_ = nullptr; @@ -81,10 +82,10 @@ std::mutex g_publishCallbackMapMutex; std::mutex g_authCallbackMapMutex; std::mutex g_dmUiCallbackMapMutex; -enum DMBussinessErrorCode { +enum class DMBussinessErrorCode : int32_t { // Permission verify failed. ERR_NO_PERMISSION = 201, - //The caller is not a system application. + // The caller is not a system application. ERR_NOT_SYSTEM_APP = 202, // Input parameter error. ERR_INVALID_PARAMS = 401, @@ -127,7 +128,8 @@ bool CheckArgsVal(napi_env env, bool assertion, const std::string ¶m, const { if (!(assertion)) { std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The value of " + param + ": " + msg; - napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + napi_throw_error(env, std::to_string( + static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS)).c_str(), errMsg.c_str()); return false; } return true; @@ -137,7 +139,8 @@ bool CheckArgsCount(napi_env env, bool assertion, const std::string &message) { if (!(assertion)) { std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + message; - napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + napi_throw_error(env, std::to_string( + static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS)).c_str(), errMsg.c_str()); return false; } return true; @@ -148,7 +151,8 @@ bool CheckArgsType(napi_env env, bool assertion, const std::string ¶mName, c if (!(assertion)) { std::string errMsg = ERR_MESSAGE_INVALID_PARAMS + "The type of " + paramName + " must be " + type; - napi_throw_error(env, std::to_string(ERR_INVALID_PARAMS).c_str(), errMsg.c_str()); + napi_throw_error(env, std::to_string( + static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS)).c_str(), errMsg.c_str()); return false; } return true; @@ -171,30 +175,37 @@ napi_value CreateBusinessError(napi_env env, int32_t errCode, bool isAsync = tru napi_value error = nullptr; switch (errCode) { case ERR_DM_NO_PERMISSION: - error = CreateErrorForCall(env, ERR_NO_PERMISSION, ERR_MESSAGE_NO_PERMISSION, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::ERR_NO_PERMISSION), + ERR_MESSAGE_NO_PERMISSION, isAsync); break; case ERR_DM_DISCOVERY_REPEATED: - error = CreateErrorForCall(env, DM_ERR_DISCOVERY_INVALID, ERR_MESSAGE_DISCOVERY_INVALID, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_DISCOVERY_INVALID), + ERR_MESSAGE_DISCOVERY_INVALID, isAsync); break; case ERR_DM_PUBLISH_REPEATED: - error = CreateErrorForCall(env, DM_ERR_PUBLISH_INVALID, ERR_MESSAGE_PUBLISH_INVALID, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_PUBLISH_INVALID), + ERR_MESSAGE_PUBLISH_INVALID, isAsync); break; case ERR_DM_AUTH_BUSINESS_BUSY: - error = CreateErrorForCall(env, DM_ERR_AUTHENTICALTION_INVALID, + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_AUTHENTICALTION_INVALID), ERR_MESSAGE_AUTHENTICALTION_INVALID, isAsync); break; case ERR_DM_INPUT_PARA_INVALID: case ERR_DM_UNSUPPORTED_AUTH_TYPE: - error = CreateErrorForCall(env, ERR_INVALID_PARAMS, ERR_MESSAGE_INVALID_PARAMS, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::ERR_INVALID_PARAMS), + ERR_MESSAGE_INVALID_PARAMS, isAsync); break; case ERR_DM_INIT_FAILED: - error = CreateErrorForCall(env, DM_ERR_OBTAIN_SERVICE, ERR_MESSAGE_OBTAIN_SERVICE, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_OBTAIN_SERVICE), + ERR_MESSAGE_OBTAIN_SERVICE, isAsync); break; - case ERR_NOT_SYSTEM_APP: - error = CreateErrorForCall(env, ERR_NOT_SYSTEM_APP, ERR_MESSAGE_NOT_SYSTEM_APP, isAsync); + case ERR_DM_NOT_SYSTEM_APP: + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP), + ERR_MESSAGE_NOT_SYSTEM_APP, isAsync); break; default: - error = CreateErrorForCall(env, DM_ERR_FAILED, ERR_MESSAGE_FAILED, isAsync); + error = CreateErrorForCall(env, static_cast(DMBussinessErrorCode::DM_ERR_FAILED), + ERR_MESSAGE_FAILED, isAsync); break; } return error; @@ -1482,7 +1493,7 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i { LOGI("SetUserOperationSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -1526,6 +1537,14 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { + if (deviceInfoListAsyncCallbackInfo == nullptr) { + LOGE("CallGetTrustedDeviceListStatusSync deviceInfoListAsyncCallbackInfo is null"); + return; + } + if (deviceInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { + LOGE("CallGetTrustedDeviceListStatusSync invalid devList size"); + return; + } for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) { LOGI("DeviceManager::GetTrustedDeviceList deviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", GetAnonyString(deviceInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(), @@ -1613,6 +1632,10 @@ void DeviceManagerNapi::OnDmUiCall(const std::string ¶mJson) void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { + if (deviceInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { + LOGE("CallGetTrustedDeviceListStatus invalid devList size"); + return; + } for (unsigned int i = 0; i < deviceInfoListAsyncCallbackInfo->devList.size(); i++) { LOGI("DeviceManager::GetTrustedDeviceList deviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", GetAnonyString(deviceInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(), @@ -2024,7 +2047,7 @@ napi_value DeviceManagerNapi::GetTrustedDeviceListByFilter(napi_env env, napi_ca napi_value DeviceManagerNapi::GetTrustedDeviceList(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2071,7 +2094,7 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfoSync(napi_env env, napi_callback { LOGI("GetLocalDeviceInfoSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2109,7 +2132,7 @@ napi_value DeviceManagerNapi::GetLocalDeviceInfo(napi_env env, napi_callback_inf { LOGI("GetLocalDeviceInfo in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } if (DeviceManager::GetInstance().CheckAPIAccessPermission() != 0) { @@ -2161,7 +2184,7 @@ napi_value DeviceManagerNapi::UnAuthenticateDevice(napi_env env, napi_callback_i { LOGI("UnAuthenticateDevice"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } napi_value result = nullptr; @@ -2214,7 +2237,7 @@ bool DeviceManagerNapi::CheckPermissions(napi_env env) { LOGI("CheckPermissions in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return false; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2252,7 +2275,7 @@ napi_value DeviceManagerNapi::StartDeviceDiscoverSync(napi_env env, napi_callbac { LOGI("StartDeviceDiscoverSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } std::string extra = ""; @@ -2290,7 +2313,7 @@ napi_value DeviceManagerNapi::StopDeviceDiscoverSync(napi_env env, napi_callback { LOGI("StopDeviceDiscoverSync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); @@ -2332,7 +2355,7 @@ napi_value DeviceManagerNapi::PublishDeviceDiscoverySync(napi_env env, napi_call { LOGI("PublishDeviceDiscoverySync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); @@ -2383,7 +2406,7 @@ napi_value DeviceManagerNapi::UnPublishDeviceDiscoverySync(napi_env env, napi_ca { LOGI("UnPublishDeviceDiscoverySync in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_ONE); @@ -2421,7 +2444,7 @@ napi_value DeviceManagerNapi::UnPublishDeviceDiscoverySync(napi_env env, napi_ca napi_value DeviceManagerNapi::AuthenticateDevice(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_THREE); @@ -2477,7 +2500,7 @@ napi_value DeviceManagerNapi::RequestCredential(napi_env env, napi_callback_info LOGI("RequestCredential function has been discarded"); return nullptr; if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -2549,7 +2572,7 @@ napi_value DeviceManagerNapi::ImportCredential(napi_env env, napi_callback_info { LOGI("ImportCredential start."); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -2602,7 +2625,7 @@ napi_value DeviceManagerNapi::DeleteCredential(napi_env env, napi_callback_info LOGE("DeleteCredential function has been discarded"); return nullptr; if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); @@ -2702,7 +2725,7 @@ napi_value DeviceManagerNapi::JsOnFrench(napi_env env, int32_t num, napi_value t napi_value DeviceManagerNapi::JsOn(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -2788,7 +2811,7 @@ napi_value DeviceManagerNapi::JsOffFrench(napi_env env, int32_t num, napi_value napi_value DeviceManagerNapi::JsOff(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } size_t argc = 0; @@ -2870,7 +2893,7 @@ napi_value DeviceManagerNapi::ReleaseDeviceManager(napi_env env, napi_callback_i { LOGI("ReleaseDeviceManager in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } int32_t ret = DeviceManager::GetInstance().CheckAPIAccessPermission(); @@ -3069,7 +3092,7 @@ void DeviceManagerNapi::DeviceInfotoJsByNetworkId(const napi_env &env, const DmD napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } napi_value result = nullptr; @@ -3121,7 +3144,7 @@ napi_value DeviceManagerNapi::CreateDeviceManager(napi_env env, napi_callback_in { LOGI("CreateDeviceManager in"); if (!IsSystemApp()) { - CreateBusinessError(env, ERR_NOT_SYSTEM_APP); + CreateBusinessError(env, static_cast(DMBussinessErrorCode::ERR_NOT_SYSTEM_APP)); return nullptr; } GET_PARAMS(env, info, DM_NAPI_ARGS_TWO); diff --git a/interfaces/kits/js4.0/include/dm_native_util.h b/interfaces/kits/js4.0/include/dm_native_util.h index c4d97572d..5ddde1ede 100644 --- a/interfaces/kits/js4.0/include/dm_native_util.h +++ b/interfaces/kits/js4.0/include/dm_native_util.h @@ -32,7 +32,7 @@ namespace DistributedHardware { enum DMBussinessErrorCode { // Permission verify failed. ERR_NO_PERMISSION = 201, - //The caller is not a system application. + // The caller is not a system application. ERR_NOT_SYSTEM_APP = 202, // Input parameter error. ERR_INVALID_PARAMS = 401, diff --git a/interfaces/kits/js4.0/include/native_devicemanager_js.h b/interfaces/kits/js4.0/include/native_devicemanager_js.h index 2d1faa73f..4e2e12e1e 100644 --- a/interfaces/kits/js4.0/include/native_devicemanager_js.h +++ b/interfaces/kits/js4.0/include/native_devicemanager_js.h @@ -271,7 +271,8 @@ private: static int32_t BindTargetWarpper(const std::string &pkgName, const std::string &deviceId, const std::string &bindParam, std::shared_ptr callback); static void RegisterDevStatusCallback(napi_env env, std::string &bundleName); - + static int32_t DumpDeviceInfo(DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo); + private: napi_env env_; static thread_local napi_ref sConstructor_; diff --git a/interfaces/kits/js4.0/src/dm_native_event.cpp b/interfaces/kits/js4.0/src/dm_native_event.cpp index d0c3f9bb9..17d8846cf 100644 --- a/interfaces/kits/js4.0/src/dm_native_event.cpp +++ b/interfaces/kits/js4.0/src/dm_native_event.cpp @@ -30,6 +30,10 @@ DmNativeEvent::~DmNativeEvent() { for (auto iter = eventMap_.begin(); iter != eventMap_.end(); iter++) { auto listener = iter->second; + if (listener == nullptr) { + LOGE("listener is nullptr"); + return; + } napi_delete_reference(env_, listener->handlerRef); } eventMap_.clear(); diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp index cdc023721..686c5c699 100644 --- a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -54,6 +54,7 @@ const int32_t DM_NAPI_ARGS_ONE = 1; const int32_t DM_NAPI_ARGS_TWO = 2; const int32_t DM_NAPI_ARGS_THREE = 3; const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7; +const int32_t DM_MAX_DEVICE_SIZE = 100; napi_ref deviceStateChangeActionEnumConstructor_ = nullptr; @@ -989,16 +990,32 @@ void DmNapiBindTargetCallback::OnBindResult(const PeerTargetId &targetId, int32_ } } -void DeviceManagerNapi::CallGetAvailableDeviceListStatus(napi_env env, napi_status &status, +int32_t DeviceManagerNapi::DumpDeviceInfo( DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo) { + if (deviceBasicInfoListAsyncCallbackInfo == nullptr) { + LOGE("CallGetAvailableDeviceListStatus deviceBasicInfoListAsyncCallbackInfo is null"); + return DM_ERR_FAILED; + } + if (deviceBasicInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { + LOGE("CallGetAvailableDeviceListStatus invalid devList size"); + return DM_ERR_FAILED; + } for (unsigned int i = 0; i < deviceBasicInfoListAsyncCallbackInfo->devList.size(); i++) { LOGI("DeviceId:%{public}s deviceName:%{public}s deviceTypeId:%{public}d ", GetAnonyString(deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceId).c_str(), GetAnonyString(deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceName).c_str(), deviceBasicInfoListAsyncCallbackInfo->devList[i].deviceTypeId); } + return DM_OK; +} +void DeviceManagerNapi::CallGetAvailableDeviceListStatus(napi_env env, napi_status &status, + DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo) +{ + if (DumpDeviceInfo(deviceBasicInfoListAsyncCallbackInfo) != DM_OK) { + return; + } napi_value array[DM_NAPI_ARGS_TWO] = {0}; bool isArray = false; NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &array[1])); @@ -1013,7 +1030,7 @@ void DeviceManagerNapi::CallGetAvailableDeviceListStatus(napi_env env, napi_stat } LOGI("devList is OK"); } else { - LOGE("devList is null"); //CB come here + LOGE("devList is null"); // CB come here } } else { array[0] = CreateBusinessError(env, deviceBasicInfoListAsyncCallbackInfo->ret, false); diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 725bc8ff8..de6028f18 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -42,6 +42,10 @@ AuthMessageProcessor::~AuthMessageProcessor() void AuthMessageProcessor::GetJsonObj(nlohmann::json &jsonObj) { + if (authResponseContext_->bindType.size() > MAX_BINDTYPE_SIZE) { + LOGE("GetJsonObj invalid bindType size."); + return; + } jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH; jsonObj[TAG_INDEX] = 0; diff --git a/services/implementation/src/authentication/auth_request_state.cpp b/services/implementation/src/authentication/auth_request_state.cpp index 77f670978..7181d2947 100644 --- a/services/implementation/src/authentication/auth_request_state.cpp +++ b/services/implementation/src/authentication/auth_request_state.cpp @@ -172,7 +172,7 @@ int32_t AuthRequestFinishState::Enter() return DM_OK; } -//pkgbind +// pkgbind int32_t AuthRequestCredential::GetStateType() { return AuthState::AUTH_REQUEST_CREDENTIAL; diff --git a/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp b/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp index 964033d45..db426f532 100644 --- a/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp +++ b/services/implementation/src/dependency/commonevent/dm_common_event_manager.cpp @@ -66,7 +66,8 @@ bool DmCommonEventManager::SubscribeServiceEvent(const std::vector subscriber_ = nullptr; return false; } - statusChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener(subscriber_); + statusChangeListener_ = sptr( + new SystemAbilityStatusChangeListener(subscriber_)); if (statusChangeListener_ == nullptr) { LOGE("statusChangeListener_ is nullptr"); subscriber_ = nullptr; diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 3b9307bc6..f0ac4aad7 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -127,7 +127,11 @@ int32_t SoftbusConnector::UnRegisterSoftbusPublishCallback(const std::string &pk int32_t SoftbusConnector::PublishDiscovery(const DmPublishInfo &dmPublishInfo) { PublishInfo publishInfo; - (void)memset_s(&publishInfo, sizeof(PublishInfo), 0, sizeof(PublishInfo)); + errno_t retValue = memset_s(&publishInfo, sizeof(PublishInfo), 0, sizeof(PublishInfo)); + if (retValue != EOK) { + LOGE("PublishDiscovery memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } publishInfo.publishId = dmPublishInfo.publishId; publishInfo.mode = static_cast(dmPublishInfo.mode); publishInfo.medium = ExchangeMedium::AUTO; @@ -158,7 +162,11 @@ int32_t SoftbusConnector::UnPublishDiscovery(int32_t publishId) int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) { SubscribeInfo subscribeInfo; - (void)memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + errno_t retValue = memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + if (retValue != EOK) { + LOGE("StartDiscovery memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; subscribeInfo.mode = static_cast(dmSubscribeInfo.mode); subscribeInfo.medium = static_cast(dmSubscribeInfo.medium); @@ -192,7 +200,11 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) int32_t SoftbusConnector::StartDiscovery(const uint16_t subscribeId) { SubscribeInfo subscribeInfo; - (void)memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + errno_t retValue = memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + if (retValue != EOK) { + LOGE("StartDiscovery memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } subscribeInfo.subscribeId = subscribeId; subscribeInfo.mode = static_cast(DmDiscoverMode::DM_DISCOVER_MODE_ACTIVE); subscribeInfo.medium = static_cast(DmExchangeMedium::DM_AUTO); @@ -357,32 +369,52 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo) { - (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); + errno_t retValue = memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (retValue != EOK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed, ret: %d.", retValue); + return; } - if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + retValue = memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))); + if (retValue != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + return; } + + retValue = memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))); + if (retValue != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return; + } + dmDeviceInfo.deviceTypeId = deviceInfo.devType; dmDeviceInfo.range = deviceInfo.range; } void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceBasicInfo &dmDeviceBasicInfo) { - (void)memset_s(&dmDeviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); + errno_t retValue = memset_s(&dmDeviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (retValue != EOK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed, ret: %d.", retValue); + return; } - if (memcpy_s(dmDeviceBasicInfo.deviceName, sizeof(dmDeviceBasicInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + retValue = memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), deviceInfo.devId, + std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))); + if (retValue != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + return; } + + retValue = memcpy_s(dmDeviceBasicInfo.deviceName, sizeof(dmDeviceBasicInfo.deviceName), deviceInfo.devName, + std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))); + if (retValue != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return; + } + dmDeviceBasicInfo.deviceTypeId = deviceInfo.devType; } @@ -767,16 +799,26 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo) { - (void)memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (memcpy_s(dmDeviceInfo.networkId, sizeof(dmDeviceInfo.networkId), nodeBasicInfo.networkId, - std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); + errno_t retValue = memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + return; } - if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + retValue = memcpy_s(dmDeviceInfo.networkId, sizeof(dmDeviceInfo.networkId), nodeBasicInfo.networkId, + std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + return; } + + retValue = memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))); + if (retValue != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return; + } + dmDeviceInfo.deviceTypeId = nodeBasicInfo.deviceTypeId; std::string extraData = dmDeviceInfo.extraData; nlohmann::json extraJson; diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 73efad2e5..71a839e45 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -44,6 +44,10 @@ static void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t q { LOGI("[SOFTBUS]OnQos, socket: %{public}d, QoSEvent: %{public}d, qosCount: %{public}u", socket, (int32_t)eventId, qosCount); + if (qosCount > QOS_TYPE_BUTT) { + LOGE("OnQos invalid qosCount"); + return; + } for (uint32_t idx = 0; idx < qosCount; idx++) { LOGI("QosTV: type: %{public}d, value: %{public}d", (int32_t)qos[idx].qos, qos[idx].value); } @@ -52,7 +56,11 @@ static void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t q SoftbusSession::SoftbusSession() { LOGD("SoftbusSession constructor."); - (void)memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)); + errno_t retValue = memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)); + if (retValue != DM_OK) { + LOGE("SoftbusSession::SoftbusSession memset_s failed, ret: %d.", retValue); + } + iSocketListener_.OnShutdown = OnShutdown; iSocketListener_.OnBytes = OnBytes; iSocketListener_.OnQos = OnQos; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0d6df0547..daccb70c6 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -357,7 +357,11 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string udidHashTemp = ""; if (ConvertUdidHashToAnoyDeviceId(localDeviceId_, udidHashTemp) == DM_OK) { - (void)memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + errno_t retValue = memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + if (retValue != DM_OK) { + LOGE("GetLocalDeviceInfo memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); return ERR_DM_FAILED; @@ -923,7 +927,6 @@ bool DeviceManagerService::IsDMServiceImplReady() dmServiceImpl_ = std::shared_ptr(func()); if (dmServiceImpl_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImpl_ = nullptr; isImplsoLoaded_ = false; return false; @@ -1166,7 +1169,6 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() dmServiceImplExt_ = std::shared_ptr(func()); if (dmServiceImplExt_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImplExt_ = nullptr; isAdapterSoLoaded_ = false; LOGE("dm service adapter impl ext init failed."); @@ -1760,7 +1762,11 @@ void DeviceManagerService::ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInf { std::string udidHashTemp = ""; if (ConvertUdidHashToAnoyDeviceId(deviceInfo.deviceId, udidHashTemp) == DM_OK) { - (void)memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + errno_t retValue = memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + if (retValue != DM_OK) { + LOGE("ConvertUdidHashToAnoyDeviceId memset_s failed, ret: %d.", retValue); + return; + } if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); } diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index d3f788164..19043747a 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -50,20 +50,33 @@ const int32_t LAST_APP_ONLINE_NUMS = 8; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { - (void)memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); + errno_t retValue = memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (retValue != DM_OK) { + LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed, ret: %d.", retValue); + return; } - if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, - std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + retValue = memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))); + if (retValue != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return; } - if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, - std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); + + retValue = memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, + std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))); + if (retValue != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + return; } + + retValue = memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, + std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))); + if (retValue != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + return; + } + deviceBasicInfo.deviceTypeId = info.deviceTypeId; } diff --git a/services/service/src/discovery/discovery_filter.cpp b/services/service/src/discovery/discovery_filter.cpp index 00b5dc4ec..bf835ccbf 100644 --- a/services/service/src/discovery/discovery_filter.cpp +++ b/services/service/src/discovery/discovery_filter.cpp @@ -27,7 +27,7 @@ const std::string FILTERS_TYPE_OR = "OR"; const std::string FILTERS_TYPE_AND = "AND"; const int32_t DM_OK = 0; const int32_t ERR_DM_INPUT_PARA_INVALID = 96929749; -enum DmDiscoveryDeviceFilter { +enum class DmDiscoveryDeviceFilter : int32_t { DM_INVALID_DEVICE = 0, DM_VALID_DEVICE = 1, DM_ALL_DEVICE = 2 @@ -115,7 +115,7 @@ int32_t DeviceFilterOption::TransformToFilter(const std::string &filterOptions) filterOp_ = FILTERS_TYPE_OR; DeviceFilters deviceFilters; deviceFilters.type = "credible"; - deviceFilters.value = DM_INVALID_DEVICE; + deviceFilters.value = static_cast(DmDiscoveryDeviceFilter::DM_INVALID_DEVICE); filters_.push_back(deviceFilters); return DM_OK; } @@ -129,7 +129,7 @@ int32_t DeviceFilterOption::TransformFilterOption(const std::string &filterOptio filterOp_ = FILTERS_TYPE_OR; DeviceFilters deviceFilters; deviceFilters.type = "credible"; - deviceFilters.value = DM_INVALID_DEVICE; + deviceFilters.value = static_cast(DmDiscoveryDeviceFilter::DM_INVALID_DEVICE); filters_.push_back(deviceFilters); return DM_OK; } @@ -138,13 +138,13 @@ int32_t DeviceFilterOption::TransformFilterOption(const std::string &filterOptio bool DiscoveryFilter::FilterByDeviceState(int32_t value, bool isActive) { - if (value == DM_INVALID_DEVICE) { + if (value == static_cast(DmDiscoveryDeviceFilter::DM_INVALID_DEVICE)) { return !isActive; } - if (value == DM_VALID_DEVICE) { + if (value == static_cast(DmDiscoveryDeviceFilter::DM_VALID_DEVICE)) { return isActive; } - return (value == DM_ALL_DEVICE); + return (value == static_cast(DmDiscoveryDeviceFilter::DM_ALL_DEVICE)); } bool DiscoveryFilter::FilterByRange(int32_t value, int32_t range) diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index cef804f68..23fc34d23 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -37,19 +37,19 @@ constexpr const char* DM_MONITOR_DEVICE_NETWORK_STATE_PERMISSION = "ohos.permiss constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; constexpr int32_t PKG_NAME_SIZE_MAX = 256; -#define AUTH_CODE_WHITE_LIST_NUM (3) +constexpr int32_t AUTH_CODE_WHITE_LIST_NUM = 3; constexpr const static char g_authCodeWhiteList[AUTH_CODE_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "com.huawei.msdp.hmringgenerator", "com.huawei.msdp.hmringdiscriminator", "CollaborationFwk", }; -#define PIN_HOLDER_WHITE_LIST_NUM (1) +constexpr int32_t PIN_HOLDER_WHITE_LIST_NUM = 1; constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "CollaborationFwk", }; -#define SYSTEM_SA_WHITE_LIST_NUM (7) +constexpr int32_t SYSTEM_SA_WHITE_LIST_NUM = 7; constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index bf8420320..a787519fe 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -494,7 +494,12 @@ int32_t SoftbusListener::RefreshSoftbusLNN(const char *pkgName, const DmSubscrib { LOGI("RefreshSoftbusLNN begin, subscribeId: %{public}d.", dmSubInfo.subscribeId); SubscribeInfo subscribeInfo; - (void)memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + errno_t retValue = memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); + if (retValue != DM_OK) { + LOGE("RefreshSoftbusLNN memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } + subscribeInfo.subscribeId = dmSubInfo.subscribeId; subscribeInfo.mode = static_cast(dmSubInfo.mode); subscribeInfo.medium = static_cast(dmSubInfo.medium); @@ -687,15 +692,24 @@ int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &node int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { - (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + errno_t retValue = memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } + + retValue = memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + return ERR_DM_FAILED; } - if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + retValue = memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return ERR_DM_FAILED; } devInfo.deviceTypeId = nodeInfo.deviceTypeId; nlohmann::json extraJson; @@ -707,16 +721,26 @@ int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nod int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceBasicInfo &devInfo) { - (void)memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + errno_t retValue = memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; } - if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + retValue = memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } + + retValue = memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))); + if (retValue != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return ERR_DM_FAILED; } + devInfo.deviceTypeId = nodeInfo.deviceTypeId; return DM_OK; } @@ -734,18 +758,36 @@ std::string SoftbusListener::ConvertBytesToUpperCaseHexString(const uint8_t arr[ return result; } -void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +int32_t SoftbusListener::FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice) { - (void)memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + errno_t retValue = memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (retValue != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } + + retValue = memcpy_s(dmDevice.deviceId, sizeof(dmDevice.deviceId), device.devId, + std::min(sizeof(dmDevice.deviceId), sizeof(device.devId))); + if (retValue != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice: copy device id failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } - if (memcpy_s(dmDevice.deviceId, sizeof(dmDevice.deviceId), device.devId, - std::min(sizeof(dmDevice.deviceId), sizeof(device.devId))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice: copy device id failed."); + retValue = memcpy_s(dmDevice.deviceName, sizeof(dmDevice.deviceName), device.devName, + std::min(sizeof(dmDevice.deviceName), sizeof(device.devName))); + if (retValue != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice: copy device name failed, ret: %d.", retValue); + return ERR_DM_FAILED; } - if (memcpy_s(dmDevice.deviceName, sizeof(dmDevice.deviceName), device.devName, - std::min(sizeof(dmDevice.deviceName), sizeof(device.devName))) != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice: copy device name failed."); + return DM_OK; +} + +void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +{ + if (FillDeviceInfo(device, dmDevice) != DM_OK) { + LOGE("FillDeviceInfo failed."); + return; } dmDevice.deviceTypeId = device.devType; diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 3a4e11ea9..02b2d0567 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -255,16 +255,26 @@ int32_t SoftbusCache::GetUuidFromCache(const char *networkId, std::string &uuid) int32_t SoftbusCache::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { - (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + errno_t retValue = memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (retValue != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + return ERR_DM_FAILED; + } + + retValue = memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))); + if (retValue != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + return ERR_DM_FAILED; } - if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + retValue = memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))); + if (retValue != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + return ERR_DM_FAILED; } + devInfo.deviceTypeId = nodeInfo.deviceTypeId; nlohmann::json extraJson; extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType; diff --git a/test/unittest/UTTest_ipc_client_stub.cpp b/test/unittest/UTTest_ipc_client_stub.cpp index 752d54f68..1affae3a7 100644 --- a/test/unittest/UTTest_ipc_client_stub.cpp +++ b/test/unittest/UTTest_ipc_client_stub.cpp @@ -200,7 +200,7 @@ HWTEST_F(IpcClientStubTest, SendCmd_004, testing::ext::TestSize.Level0) int cmdCode = -1; std::shared_ptr req = nullptr; std::shared_ptr rsp = nullptr; - sptr instance = new IpcClientStub(); + sptr instance = sptr(new IpcClientStub()); int ret = instance->SendCmd(cmdCode, req, rsp); ASSERT_EQ(ret, result); } diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index d5fef1751..a97d1a3ef 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -16,8 +16,8 @@ #ifndef OHOS_DM_LITE_APP_MANAGER_H #define OHOS_DM_LITE_APP_MANAGER_H -#include "dm_single_instance.h" #include +#include "dm_single_instance.h" namespace OHOS { namespace DistributedHardware { diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index 0dca4459c..86df1b2a5 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -44,12 +44,12 @@ constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessi using TimerCallback = std::function; class CommonEventHandler : public AppExecFwk::EventHandler { - public: - CommonEventHandler(const std::shared_ptr &runner); - ~CommonEventHandler() override = default; +public: + CommonEventHandler(const std::shared_ptr &runner); + ~CommonEventHandler() override = default; - bool PostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); - void RemoveTask(const std::string &name); + bool PostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); + void RemoveTask(const std::string &name); }; class DmTimer { -- Gitee From 3375bb26cc5e82ab009c0520ed69f963a3849673 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 18 Sep 2024 10:08:40 +0800 Subject: [PATCH 210/520] =?UTF-8?q?stoi=E6=94=B9=E4=B8=BAatoi=20Signed-off?= =?UTF-8?q?-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- interfaces/kits/js/src/native_devicemanager_js.cpp | 2 +- .../implementation/src/authentication/dm_auth_manager.cpp | 8 ++++---- services/service/src/device_manager_service.cpp | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 111711b17..2a16e7042 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -964,7 +964,7 @@ void DeviceManagerNapi::DmAuthParamToJsAuthParam(const napi_env &env, const DmAu napi_create_object(env, &extraInfo); SetValueInt32(env, "direction", authParam.direction, extraInfo); SetValueInt32(env, "authType", authParam.authType, paramResult); - SetValueInt32(env, "pinToken", stoi(authParam.authToken), extraInfo); + SetValueInt32(env, "pinToken", atoi(authParam.authToken.c_str()), extraInfo); if (authParam.direction == DM_AUTH_DIRECTION_CLIENT) { napi_set_named_property(env, paramResult, "extraInfo", extraInfo); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index bac7aa386..2601101f9 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1517,7 +1517,7 @@ int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms } break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: - ProcessPincode(std::stoi(params)); + ProcessPincode(std::atoi(params.c_str())); info.stageRes = static_cast(StageRes::STAGE_SUCC); if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { LOGE("ReportAuthInputPinBox failed"); @@ -1674,7 +1674,7 @@ int32_t DmAuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::strin if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { LOGI("DmAuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); if (!addrType.empty()) { - addr.type = static_cast(std::stoi(addrType)); + addr.type = static_cast(std::atoi(addrType.c_str())); } else { addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; } @@ -1735,7 +1735,7 @@ int32_t DmAuthManager::ParseAuthType(const std::map &b LOGE("DmAuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); return ERR_DM_INPUT_PARA_INVALID; } - authType = std::stoi(authTypeStr); + authType = std::atoi(authTypeStr.c_str()); return DM_OK; } @@ -1780,7 +1780,7 @@ int32_t DmAuthManager::GetAuthCode(const std::string &pkgName, int32_t &pinCode) LOGE("GetAuthCode failed, pkgName not supported."); return ERR_DM_FAILED; } - pinCode = std::stoi(importAuthCode_); + pinCode = std::atoi(importAuthCode_.c_str()); return DM_OK; } diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0d6df0547..8889a6257 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1745,8 +1745,8 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::mapsecond); - int32_t timeOut = std::stoi(timeOutIter->second); + int32_t policyStrategy = std::atoi(policyStrategyIter->second.c_str()); + int32_t timeOut = std::atoi(timeOutIter->second.c_str()); LOGD("strategy: %{public}d, timeOut: %{public}d", policyStrategy, timeOut); if (!IsDMServiceAdapterLoad()) { LOGE("SetDnPolicy failed, instance not init or init failed."); -- Gitee From c2c37da9928348cc201957df54effe555a5f92ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 18 Sep 2024 11:07:19 +0800 Subject: [PATCH 211/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../dm_package_common_event.cpp | 7 ++++--- utils/include/timer/dm_timer.h | 4 ++-- utils/src/timer/dm_timer.cpp | 16 +++++++++++----- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/services/service/src/publishcommonevent/dm_package_common_event.cpp b/services/service/src/publishcommonevent/dm_package_common_event.cpp index 54272d6f9..f394e5f4a 100644 --- a/services/service/src/publishcommonevent/dm_package_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_package_common_event.cpp @@ -23,7 +23,7 @@ #include "dm_constants.h" #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -#include "dm_thread_manager.h" +#include "ffrt.h" #endif #include "iservice_registry.h" #include "system_ability_definition.h" @@ -32,8 +32,9 @@ namespace OHOS { namespace DistributedHardware { using OHOS::EventFwk::MatchingSkills; using OHOS::EventFwk::CommonEventManager; - +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) constexpr const char* DEAL_THREAD = "package_common_event"; +#endif const std::string APP_ID = "appId"; constexpr int32_t MAX_TRY_TIMES = 3; @@ -143,7 +144,7 @@ void DmPackageEventSubscriber::OnReceiveEvent(const CommonEventData &data) return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ThreadManager::GetInstance().Submit(DEAL_THREAD, [=]() { callback_(appId, receiveEvent); }); + ffrt::submit([=]() { callback_(appId, receiveEvent); }); #else std::thread dealThread([=]() { callback_(appId, receiveEvent); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index 1472ca2ac..6c57a09fd 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -24,7 +24,7 @@ #include #include -#include "ffrt" +#include "ffrt.h" namespace OHOS { namespace DistributedHardware { @@ -70,7 +70,7 @@ public: private: mutable std::mutex timerMutex_; std::unordered_map timerVec_ = {}; - ffrt::queue queue_; + std::shared_ptr queue_; }; } } diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index 3d79ccd6e..e187f9730 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -27,6 +27,11 @@ constexpr const char* TIMER_TASK = "TimerTask"; DmTimer::DmTimer() { LOGI("DmTimer constructor"); + if (queue_ != nullptr) { + LOGI("Timer is already init."); + return; + } + queue_ = std::make_shared(TIMER_TASK); } DmTimer::~DmTimer() @@ -41,11 +46,12 @@ int32_t DmTimer::StartTimer(std::string name, int32_t timeOut, TimerCallback cal LOGE("DmTimer StartTimer input value invalid"); return ERR_DM_INPUT_PARA_INVALID; } + CHECK_NULL_RETURN(queue_, ERR_DM_POINT_NULL); LOGI("DmTimer StartTimer start name: %{public}s", name.c_str()); std::lock_guard locker(timerMutex_); auto taskFunc = [callback, name] () { callback(name); }; - ffrt::task_handle handle = queue_.submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MILLISECOND_TO_SECOND)); + ffrt::task_handle handle = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MILLISECOND_TO_SECOND)); if (handle == nullptr) { LOGE("handle is nullptr."); return ERR_DM_FAILED; @@ -67,8 +73,8 @@ int32_t DmTimer::DeleteTimer(std::string timerName) LOGI("Invalid task."); return ERR_DM_FAILED; } - if (item->second != nullptr) { - int32_t ret = queue_.cancel(item->second); + if (item->second != nullptr && queue_ != nullptr) { + int32_t ret = queue_->cancel(item->second); if (ret != 0) { LOGE("Cancel failed, errCode: %{public}d.", ret); } @@ -86,8 +92,8 @@ int32_t DmTimer::DeleteAll() return DM_OK; } for (const auto &name : timerVec_) { - if (name.second != nullptr) { - int32_t ret = queue_.cancel(name.second); + if (name.second != nullptr && queue_ != nullptr) { + int32_t ret = queue_->cancel(name.second); if (ret != 0) { LOGE("Cancel failed, errCode: %{public}d.", ret); } -- Gitee From 47591c21863db22c6189f4ede64fa5a4fcc05b61 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Wed, 18 Sep 2024 14:20:52 +0800 Subject: [PATCH 212/520] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- services/service/include/softbus/softbus_listener.h | 1 + 1 file changed, 1 insertion(+) diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index c73f2c427..cd14f6ffd 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -99,6 +99,7 @@ public: void SendAclChangedBroadcast(const std::string &msg); int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); private: + static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); int32_t InitSoftPublishLNN(); private: -- Gitee From c192fd75a25e9549f7ecc86165685888388d2805 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 18 Sep 2024 14:58:38 +0800 Subject: [PATCH 213/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/commonfuzztest/onerror_fuzzer/BUILD.gn | 1 + .../onsessionopened_fuzzer/BUILD.gn | 1 + .../softbusconnectorregister_fuzzer/BUILD.gn | 5 +++- test/unittest/BUILD.gn | 23 +++++++++++++++++++ utils/include/timer/dm_timer.h | 2 +- utils/src/timer/dm_timer.cpp | 2 +- 6 files changed, 31 insertions(+), 3 deletions(-) diff --git a/test/commonfuzztest/onerror_fuzzer/BUILD.gn b/test/commonfuzztest/onerror_fuzzer/BUILD.gn index ab69405b3..51028c63b 100644 --- a/test/commonfuzztest/onerror_fuzzer/BUILD.gn +++ b/test/commonfuzztest/onerror_fuzzer/BUILD.gn @@ -52,6 +52,7 @@ ohos_fuzztest("OnErrorFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "ipc:ipc_single", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn index 2b3a6c249..9a4ddcc95 100644 --- a/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/onsessionopened_fuzzer/BUILD.gn @@ -60,6 +60,7 @@ ohos_fuzztest("OnSessionOpenedFuzzTest") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "safwk:system_ability_fwk", ] diff --git a/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn b/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn index 8228ac0c6..75a2d30bf 100644 --- a/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn +++ b/test/softbusfuzztest/softbusconnectorregister_fuzzer/BUILD.gn @@ -50,7 +50,10 @@ ohos_fuzztest("SoftbusConnectorRegisterFuzzTest") { "${utils_path}:devicemanagerutils", ] - external_deps = [ "safwk:system_ability_fwk" ] + external_deps = [ + "ffrt:libffrt", + "safwk:system_ability_fwk", + ] defines = [ "HI_LOG_ENABLE", diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 418192cfa..3641dee2f 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -96,6 +96,7 @@ ohos_unittest("UTTest_pin_auth") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -120,6 +121,7 @@ ohos_unittest("UTTest_pin_auth_ui") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -303,6 +305,7 @@ ohos_unittest("UTTest_dm_credential_manager") { "access_token:libnativetoken", "access_token:libtoken_setproc", "device_auth:deviceauth_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -327,6 +330,7 @@ ohos_unittest("UTTest_device_manager_service") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -347,6 +351,7 @@ ohos_unittest("UTTest_hichain_auth_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -369,6 +374,7 @@ ohos_unittest("UTTest_hichain_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -418,6 +424,7 @@ ohos_unittest("UTTest_mine_softbus_listener") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -443,6 +450,7 @@ ohos_unittest("UTTest_softbus_connector") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -526,6 +534,7 @@ ohos_unittest("UTTest_softbus_session") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -584,6 +593,7 @@ ohos_unittest("UTTest_dm_timer") { external_deps = [ "device_auth:deviceauth_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -665,6 +675,7 @@ ohos_unittest("UTTest_ipc_server_client_proxy") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", "hicollie:libhicollie", ] @@ -700,6 +711,7 @@ ohos_unittest("UTTest_ipc_server_stub") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -853,6 +865,7 @@ ohos_unittest("UTTest_dm_device_state_manager") { external_deps = [ "device_auth:deviceauth_sdk", + "ffrt:libffrt", "googletest:gmock", "hisysevent:libhisysevent", "hitrace:hitrace_meter", @@ -918,6 +931,7 @@ ohos_unittest("UTTest_device_manager_service_impl") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", "os_account:libaccountkits", "os_account:os_account_innerkits", @@ -956,6 +970,7 @@ ohos_unittest("UTTest_auth_message_processor") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -974,6 +989,7 @@ ohos_unittest("UTTest_auth_response_state") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -992,6 +1008,7 @@ ohos_unittest("UTTest_auth_request_state") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -1028,6 +1045,7 @@ ohos_unittest("UTTest_dm_auth_manager_first") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] @@ -1058,6 +1076,7 @@ ohos_unittest("UTTest_dm_auth_manager_second") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -1079,6 +1098,7 @@ ohos_unittest("UTTest_dm_auth_manager_third") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] @@ -1155,6 +1175,7 @@ ohos_unittest("UTTest_discovery_manager") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", "hitrace:hitrace_meter", ] @@ -1182,6 +1203,7 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { external_deps = [ "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", ] } @@ -1206,6 +1228,7 @@ ohos_unittest("UTTest_dm_discovery_manager") { "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", "googletest:gmock", "hitrace:hitrace_meter", ] diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index 6c57a09fd..30f9b5c70 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index e187f9730..fe7f0047b 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From 5e1dddb5f7520ebb89bd6be194af1f135a080a4e Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 18 Sep 2024 15:53:45 +0800 Subject: [PATCH 214/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B=5F20240918?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 138 +++++++++++++++++- 1 file changed, 137 insertions(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 30cf5f847..2743595e4 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1875,7 +1875,7 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::T std::map extraParam; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, SOFTBUS_ERR); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -2237,6 +2237,142 @@ HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_007, testing::ext::TestS DeviceManagerService::GetInstance().UninitDMServiceListener(); } +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, SendAppUnBindBroadCast_001, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + int32_t userId = 12; + uint64_t tokenId = 23; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().SendAppUnBindBroadCast(peerUdids, userId, tokenId); + EXPECT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, SendServiceUnBindBroadCast_001, testing::ext::TestSize.Level0) +{ + std::vector peerUdids; + int32_t userId = 12; + uint64_t tokenId = 23; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().SendServiceUnBindBroadCast(peerUdids, userId, tokenId); + EXPECT_NE(DeviceManagerService::GetInstance().softbusListener_, nullptr); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, ClearDiscoveryCache_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName001"; + DeviceManagerService::GetInstance().InitDMServiceListener(); + DeviceManagerService::GetInstance().ClearDiscoveryCache(pkgName); + EXPECT_NE(DeviceManagerService::GetInstance().discoveryMgr_, nullptr); + DeviceManagerService::GetInstance().UninitDMServiceListener(); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string networkId; + int32_t screenStatus = 1; + DeletePermission(); + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string networkId; + int32_t screenStatus = 1; + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string networkId = "networkId_003"; + int32_t screenStatus = 1; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_NE(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgname"; + std::string networkId = "networkId_003"; + int32_t screenStatus = 1; + int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, HandleDeviceScreenStatusChange_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo deviceInfo; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().IsDMServiceImplReady(); + DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); + EXPECT_NE(DeviceManagerService::GetInstance().dmServiceImpl_, nullptr); +} + +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map discoverParam; + std::map filterOptions; + int32_t ret = DeviceManagerService::GetInstance().EnableDiscoveryListener(pkgName, discoverParam, filterOptions); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_003, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkIdTest3"; + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeletePermission(); + std::string msg = ""; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + bool result = DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_TRUE(result); + msg = "0"; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + msg = "1"; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + msg = "2"; + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From 7dd870f481ee528ca9070544c19fdc7d5da5c206 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 18 Sep 2024 16:54:06 +0800 Subject: [PATCH 215/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager/test/unittest/UTTest=5Fdevice=5Fmana?= =?UTF-8?q?ger=5Fservice.cpp=E7=9A=84UT=E7=94=A8=E4=BE=8B=5F20240918?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 2743595e4..9e104e3ab 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2326,16 +2326,6 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceScreenStatusChange_001, testing:: EXPECT_NE(DeviceManagerService::GetInstance().dmServiceImpl_, nullptr); } -HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - PeerTargetId targetId; - DmPinType pinType = DmPinType::QR_CODE; - std::string payload; - int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - HWTEST_F(DeviceManagerServiceTest, EnableDiscoveryListener_005, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; -- Gitee From 200a6f866bb59b6dbc334806d165fc6629833940 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Wed, 18 Sep 2024 20:28:42 +0800 Subject: [PATCH 216/520] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../native_cpp/src/mini/softbus_adapter.c | 55 +++++++------- .../dependency/softbus/softbus_connector.cpp | 62 +++++++--------- .../dependency/softbus/softbus_session.cpp | 5 +- .../service/src/device_manager_service.cpp | 10 ++- .../src/device_manager_service_listener.cpp | 41 ++++++----- .../service/src/softbus/softbus_listener.cpp | 71 +++++++++---------- 6 files changed, 114 insertions(+), 130 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c index d850c994e..07e2e3b50 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c +++ b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c @@ -1000,21 +1000,18 @@ static void OnSoftbusDeviceOffline(NodeBasicInfo *deviceInfo) static void NodeBasicInfoCopyToDmDevice(DmDeviceBasicInfo *dmDeviceInfo, const NodeBasicInfo *nodeBasicInfo) { - errno_t retValue = memset_s(dmDeviceInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (retValue != EOK) { - LOGE("NodeBasicInfoCopyToDmDevice memset_s failed, ret: %d.", retValue); + if (memset_s(dmDeviceInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + LOGE("NodeBasicInfoCopyToDmDevice memset_s failed."); return; } - retValue = strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), nodeBasicInfo->deviceName); - if (retValue != EOK) { - DMLOGE("failed to copy device name with ret: %d.", retValue); + if (strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), nodeBasicInfo->deviceName) != EOK) { + DMLOGE("failed to copy device name."); return; } - retValue = strcpy_s(dmDeviceInfo->networkId, sizeof(dmDeviceInfo->networkId), nodeBasicInfo->networkId); - if (retValue != EOK) { - DMLOGE("failed to copy networkId with ret: %d.", retValue); + if (strcpy_s(dmDeviceInfo->networkId, sizeof(dmDeviceInfo->networkId), nodeBasicInfo->networkId) != EOK) { + DMLOGE("failed to copy networkId."); return; } @@ -1025,19 +1022,18 @@ static void NodeBasicInfoCopyToDmDevice(DmDeviceBasicInfo *dmDeviceInfo, const N static void DeviceInfoCopyToDmDevice(DmDeviceInfo *dmDeviceInfo, const DeviceInfo *deviceInfo) { const size_t arrayStartPosition = 0; - errno_t retValue = memset_s(dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (retValue != EOK) { - DMLOGE("failed to memset device id with ret: %d.", retValue); + if (memset_s(dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + DMLOGE("failed to memset device id."); return; } - retValue = strcpy_s(dmDeviceInfo->deviceId, sizeof(dmDeviceInfo->deviceId), deviceInfo->devId); - if (retValue != EOK) { - DMLOGE("failed to copy device id with ret: %d.", retValue); + + if (strcpy_s(dmDeviceInfo->deviceId, sizeof(dmDeviceInfo->deviceId), deviceInfo->devId) != EOK) { + DMLOGE("failed to copy device id."); return; } - retValue = strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), deviceInfo->devName); - if (retValue != EOK) { - DMLOGE("failed to copy device name with ret: %d.", retValue); + + if (strcpy_s(dmDeviceInfo->deviceName, sizeof(dmDeviceInfo->deviceName), deviceInfo->devName) != EOK) { + DMLOGE("failed to copy device name."); return; } dmDeviceInfo->credible = deviceInfo->isOnline; @@ -1056,18 +1052,21 @@ static void DeviceInfoCopyToDmDevice(DmDeviceInfo *dmDeviceInfo, const DeviceInf static void DmDeviceInfoToDmBasicInfo(const DmDeviceInfo *dmDeviceInfo, DmDeviceBasicInfo *dmBasicInfo) { - (void)memset_s(dmBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - errno_t retValue = strcpy_s(dmBasicInfo->deviceId, sizeof(dmBasicInfo->deviceId), dmDeviceInfo->deviceId); - if (retValue != EOK) { - DMLOGE("failed to copy device id with ret: %d.", retValue); + if (memset_s(dmBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + DMLOGE("DmDeviceInfoToDmBasicInfo memset_s failed"); + return; } - retValue = strcpy_s(dmBasicInfo->deviceName, sizeof(dmBasicInfo->deviceName), dmDeviceInfo->deviceName); - if (retValue != EOK) { - DMLOGE("failed to copy device name with ret: %d.", retValue); + if (strcpy_s(dmBasicInfo->deviceId, sizeof(dmBasicInfo->deviceId), dmDeviceInfo->deviceId) != EOK) { + DMLOGE("failed to copy device id."); + return; } - retValue = strcpy_s(dmBasicInfo->networkId, sizeof(dmBasicInfo->networkId), dmDeviceInfo->networkId); - if (retValue != EOK) { - DMLOGE("failed to copy device networkId with ret: %d.", retValue); + if (strcpy_s(dmBasicInfo->deviceName, sizeof(dmBasicInfo->deviceName), dmDeviceInfo->deviceName) != EOK) { + DMLOGE("failed to copy device name."); + return; + } + if (strcpy_s(dmBasicInfo->networkId, sizeof(dmBasicInfo->networkId), dmDeviceInfo->networkId) != EOK) { + DMLOGE("failed to copy device networkId."); + return; } dmBasicInfo->deviceTypeId = dmDeviceInfo->deviceTypeId; } diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index f0ac4aad7..f31a633bf 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -127,9 +127,8 @@ int32_t SoftbusConnector::UnRegisterSoftbusPublishCallback(const std::string &pk int32_t SoftbusConnector::PublishDiscovery(const DmPublishInfo &dmPublishInfo) { PublishInfo publishInfo; - errno_t retValue = memset_s(&publishInfo, sizeof(PublishInfo), 0, sizeof(PublishInfo)); - if (retValue != EOK) { - LOGE("PublishDiscovery memset_s failed, ret: %d.", retValue); + if (memset_s(&publishInfo, sizeof(PublishInfo), 0, sizeof(PublishInfo)) != EOK) { + LOGE("PublishDiscovery memset_s failed."); return ERR_DM_FAILED; } publishInfo.publishId = dmPublishInfo.publishId; @@ -162,9 +161,8 @@ int32_t SoftbusConnector::UnPublishDiscovery(int32_t publishId) int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) { SubscribeInfo subscribeInfo; - errno_t retValue = memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); - if (retValue != EOK) { - LOGE("StartDiscovery memset_s failed, ret: %d.", retValue); + if (memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)) != EOK) { + LOGE("StartDiscovery memset_s failed."); return ERR_DM_FAILED; } subscribeInfo.subscribeId = dmSubscribeInfo.subscribeId; @@ -200,9 +198,8 @@ int32_t SoftbusConnector::StartDiscovery(const DmSubscribeInfo &dmSubscribeInfo) int32_t SoftbusConnector::StartDiscovery(const uint16_t subscribeId) { SubscribeInfo subscribeInfo; - errno_t retValue = memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); - if (retValue != EOK) { - LOGE("StartDiscovery memset_s failed, ret: %d.", retValue); + if (memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)) != EOK) { + LOGE("StartDiscovery memset_s failed."); return ERR_DM_FAILED; } subscribeInfo.subscribeId = subscribeId; @@ -369,23 +366,20 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceInfo &dmDeviceInfo) { - errno_t retValue = memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (retValue != EOK) { - LOGE("ConvertDeviceInfoToDmDevice memset_s failed, ret: %d.", retValue); + if (memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed."); return; } - retValue = memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))); - if (retValue != EOK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); return; } - retValue = memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))); - if (retValue != EOK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } @@ -395,23 +389,20 @@ void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, DmDeviceBasicInfo &dmDeviceBasicInfo) { - errno_t retValue = memset_s(&dmDeviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (retValue != EOK) { - LOGE("ConvertDeviceInfoToDmDevice memset_s failed, ret: %d.", retValue); + if (memset_s(&dmDeviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed."); return; } - retValue = memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))); - if (retValue != EOK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + if (memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), deviceInfo.devId, + std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); return; } - retValue = memcpy_s(dmDeviceBasicInfo.deviceName, sizeof(dmDeviceBasicInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))); - if (retValue != EOK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + if (memcpy_s(dmDeviceBasicInfo.deviceName, sizeof(dmDeviceBasicInfo.deviceName), deviceInfo.devName, + std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } @@ -799,23 +790,22 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo) { - errno_t retValue = memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + if (memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return; } retValue = memcpy_s(dmDeviceInfo.networkId, sizeof(dmDeviceInfo.networkId), nodeBasicInfo.networkId, std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))); if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } retValue = memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))); if (retValue != EOK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 71a839e45..30ded78bf 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -56,9 +56,8 @@ static void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t q SoftbusSession::SoftbusSession() { LOGD("SoftbusSession constructor."); - errno_t retValue = memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)); - if (retValue != DM_OK) { - LOGE("SoftbusSession::SoftbusSession memset_s failed, ret: %d.", retValue); + if (memset_s(&iSocketListener_, sizeof(ISocketListener), 0, sizeof(ISocketListener)) != DM_OK) { + LOGE("SoftbusSession::SoftbusSession memset_s failed."); } iSocketListener_.OnShutdown = OnShutdown; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index daccb70c6..0a38e973b 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -357,9 +357,8 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string udidHashTemp = ""; if (ConvertUdidHashToAnoyDeviceId(localDeviceId_, udidHashTemp) == DM_OK) { - errno_t retValue = memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); - if (retValue != DM_OK) { - LOGE("GetLocalDeviceInfo memset_s failed, ret: %d.", retValue); + if (memset_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { + LOGE("GetLocalDeviceInfo memset_s failed."); return ERR_DM_FAILED; } if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { @@ -1762,9 +1761,8 @@ void DeviceManagerService::ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInf { std::string udidHashTemp = ""; if (ConvertUdidHashToAnoyDeviceId(deviceInfo.deviceId, udidHashTemp) == DM_OK) { - errno_t retValue = memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); - if (retValue != DM_OK) { - LOGE("ConvertUdidHashToAnoyDeviceId memset_s failed, ret: %d.", retValue); + if (memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { + LOGE("ConvertUdidHashToAnoyDeviceId memset_s failed."); return; } if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 19043747a..eef7ccc31 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -50,30 +50,26 @@ const int32_t LAST_APP_ONLINE_NUMS = 8; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { - errno_t retValue = memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (retValue != DM_OK) { - LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed, ret: %d.", retValue); + if (memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != DM_OK) { + LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed."); return; } - retValue = memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))); - if (retValue != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } - retValue = memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, - std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))); - if (retValue != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, + std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return; } - retValue = memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, - std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))); - if (retValue != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, + std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } @@ -97,10 +93,14 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceInfo(dmDeviceInfo); pReq->SetDeviceBasicInfo(dmDeviceBasicInfo); @@ -455,9 +455,12 @@ int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoyAndSave(const std::st if (ret != DM_OK) { return ERR_DM_FAILED; } - (void)memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN); + if (memset_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { + LOGE("ConvertUdidHashToAnoyAndSave memset failed."); + return ERR_DM_FAILED; + } if (memcpy_s(deviceInfo.deviceId, sizeof(deviceInfo.deviceId), kvValue.anoyDeviceId.c_str(), - std::min(sizeof(deviceInfo.deviceId), kvValue.anoyDeviceId.length())) != DM_OK) { + std::min(sizeof(deviceInfo.deviceId), kvValue.anoyDeviceId.length())) != DM_OK) { LOGE("copy deviceId data failed."); return ERR_DM_FAILED; } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a787519fe..8f2955531 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -494,9 +494,8 @@ int32_t SoftbusListener::RefreshSoftbusLNN(const char *pkgName, const DmSubscrib { LOGI("RefreshSoftbusLNN begin, subscribeId: %{public}d.", dmSubInfo.subscribeId); SubscribeInfo subscribeInfo; - errno_t retValue = memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)); - if (retValue != DM_OK) { - LOGE("RefreshSoftbusLNN memset_s failed, ret: %d.", retValue); + if (memset_s(&subscribeInfo, sizeof(SubscribeInfo), 0, sizeof(SubscribeInfo)) != DM_OK) { + LOGE("RefreshSoftbusLNN memset_s failed."); return ERR_DM_FAILED; } @@ -671,15 +670,20 @@ int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp) int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, DmDeviceInfo &devInfo) { - (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); + return ERR_DM_FAILED; + } if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); + return ERR_DM_FAILED; } if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); + return ERR_DM_FAILED; } devInfo.deviceTypeId = nodeInfo.deviceTypeId; nlohmann::json extraJson; @@ -692,23 +696,20 @@ int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &node int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { - errno_t retValue = memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return ERR_DM_FAILED; } - retValue = memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))); - if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return ERR_DM_FAILED; } - retValue = memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))); - if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); return ERR_DM_FAILED; } devInfo.deviceTypeId = nodeInfo.deviceTypeId; @@ -721,23 +722,20 @@ int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nod int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceBasicInfo &devInfo) { - errno_t retValue = memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + if (memset_s(&devInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return ERR_DM_FAILED; } - retValue = memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))); - if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return ERR_DM_FAILED; } - retValue = memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))); - if (retValue != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); return ERR_DM_FAILED; } @@ -760,23 +758,20 @@ std::string SoftbusListener::ConvertBytesToUpperCaseHexString(const uint8_t arr[ int32_t SoftbusListener::FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice) { - errno_t retValue = memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (retValue != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice memset_s failed, ret: %d.", retValue); + if (memset_s(&dmDevice, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice memset_s failed."); return ERR_DM_FAILED; } - retValue = memcpy_s(dmDevice.deviceId, sizeof(dmDevice.deviceId), device.devId, - std::min(sizeof(dmDevice.deviceId), sizeof(device.devId))); - if (retValue != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice: copy device id failed, ret: %d.", retValue); + if (memcpy_s(dmDevice.deviceId, sizeof(dmDevice.deviceId), device.devId, + std::min(sizeof(dmDevice.deviceId), sizeof(device.devId))) != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice: copy device id failed."); return ERR_DM_FAILED; } - retValue = memcpy_s(dmDevice.deviceName, sizeof(dmDevice.deviceName), device.devName, - std::min(sizeof(dmDevice.deviceName), sizeof(device.devName))); - if (retValue != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice: copy device name failed, ret: %d.", retValue); + if (memcpy_s(dmDevice.deviceName, sizeof(dmDevice.deviceName), device.devName, + std::min(sizeof(dmDevice.deviceName), sizeof(device.devName))) != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice: copy device name failed."); return ERR_DM_FAILED; } -- Gitee From 0987243f63c74d92c655c8ed6d2669e743669fcc Mon Sep 17 00:00:00 2001 From: dengxiaoyu Date: Wed, 18 Sep 2024 20:30:41 +0800 Subject: [PATCH 217/520] add inputdialog gap Signed-off-by: dengxiaoyu --- .../src/main/ets/pages/InputPinDialog.ets | 97 +++++++++---------- 1 file changed, 46 insertions(+), 51 deletions(-) diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index bf8fb439d..77f6662a8 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -64,7 +64,7 @@ struct InputCustomDialog { this.isPC = Constant.isPC(); let ims = inputMethod.getSetting(); ims.on('imeShow', (info: Array) => { - this.scroller.scrollTo({ yOffset: 72, xOffset: 0 }); + this.scroller.scrollTo({yOffset: 72, xOffset: 0}); }); if (AppStorage.get('targetDeviceName') != null) { this.targetDeviceName = AppStorage.get('targetDeviceName') as string; @@ -76,37 +76,37 @@ struct InputCustomDialog { } deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', (err: Error, dm: deviceManager.DeviceManager) => { - if (err) { - console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); + if (err) { + console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); + return; + } + dmClass = dm; + dmClass.on('uiStateChange', (data: Record) => { + console.log('uiStateChange executed, dialog closed' + JSON.stringify(data)); + let tmpStr: Record = JSON.parse(data.param); + let msg: number = tmpStr.uiStateMsg as number; + if (msg === MSG_DOING_AUTH) { + this.errorTips = $r('app.string.dm_authenticating'); + this.errorTipsVisible = Visibility.Visible; return; } - dmClass = dm; - dmClass.on('uiStateChange', (data: Record) => { - console.log('uiStateChange executed, dialog closed' + JSON.stringify(data)); - let tmpStr: Record = JSON.parse(data.param); - let msg: number = tmpStr.uiStateMsg as number; - if (msg === MSG_DOING_AUTH) { - this.errorTips = $r('app.string.dm_authenticating'); - this.errorTipsVisible = Visibility.Visible; - return; - } - if (msg === MSG_CANCEL_PIN_CODE_INPUT) { - this.destruction(); - return; - } - if (msg === MSG_PIN_CODE_ERROR) { - if (this.model == MODEL_PASSWORD) { - this.errorTips = $r('app.string.dm_password_error'); - } else { - this.isTimes--; - this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); - } - this.password = ''; - this.errorTipsVisible = Visibility.Visible; - this.passwordCircle = ['', '', '', '', '', '']; + if (msg === MSG_CANCEL_PIN_CODE_INPUT) { + this.destruction(); + return; + } + if (msg === MSG_PIN_CODE_ERROR) { + if (this.model == MODEL_PASSWORD) { + this.errorTips = $r('app.string.dm_password_error'); + } else { + this.isTimes--; + this.errorTips = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); } - }) - }); + this.password = ''; + this.errorTipsVisible = Visibility.Visible; + this.passwordCircle = ['', '', '', '', '', '']; + } + }) + }); this.listener.on('change', (mediaQueryResult: mediaquery.MediaQueryResult) => { this.onPortrait(mediaQueryResult); }); @@ -221,7 +221,7 @@ struct InputCustomDialog { List() { ListItem() { Flex({ justifyContent: FlexAlign.Center }) { - ForEach(this.passwordCircle, (item: string) => { + ForEach(this.passwordCircle, (item:string) => { Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text(item) .fontSize($r('sys.float.ohos_id_text_size_headline7')) @@ -237,7 +237,7 @@ struct InputCustomDialog { Column() .width(12) .height(12) - .border({ width: 2, color: $r('sys.color.ohos_id_color_primary'), radius: 12 }) + .border({ width: 2, color: $r('sys.color.ohos_id_color_primary'), radius: 12}) }.width('10%') .height('100%') .visibility(item === '' ? Visibility.Visible : Visibility.None) @@ -245,8 +245,7 @@ struct InputCustomDialog { } } } - - TextInput({ placeholder: '', text: this.password }) + TextInput({ placeholder: '', text: this.password}) .defaultFocus(true) .type(8) .height(60) @@ -271,23 +270,23 @@ struct InputCustomDialog { } } let gThis = this; - setTimeout(() => { + setTimeout(()=> { gThis.passwordOnChange(value); }, 50) console.log(TAG + 'this.password: ' + this.password); }) }.height(48) - .margin({ top: 12, bottom: 16 }) + .margin({ top: 12, bottom: 16}) Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text(this.errorTips) - .fontSize($r('sys.float.ohos_id_text_size_body2')) - .fontWeight(FontWeight.Medium) - .fontColor($r('sys.color.ohos_id_color_warning')) + .fontSize($r('sys.float.ohos_id_text_size_body2')) + .fontWeight(FontWeight.Medium) + .fontColor($r('sys.color.ohos_id_color_warning')) }.visibility(this.errorTipsVisible) .margin({ bottom: 16, - left: $r('sys.float.ohos_id_corner_radius_dialog'), - right: $r('sys.float.ohos_id_corner_radius_dialog') }) + left: $r('sys.float.ohos_id_corner_radius_dialog'), + right: $r('sys.float.ohos_id_corner_radius_dialog') }) Flex({ justifyContent: FlexAlign.Center }) { Button($r('app.string.dm_cancel')) @@ -325,22 +324,19 @@ struct InputCustomDialog { } .scrollable(ScrollDirection.Vertical) .scrollBar(BarState.On) - .constraintSize({ maxHeight: `${this.heightNum}` }) + .constraintSize({ maxHeight: `${this.heightNum}`}) .borderRadius($r('sys.float.ohos_id_corner_radius_dialog')) .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) - .margin({ - left: $r('sys.float.ohos_id_dialog_margin_bottom'), - right: $r('sys.float.ohos_id_dialog_margin_bottom') - }) + .margin({ left: $r('sys.float.ohos_id_dialog_margin_start'), right: $r('sys.float.ohos_id_dialog_margin_end') }) } - }.margin({ top: 8, bottom: 20 }) + }.margin({top: 8, bottom: 20}) } } @Entry @Component struct dialogPlusPage { - @State isPC: boolean = false; + @State isPC: boolean = Constant.isPC(); dialogController: CustomDialogController = new CustomDialogController({ builder: InputCustomDialog(), autoCancel: false, @@ -351,12 +347,11 @@ struct dialogPlusPage { }); aboutToAppear() { - console.log(TAG + 'aboutToAppear aboutToAppear'); - this.isPC = Constant.isPC(); + console.log(TAG + 'aboutToAppear : this.isPC: ' + this.isPC); } aboutToDisappear() { - console.log(TAG + 'aboutToDisappear aboutToDisappear'); + console.log(TAG + 'aboutToDisappear aboutToDisappear') if (dmClass != null) { try { dmClass.off('uiStateChange'); @@ -364,7 +359,7 @@ struct dialogPlusPage { } catch (error) { console.log('dmClass release failed'); } - dmClass = null; + dmClass = null } } -- Gitee From 9bd5142d3ee9078c8158b82f9f5d7b13cced3a6a Mon Sep 17 00:00:00 2001 From: dengxiaoyu Date: Wed, 18 Sep 2024 20:37:15 +0800 Subject: [PATCH 218/520] add inputdialog gap Signed-off-by: dengxiaoyu --- display/entry/src/main/ets/pages/InputPinDialog.ets | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index 77f6662a8..6818d0732 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -327,7 +327,10 @@ struct InputCustomDialog { .constraintSize({ maxHeight: `${this.heightNum}`}) .borderRadius($r('sys.float.ohos_id_corner_radius_dialog')) .backgroundBlurStyle(BlurStyle.COMPONENT_ULTRA_THICK) - .margin({ left: $r('sys.float.ohos_id_dialog_margin_start'), right: $r('sys.float.ohos_id_dialog_margin_end') }) + .margin({ + left: $r('sys.float.ohos_id_dialog_margin_bottom'), + right: $r('sys.float.ohos_id_dialog_margin_bottom') + }) } }.margin({top: 8, bottom: 20}) } -- Gitee From 29536fed6f5b33b59049911da22b01b23a41328c Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Wed, 18 Sep 2024 20:38:29 +0800 Subject: [PATCH 219/520] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../native_cpp/src/ipc/lite/ipc_client_manager.cpp | 6 ++---- interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c | 4 +--- interfaces/kits/js/src/native_devicemanager_js.cpp | 5 +---- interfaces/kits/js4.0/src/dm_native_event.cpp | 5 +---- interfaces/kits/js4.0/src/native_devicemanager_js.cpp | 5 +---- 5 files changed, 6 insertions(+), 19 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp index e542d7aa1..d8584b2b3 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_client_manager.cpp @@ -84,10 +84,8 @@ int32_t IpcClientManager::UnInit(const std::string &pkgName) int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - if (req == nullptr) { - LOGE("req is null"); - return ERR_DM_INIT_FAILED; - } + CHECK_NULL_RETURN(req, ERR_DM_POINT_NULL); + CHECK_NULL_RETURN(rsp, ERR_DM_POINT_NULL); std::string pkgName = req->GetPkgName(); if (!IsInit(pkgName)) { return ERR_DM_INIT_FAILED; diff --git a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c index 07e2e3b50..67734a883 100644 --- a/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c +++ b/interfaces/inner_kits/native_cpp/src/mini/softbus_adapter.c @@ -743,9 +743,7 @@ static int DeleteSoftbusSemaphoreAndMutex(void) static int FilterDevice(const DmDeviceInfo *dmDeviceInfo) { DMLOGI("FilterDevice start."); - if (dmDeviceInfo == NULL) { - return ERR_DM_FAILED; - } + CHECK_NULL_RETURN(dmDeviceInfo, ERR_DM_POINT_NULL); int ret = DM_OK; if (g_discoveryCallbackMap.filterOption.isTrusted != NOT_FILTER && dmDeviceInfo->isLocalExistCredential != g_discoveryCallbackMap.filterOption.isTrusted) { diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 6242094d2..3ab726eef 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1537,10 +1537,7 @@ napi_value DeviceManagerNapi::SetUserOperationSync(napi_env env, napi_callback_i void DeviceManagerNapi::CallGetTrustedDeviceListStatusSync(napi_env env, napi_status &status, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { - if (deviceInfoListAsyncCallbackInfo == nullptr) { - LOGE("CallGetTrustedDeviceListStatusSync deviceInfoListAsyncCallbackInfo is null"); - return; - } + CHECK_NULL_VOID(deviceInfoListAsyncCallbackInfo); if (deviceInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { LOGE("CallGetTrustedDeviceListStatusSync invalid devList size"); return; diff --git a/interfaces/kits/js4.0/src/dm_native_event.cpp b/interfaces/kits/js4.0/src/dm_native_event.cpp index 17d8846cf..10d7dd77e 100644 --- a/interfaces/kits/js4.0/src/dm_native_event.cpp +++ b/interfaces/kits/js4.0/src/dm_native_event.cpp @@ -30,10 +30,7 @@ DmNativeEvent::~DmNativeEvent() { for (auto iter = eventMap_.begin(); iter != eventMap_.end(); iter++) { auto listener = iter->second; - if (listener == nullptr) { - LOGE("listener is nullptr"); - return; - } + CHECK_NULL_VOID(listener); napi_delete_reference(env_, listener->handlerRef); } eventMap_.clear(); diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp index 686c5c699..72d024acc 100644 --- a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -993,10 +993,7 @@ void DmNapiBindTargetCallback::OnBindResult(const PeerTargetId &targetId, int32_ int32_t DeviceManagerNapi::DumpDeviceInfo( DeviceBasicInfoListAsyncCallbackInfo *deviceBasicInfoListAsyncCallbackInfo) { - if (deviceBasicInfoListAsyncCallbackInfo == nullptr) { - LOGE("CallGetAvailableDeviceListStatus deviceBasicInfoListAsyncCallbackInfo is null"); - return DM_ERR_FAILED; - } + CHECK_NULL_RETURN(deviceBasicInfoListAsyncCallbackInfo, ERR_DM_POINT_NULL); if (deviceBasicInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { LOGE("CallGetAvailableDeviceListStatus invalid devList size"); return DM_ERR_FAILED; -- Gitee From 83e0020dd307b23e8b24154b0716e11f3dbb82ec Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 18 Sep 2024 20:45:40 +0800 Subject: [PATCH 220/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=81=9C=E6=AD=A2?= =?UTF-8?q?=E5=8F=91=E7=8E=B0=E6=97=B6=E5=BA=8F=20Signed-off-by:=20liuzhon?= =?UTF-8?q?gming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../inner_kits/native_cpp/src/device_manager_impl.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 023c6279a..9abe58c4b 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -1657,8 +1657,13 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); + uint16_t subscribeId = DM_INVALID_FLAG_ID; + { + std::lock_guard autoLock(subMapLock); + if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { + subscribeId = pkgName2SubIdMap_[pkgName]; + } + } if (subscribeId == DM_INVALID_FLAG_ID) { LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); return ERR_DM_INPUT_PARA_INVALID; @@ -1680,7 +1685,7 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, LOGE("StopDiscovering error: Failed with ret %{public}d", ret); return ret; } - + RemoveDiscoveryCallback(pkgName); LOGI("Completed"); return DM_OK; } -- Gitee From 3fe58a4e5014dcc5c45fcdb3513487ea276bcd7e Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Thu, 19 Sep 2024 15:20:34 +0800 Subject: [PATCH 221/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../native_cpp/src/device_manager_impl.cpp | 27 ++++++++----------- .../dependency/softbus/softbus_connector.cpp | 10 +++---- .../softbuscache/src/dm_softbus_cache.cpp | 13 ++++----- 3 files changed, 20 insertions(+), 30 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index b9b5ab5cd..84ce387e5 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -181,31 +181,26 @@ int32_t DeviceManagerImpl::UnInitDeviceManager(const std::string &pkgName) void DeviceManagerImpl::ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { - errno_t retValue = DM_OK; - retValue = memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)); - if (retValue != DM_OK) { - LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed, ret: %d.", retValue); + if (memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != DM_OK) { + LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed."); return; } - retValue = memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))); - if (retValue != DM_OK) { - LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { + LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } - retValue = memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, - std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))); - if (retValue != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, + std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return; } - retValue = memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, - std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))); - if (retValue != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed, ret: %d.", retValue); + if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, + std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index f31a633bf..be337d049 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -795,16 +795,14 @@ void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeB return; } - retValue = memcpy_s(dmDeviceInfo.networkId, sizeof(dmDeviceInfo.networkId), nodeBasicInfo.networkId, - std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))); - if (retValue != EOK) { + if (memcpy_s(dmDeviceInfo.networkId, sizeof(dmDeviceInfo.networkId), nodeBasicInfo.networkId, + std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } - retValue = memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))); - if (retValue != EOK) { + if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 02b2d0567..2cad2f6ba 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -255,22 +255,19 @@ int32_t SoftbusCache::GetUuidFromCache(const char *networkId, std::string &uuid) int32_t SoftbusCache::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { - errno_t retValue = memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); - if (retValue != DM_OK) { + if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); return ERR_DM_FAILED; } - retValue = memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, - std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))); - if (retValue != DM_OK) { + if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, + std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); return ERR_DM_FAILED; } - retValue = memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))); - if (retValue != DM_OK) { + if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); return ERR_DM_FAILED; } -- Gitee From ebce860cd1a789da64305a5927ba6ea6c16ef058 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 19 Sep 2024 16:20:42 +0800 Subject: [PATCH 222/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- utils/src/timer/dm_timer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index fe7f0047b..322da3904 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -21,7 +21,7 @@ namespace OHOS { namespace DistributedHardware { const int32_t MIN_TIME_OUT = 0; const int32_t MAX_TIME_OUT = 300; -const int32_t MILLISECOND_TO_SECOND = 1000; +const int64_t DELAY_TIME = 1000000L; constexpr const char* TIMER_TASK = "TimerTask"; DmTimer::DmTimer() @@ -51,7 +51,7 @@ int32_t DmTimer::StartTimer(std::string name, int32_t timeOut, TimerCallback cal std::lock_guard locker(timerMutex_); auto taskFunc = [callback, name] () { callback(name); }; - ffrt::task_handle handle = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MILLISECOND_TO_SECOND)); + ffrt::task_handle handle = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * DELAY_TIME)); if (handle == nullptr) { LOGE("handle is nullptr."); return ERR_DM_FAILED; -- Gitee From a8938a12d7743aa4b75c8f2e36d45ebcfaedfe7a Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Thu, 19 Sep 2024 19:50:56 +0800 Subject: [PATCH 223/520] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- services/softbuscache/src/dm_softbus_cache.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 2cad2f6ba..da89f40a2 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -256,19 +256,19 @@ int32_t SoftbusCache::GetUuidFromCache(const char *networkId, std::string &uuid) int32_t SoftbusCache::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed, ret: %d.", retValue); + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return ERR_DM_FAILED; } if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed, ret: %d.", retValue); + LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return ERR_DM_FAILED; } if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { - LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed, ret: %d.", retValue); + LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); return ERR_DM_FAILED; } -- Gitee From 6c93645cd8b286ce8044bc5d93574f49b5451909 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Fri, 20 Sep 2024 10:16:52 +0800 Subject: [PATCH 224/520] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=A3=80=E8=A7=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../inner_kits/native_cpp/src/device_manager_impl.cpp | 6 +++--- services/service/src/softbus/softbus_listener.cpp | 2 +- services/softbuscache/src/dm_softbus_cache.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 84ce387e5..ad5d780fb 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -187,19 +187,19 @@ void DeviceManagerImpl::ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &i } if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, - std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return; } if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, - std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 8f2955531..85b76b586 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -681,7 +681,7 @@ int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &node } if (memcpy_s(devInfo.deviceName, sizeof(devInfo.deviceName), nodeInfo.deviceName, - std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { + std::min(sizeof(devInfo.deviceName), sizeof(nodeInfo.deviceName))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceName data failed."); return ERR_DM_FAILED; } diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index da89f40a2..eb1210e7e 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -131,7 +131,7 @@ void SoftbusCache::SaveDeviceInfo(DmDeviceInfo deviceInfo) return; } if (memcpy_s(deviceInfo.deviceId, sizeof(deviceInfo.deviceId), udidHash, - std::min(sizeof(deviceInfo.deviceId), sizeof(udidHash))) != DM_OK) { + std::min(sizeof(deviceInfo.deviceId), sizeof(udidHash))) != DM_OK) { LOGE("SaveDeviceInfo copy deviceId failed."); return; } -- Gitee From e2dae0cafa23329d92dd27b0c58171f275808c18 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 20 Sep 2024 09:43:26 +0800 Subject: [PATCH 225/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BA=8C=E6=AC=A1?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../service/include/pinholder/pin_holder.h | 2 ++ services/service/src/pinholder/pin_holder.cpp | 27 ++++++++++++------- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index b1aa7c149..d8f4b6205 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -21,6 +21,7 @@ #include "pin_holder_session.h" #include "pinholder_session_callback.h" +#include #include #include @@ -76,6 +77,7 @@ private: PinHolderState sourceState_; int32_t sessionId_ = -1; bool isRemoteSupported_ = false; + std::atomic isDestroy_; }; } } diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 2114f58dd..7b15f42f4 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -45,6 +45,7 @@ constexpr const char* TAG_REMOTE_DEVICE_ID = "REMOTE_DEVICE_ID"; constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; +constexpr int32_t ERR_DM_TIME_OUT = 96929745; constexpr const char* TAG_MSG_TYPE = "MSG_TYPE"; constexpr const char* TAG_DM_VERSION = "DM_VERSION"; constexpr const char* DM_CONNECTION_DISCONNECTED = "DM_CONNECTION_DISCONNECTED"; @@ -335,12 +336,15 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; sinkState_ = SINK_INIT; sourceState_ = SOURCE_INIT; - listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); - nlohmann::json jsonContent; - jsonContent[TAG_PIN_TYPE] = pinType; - jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + if (!isDestroy_.load()) { + listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); + nlohmann::json jsonContent; + jsonContent[TAG_PIN_TYPE] = pinType; + jsonContent[TAG_PAYLOAD] = payload; + std::string content = jsonContent.dump(); + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + isDestroy_.store(true); + } } std::string msg = jsonObj.dump(); @@ -362,13 +366,14 @@ void PinHolder::CloseSession(const std::string &name) nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); - if (listener_ != nullptr) { + if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + isDestroy_.store(true); } session_->CloseSessionServer(sessionId_); timer_->DeleteAll(); @@ -462,6 +467,7 @@ void PinHolder::GetPeerDeviceId(int32_t sessionId, std::string &udidHash) void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { + isDestroy_.store(false); char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; int32_t ret = ::GetPeerDeviceId(sessionId, &peerDeviceId[0], DEVICE_UUID_LENGTH); if (ret != DM_OK) { @@ -499,13 +505,14 @@ void PinHolder::OnSessionClosed(int32_t sessionId) nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); - if (listener_ != nullptr) { + if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + isDestroy_.store(true); } if (timer_ != nullptr) { timer_->DeleteAll(); -- Gitee From 33d11cf2128767cf58a2d8ed8894315ff93341a2 Mon Sep 17 00:00:00 2001 From: dengxiaoyu Date: Fri, 20 Sep 2024 16:36:41 +0800 Subject: [PATCH 226/520] back center Signed-off-by: dengxiaoyu --- display/AppScope/app.json | 4 ++-- display/entry/src/main/ets/pages/InputPinDialog.ets | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 606cb31cd..179930d77 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000022, - "versionName": "1.0.22", + "versionCode": 1000023, + "versionName": "1.0.23", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index 6818d0732..c998ef202 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -339,18 +339,17 @@ struct InputCustomDialog { @Entry @Component struct dialogPlusPage { - @State isPC: boolean = Constant.isPC(); dialogController: CustomDialogController = new CustomDialogController({ builder: InputCustomDialog(), autoCancel: false, - alignment: this.isPC ? DialogAlignment.Center : DialogAlignment.Bottom, + alignment: DialogAlignment.Center, offset: { dx: 0, dy: 0 }, customStyle: true, maskColor: $r('sys.color.ohos_id_color_mask_thin') }); aboutToAppear() { - console.log(TAG + 'aboutToAppear : this.isPC: ' + this.isPC); + console.log(TAG + 'aboutToAppear aboutToAppear'); } aboutToDisappear() { -- Gitee From bee289a835162b32cf88d9f1455bc67d3caea1bc Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 20 Sep 2024 21:12:23 +0800 Subject: [PATCH 227/520] =?UTF-8?q?=E5=9B=9E=E8=B0=83=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- services/service/include/pinholder/pin_holder.h | 7 +++++++ services/service/src/pinholder/pin_holder.cpp | 11 ++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index d8f4b6205..c6e747ee6 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -36,6 +36,12 @@ typedef enum PinHolderState { SINK_DESTROY, } PinHolderState; +typedef enum DestroyState { + STATE_UNKNOW = 0x0, + STATE_REMOTE_WRONG = 0x1, + STATE_TIME_OUT = 0x2, +} DestroyState; + class PinHolder final : public IPinholderSessionCallback, public std::enable_shared_from_this { public: @@ -78,6 +84,7 @@ private: int32_t sessionId_ = -1; bool isRemoteSupported_ = false; std::atomic isDestroy_; + DestroyState destroyState_ = STATE_UNKNOW; }; } } diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 7b15f42f4..23108f10c 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -306,6 +306,7 @@ void PinHolder::ProcessCreateRespMsg(const std::string &message) listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); session_->CloseSessionServer(sessionId_); sessionId_ = SESSION_ID_INVALID; + destroyState_ = STATE_REMOTE_WRONG; } } @@ -377,6 +378,7 @@ void PinHolder::CloseSession(const std::string &name) } session_->CloseSessionServer(sessionId_); timer_->DeleteAll(); + destroyState_ = STATE_TIME_OUT; sessionId_ = SESSION_ID_INVALID; sinkState_ = SINK_INIT; sourceState_ = SOURCE_INIT; @@ -468,6 +470,7 @@ void PinHolder::GetPeerDeviceId(int32_t sessionId, std::string &udidHash) void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { isDestroy_.store(false); + destroyState_ = STATE_UNKNOW; char peerDeviceId[DEVICE_UUID_LENGTH] = {0}; int32_t ret = ::GetPeerDeviceId(sessionId, &peerDeviceId[0], DEVICE_UUID_LENGTH); if (ret != DM_OK) { @@ -511,7 +514,13 @@ void PinHolder::OnSessionClosed(int32_t sessionId) jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + if (destroyState_ == STATE_UNKNOW) { + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, sessionId, content); + } else if (destroyState_ == STATE_REMOTE_WRONG) { + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_FAILED, content); + } else if (destroyState_ == STATE_TIME_OUT) { + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + } isDestroy_.store(true); } if (timer_ != nullptr) { -- Gitee From 9d6c97242ab8bdc5d5d38be9e04ab33ac0118275 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 21 Sep 2024 14:49:43 +0800 Subject: [PATCH 228/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=88=87=E6=8D=A2?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/include/i_dm_service_impl_ext.h | 7 +++++++ services/service/src/device_manager_service.cpp | 3 +++ 2 files changed, 10 insertions(+) diff --git a/services/service/include/i_dm_service_impl_ext.h b/services/service/include/i_dm_service_impl_ext.h index d01eed782..b70ba754e 100644 --- a/services/service/include/i_dm_service_impl_ext.h +++ b/services/service/include/i_dm_service_impl_ext.h @@ -92,6 +92,13 @@ public: * @tc.type: FUNC */ virtual int32_t SetDnPolicy(int32_t policy, int32_t timeOut) = 0; + + /** + * @tc.name: IDMServiceImplExt::AccountUserSwitched + * @tc.desc: AccountUserSwitched + * @tc.type: FUNC + */ + virtual int32_t AccountUserSwitched(int32_t userId, const std::string &oldAccountId) = 0; }; using CreateDMServiceImplExtFuncPtr = IDMServiceImplExt *(*)(void); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 8889a6257..6c8d0b384 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1600,6 +1600,9 @@ void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std: MultipleUserConnector::SetSwitchOldUserId(userId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); + if (IsDMServiceAdapterLoad()) { + dmServiceImplExt_->AccountUserSwitched(userId, MultipleUserConnector::GetOhosAccountId()); + } } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); -- Gitee From d7f7e3e249e6de70a14a95a18a23ba770353b62d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 21 Sep 2024 14:53:37 +0800 Subject: [PATCH 229/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/include/i_dm_service_impl_ext.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/include/i_dm_service_impl_ext.h b/services/service/include/i_dm_service_impl_ext.h index b70ba754e..fe5da7e43 100644 --- a/services/service/include/i_dm_service_impl_ext.h +++ b/services/service/include/i_dm_service_impl_ext.h @@ -98,7 +98,7 @@ public: * @tc.desc: AccountUserSwitched * @tc.type: FUNC */ - virtual int32_t AccountUserSwitched(int32_t userId, const std::string &oldAccountId) = 0; + virtual int32_t AccountUserSwitched(int32_t userId, const std::string &accountId) = 0; }; using CreateDMServiceImplExtFuncPtr = IDMServiceImplExt *(*)(void); -- Gitee From 487e62a2d799157b00d2e70ae01cde4034095b08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sat, 21 Sep 2024 15:49:56 +0800 Subject: [PATCH 230/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- utils/src/timer/dm_timer.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index 322da3904..ab1a55d59 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -19,10 +19,12 @@ namespace OHOS { namespace DistributedHardware { +namespace { const int32_t MIN_TIME_OUT = 0; const int32_t MAX_TIME_OUT = 300; const int64_t DELAY_TIME = 1000000L; constexpr const char* TIMER_TASK = "TimerTask"; +} DmTimer::DmTimer() { @@ -87,10 +89,6 @@ int32_t DmTimer::DeleteAll() { LOGI("DmTimer DeleteAll start"); std::lock_guard locker(timerMutex_); - if (timerVec_.empty()) { - LOGI("DmTimer is empty"); - return DM_OK; - } for (const auto &name : timerVec_) { if (name.second != nullptr && queue_ != nullptr) { int32_t ret = queue_->cancel(name.second); -- Gitee From 173e9d735e7ef8bc7a028fc976f631a064ceba5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 23 Sep 2024 10:26:04 +0800 Subject: [PATCH 231/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- utils/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 0608e53bc..b3b56d221 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -123,6 +123,7 @@ if (defined(ohos_lite)) { "bundle_framework:appexecfwk_core", "cJSON:cjson", "c_utils:utils", + "eventhandler:libeventhandler", "ffrt:libffrt", "hilog:libhilog", "ipc:ipc_core", -- Gitee From 59485feded60c999dfbd684dbde1ed547c324091 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 23 Sep 2024 15:07:29 +0800 Subject: [PATCH 232/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/commonunittest/UTTest_dm_timer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/commonunittest/UTTest_dm_timer.cpp b/test/commonunittest/UTTest_dm_timer.cpp index f883a68af..bcb9066b5 100644 --- a/test/commonunittest/UTTest_dm_timer.cpp +++ b/test/commonunittest/UTTest_dm_timer.cpp @@ -101,7 +101,7 @@ HWTEST_F(TimeHeapTest, DeleteTimer_001, testing::ext::TestSize.Level0) EXPECT_EQ(ERR_DM_INPUT_PARA_INVALID, ret); ret = timer->DeleteTimer(name); - EXPECT_EQ(DM_OK, ret); + EXPECT_EQ(ERR_DM_FAILED, ret); } /** -- Gitee From 1d76c15fe8433f73399c824823f6c1a93531e34b Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 23 Sep 2024 16:16:51 +0800 Subject: [PATCH 233/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9device=5Fmanager?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E7=9A=84UT=E5=A4=B1=E8=B4=A5=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=5F20240923?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_discovery_manager.cpp | 6 +++--- test/commonunittest/UTTest_dm_publish_manager.cpp | 2 +- .../UTTest_mine_softbus_listener.cpp | 4 ++-- test/softbusunittest/UTTest_softbus_connector.cpp | 7 +++---- .../unittest/UTTest_device_manager_service_impl.cpp | 13 +++++++------ 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/test/commonunittest/UTTest_dm_discovery_manager.cpp b/test/commonunittest/UTTest_dm_discovery_manager.cpp index 0f52e28ed..5aa726f57 100644 --- a/test/commonunittest/UTTest_dm_discovery_manager.cpp +++ b/test/commonunittest/UTTest_dm_discovery_manager.cpp @@ -135,7 +135,7 @@ HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_003, testing::ext::TestSiz std::queue emptyQueue; discoveryMgr_->discoveryQueue_ = emptyQueue; int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - ASSERT_EQ(ret, SOFTBUS_INVALID_PARAM); + ASSERT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeInfo.subscribeId); } @@ -174,7 +174,7 @@ HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_005, testing::ext::TestSiz std::queue emptyQueue; discoveryMgr_->discoveryQueue_ = emptyQueue; int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - ASSERT_EQ(ret, SOFTBUS_IPC_ERR); + ASSERT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); } @@ -203,7 +203,7 @@ HWTEST_F(DmDiscoveryManagerTest, StopDeviceDiscovery_002, testing::ext::TestSize std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; int32_t ret = discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** diff --git a/test/commonunittest/UTTest_dm_publish_manager.cpp b/test/commonunittest/UTTest_dm_publish_manager.cpp index 1eef1fff1..70ec4cb32 100644 --- a/test/commonunittest/UTTest_dm_publish_manager.cpp +++ b/test/commonunittest/UTTest_dm_publish_manager.cpp @@ -111,7 +111,7 @@ HWTEST_F(DmPublishManagerTest, PublishDeviceDiscovery_002, testing::ext::TestSiz publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); pkgName = "com.ohos.helloworld.new"; int32_t ret = publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); - ASSERT_EQ(ret, SOFTBUS_INVALID_PARAM); + ASSERT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); publishMgr_->UnPublishDeviceDiscovery(pkgName, publishInfo.publishId); } diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 6e454e399..37f411872 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -72,7 +72,7 @@ HWTEST_F(MineSoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestS uint16_t subscribeId = 1; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->StopRefreshSoftbusLNN(subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } HWTEST_F(MineSoftbusListenerTest, OnPublishResult_001, testing::ext::TestSize.Level0) @@ -755,7 +755,7 @@ HWTEST_F(MineSoftbusListenerTest, PublishDeviceDiscovery_001, testing::ext::Test { std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->PublishDeviceDiscovery(); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } HWTEST_F(MineSoftbusListenerTest, MatchSearchDealTask_001, testing::ext::TestSize.Level0) diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 54a993956..25b2ad60a 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -207,8 +207,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0 DmSubscribeInfo dmSubscribeInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); -} + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); /** * @tc.name: StartDiscovery_002 @@ -221,7 +220,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_002, testing::ext::TestSize.Level0 uint16_t subscribeId = 0; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -249,7 +248,7 @@ HWTEST_F(SoftbusConnectorTest, PublishDiscovery_001, testing::ext::TestSize.Leve DmPublishInfo dmPublishInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->PublishDiscovery(dmPublishInfo); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 252ed1e38..f6d0e1ef2 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -831,7 +831,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_001, testing::ext::T uint16_t subscribeId = 0; std::string filterOptions; int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -865,7 +865,8 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_003, testing::ext::T deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); +} } /** @@ -914,7 +915,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StopDeviceDiscovery_002, testing::ext::Te deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -946,7 +947,7 @@ HWTEST_F(DeviceManagerServiceImplTest, PublishDeviceDiscovery_002, testing::ext: deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->PublishDeviceDiscovery(pkgName, publishInfo); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -978,7 +979,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnPublishDeviceDiscovery_002, testing::ex deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -1028,7 +1029,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetUdidHashByNetWorkId_003, testing::ext: deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->GetUdidHashByNetWorkId(networkId, deviceId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** -- Gitee From 4b212e2bd33e4e6a401119d75ff8118b2b425c5e Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 23 Sep 2024 16:44:39 +0800 Subject: [PATCH 234/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9device=5Fmanager?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E7=9A=84UT=E5=A4=B1=E8=B4=A5=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=5F20240923?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_discovery_manager.cpp | 2 +- test/softbusunittest/UTTest_softbus_connector.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_discovery_manager.cpp b/test/commonunittest/UTTest_dm_discovery_manager.cpp index 5aa726f57..895b74e2e 100644 --- a/test/commonunittest/UTTest_dm_discovery_manager.cpp +++ b/test/commonunittest/UTTest_dm_discovery_manager.cpp @@ -135,7 +135,7 @@ HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_003, testing::ext::TestSiz std::queue emptyQueue; discoveryMgr_->discoveryQueue_ = emptyQueue; int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - ASSERT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + ASSERT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeInfo.subscribeId); } diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 25b2ad60a..c47e3fd53 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -208,7 +208,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0 std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); - +} /** * @tc.name: StartDiscovery_002 * @tc.desc: get StartDiscovery to wrong branch and return SOFTBUS_IPC_ERR -- Gitee From 6e32b5fb43543ec2a52accdb490f1338c3cc5f64 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 23 Sep 2024 18:01:03 +0800 Subject: [PATCH 235/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9device=5Fmanager?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E7=9A=84UT=E5=A4=B1=E8=B4=A5=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=5F20240923?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/softbusunittest/UTTest_softbus_connector.cpp | 4 ++-- .../unittest/UTTest_device_manager_service_impl.cpp | 13 ++++++------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index c47e3fd53..b59395912 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -207,7 +207,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0 DmSubscribeInfo dmSubscribeInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); - EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** * @tc.name: StartDiscovery_002 @@ -220,7 +220,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_002, testing::ext::TestSize.Level0 uint16_t subscribeId = 0; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index f6d0e1ef2..ce711d1d3 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -831,7 +831,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_001, testing::ext::T uint16_t subscribeId = 0; std::string filterOptions; int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -865,8 +865,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_003, testing::ext::T deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); -} + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -915,7 +914,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StopDeviceDiscovery_002, testing::ext::Te deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -947,7 +946,7 @@ HWTEST_F(DeviceManagerServiceImplTest, PublishDeviceDiscovery_002, testing::ext: deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->PublishDeviceDiscovery(pkgName, publishInfo); - EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -979,7 +978,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnPublishDeviceDiscovery_002, testing::ex deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** @@ -1029,7 +1028,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetUdidHashByNetWorkId_003, testing::ext: deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->GetUdidHashByNetWorkId(networkId, deviceId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); } /** -- Gitee From 0ffa8949d74bc813d953f835ee8c9c303d153211 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 24 Sep 2024 09:01:07 +0800 Subject: [PATCH 236/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9device=5Fmanager?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E7=9A=84UT=E5=A4=B1=E8=B4=A5=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=5F20240923?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/softbusunittest/UTTest_softbus_connector.cpp | 11 ++++++++--- test/softbusunittest/UTTest_softbus_connector.h | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index b59395912..8c467dd65 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -100,6 +100,11 @@ void SoftbusConnectorTest::TearDownTestCase() { } +bool SoftbusConnectorTest::CheckReturnResult(int ret) +{ + return ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR; +} + namespace { std::shared_ptr listener = std::make_shared(); @@ -207,7 +212,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0 DmSubscribeInfo dmSubscribeInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); - EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckReturnResult(ret)); } /** * @tc.name: StartDiscovery_002 @@ -220,7 +225,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_002, testing::ext::TestSize.Level0 uint16_t subscribeId = 0; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckReturnResult(ret)); } /** @@ -248,7 +253,7 @@ HWTEST_F(SoftbusConnectorTest, PublishDiscovery_001, testing::ext::TestSize.Leve DmPublishInfo dmPublishInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->PublishDiscovery(dmPublishInfo); - EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckReturnResult(ret)); } /** diff --git a/test/softbusunittest/UTTest_softbus_connector.h b/test/softbusunittest/UTTest_softbus_connector.h index 721ba4a71..e0c48f24b 100644 --- a/test/softbusunittest/UTTest_softbus_connector.h +++ b/test/softbusunittest/UTTest_softbus_connector.h @@ -44,6 +44,7 @@ public: static void TearDownTestCase(); void SetUp() override; void TearDown() override; + bool CheckReturnResult(int ret); }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 3fcc518b31d2457950508ee2f60c9821fb07b016 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 24 Sep 2024 11:08:46 +0800 Subject: [PATCH 237/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- utils/src/timer/dm_timer.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/src/timer/dm_timer.cpp b/utils/src/timer/dm_timer.cpp index ab1a55d59..14d87537d 100644 --- a/utils/src/timer/dm_timer.cpp +++ b/utils/src/timer/dm_timer.cpp @@ -22,7 +22,7 @@ namespace DistributedHardware { namespace { const int32_t MIN_TIME_OUT = 0; const int32_t MAX_TIME_OUT = 300; -const int64_t DELAY_TIME = 1000000L; +const int64_t MICROSECOND_TO_SECOND = 1000000L; constexpr const char* TIMER_TASK = "TimerTask"; } @@ -53,7 +53,7 @@ int32_t DmTimer::StartTimer(std::string name, int32_t timeOut, TimerCallback cal std::lock_guard locker(timerMutex_); auto taskFunc = [callback, name] () { callback(name); }; - ffrt::task_handle handle = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * DELAY_TIME)); + ffrt::task_handle handle = queue_->submit_h(taskFunc, ffrt::task_attr().delay(timeOut * MICROSECOND_TO_SECOND)); if (handle == nullptr) { LOGE("handle is nullptr."); return ERR_DM_FAILED; -- Gitee From 50c5425040eb863ef45cb594426c697a3e3ceb64 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 20 Sep 2024 21:14:52 +0800 Subject: [PATCH 238/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0stopauth=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../device_manager_ipc_interface_code.h | 1 + .../native_cpp/include/device_manager.h | 1 + .../native_cpp/include/device_manager_impl.h | 1 + .../native_cpp/src/device_manager_impl.cpp | 28 +++++++++++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 25 +++++++++++++++++ .../include/authentication/dm_auth_manager.h | 1 + .../softbus/softbus_discovery_callback.h | 8 +++++- .../include/device_manager_service_impl.h | 1 + .../device_manager_service_impl_lite.h | 1 + .../src/authentication/dm_auth_manager.cpp | 20 ++++++++++++- .../src/device_manager_service_impl.cpp | 9 ++++++ .../src/device_manager_service_impl_lite.cpp | 6 ++++ .../service/include/device_manager_service.h | 2 ++ .../include/idevice_manager_service_impl.h | 2 +- .../service/src/device_manager_service.cpp | 23 +++++++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 11 ++++++++ 16 files changed, 137 insertions(+), 3 deletions(-) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index a1dc2566c..f7829797d 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -36,6 +36,7 @@ enum DMIpcCmdInterfaceCode { UNPUBLISH_DEVICE_DISCOVER, AUTHENTICATE_DEVICE, UNAUTHENTICATE_DEVICE, + STOP_AUTHENTICATE_DEVICE, VERIFY_AUTHENTICATION, SERVER_DEVICE_STATE_NOTIFY, SERVER_DEVICE_FOUND, diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index a5d154f10..20a83ae75 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -623,6 +623,7 @@ public: * @return Returns 0 if success. */ virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index b032b0589..399d38266 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -394,6 +394,7 @@ public: virtual int32_t UnRegisterDeviceScreenStatusCallback(const std::string &pkgName) override; virtual int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, int32_t &screenStatus) override; + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) override; private: DeviceManagerImpl() = default; diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 9abe58c4b..abd36f40a 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -733,6 +733,34 @@ int32_t DeviceManagerImpl::UnAuthenticateDevice(const std::string &pkgName, cons return DM_OK; } +int32_t DeviceManagerImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + if (pkgName.empty()) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "StopAuthenticateDevice", ERR_DM_INPUT_PARA_INVALID); + LOGE("StopAuthenticateDevice error: Invalid para. pkgName %{public}s", pkgName.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + int32_t ret = ipcClientProxy_->SendRequest(STOP_AUTHENTICATE_DEVICE, req, rsp); + if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "StopAuthenticateDevice", ret); + LOGE("StopAuthenticateDevice error: Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "StopAuthenticateDevice", ret); + LOGE("StopAuthenticateDevice error: Failed with ret %{public}d", ret); + return ret; + } + + LOGI("Completed"); + return DM_OK; +} + int32_t DeviceManagerImpl::RegisterDeviceManagerFaCallback(const std::string &pkgName, std::shared_ptr callback) { 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 ae7bb9402..12d8d0738 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 @@ -1422,6 +1422,31 @@ ON_IPC_READ_RESPONSE(SET_DN_POLICY, MessageParcel &reply, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(STOP_AUTHENTICATE_DEVICE, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_CMD(SERVER_CREATE_PIN_HOLDER, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 0953fe900..c9716d65a 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -503,6 +503,7 @@ public: void OnScreenLocked(); void HandleDeviceNotTrust(const std::string &udid); int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t StopAuthenticateDevice(const std::string &pkgName); private: int32_t ImportCredential(std::string &deviceId, std::string &publicKey); void GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, diff --git a/services/implementation/include/dependency/softbus/softbus_discovery_callback.h b/services/implementation/include/dependency/softbus/softbus_discovery_callback.h index 72ac4280a..6457d1a49 100644 --- a/services/implementation/include/dependency/softbus/softbus_discovery_callback.h +++ b/services/implementation/include/dependency/softbus/softbus_discovery_callback.h @@ -22,7 +22,13 @@ class ISoftbusDiscoveryCallback { public: virtual void OnDeviceFound(const std::string &pkgName, DmDeviceInfo &info, bool isOnline) = 0; virtual void OnDeviceFound(const std::string &pkgName, DmDeviceBasicInfo &info, - const int32_t range, bool isOnline) {}; + const int32_t range, bool isOnline) + { + (void)pkgName; + (void)info; + (void)range; + (void)isOnline; + }; virtual void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) = 0; virtual void OnDiscoveryFailed(const std::string &pkgName, int32_t subscribeId, int32_t failedReason) = 0; }; diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index ec8fee3d7..8fcd1502f 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -130,6 +130,7 @@ public: const std::string &udid, uint64_t &tokenId); void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + int32_t StopAuthenticateDevice(const std::string &pkgName); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index b676ba5f8..788447f84 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -136,6 +136,7 @@ public: void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); + int32_t StopAuthenticateDevice(const std::string &pkgName); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 2601101f9..d6c98287e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -297,6 +297,24 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel); } +int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + if (authRequestState_!= nullptr || authResponseContext_ != nullptr) { + if (isAuthenticateDevice_) { + LOGI("Stop previous AuthenticateDevice."); + authRequestContext_->reason = STOP_BIND; + authResponseContext_->state = authRequestState_->GetStateType(); + authRequestState_->TransitionTo(std::make_shared()); + return DM_OK; + } + } + return DM_OK; +} + int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string &localUdid, const std::string &remoteUdid, int32_t bindLevel) { @@ -1181,11 +1199,11 @@ void DmAuthManager::SrcAuthenticateFinish() authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) && authPtr_ != nullptr) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); } + usleep(USLEEP_TIME_MS); // 500ms listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, authRequestContext_->reason, authResponseContext_->state, GenerateBindResultContent()); - usleep(USLEEP_TIME_MS); // 500ms softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); authRequestContext_ = nullptr; authRequestState_ = nullptr; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 1cc214a35..dc6d1df62 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -161,6 +161,15 @@ int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgNam return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); } +int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed"); + return ERR_DM_INPUT_PARA_INVALID; + } + return authMgr_->StopAuthenticateDevice(pkgName); +} + int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) { diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 873d260d2..de163f557 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -518,6 +518,12 @@ void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) return; } +int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + (void)pkgName; + return 0; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index bc3985d65..9987dfd61 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -93,6 +93,8 @@ public: int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &networkId); + int32_t StopAuthenticateDevice(const std::string &pkgName); + int32_t BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &bindParam); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 45147e568..90e35e986 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -89,7 +89,6 @@ public: * @tc.type: FUNC */ virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; - /** * @tc.name: IDeviceManagerServiceImpl::UnBindDevice * @tc.desc: UnBindDevice Device of the device manager service impl @@ -273,6 +272,7 @@ public: virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 8889a6257..3aa541ba8 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -579,6 +579,29 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c return DM_OK; } +int32_t DeviceManagerService::StopAuthenticateDevice(const std::string &pkgName) +{ + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGE("The caller: %{public}s does not have permission to call StopAuthenticateDevice.", pkgName.c_str()); + return ERR_DM_NO_PERMISSION; + } + if (pkgName.empty()) { + LOGE("DeviceManagerService::StopAuthenticateDevice error: Invalid parameter, pkgName: %{public}s", + pkgName.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); + if (!IsDMServiceImplReady()) { + LOGE("StopAuthenticateDevice failed, instance not init or init failed."); + return ERR_DM_NOT_INIT; + } + if (dmServiceImpl_->StopAuthenticateDevice(pkgName) != DM_OK) { + LOGE("dmServiceImpl_ StopAuthenticateDevice failed."); + return ERR_DM_FAILED; + } + return DM_OK; +} + int32_t DeviceManagerService::BindDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &bindParam) { diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 2a9a435df..a3ef6cabe 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1459,6 +1459,17 @@ ON_IPC_CMD(SET_DN_POLICY, MessageParcel &data, MessageParcel &reply) return DM_OK; } +ON_IPC_CMD(STOP_AUTHENTICATE_DEVICE, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + int32_t result = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + ON_IPC_SET_REQUEST(REMOTE_DEVICE_TRUST_CHANGE, std::shared_ptr pBaseReq, MessageParcel &data) { if (pBaseReq == nullptr) { -- Gitee From 2aee422b33c2b6442772e258e73b566a9e627918 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 24 Sep 2024 17:45:05 +0800 Subject: [PATCH 239/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=5F20240924?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_anonymous.cpp | 63 +++++++++++++++++++ .../UTTest_permission_manager.cpp | 26 ++++++++ .../UTTest_softbus_publish.cpp | 8 +++ .../UTTest_device_manager_service_impl.cpp | 49 ++++++++++++++- 4 files changed, 145 insertions(+), 1 deletion(-) diff --git a/test/commonunittest/UTTest_dm_anonymous.cpp b/test/commonunittest/UTTest_dm_anonymous.cpp index c9bf7d64d..087aeb301 100644 --- a/test/commonunittest/UTTest_dm_anonymous.cpp +++ b/test/commonunittest/UTTest_dm_anonymous.cpp @@ -436,6 +436,69 @@ HWTEST_F(DmAnonymousTest, StringToInt64_001, testing::ext::TestSize.Level0) int64_t ret = StringToInt64(str, base); EXPECT_EQ(ret, 0); } + + +HWTEST_F(DmAnonymousTest, ParseMapFromJsonString_001, testing::ext::TestSize.Level0) +{ + std::string jsonStr = R"( + { + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "CRYPTOSUPPORT" : "cryptosupportTest", + "credentialType" : 1, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "hello", + "pkInfoSignature" : "world", + "pkInfo" : "pkginfo", + "peerDeviceId" : "3515656546" + } + ] + } + )"; + std::map paramMap; + nlohmann::json jsonObj = nlohmann::json::parse(jsonStr, nullptr, false); + ParseMapFromJsonString(jsonStr, paramMap); + EXPECT_GE(paramMap.size(), 0); +} + +HWTEST_F(DmAnonymousTest, ParseMapFromJsonString_002, testing::ext::TestSize.Level0) +{ + std::string jsonStr = R"( + { + "authType" : 1, + "userId" : "123", + "credentialData" : + [ + { + "CRYPTOSUPPORT" : "cryptosupportTest", + "credentialType" : 1, + "credentialId" : "104", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "hello", + "pkInfoSignature" : "world", + "pkInfo" : "pkginfo", + "peerDeviceId" : "3515656546" + } + ] + )"; + std::map paramMap; + nlohmann::json jsonObj = nlohmann::json::parse(jsonStr, nullptr, false); + ParseMapFromJsonString(jsonStr, paramMap); + EXPECT_EQ(paramMap.size(), 0); +} + +HWTEST_F(DmAnonymousTest, ParseMapFromJsonString_003, testing::ext::TestSize.Level0) +{ + std::string jsonStr = ""; + std::map paramMap; + nlohmann::json jsonObj = nlohmann::json::parse(jsonStr, nullptr, false); + ParseMapFromJsonString(jsonStr, paramMap); + EXPECT_EQ(paramMap.size(), 0); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index e3c48e8d2..8c8ef0f39 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -147,6 +147,12 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_003, testing::ex ASSERT_EQ(ret, true); } +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnAuthCode_004, testing::ext::TestSize.Level0) +{ + std::string processName = "CollaborationFwk"; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnAuthCode(processName); + ASSERT_TRUE(ret); +} /** * @tc.name: PinAuthUi::CheckProcessNameValidOnPinHolder_001 * @tc.desc: the return value is false @@ -186,6 +192,12 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_003, testing::e ASSERT_EQ(ret, true); } +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_004, testing::ext::TestSize.Level0) +{ + std::string processName = "CollaborationFwk"; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnPinHolder(processName); + ASSERT_TRUE(ret); +} /** * @tc.name: PinAuthUi::CheckSystemSA_001 * @tc.desc: the return value is false @@ -223,6 +235,20 @@ HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.Level0 ret = PermissionManager::GetInstance().CheckSystemSA(pkgName4); ASSERT_EQ(ret, true); } + +HWTEST_F(PermissionManagerTest, CheckSystemSA_101, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_FALSE(ret); +} + +HWTEST_F(PermissionManagerTest, CheckSystemSA_102, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos.dhardware"; + bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ASSERT_TRUE(ret); +} } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/softbusunittest/UTTest_softbus_publish.cpp b/test/softbusunittest/UTTest_softbus_publish.cpp index 8e4e695af..1237fe0e7 100644 --- a/test/softbusunittest/UTTest_softbus_publish.cpp +++ b/test/softbusunittest/UTTest_softbus_publish.cpp @@ -45,6 +45,14 @@ HWTEST_F(SoftbusPublishTest, PublishSoftbusLNN_001, testing::ext::TestSize.Level SoftbusPublish::OnSoftbusPublishResult(publishId, PUBLISH_LNN_SUCCESS); EXPECT_EQ(ret, ERR_DM_PUBLISH_FAILED); } + +HWTEST_F(SoftbusPublishTest, StopPublishSoftbusLNN_001, testing::ext::TestSize.Level0) +{ + SoftbusPublish spftbusPublish; + int publishId = 2; + int32_t ret = spftbusPublish.StopPublishSoftbusLNN(publishId); + EXPECT_EQ(ret, ERR_DM_STOP_PUBLISH_LNN_FAILED); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index ce711d1d3..5865aac98 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -15,7 +15,7 @@ #include "UTTest_device_manager_service_impl.h" #include "softbus_error_code.h" - +#include "common_event_support.h" namespace OHOS { namespace DistributedHardware { void DeviceManagerServiceImplTest::SetUp() @@ -257,6 +257,38 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_003, testing::ext::TestSize.L EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } +HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test_004"; + int32_t eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; + std::string event = R"({"extra": {"deviceId": "789"}})"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->deviceStateMgr_ = nullptr; + int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); +} + +HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test_005"; + int32_t eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; + std::string event = R"({"extra": {"deviceId": "789"}})"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->Initialize(listener_); + std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED; + deviceManagerServiceImpl_->ScreenCommonEventCallback(commonEventType); + int32_t remoteUserId = 1; + std::string remoteAccountHash = "45552878"; + std::string remoteUdid = "ajdakndkwj98877"; + deviceManagerServiceImpl_->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid); + int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, DM_OK); +} + /** * @tc.name: RequestCredential_001 * @tc.desc: return ERR_DM_INPUT_PARA_INVALID @@ -1454,6 +1486,21 @@ HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_102, testing::e DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); EXPECT_EQ(authForm, DmAuthForm::IDENTICAL_ACCOUNT); } + + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_103, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_POINT_TO_POINT; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::PEER_TO_PEER); +} + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::ext::TestSize.Level0) +{ + int32_t bindType = DM_ACROSS_ACCOUNT; + DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); + EXPECT_EQ(authForm, DmAuthForm::ACROSS_ACCOUNT); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From 6c64ce9a9c4d5298c6e76173f2887aa6e56856ff Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 24 Sep 2024 15:21:57 +0800 Subject: [PATCH 240/520] =?UTF-8?q?OOBE=E5=BC=82=E5=B8=B8=E5=9C=BA?= =?UTF-8?q?=E6=99=AF=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../src/authentication/dm_auth_manager.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 2601101f9..9a143273e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -856,6 +856,14 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) { LOGI("ProcessAuthRequest start."); + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { + if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } + } + if (authResponseContext_->isOnline && softbusConnector_->CheckIsOnline(remoteDeviceId_)) { authResponseContext_->isOnline = true; } else { @@ -2262,13 +2270,8 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) int32_t DmAuthManager::CheckTrustState() { - if (authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && - !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { - if (authResponseContext_->importAuthCode == Crypto::Sha256(importAuthCode_)) { - SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH); - } else { - SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); - } + if (authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH); return ALREADY_BIND; } if (authResponseContext_->isIdenticalAccount) { -- Gitee From 73dec5766977706890fb63a693cb01455b2cb879 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Tue, 24 Sep 2024 20:55:16 +0800 Subject: [PATCH 241/520] =?UTF-8?q?=E6=88=90=E5=91=98=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- services/service/include/pinholder/pin_holder.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index c6e747ee6..75d999cd9 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -83,7 +83,7 @@ private: PinHolderState sourceState_; int32_t sessionId_ = -1; bool isRemoteSupported_ = false; - std::atomic isDestroy_; + std::atomic isDestroy_ {false}; DestroyState destroyState_ = STATE_UNKNOW; }; } -- Gitee From 29c2edb20b1207f85de250037b204a5af65a9d22 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Tue, 24 Sep 2024 20:59:22 +0800 Subject: [PATCH 242/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../src/authentication/dm_auth_manager.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index d6c98287e..4a66bf380 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -303,14 +303,11 @@ int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_FAILED; } - if (authRequestState_!= nullptr || authResponseContext_ != nullptr) { - if (isAuthenticateDevice_) { - LOGI("Stop previous AuthenticateDevice."); - authRequestContext_->reason = STOP_BIND; - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestState_->TransitionTo(std::make_shared()); - return DM_OK; - } + if ((authRequestState_!= nullptr || authResponseContext_ != nullptr) && isAuthenticateDevice_) { + LOGI("Stop previous AuthenticateDevice."); + authRequestContext_->reason = STOP_BIND; + authResponseContext_->state = authRequestState_->GetStateType(); + authRequestState_->TransitionTo(std::make_shared()); } return DM_OK; } -- Gitee From 5599dcdd8ce1506cd075d2fcd4296ee0195118a2 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Tue, 24 Sep 2024 21:23:17 +0800 Subject: [PATCH 243/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../native_cpp/src/device_manager_impl.cpp | 6 +++--- .../src/dependency/softbus/softbus_connector.cpp | 12 ++++++------ .../src/device_manager_service_listener.cpp | 10 +++++----- .../service/src/softbus/softbus_listener.cpp | 16 ++++++++-------- services/softbuscache/src/dm_softbus_cache.cpp | 6 +++--- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index ad5d780fb..84ce387e5 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -187,19 +187,19 @@ void DeviceManagerImpl::ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &i } if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, - std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return; } if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, - std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index be337d049..0cb6a149d 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -372,13 +372,13 @@ void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, } if (memcpy_s(dmDeviceInfo.deviceId, sizeof(dmDeviceInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { + std::min(sizeof(dmDeviceInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); return; } if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } @@ -395,13 +395,13 @@ void SoftbusConnector::ConvertDeviceInfoToDmDevice(const DeviceInfo &deviceInfo, } if (memcpy_s(dmDeviceBasicInfo.deviceId, sizeof(dmDeviceBasicInfo.deviceId), deviceInfo.devId, - std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { + std::min(sizeof(dmDeviceBasicInfo.deviceId), sizeof(deviceInfo.devId))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceId data failed."); return; } if (memcpy_s(dmDeviceBasicInfo.deviceName, sizeof(dmDeviceBasicInfo.deviceName), deviceInfo.devName, - std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { + std::min(sizeof(dmDeviceBasicInfo.deviceName), sizeof(deviceInfo.devName))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } @@ -796,13 +796,13 @@ void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeB } if (memcpy_s(dmDeviceInfo.networkId, sizeof(dmDeviceInfo.networkId), nodeBasicInfo.networkId, - std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))) != EOK) { + std::min(sizeof(dmDeviceInfo.networkId), sizeof(nodeBasicInfo.networkId))) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } if (memcpy_s(dmDeviceInfo.deviceName, sizeof(dmDeviceInfo.deviceName), nodeBasicInfo.deviceName, - std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != EOK) { + std::min(sizeof(dmDeviceInfo.deviceName), sizeof(nodeBasicInfo.deviceName))) != EOK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index eef7ccc31..62ee556a1 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -56,19 +56,19 @@ void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std: } if (memcpy_s(deviceBasicInfo.deviceName, sizeof(deviceBasicInfo.deviceName), info.deviceName, - std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceName), sizeof(info.deviceName))) != DM_OK) { LOGE("ConvertDeviceInfoToDmDevice copy deviceName data failed."); return; } if (memcpy_s(deviceBasicInfo.networkId, sizeof(deviceBasicInfo.networkId), info.networkId, - std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.networkId), sizeof(info.networkId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); return; } if (memcpy_s(deviceBasicInfo.deviceId, sizeof(deviceBasicInfo.deviceId), info.deviceId, - std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { + std::min(sizeof(deviceBasicInfo.deviceId), sizeof(info.deviceId))) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice copy deviceId data failed."); return; } @@ -98,7 +98,7 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptr Date: Tue, 24 Sep 2024 21:38:51 +0800 Subject: [PATCH 244/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- utils/include/timer/dm_timer.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/utils/include/timer/dm_timer.h b/utils/include/timer/dm_timer.h index 86df1b2a5..0dca4459c 100644 --- a/utils/include/timer/dm_timer.h +++ b/utils/include/timer/dm_timer.h @@ -44,12 +44,12 @@ constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessi using TimerCallback = std::function; class CommonEventHandler : public AppExecFwk::EventHandler { -public: - CommonEventHandler(const std::shared_ptr &runner); - ~CommonEventHandler() override = default; + public: + CommonEventHandler(const std::shared_ptr &runner); + ~CommonEventHandler() override = default; - bool PostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); - void RemoveTask(const std::string &name); + bool PostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); + void RemoveTask(const std::string &name); }; class DmTimer { -- Gitee From 4da4d082d3e680707d60d53bdd35a59bbbdbdd49 Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Thu, 26 Sep 2024 09:43:06 +0800 Subject: [PATCH 245/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E5=8F=98=E9=87=8F=E8=87=AA=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- .../inner_kits/native_cpp/src/device_manager_impl.cpp | 6 +++--- .../implementation/src/authentication/dm_auth_manager.cpp | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index abd36f40a..5a02d5ba7 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -101,7 +101,7 @@ const uint16_t DM_IMPORT_AUTH_CODE_LENGTH = 6; const int32_t NORMAL = 0; const int32_t SYSTEM_BASIC = 1; const int32_t SYSTEM_CORE = 2; -const int32_t USLEEP_TIME_MS = 100000; // 100ms +const int32_t USLEEP_TIME_US_100000 = 100000; // 100ms uint16_t GenRandUint(uint16_t randMin, uint16_t randMax) { std::random_device randDevice; @@ -133,7 +133,7 @@ int32_t DeviceManagerImpl::InitDeviceManager(const std::string &pkgName, std::sh if (ret == DM_OK) { break; } - usleep(USLEEP_TIME_MS); + usleep(USLEEP_TIME_US_100000); retryNum++; if (retryNum == SERVICE_INIT_TRY_MAX_NUM) { DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "InitDeviceManager", ERR_DM_NOT_INIT); @@ -376,7 +376,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, } while (samgr->CheckSystemAbility(ACCESS_TOKEN_MANAGER_SERVICE_ID) == nullptr) { LOGD("Access_token SA not start."); - usleep(USLEEP_TIME_MS); + usleep(USLEEP_TIME_US_100000); } int32_t ret = CheckApiPermission(SYSTEM_CORE); if (ret != DM_OK) { diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 329831c4d..cabb11840 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -69,7 +69,7 @@ const int32_t MAX_PIN_CODE = 999999; const int32_t DM_AUTH_TYPE_MAX = 5; const int32_t DM_AUTH_TYPE_MIN = 0; const int32_t AUTH_SESSION_SIDE_SERVER = 0; -const int32_t USLEEP_TIME_MS = 500000; // 500ms +const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms const int32_t AUTH_DEVICE_TIMEOUT = 10; const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; @@ -1204,7 +1204,7 @@ void DmAuthManager::SrcAuthenticateFinish() authResponseContext_->state == AuthState::AUTH_REQUEST_FINISH) && authPtr_ != nullptr) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); } - usleep(USLEEP_TIME_MS); // 500ms + usleep(USLEEP_TIME_US_500000); // 500ms listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, authRequestContext_->reason, -- Gitee From 98d0863aea26ccd5f206c27794af646d11e2f28f Mon Sep 17 00:00:00 2001 From: liqinglin <996260657@qq.com> Date: Thu, 26 Sep 2024 10:23:22 +0800 Subject: [PATCH 246/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: liqinglin <996260657@qq.com> --- interfaces/kits/js/src/native_devicemanager_js.cpp | 1 + services/service/src/device_manager_service.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 3ab726eef..935aec6cb 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1629,6 +1629,7 @@ void DeviceManagerNapi::OnDmUiCall(const std::string ¶mJson) void DeviceManagerNapi::CallGetTrustedDeviceListStatus(napi_env env, napi_status &status, DeviceInfoListAsyncCallbackInfo *deviceInfoListAsyncCallbackInfo) { + CHECK_NULL_VOID(deviceInfoListAsyncCallbackInfo); if (deviceInfoListAsyncCallbackInfo->devList.size() > DM_MAX_DEVICE_SIZE) { LOGE("CallGetTrustedDeviceListStatus invalid devList size"); return; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0a38e973b..4c00408ec 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -926,6 +926,7 @@ bool DeviceManagerService::IsDMServiceImplReady() dmServiceImpl_ = std::shared_ptr(func()); if (dmServiceImpl_->Initialize(listener_) != DM_OK) { + dlclose(so_handle); dmServiceImpl_ = nullptr; isImplsoLoaded_ = false; return false; @@ -1168,6 +1169,7 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() dmServiceImplExt_ = std::shared_ptr(func()); if (dmServiceImplExt_->Initialize(listener_) != DM_OK) { + dlclose(so_handle); dmServiceImplExt_ = nullptr; isAdapterSoLoaded_ = false; LOGE("dm service adapter impl ext init failed."); -- Gitee From e47b4e792b05446ffab3412792786a889a2ab8ca Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 26 Sep 2024 13:09:56 +0800 Subject: [PATCH 247/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=B4=E6=97=B6?= =?UTF-8?q?=E4=BF=A1=E4=BB=BB=E5=88=A0=E9=99=A4=E5=8F=AF=E4=BF=A1=E5=85=B3?= =?UTF-8?q?=E7=B3=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../devicestate/dm_device_state_manager.h | 1 + .../src/authentication/dm_auth_manager.cpp | 2 -- .../devicestate/dm_device_state_manager.cpp | 26 +++++++++++++++---- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index fc58a3dfa..ea557f169 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -116,6 +116,7 @@ private: std::map remoteDeviceInfos_; std::map stateDeviceInfos_; std::map stateTimerInfoMap_; + std::map deviceIdMap_; std::shared_ptr timer_; std::shared_ptr hiChainConnector_; std::shared_ptr hiChainAuthConnector_; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 329831c4d..74c092e40 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -145,8 +145,6 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a if (authRequestState_ != nullptr || authResponseState_ != nullptr) { LOGE("DmAuthManager::CheckAuthParamVaild %{public}s is request authentication.", pkgName.c_str()); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_AUTH_BUSINESS_BUSY); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_AUTH_BUSINESS_BUSY, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_AUTH_BUSINESS_BUSY; } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 195eb1b67..4b3e627e2 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -224,6 +224,10 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) if ((iter.first == std::string(udidHash)) && (timer_ != nullptr)) { timer_->DeleteTimer(iter.second.timerName); stateTimerInfoMap_.erase(iter.first); + auto idIter = deviceIdMap_.find(udidHash); + if (idIter != deviceIdMap_.end()) { + deviceIdMap_.erase(idIter->first); + } break; } } @@ -236,6 +240,9 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) }; stateTimerInfoMap_[std::string(udidHash)] = stateTimer; } + if (deviceIdMap_.find(std::string(udidHash)) == deviceIdMap_.end()) { + deviceIdMap_[std::string(udidHash)] = deviceUdid; + } } void DmDeviceStateManager::StartOffLineTimer(const DmDeviceInfo &deviceInfo) @@ -269,6 +276,10 @@ void DmDeviceStateManager::DeleteOffLineTimer(std::string udidHash) timer_->DeleteTimer(iter->second.timerName); iter->second.isStart = false; stateTimerInfoMap_.erase(iter->first); + auto idIter = deviceIdMap_.find(udidHash); + if (idIter != deviceIdMap_.end()) { + deviceIdMap_.erase(idIter->first); + } } return; } @@ -278,13 +289,18 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) std::lock_guard mutexLock(timerMapMutex_); for (auto iter = stateTimerInfoMap_.begin(); iter != stateTimerInfoMap_.end(); iter++) { if (((iter->second).timerName == name) && (hiChainConnector_ != nullptr)) { - LOGI("remove hichain group with deviceId: %{public}s", GetAnonyString(iter->first).c_str()); - hiChainConnector_->DeleteTimeOutGroup((iter->first).c_str()); + auto idIter = deviceIdMap_.find(iter->first); + if (idIter == deviceIdMap_.end()) { + LOGE("remove hichain group find deviceId: %{public}s failed.", GetAnonyString(iter->first).c_str()); + break; + } + LOGI("remove hichain group with deviceId: %{public}s", GetAnonyString(idIter->second).c_str()); + hiChainConnector_->DeleteTimeOutGroup((idIter->second).c_str()); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - DeleteGroupByDP(iter->first); - uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(iter->first); + DeleteGroupByDP(idIter->second); + uint32_t res = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(idIter->second); if (res == 0) { - hiChainAuthConnector_->DeleteCredential(iter->first, + hiChainAuthConnector_->DeleteCredential(idIter->second, MultipleUserConnector::GetCurrentAccountUserID()); } #endif -- Gitee From d9a84ee283924c8605653e3197eb40988add0b6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 14:28:21 +0800 Subject: [PATCH 248/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- commondependency/src/deviceprofile_connector.cpp | 14 ++++++++------ .../relationshipsyncmgr/relationship_sync_mgr.h | 2 +- services/service/src/device_manager_service.cpp | 16 +++++++++------- .../relationship_sync_mgr.cpp | 11 +++-------- 4 files changed, 21 insertions(+), 22 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 6843b854e..c9af3d4dc 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -830,8 +830,8 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) { - LOGI("pkgName %{public}s, tokenId %{public}" PRId64", udid %{public}s.", pkgName.c_str(), - tokenId, GetAnonyString(udid).c_str()); + LOGI("pkgName %{public}s, tokenId %{public}s, udid %{public}s.", pkgName.c_str(), + GetAnonyInt32(static_cast(tokenId)).c_str(), GetAnonyString(udid).c_str()); std::vector profiles = GetAccessControlProfile(); int32_t bindLevel = INVALIED_TYPE; for (auto &item : profiles) { @@ -842,16 +842,18 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccessee().GetAccesseeDeviceId() == udid) { tokenId = item.GetAccesser().GetAccesserTokenId(); - bindLevel = item.GetBindLevel(); - LOGI("Src get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); + bindLevel = static_cast(item.GetBindLevel()); + LOGI("Src get bindLevel %{public}d, tokenid %{public}s", bindLevel, + GetAnonyInt32(static_cast(tokenId)).c_str()); continue; } if (item.GetAccessee().GetAccesseeBundleName() == pkgName && item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccesser().GetAccesserDeviceId() == udid) { tokenId = item.GetAccessee().GetAccesseeTokenId(); - bindLevel = item.GetBindLevel(); - LOGI("Sink get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); + bindLevel = static_cast(item.GetBindLevel()); + LOGI("Sink get bindLevel %{public}d, tokenid %{public}s.", bindLevel, + GetAnonyInt32(static_cast(tokenId)).c_str()); continue; } } diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index b471daaf0..10156b19d 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -50,7 +50,7 @@ struct RelationShipChangeMsg { void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; - cJSON *ToArrayJson(cJSON *msg) const; + cJSON *ToArrayJson() const; bool FromAccountLogoutPayLoad(const cJSON *payloadJson); bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 95abb67fa..02daf1805 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1693,7 +1693,7 @@ void DeviceManagerService::SendAccountLogoutBroadCast(const std::vector(userId); msg.peerUdids = peerUdids; msg.accountId = accountId; msg.accountName = accountName; @@ -1826,7 +1826,8 @@ int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(const std::string &anoyD void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, int32_t bindLevel) { - LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); + LOGI("TokenId %{public}s, bindLevel %{public}d, userId %{public}d.", + GetAnonyInt32(static_cast(tokenId)).c_str(), bindLevel, userId); if (bindLevel == DEVICE) { SendDeviceUnBindBroadCast(peerUdids, userId); return; @@ -1845,7 +1846,7 @@ void DeviceManagerService::SendDeviceUnBindBroadCast(const std::vector(userId); msg.peerUdids = peerUdids; std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); CHECK_NULL_VOID(softbusListener_); @@ -1857,7 +1858,7 @@ void DeviceManagerService::SendAppUnBindBroadCast(const std::vector { RelationShipChangeMsg msg; msg.type = RelationShipChangeType::APP_UNBIND; - msg.userId = userId; + msg.userId = static_cast(userId); msg.peerUdids = peerUdids; msg.tokenId = tokenId; std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); @@ -1870,7 +1871,7 @@ void DeviceManagerService::SendServiceUnBindBroadCast(const std::vector(userId); msg.peerUdids = peerUdids; msg.tokenId = tokenId; std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); @@ -1887,9 +1888,10 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) } RelationShipChangeMsg relationShipMsg = ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); - LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s, tokenId %{public}" PRId64"," + LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s, tokenId %{public}s," "peerUdid %{public}s, accountName %{public}s.", relationShipMsg.type, relationShipMsg.userId, - GetAnonyString(relationShipMsg.accountId).c_str(), relationShipMsg.tokenId, + GetAnonyString(relationShipMsg.accountId).c_str(), + GetAnonyInt32(static_cast(relationShipMsg.tokenId)).c_str(), GetAnonyString(relationShipMsg.peerUdid).c_str(), GetAnonyString(relationShipMsg.accountName).c_str()); if (!IsDMServiceImplReady()) { LOGE("Imp instance not init or init failed."); diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index babb96ffd..cb386f1f2 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -271,23 +271,17 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return true; } -cJSON *RelationShipChangeMsg::ToArrayJson(cJSON *msg) const +cJSON *RelationShipChangeMsg::ToArrayJson() const { - if (msg == nullptr) { - LOGE("Msg is nullptr."); - return nullptr; - } uint8_t *payload = nullptr; uint32_t len = 0; if (!this->ToBroadcastPayLoad(payload, len)) { LOGE("Get broadcast payload failed"); - cJSON_Delete(msg); return nullptr; } cJSON *arrayObj = cJSON_CreateArray(); if (arrayObj == nullptr) { LOGE("cJSON_CreateArray failed"); - cJSON_Delete(msg); return nullptr; } for (uint32_t index = 0; index < len; index++) { @@ -307,9 +301,10 @@ std::string RelationShipChangeMsg::ToJson() const return ""; } cJSON_AddNumberToObject(msg, MSG_TYPE, (uint32_t)type); - cJSON *arrayObj = ToArrayJson(msg); + cJSON *arrayObj = ToArrayJson(); if (arrayObj == nullptr) { LOGE("ArrayObj is nullptr."); + cJSON_Delete(msg); return ""; } cJSON_AddItemToObject(msg, MSG_VALUE, arrayObj); -- Gitee From fcce6b03162ef118bdfc9c1017dc6ee7937b3b59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 14:48:45 +0800 Subject: [PATCH 249/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- commondependency/src/deviceprofile_connector.cpp | 13 ++++++------- radar/src/dm_radar_helper.cpp | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index c9af3d4dc..af1a27611 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -830,8 +830,8 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) { - LOGI("pkgName %{public}s, tokenId %{public}s, udid %{public}s.", pkgName.c_str(), - GetAnonyInt32(static_cast(tokenId)).c_str(), GetAnonyString(udid).c_str()); + LOGI("pkgName %{public}s, tokenId %{public}" PRId64", udid %{public}s.", pkgName.c_str(), + tokenId, GetAnonyString(udid).c_str()); std::vector profiles = GetAccessControlProfile(); int32_t bindLevel = INVALIED_TYPE; for (auto &item : profiles) { @@ -841,8 +841,8 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s if (item.GetAccesser().GetAccesserBundleName() == pkgName && item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccessee().GetAccesseeDeviceId() == udid) { - tokenId = item.GetAccesser().GetAccesserTokenId(); - bindLevel = static_cast(item.GetBindLevel()); + tokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); + bindLevel = item.GetBindLevel(); LOGI("Src get bindLevel %{public}d, tokenid %{public}s", bindLevel, GetAnonyInt32(static_cast(tokenId)).c_str()); continue; @@ -851,9 +851,8 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccesser().GetAccesserDeviceId() == udid) { tokenId = item.GetAccessee().GetAccesseeTokenId(); - bindLevel = static_cast(item.GetBindLevel()); - LOGI("Sink get bindLevel %{public}d, tokenid %{public}s.", bindLevel, - GetAnonyInt32(static_cast(tokenId)).c_str()); + bindLevel = item.GetBindLevel(); + LOGI("Sink get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); continue; } } diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index 6446d9e04..c8dfb49b5 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -735,7 +735,7 @@ void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, int32_t res = DM_OK; std::string discoverDevList = GetDeviceInfoList(deviceInfoList); if (errCode == DM_OK) { - int32_t deviceCount = deviceInfoList.size(); + int32_t deviceCount = static_cast(deviceInfoList.size()); static std::string TrustCallerName = ""; if (deviceCount > 0 && TrustCallerName != hostName) { TrustCallerName = hostName; -- Gitee From 277ce80503436b94f5e9dd1d7cf457fdf2ec0948 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 14:50:37 +0800 Subject: [PATCH 250/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- commondependency/src/deviceprofile_connector.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index af1a27611..4092aa9c7 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -843,8 +843,7 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s item.GetAccessee().GetAccesseeDeviceId() == udid) { tokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); bindLevel = item.GetBindLevel(); - LOGI("Src get bindLevel %{public}d, tokenid %{public}s", bindLevel, - GetAnonyInt32(static_cast(tokenId)).c_str()); + LOGI("Src get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); continue; } if (item.GetAccessee().GetAccesseeBundleName() == pkgName && -- Gitee From 84d71a5b7e4168dfc33c33f33f5aba2296c987fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 15:04:18 +0800 Subject: [PATCH 251/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- commondependency/src/deviceprofile_connector.cpp | 2 +- services/service/src/device_manager_service.cpp | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 4092aa9c7..1225e0ef7 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -841,7 +841,7 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s if (item.GetAccesser().GetAccesserBundleName() == pkgName && item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccessee().GetAccesseeDeviceId() == udid) { - tokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); + tokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); bindLevel = item.GetBindLevel(); LOGI("Src get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); continue; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 02daf1805..e83cd4e57 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1826,8 +1826,7 @@ int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(const std::string &anoyD void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, int32_t bindLevel) { - LOGI("TokenId %{public}s, bindLevel %{public}d, userId %{public}d.", - GetAnonyInt32(static_cast(tokenId)).c_str(), bindLevel, userId); + LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); if (bindLevel == DEVICE) { SendDeviceUnBindBroadCast(peerUdids, userId); return; @@ -1888,10 +1887,9 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) } RelationShipChangeMsg relationShipMsg = ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); - LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s, tokenId %{public}s," + LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s," "peerUdid %{public}s, accountName %{public}s.", relationShipMsg.type, relationShipMsg.userId, GetAnonyString(relationShipMsg.accountId).c_str(), - GetAnonyInt32(static_cast(relationShipMsg.tokenId)).c_str(), GetAnonyString(relationShipMsg.peerUdid).c_str(), GetAnonyString(relationShipMsg.accountName).c_str()); if (!IsDMServiceImplReady()) { LOGE("Imp instance not init or init failed."); -- Gitee From f8ede984903b2d2e92d69cd8a5973882d43f0673 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 15:11:48 +0800 Subject: [PATCH 252/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index e83cd4e57..d688ff5bd 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1826,7 +1826,8 @@ int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(const std::string &anoyD void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, int32_t bindLevel) { - LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); + std::string tokenIdStr = std::to_string(tokenId); + LOGI("TokenId %{public}s, bindLevel %{public}d, userId %{public}d.", GetAnonyString(tokenIdStr).c_str(), bindLevel, userId); if (bindLevel == DEVICE) { SendDeviceUnBindBroadCast(peerUdids, userId); return; -- Gitee From 689a0747a560e87cf213d6de87e938984da87551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 15:18:01 +0800 Subject: [PATCH 253/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index d688ff5bd..d0c1e98c6 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1826,8 +1826,7 @@ int32_t DeviceManagerService::GetUdidHashByAnoyDeviceId(const std::string &anoyD void DeviceManagerService::SendUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId, int32_t bindLevel) { - std::string tokenIdStr = std::to_string(tokenId); - LOGI("TokenId %{public}s, bindLevel %{public}d, userId %{public}d.", GetAnonyString(tokenIdStr).c_str(), bindLevel, userId); + LOGI("TokenId %{public}" PRId64", bindLevel %{public}d, userId %{public}d.", tokenId, bindLevel, userId); if (bindLevel == DEVICE) { SendDeviceUnBindBroadCast(peerUdids, userId); return; @@ -1886,11 +1885,13 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) LOGE("Msg is empty."); return; } + + std::string tokenIdStr = std::to_string(relationShipMsg.tokenId); RelationShipChangeMsg relationShipMsg = ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); - LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s," + LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s, tokenId %{public}s," "peerUdid %{public}s, accountName %{public}s.", relationShipMsg.type, relationShipMsg.userId, - GetAnonyString(relationShipMsg.accountId).c_str(), + GetAnonyString(relationShipMsg.accountId).c_str(), GetAnonyString(tokenIdStr).c_str(), GetAnonyString(relationShipMsg.peerUdid).c_str(), GetAnonyString(relationShipMsg.accountName).c_str()); if (!IsDMServiceImplReady()) { LOGE("Imp instance not init or init failed."); -- Gitee From 3c7e950e100d65a76cb2b7322dc1c5ccef08570b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 15:41:15 +0800 Subject: [PATCH 254/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=9D=99=E6=80=81?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index e43a2889b..542ccac1a 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -614,9 +614,7 @@ int32_t SoftbusListener::RegisterSoftbusLnnOpsCbk(const std::string &pkgName, int32_t SoftbusListener::UnRegisterSoftbusLnnOpsCbk(const std::string &pkgName) { std::lock_guard lock(g_lnnCbkMapMutex); - if (lnnOpsCbkMap.find(pkgName) != lnnOpsCbkMap.end()) { - lnnOpsCbkMap.erase(pkgName); - } + lnnOpsCbkMap.erase(pkgName); return DM_OK; } -- Gitee From 8b0dda315b95376345d9a34cab9c2404e69bbdc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 26 Sep 2024 16:07:48 +0800 Subject: [PATCH 255/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9cppcode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- radar/src/dm_radar_helper.cpp | 20 +++++++++++++++---- .../service/src/device_manager_service.cpp | 3 +-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index c8dfb49b5..792ec11a6 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -769,7 +769,10 @@ void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, "DISCOVERY_DEVICE_LIST", discoverDevList, "ERROR_CODE", GetErrCode(errCode)); } - return; + if (res != DM_OK) { + LOGE("ReportGetTrustDeviceList error, res:%{public}d", res); + return; + } } void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, int32_t errCode) @@ -803,7 +806,10 @@ void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, "LOCAL_UDID", GetAnonyLocalUdid(), "ERROR_CODE", GetErrCode(errCode)); } - return; + if (res != DM_OK) { + LOGE("ReportDmBehavior error, res:%{public}d", res); + return; + } } void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, @@ -846,7 +852,10 @@ void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, "ERROR_CODE", GetErrCode(errCode)); } } - return; + if (res != DM_OK) { + LOGE("ReportGetLocalDevInfo error, res:%{public}d", res); + return; + } } void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, @@ -891,7 +900,10 @@ void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, "ERROR_CODE", GetErrCode(errCode)); } } - return; + if (res != DM_OK) { + LOGE("ReportGetDeviceInfo error, res:%{public}d", res); + return; + } } std::string DmRadarHelper::ConvertHexToString(uint16_t hex) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index d0c1e98c6..2b28f60bd 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1885,10 +1885,9 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) LOGE("Msg is empty."); return; } - - std::string tokenIdStr = std::to_string(relationShipMsg.tokenId); RelationShipChangeMsg relationShipMsg = ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); + std::string tokenIdStr = std::to_string(relationShipMsg.tokenId); LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s, tokenId %{public}s," "peerUdid %{public}s, accountName %{public}s.", relationShipMsg.type, relationShipMsg.userId, GetAnonyString(relationShipMsg.accountId).c_str(), GetAnonyString(tokenIdStr).c_str(), -- Gitee From 92b196f8a719e4495624daae1090bbb1e3acbc98 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 26 Sep 2024 17:56:24 +0800 Subject: [PATCH 256/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9map=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../devicestate/dm_device_state_manager.h | 2 +- .../devicestate/dm_device_state_manager.cpp | 20 +++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index ea557f169..8e6806ef4 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -116,7 +116,7 @@ private: std::map remoteDeviceInfos_; std::map stateDeviceInfos_; std::map stateTimerInfoMap_; - std::map deviceIdMap_; + std::map udidhash2udidMap_; std::shared_ptr timer_; std::shared_ptr hiChainConnector_; std::shared_ptr hiChainAuthConnector_; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 4b3e627e2..ad0ddca1e 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -224,9 +224,9 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) if ((iter.first == std::string(udidHash)) && (timer_ != nullptr)) { timer_->DeleteTimer(iter.second.timerName); stateTimerInfoMap_.erase(iter.first); - auto idIter = deviceIdMap_.find(udidHash); - if (idIter != deviceIdMap_.end()) { - deviceIdMap_.erase(idIter->first); + auto idIter = udidhash2udidMap_.find(udidHash); + if (idIter != udidhash2udidMap_.end()) { + udidhash2udidMap_.erase(idIter->first); } break; } @@ -240,8 +240,8 @@ void DmDeviceStateManager::RegisterOffLineTimer(const DmDeviceInfo &deviceInfo) }; stateTimerInfoMap_[std::string(udidHash)] = stateTimer; } - if (deviceIdMap_.find(std::string(udidHash)) == deviceIdMap_.end()) { - deviceIdMap_[std::string(udidHash)] = deviceUdid; + if (udidhash2udidMap_.find(std::string(udidHash)) == udidhash2udidMap_.end()) { + udidhash2udidMap_[std::string(udidHash)] = deviceUdid; } } @@ -276,9 +276,9 @@ void DmDeviceStateManager::DeleteOffLineTimer(std::string udidHash) timer_->DeleteTimer(iter->second.timerName); iter->second.isStart = false; stateTimerInfoMap_.erase(iter->first); - auto idIter = deviceIdMap_.find(udidHash); - if (idIter != deviceIdMap_.end()) { - deviceIdMap_.erase(idIter->first); + auto idIter = udidhash2udidMap_.find(udidHash); + if (idIter != udidhash2udidMap_.end()) { + udidhash2udidMap_.erase(idIter->first); } } return; @@ -289,8 +289,8 @@ void DmDeviceStateManager::DeleteTimeOutGroup(std::string name) std::lock_guard mutexLock(timerMapMutex_); for (auto iter = stateTimerInfoMap_.begin(); iter != stateTimerInfoMap_.end(); iter++) { if (((iter->second).timerName == name) && (hiChainConnector_ != nullptr)) { - auto idIter = deviceIdMap_.find(iter->first); - if (idIter == deviceIdMap_.end()) { + auto idIter = udidhash2udidMap_.find(iter->first); + if (idIter == udidhash2udidMap_.end()) { LOGE("remove hichain group find deviceId: %{public}s failed.", GetAnonyString(iter->first).c_str()); break; } -- Gitee From b0f69af17623976462e6f0163e423a2d74f3556b Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 27 Sep 2024 15:56:17 +0800 Subject: [PATCH 257/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=5F=E4=BF=AE=E6=94=B9=E8=BD=AF=E6=80=BB=E7=BA=BF=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=E6=AD=BB=E5=BE=AA=E7=8E=AF=5F=5F20240927?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../service/src/softbus/softbus_listener.cpp | 9 +++- .../UTTest_discovery_manager.cpp | 17 ++++--- .../UTTest_softbus_listener.cpp | 21 +++++--- .../UTTest_device_manager_service.cpp | 51 ++++++++++++++++--- .../UTTest_dm_publish_common_event.cpp | 11 +++- 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index ec2df0919..7bb14d247 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -54,6 +54,7 @@ constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; constexpr static uint8_t BYTE_MASK = 0x0F; constexpr static uint16_t ARRAY_DOUBLE_SIZE = 2; constexpr static uint16_t BIN_HIGH_FOUR_NUM = 4; +constexpr uint32_t SOFTBUS_MAX_RETRY_TIME = 10; static std::mutex g_deviceMapMutex; static std::mutex g_lnnCbkMapMutex; @@ -452,13 +453,17 @@ SoftbusListener::~SoftbusListener() int32_t SoftbusListener::InitSoftbusListener() { int32_t ret; - int32_t retryTimes = 0; + uint32_t retryTimes = 0; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) do { ret = RegNodeDeviceStateCb(DM_PKG_NAME, &softbusNodeStateCb_); if (ret != DM_OK) { ++retryTimes; - LOGE("[SOFTBUS]RegNodeDeviceStateCb failed with ret: %{public}d, retryTimes: %{public}d.", ret, retryTimes); + LOGE("[SOFTBUS]RegNodeDeviceStateCb failed with ret: %{public}d, retryTimes: %{public}u.", ret, retryTimes); + if (retryTimes >= SOFTBUS_MAX_RETRY_TIME) { + LOGE("[SOFTBUS]RegNodeDeviceStateCb timeout."); + break; + } usleep(SOFTBUS_CHECK_INTERVAL); } } while (ret != DM_OK); diff --git a/test/commonunittest/UTTest_discovery_manager.cpp b/test/commonunittest/UTTest_discovery_manager.cpp index 74f9f3efc..65d8cbd12 100644 --- a/test/commonunittest/UTTest_discovery_manager.cpp +++ b/test/commonunittest/UTTest_discovery_manager.cpp @@ -50,6 +50,11 @@ namespace { std::shared_ptr listener = std::make_shared(); std::shared_ptr manager = std::make_shared(softbusListener, listener); +bool checkSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR; +} + HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -67,7 +72,7 @@ HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_002, testing::ext::TestSi discoverParam.insert(std::pair("SUBSCRIBE_ID", "ohos.test")); std::map filterOptions; int32_t ret = manager->EnableDiscoveryListener(pkgName, discoverParam, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_003, testing::ext::TestSize.Level0) @@ -76,7 +81,7 @@ HWTEST_F(DiscoveryManagerTest, EnableDiscoveryListener_003, testing::ext::TestSi std::map discoverParam; std::map filterOptions; int32_t ret = manager->EnableDiscoveryListener(pkgName, discoverParam, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_001, testing::ext::TestSize.Level0) @@ -94,7 +99,7 @@ HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_002, testing::ext::TestS extraParam.insert(std::pair("META_TYPE", "ohos.test")); extraParam.insert(std::pair("SUBSCRIBE_ID", "ohos.test")); int32_t ret = manager->DisableDiscoveryListener(pkgName, extraParam); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_003, testing::ext::TestSize.Level0) @@ -102,7 +107,7 @@ HWTEST_F(DiscoveryManagerTest, DisableDiscoveryListener_003, testing::ext::TestS std::string pkgName = "pkgName"; std::map extraParam; int32_t ret = manager->DisableDiscoveryListener(pkgName, extraParam); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, StartDiscovering_001, testing::ext::TestSize.Level0) @@ -124,7 +129,7 @@ HWTEST_F(DiscoveryManagerTest, StartDiscovering_002, testing::ext::TestSize.Leve discoverParam.insert(std::pair("FILTER_OPTIONS", "ohos.test")); std::map filterOptions; int32_t ret = manager->StartDiscovering(pkgName, discoverParam, filterOptions); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, StartDiscovering_003, testing::ext::TestSize.Level0) @@ -240,7 +245,7 @@ HWTEST_F(DiscoveryManagerTest, StopDiscovering_002, testing::ext::TestSize.Level DiscoveryContext context; manager->discoveryContextMap_.emplace(pkgName, context); int32_t ret = manager->StopDiscovering(pkgName, subscribeId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(DiscoveryManagerTest, OnDeviceFound_001, testing::ext::TestSize.Level0) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 8adb18538..5e50f00b2 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -48,6 +48,11 @@ void SoftbusListenerTest::TearDownTestCase() namespace { std::shared_ptr softbusListener = std::make_shared(); +bool checkSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR; +} + /** * @tc.name: ConvertNodeBasicInfoToDmDevice_001 * @tc.desc: go to the correct case and return DM_OK @@ -219,7 +224,7 @@ HWTEST_F(SoftbusListenerTest, PublishSoftbusLNN_001, testing::ext::TestSize.Leve softbusListener = std::make_shared(); } int32_t ret = softbusListener->PublishSoftbusLNN(dmPubInfo, capability, customData); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, StopPublishSoftbusLNN_001, testing::ext::TestSize.Level0) @@ -229,7 +234,7 @@ HWTEST_F(SoftbusListenerTest, StopPublishSoftbusLNN_001, testing::ext::TestSize. softbusListener = std::make_shared(); } int32_t ret = softbusListener->StopPublishSoftbusLNN(publishId); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, RegisterSoftbusLnnOpsCbk_001, testing::ext::TestSize.Level0) @@ -272,7 +277,7 @@ HWTEST_F(SoftbusListenerTest, GetUdidByNetworkId_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetUdidByNetworkId(networkId.c_str(), udid); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, GetUuidByNetworkId_001, testing::ext::TestSize.Level0) @@ -283,7 +288,7 @@ HWTEST_F(SoftbusListenerTest, GetUuidByNetworkId_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetUuidByNetworkId(networkId.c_str(), udid); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_001, testing::ext::TestSize.Level0) @@ -541,7 +546,7 @@ HWTEST_F(SoftbusListenerTest, GetDeviceInfo_001, testing::ext::TestSize.Level0) softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetDeviceInfo(networkId, info); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Level0) @@ -551,7 +556,7 @@ HWTEST_F(SoftbusListenerTest, GetLocalDeviceInfo_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetLocalDeviceInfo(info); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, ConvertBytesToUpperCaseHexString_001, testing::ext::TestSize.Level0) @@ -700,7 +705,7 @@ HWTEST_F(SoftbusListenerTest, RefreshSoftbusLNN_001, testing::ext::TestSize.Leve softbusListener = std::make_shared(); } int32_t ret = softbusListener->RefreshSoftbusLNN(pkgName.c_str(), dmSubInfo, customData); - EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); + EXPECT_EQ(true, checkSoftbusRes(ret)); } HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize.Level0) @@ -725,7 +730,7 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener->OnDeviceTrustedChange(type, msg1, msgLen2); softbusListener->OnDeviceTrustedChange(type, msg2, msgLen2); softbusListener->SendAclChangedBroadcast(msg); - EXPECT_EQ(ret, SOFTBUS_IPC_ERR); + EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 9e104e3ab..ad6fb29da 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1502,9 +1502,21 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_001, testing::ext::TestSize.Level std::string event; std::string msg = ""; DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); - msg = "hello_openharmony"; - DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); - msg = "NETWORK_ID"; + msg = R"( + { + "authType" : 1, + "userId" : "123", + "credentialData" : + "CRYPTOSUPPORT" : "cryptosupportTest", + "credentialType" : 1, + "credentialId" : "104", + "NETWORK_ID" : "108", + "authCode" : "1234567812345678123456781234567812345678123456781234567812345678", + "serverPk" : "hello", + "pkInfoSignature" : "world", + "pkInfo" : "pkginfo", + "peerDeviceId" : "3515656546" + })"; DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); std::string commonEventType = "helloworld"; DeviceManagerService::GetInstance().isImplsoLoaded_ = false; @@ -1525,13 +1537,12 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_002, testing::ext::TestSize.Level HWTEST_F(DeviceManagerServiceTest, NotifyEvent_003, testing::ext::TestSize.Level0) { - DeletePermission(); std::string pkgName; int32_t eventId = DM_NOTIFY_EVENT_ON_PINHOLDER_EVENT; std::string event; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -2354,11 +2365,35 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSiz DeviceManagerService::GetInstance().isImplsoLoaded_ = false; bool result = DeviceManagerService::GetInstance().IsDMServiceImplReady(); EXPECT_TRUE(result); - msg = "0"; + msg = R"( + { + "type" : 0, + "userId" : 123, + "accountId" : "28776", + "tokenId" : 16, + "peerUdid" : "104", + "accountName" : "account_xiao" + })"; DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); - msg = "1"; + msg = R"( + { + "type" : 1, + "userId" : 128, + "accountId" : "28778", + "tokenId" : 17, + "peerUdid" : "108", + "accountName" : "account_li" + })"; DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); - msg = "2"; + msg = R"( + { + "type" : 2, + "userId" : 124, + "accountId" : "28779", + "tokenId" : 18, + "peerUdid" : "110", + "accountName" : "account_wang" + })"; DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); EXPECT_EQ(ret, ERR_DM_POINT_NULL); diff --git a/test/unittest/UTTest_dm_publish_common_event.cpp b/test/unittest/UTTest_dm_publish_common_event.cpp index da45aabb9..8fb6144c4 100644 --- a/test/unittest/UTTest_dm_publish_common_event.cpp +++ b/test/unittest/UTTest_dm_publish_common_event.cpp @@ -66,6 +66,13 @@ HWTEST_F(DmPublishCommonEventManagerTest, UnsubscribePublishCommonEvent_001, tes ASSERT_EQ(ret, true); } +void PublishCommonEventCallback(int32_t bluetoothState, int32_t wifiState, int32_t screenState) +{ + (void)bluetoothState; + (void)wifiState; + (void)screenState; +} + HWTEST_F(DmPublishCommonEventManagerTest, OnReceiveEvent_001, testing::ext::TestSize.Level0) { AAFwk::Want want; @@ -78,7 +85,9 @@ HWTEST_F(DmPublishCommonEventManagerTest, OnReceiveEvent_001, testing::ext::Test std::string strEvent = "test"; std::vector strEventVec; strEventVec.push_back(strEvent); - PublishEventCallback callback = nullptr; + PublishEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) { + PublishCommonEventCallback(arg1, arg2, arg3); + }; EventFwk::MatchingSkills matchingSkills; matchingSkills.AddEvent(strEvent); CommonEventSubscribeInfo subscriberInfo(matchingSkills); -- Gitee From dced0a96258ea132303a8659abccb093e752d711 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Sat, 28 Sep 2024 11:56:22 +0800 Subject: [PATCH 258/520] =?UTF-8?q?=E6=9F=A5=E8=AF=A2networkid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../device_manager_ipc_interface_code.h | 1 + .../ipc/model/ipc_get_info_by_network_req.h | 21 +++++++++++++ .../ipc/model/ipc_get_info_by_network_rsp.h | 21 +++++++++++++ .../native_cpp/include/device_manager.h | 1 + .../native_cpp/include/device_manager_impl.h | 2 ++ .../native_cpp/src/device_manager_impl.cpp | 30 +++++++++++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 22 ++++++++++++++ .../service/include/device_manager_service.h | 1 + .../include/softbus/softbus_listener.h | 1 + .../service/src/device_manager_service.cpp | 14 +++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 18 +++++++++++ .../service/src/softbus/softbus_listener.cpp | 5 ++++ .../softbuscache/include/dm_softbus_cache.h | 1 + .../softbuscache/src/dm_softbus_cache.cpp | 15 ++++++++++ 14 files changed, 153 insertions(+) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index f7829797d..f45c99b44 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -95,6 +95,7 @@ enum DMIpcCmdInterfaceCode { REMOTE_DEVICE_TRUST_CHANGE, SERVER_DEVICE_SCREEN_STATE_NOTIFY, GET_DEVICE_SCREEN_STATUS, + GET_NETWORKID_BY_UDID, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/ipc/model/ipc_get_info_by_network_req.h b/common/include/ipc/model/ipc_get_info_by_network_req.h index d3bec11aa..ea4281031 100644 --- a/common/include/ipc/model/ipc_get_info_by_network_req.h +++ b/common/include/ipc/model/ipc_get_info_by_network_req.h @@ -44,8 +44,29 @@ public: netWorkId_ = netWorkId; } + /** + * @tc.name: IpcGetInfoByNetWorkReq::GetUdid + * @tc.desc: Ipc Get Info By NetWork request Get udid + * @tc.type: FUNC + */ + const std::string GetUdid() const + { + return udid_; + } + + /** + * @tc.name: IpcGetInfoByNetWorkReq::SetUdid + * @tc.desc: Ipc Get Info By NetWork request Set udid + * @tc.type: FUNC + */ + void SetUdid(const std::string &udid) + { + udid_ = udid; + } + private: std::string netWorkId_; + std::string udid_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_get_info_by_network_rsp.h b/common/include/ipc/model/ipc_get_info_by_network_rsp.h index ed95d18d5..e121e247a 100644 --- a/common/include/ipc/model/ipc_get_info_by_network_rsp.h +++ b/common/include/ipc/model/ipc_get_info_by_network_rsp.h @@ -106,9 +106,30 @@ public: securityLevel_ = securityLevel; } + /** + * @tc.name: IpcGetInfoByNetWorkRsp::GetNetWorkId + * @tc.desc: Ipc Get Info By NetWork request Get NetWorkId + * @tc.type: FUNC + */ + const std::string GetNetWorkId() const + { + return netWorkId_; + } + + /** + * @tc.name: IpcGetInfoByNetWorkRsp::SetNetWorkId + * @tc.desc: Ipc Get Info By NetWork request Set NetWorkId + * @tc.type: FUNC + */ + void SetNetWorkId(const std::string &netWorkId) + { + netWorkId_ = netWorkId; + } + private: std::string udid_; std::string uuid_; + std::string netWorkId_; int32_t networkType_; int32_t securityLevel_; }; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 20a83ae75..d62cd9a21 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -624,6 +624,7 @@ public: */ virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; + virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 399d38266..52d0c67f2 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -395,6 +395,8 @@ public: virtual int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, int32_t &screenStatus) override; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) override; + virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, + std::string &networkId) override; private: DeviceManagerImpl() = default; diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 8fe8b340e..b0e3bb30c 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2406,5 +2406,35 @@ int32_t DeviceManagerImpl::GetDeviceScreenStatus(const std::string &pkgName, con screenStatus = rsp->GetScreenStatus(); return DM_OK; } + +int32_t DeviceManagerImpl::GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, + std::string &networkId) +{ + if (pkgName.empty() || udid.empty()) { + LOGE("DeviceManagerImpl::GetNetworkIdByUdid error: Invalid para, pkgName: %{public}s, udid: %{public}s", + pkgName.c_str(), GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGD("Start, pkgName: %{public}s", GetAnonyString(pkgName).c_str()); + + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + req->SetUdid(udid); + + int32_t ret = ipcClientProxy_->SendRequest(GET_NETWORKID_BY_UDID, req, rsp); + if (ret != DM_OK) { + LOGI("GetNetworkIdByUdid Send Request failed ret: %{public}d", ret); + return ERR_DM_IPC_SEND_REQUEST_FAILED; + } + + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("GetNetworkIdByUdid Failed with ret %{public}d", ret); + return ret; + } + networkId = rsp->GetNetWorkId(); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 6eab990f4..c2ed4d06a 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 @@ -1710,5 +1710,27 @@ ON_IPC_READ_RESPONSE(GET_DEVICE_SCREEN_STATUS, MessageParcel &reply, std::shared pRsp->SetScreenStatus(reply.ReadInt32()); return DM_OK; } + +ON_IPC_SET_REQUEST(GET_NETWORKID_BY_UDID, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + std::string udid = pReq->GetUdid(); + if (!data.WriteString(pkgName)) { + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(udid)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + std::shared_ptr pRsp = std::static_pointer_cast(pBaseRsp); + pRsp->SetErrCode(reply.ReadInt32()); + pRsp->SetNetWorkId(reply.ReadString()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 9987dfd61..1a46cc713 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -200,6 +200,7 @@ public: int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, int32_t &screenStatus); void SubscribePackageCommonEvent(); + int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index cd14f6ffd..051428588 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -98,6 +98,7 @@ public: static std::string GetHostPkgName(); void SendAclChangedBroadcast(const std::string &msg); int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); + static int32_t GetNetworkIdByUdid(const std::string &udid, std::string &networkId); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 639c9098d..d477f2647 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1957,6 +1957,20 @@ int32_t DeviceManagerService::GetDeviceScreenStatus(const std::string &pkgName, return DM_OK; } +int32_t DeviceManagerService::GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, + std::string &networkId) +{ + if (!PermissionManager::GetInstance().CheckPermission()) { + LOGE("The caller: %{public}s does not have permission to call GetNetworkIdByUdid.", pkgName.c_str()); + return ERR_DM_NO_PERMISSION; + } + if (pkgName.empty() || udid.empty()) { + LOGE("Invalid parameter, pkgName: %{public}s, udid: %{public}s", pkgName.c_str(), GetAnonyString(udid).c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + return SoftbusListener::GetNetworkIdByUdid(udid, networkId); +} + void DeviceManagerService::SubscribePackageCommonEvent() { LOGI("Start"); diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index a3ef6cabe..be34d4daf 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1553,5 +1553,23 @@ ON_IPC_CMD(GET_DEVICE_SCREEN_STATUS, MessageParcel &data, MessageParcel &reply) } return DM_OK; } + +ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + std::string udid = data.ReadString(); + std::string netWorkId; + int32_t result = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, netWorkId); + + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!reply.WriteString(netWorkId)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 421c1d60e..67ab4f7f8 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -650,6 +650,11 @@ int32_t SoftbusListener::GetUuidByNetworkId(const char *networkId, std::string & return SoftbusCache::GetInstance().GetUuidFromCache(networkId, uuid); } +int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string &networkId) +{ + return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId); +} + int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp) { GearMode mode = { diff --git a/services/softbuscache/include/dm_softbus_cache.h b/services/softbuscache/include/dm_softbus_cache.h index 028bbcf41..2d4a180eb 100644 --- a/services/softbuscache/include/dm_softbus_cache.h +++ b/services/softbuscache/include/dm_softbus_cache.h @@ -47,6 +47,7 @@ public: void UpDataLocalDevInfo(); int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid); int32_t GetUuidByUdid(const std::string &udid, std::string &uuid); + int32_t GetNetworkIdFromCache(const std::string &udid, std::string &networkId); private: int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 3eb06df90..fc16a1d53 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -408,5 +408,20 @@ int32_t SoftbusCache::GetUuidByUdid(const std::string &udid, std::string &uuid) } return ERR_DM_FAILED; } + +int32_t SoftbusCache::GetNetworkIdFromCache(const std::string &udid, std::string &networkId) +{ + LOGI("udid %{public}s.", GetAnonyString(udid).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + if (deviceInfo_.find(udid) != deviceInfo_.end()) { + networkId = deviceInfo_[udid].second.networkId; + LOGI("GetNetworkIdFromCache success networkId %{public}s, udid %{public}s.", + GetAnonyString(networkId).c_str(), GetAnonyString(udid).c_str()); + return DM_OK; + } + } + return ERR_DM_FAILED; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 3e9d9a60f5979fe7363ada49f2c831113ce7212d Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sun, 29 Sep 2024 14:56:32 +0800 Subject: [PATCH 259/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=5F=E4=BF=AE=E6=94=B9=E8=BD=AF=E6=80=BB=E7=BA=BF=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96=E6=AD=BB=E5=BE=AA=E7=8E=AF=5F=5F20240927?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- services/service/src/softbus/softbus_listener.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index df80c5904..99055d689 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -460,13 +460,9 @@ int32_t SoftbusListener::InitSoftbusListener() if (ret != DM_OK) { ++retryTimes; LOGE("[SOFTBUS]RegNodeDeviceStateCb failed with ret: %{public}d, retryTimes: %{public}u.", ret, retryTimes); - if (retryTimes >= SOFTBUS_MAX_RETRY_TIME) { - LOGE("[SOFTBUS]RegNodeDeviceStateCb timeout."); - break; - } usleep(SOFTBUS_CHECK_INTERVAL); } - } while (ret != DM_OK); + } while (ret != DM_OK && retryTimes < SOFTBUS_MAX_RETRY_TIME); #endif return InitSoftPublishLNN(); } -- Gitee From dd927c3cb8c823781e532f68cfd32be3aa058c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Sun, 29 Sep 2024 15:56:21 +0800 Subject: [PATCH 260/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9shiftLnn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/include/softbus/softbus_listener.h | 2 +- services/service/src/device_manager_service.cpp | 2 +- services/service/src/softbus/softbus_listener.cpp | 4 ++-- test/softbusunittest/UTTest_softbus_listener.cpp | 3 ++- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 051428588..cdc8643d0 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -75,7 +75,7 @@ public: int32_t GetTrustedDeviceList(std::vector &deviceInfoList); int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo); int32_t GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info); - int32_t ShiftLNNGear(bool isWakeUp); + int32_t ShiftLNNGear(bool isWakeUp, const std::string &callerId); static int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); int32_t GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel); int32_t GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index d477f2647..a2ef449be 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -295,7 +295,7 @@ int32_t DeviceManagerService::ShiftLNNGear(const std::string &pkgName, const std } if (isRefresh) { CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); - int32_t ret = softbusListener_->ShiftLNNGear(isWakeUp); + int32_t ret = softbusListener_->ShiftLNNGear(isWakeUp, callerId); if (ret != DM_OK) { LOGE("ShiftLNNGear error, failed ret: %{public}d", ret); return ret; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 67ab4f7f8..64e3bd285 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -655,14 +655,14 @@ int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId); } -int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp) +int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId) { GearMode mode = { .cycle = HIGH_FREQ_CYCLE, .duration = DEFAULT_DURATION, .wakeupFlag = isWakeUp, }; - int32_t ret = ::ShiftLNNGear(DM_PKG_NAME, DM_PKG_NAME, nullptr, &mode); + int32_t ret = ::ShiftLNNGear(DM_PKG_NAME, callerId.c_str(), nullptr, &mode); if (ret != DM_OK) { LOGE("[SOFTBUS]ShiftLNNGear error, failed ret: %{public}d", ret); return ret; diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 8adb18538..f11309068 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -112,7 +112,8 @@ HWTEST_F(SoftbusListenerTest, ShiftLNNGear_001, testing::ext::TestSize.Level0) if (softbusListener == nullptr) { softbusListener = std::make_shared(); } - EXPECT_NE(softbusListener->ShiftLNNGear(false), DM_OK); + std::string callerId = "callerId"; + EXPECT_NE(softbusListener->ShiftLNNGear(false, callerId), DM_OK); } HWTEST_F(SoftbusListenerTest, DeviceOnLine_001, testing::ext::TestSize.Level0) -- Gitee From d1741881beedda071150f32a2ead56497fd78d22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 30 Sep 2024 11:23:18 +0800 Subject: [PATCH 261/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- display/AppScope/app.json | 4 ++-- display/entry/src/main/module.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 179930d77..5462a6ca1 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000023, - "versionName": "1.0.23", + "versionCode": 1000024, + "versionName": "1.0.24", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/module.json b/display/entry/src/main/module.json index a18b0c6a7..0c27af8a5 100644 --- a/display/entry/src/main/module.json +++ b/display/entry/src/main/module.json @@ -5,7 +5,7 @@ "srcEntrance": "", "description": "$string:entry_desc", "mainElement": "MainAbility", - "deviceTypes": ["default", "tablet", "2in1", "wearable"], + "deviceTypes": ["default", "tablet", "2in1", "wearable", "car"], "deliveryWithInstall": true, "installationFree": false, "pages": "$profile:main_pages", -- Gitee From a18856e494ac232270b93dd1d04a2ef2db1f81fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 30 Sep 2024 14:31:49 +0800 Subject: [PATCH 262/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 64e3bd285..0c18b68a8 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -657,6 +657,11 @@ int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId) { + if (callerId.empty()) { + LOGE("Invalid parameter, callerId is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + LOGD("Begin for callerId = %{public}s", GetAnonyString(callerId).c_str()); GearMode mode = { .cycle = HIGH_FREQ_CYCLE, .duration = DEFAULT_DURATION, -- Gitee From 7058031ca6b367adea30f9bbbf903c5f90a802f7 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 8 Oct 2024 11:02:33 +0800 Subject: [PATCH 263/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=5F20241008?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index ad6fb29da..4dd412296 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2398,6 +2398,58 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_002, testing::ext::TestSiz int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); EXPECT_EQ(ret, ERR_DM_POINT_NULL); } + +HWTEST_F(DeviceManagerServiceTest, GetNetworkIdByUdid_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + std::string networkId = "networkIdTest_001"; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, GetNetworkIdByUdid_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string udid; + std::string networkId = "networkIdTest_002"; + int32_t ret = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetNetworkIdByUdid_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_003"; + std::string udid = "sewdwed98897"; + std::string networkId = "networkIdTest_003"; + int32_t ret = DeviceManagerService::GetInstance().GetNetworkIdByUdid(pkgName, udid, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + DeletePermission(); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); +} + +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_003, testing::ext::TestSi + +ze.Level0) +{ + std::string pkgName = "pkgName_003"; + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From b2eb71da5e2c35e14c5ff299f2affa03d0da780e Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 8 Oct 2024 11:54:34 +0800 Subject: [PATCH 264/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=5F20241008?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 4dd412296..e7344fe2a 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2442,9 +2442,7 @@ HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_002, testing::ext::Tes EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } -HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_003, testing::ext::TestSi - -ze.Level0) +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_003, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName_003"; int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); -- Gitee From 2e9c3ff7f60caad5132f2279da951bb674b199f3 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Sun, 29 Sep 2024 17:21:56 +0800 Subject: [PATCH 265/520] =?UTF-8?q?=E4=B8=8A=E4=B8=8B=E7=BA=BF=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../include/device_manager_service_listener.h | 7 +-- .../src/device_manager_service_listener.cpp | 51 +++++++++++-------- .../softbuscache/include/dm_softbus_cache.h | 1 + .../softbuscache/src/dm_softbus_cache.cpp | 15 ++++++ ...UTTest_device_manager_service_listener.cpp | 44 ++++++++-------- 5 files changed, 71 insertions(+), 47 deletions(-) diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 9bad1b561..7112ecf70 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -18,7 +18,7 @@ #include #include -#include +#include #include #include "dm_device_info.h" @@ -85,6 +85,7 @@ private: std::string ComposeOnlineKey(const std::string &pkgName, const std::string &devId); void SetDeviceScreenInfo(std::shared_ptr pReq, const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void RemoveOnlinePkgName(const DmDeviceInfo &info); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) int32_t ConvertUdidHashToAnoyAndSave(const std::string &pkgName, DmDeviceInfo &deviceInfo); int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, @@ -93,8 +94,8 @@ private: private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; - static std::mutex alreadyOnlineSetLock_; - static std::unordered_set alreadyOnlineSet_; + static std::mutex alreadyOnlinePkgNameLock_; + static std::unordered_map alreadyOnlinePkgName_; #endif }; } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 62ee556a1..326326716 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -44,9 +44,8 @@ namespace OHOS { namespace DistributedHardware { -std::mutex DeviceManagerServiceListener::alreadyOnlineSetLock_; -std::unordered_set DeviceManagerServiceListener::alreadyOnlineSet_ = {}; -const int32_t LAST_APP_ONLINE_NUMS = 8; +std::mutex DeviceManagerServiceListener::alreadyOnlinePkgNameLock_; +std::unordered_map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { @@ -123,12 +122,8 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState std::shared_ptr pRsp = std::make_shared(); std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); if (state == DEVICE_STATE_OFFLINE) { + RemoveOnlinePkgName(info); for (const auto &it : PkgNameVec) { - std::string notifyKey = ComposeOnlineKey(it, std::string(info.deviceId)); - { - std::lock_guard autoLock(alreadyOnlineSetLock_); - alreadyOnlineSet_.erase(notifyKey); - } SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } @@ -138,11 +133,11 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState std::string notifyKey = ComposeOnlineKey(it, std::string(info.deviceId)); DmDeviceState notifyState = state; { - std::lock_guard autoLock(alreadyOnlineSetLock_); - if (alreadyOnlineSet_.find(notifyKey) != alreadyOnlineSet_.end()) { + std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { notifyState = DmDeviceState::DEVICE_INFO_CHANGED; } else { - alreadyOnlineSet_.insert(notifyKey); + alreadyOnlinePkgName_[notifyKey] = info; } } SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); @@ -169,22 +164,19 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const std::string &pkgN for (const auto &it : notifyPkgnames) { std::string notifyKey = it + "_" + info.deviceId; { - std::lock_guard autoLock(alreadyOnlineSetLock_); - if (alreadyOnlineSet_.find(notifyKey) != alreadyOnlineSet_.end()) { + std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { continue; } - alreadyOnlineSet_.insert(notifyKey); + alreadyOnlinePkgName_[notifyKey] = info; } SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } if (state == DEVICE_STATE_OFFLINE) { - if (alreadyOnlineSet_.size() == LAST_APP_ONLINE_NUMS) { - { - std::lock_guard autoLock(alreadyOnlineSetLock_); - alreadyOnlineSet_.clear(); - } + if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { + RemoveOnlinePkgName(info); for (const auto &it : notifyPkgnames) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); @@ -192,9 +184,9 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const std::string &pkgN } else { std::string notifyKey = pkgName + "_" + info.deviceId; { - std::lock_guard autoLock(alreadyOnlineSetLock_); - if (alreadyOnlineSet_.find(notifyKey) != alreadyOnlineSet_.end()) { - alreadyOnlineSet_.erase(notifyKey); + std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyKey); } } SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); @@ -543,5 +535,20 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string & } } } + +void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) +{ + LOGI("udidHash: %{public}s.", GetAnonyString(info.deviceId).c_str()); + { + std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + for (auto item = alreadyOnlinePkgName_.begin(); item != alreadyOnlinePkgName_.end();) { + if (std::string(item->second.deviceId) == std::string(info.deviceId)) { + item = alreadyOnlinePkgName_.erase(item); + } else { + ++item; + } + } + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/softbuscache/include/dm_softbus_cache.h b/services/softbuscache/include/dm_softbus_cache.h index 2d4a180eb..30f88aac9 100644 --- a/services/softbuscache/include/dm_softbus_cache.h +++ b/services/softbuscache/include/dm_softbus_cache.h @@ -48,6 +48,7 @@ public: int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid); int32_t GetUuidByUdid(const std::string &udid, std::string &uuid); int32_t GetNetworkIdFromCache(const std::string &udid, std::string &networkId); + bool CheckIsOnline(const std::string &udidHash); private: int32_t GetUdidByNetworkId(const char *networkId, std::string &udid); int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid); diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index fc16a1d53..faec235e8 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -423,5 +423,20 @@ int32_t SoftbusCache::GetNetworkIdFromCache(const std::string &udid, std::string } return ERR_DM_FAILED; } + +bool SoftbusCache::CheckIsOnline(const std::string &deviceId) +{ + LOGI("deviceId %{public}s.", GetAnonyString(deviceId).c_str()); + { + std::lock_guard mutexLock(deviceInfosMutex_); + for (const auto &item : deviceInfo_) { + if (std::string(item.second.second.deviceId) == deviceId) { + LOGI("CheckIsOnline is true."); + return true; + } + } + } + return false; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index f082355c3..77a8944df 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -63,7 +63,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext .deviceTypeId = 1, }; listener_->OnDeviceStateChange(pkgName, state, info); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -84,7 +84,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext .deviceTypeId = 1, }; listener_->OnDeviceStateChange(pkgName, state, info); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -102,7 +102,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestS int32_t status = 3; int32_t reason = 2006; listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -120,7 +120,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestS int32_t status = 8; int32_t reason = 2006; listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -138,7 +138,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_003, testing::ext::TestS int32_t status = -1; int32_t reason = 2006; listener_->OnAuthResult(pkgName, deviceId, token, status, reason); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -159,7 +159,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_001, testing::ext::Test }; uint16_t subscribeId = 1; listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -176,7 +176,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoveryFailed_001, testing::ext:: uint16_t subscribeId = 1; int32_t failedReason = 1; listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -191,7 +191,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoverySuccess_001, testing::ext: std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; listener_->OnDiscoverySuccess(pkgName, subscribeId); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -208,7 +208,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_001, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 1; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -224,7 +224,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_002, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 0; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -239,7 +239,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnUiCall_001, testing::ext::TestSize. std::string pkgName = "com.ohos.helloworld"; std::string paramJson = "ahaha"; listener_->OnUiCall(pkgName, paramJson); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -254,7 +254,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: int32_t action = 1; std::string resultInfo = "resultInfo"; listener_->OnCredentialResult(pkgName, action, resultInfo); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -271,7 +271,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestS int32_t status = 1; std::string content = "content"; listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -288,7 +288,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestS int32_t status = 8; std::string content = "content"; listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -305,7 +305,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestS int32_t status = -1; std::string content = "content"; listener_->OnBindResult(pkgName, targetId, result, status, content); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -321,7 +321,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnUnbindResult_001, testing::ext::Tes int32_t result = 0; std::string content = "content"; listener_->OnUnbindResult(pkgName, targetId, result, content); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -355,7 +355,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_002, testing::ext::Test uint16_t subscribeId = 1; DmDeviceBasicInfo info; listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -371,7 +371,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext:: DmPinType pinType = static_cast(1); std::string payload = "payload"; listener_->OnPinHolderCreate(pkgName, deviceId, pinType, payload); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -386,7 +386,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext: DmPinType pinType = static_cast(1); std::string payload = "payload"; listener_->OnPinHolderDestroy(pkgName, pinType, payload); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -400,7 +400,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::Tes std::string pkgName = "com.ohos.helloworld"; int32_t result = 0; listener_->OnCreateResult(pkgName, result); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -414,7 +414,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::Te std::string pkgName = "com.ohos.helloworld"; int32_t result = 0; listener_->OnDestroyResult(pkgName, result); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } /** @@ -430,7 +430,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::T int32_t result = 0; std::string content = "content"; listener_->OnPinHolderEvent(pkgName, event, result, content); - EXPECT_EQ(listener_->alreadyOnlineSet_.empty(), false); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } } // namespace } // namespace DistributedHardware -- Gitee From 65558532c817251633728955466f243e0ddd4153 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 9 Oct 2024 11:10:21 +0800 Subject: [PATCH 266/520] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E5=9B=9E=E8=B0=83sta?= =?UTF-8?q?tus=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../inner_kits/native_cpp/src/notify/device_manager_notify.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 4bd78d805..8c01f8b90 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 @@ -823,7 +823,7 @@ void DeviceManagerNotify::OnBindResult(const std::string &pkgName, const PeerTar return; } tempCbk = iter->second; - if (result != DM_OK || status > STATUS_DM_CLOSE_PIN_INPUT_UI || status < STATUS_DM_SHOW_AUTHORIZE_UI) { + if (result != DM_OK || status < STATUS_DM_SHOW_AUTHORIZE_UI) { LOGI("notify end, result: %{public}d, status: %{public}d", result, status); bindCallback_[pkgName].erase(targetId); if (bindCallback_[pkgName].empty()) { -- Gitee From 6adedb8536a06bfdfe329e0ddb3bb094102497cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 9 Oct 2024 11:28:31 +0800 Subject: [PATCH 267/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index a2ef449be..f7b5d0ff2 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1172,6 +1172,10 @@ void DeviceManagerService::UnloadDMServiceImplSo() bool DeviceManagerService::IsDMServiceAdapterLoad() { LOGI("Start."); + if (listener_ == nullptr) { + LOGE("Dm service is not init."); + return false; + } std::lock_guard lock(isAdapterLoadLock_); if (isAdapterSoLoaded_ && (dmServiceImplExt_ != nullptr)) { return true; -- Gitee From 956e083e18e706652a06f5ce3208de353e47001b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 10 Oct 2024 10:38:26 +0800 Subject: [PATCH 268/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= 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 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 744dd597f..45d485c91 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -3112,7 +3112,10 @@ napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info inf char networkIdValue[DM_NAPI_BUF_LENGTH] = {0}; napi_get_value_string_utf8(env, argv[0], networkIdValue, networkIdLen + 1, &networkIdLen); DeviceManagerNapi *deviceManagerWrapper = nullptr; - napi_unwrap(env, thisVar, reinterpret_cast(&deviceManagerWrapper)); + if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) { + napi_create_uint32(env, ERR_DM_POINT_NULL, &result); + return result; + } auto *networkIdAsyncCallbackInfo = new NetworkIdAsyncCallbackInfo(); networkIdAsyncCallbackInfo->env = env; networkIdAsyncCallbackInfo->deviceInfo = deviceInfo; -- Gitee From b22debcc2e62b043d871eaa60e074984c990befe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 10 Oct 2024 16:32:58 +0800 Subject: [PATCH 269/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- commondependency/src/deviceprofile_connector.cpp | 2 +- .../service/src/relationshipsyncmgr/relationship_sync_mgr.cpp | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 1225e0ef7..ee5930d8c 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -850,7 +850,7 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccesser().GetAccesserDeviceId() == udid) { tokenId = item.GetAccessee().GetAccesseeTokenId(); - bindLevel = item.GetBindLevel(); + bindLevel = static_cast(item.GetBindLevel()); LOGI("Sink get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); continue; } diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index cb386f1f2..494e959a8 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -282,6 +282,9 @@ cJSON *RelationShipChangeMsg::ToArrayJson() const cJSON *arrayObj = cJSON_CreateArray(); if (arrayObj == nullptr) { LOGE("cJSON_CreateArray failed"); + if (payload != nullptr) { + delete[] payload; + } return nullptr; } for (uint32_t index = 0; index < len; index++) { -- Gitee From 4ec6832542e8316b59ca0cac22fb39a70da58d23 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 10 Oct 2024 20:08:02 +0800 Subject: [PATCH 270/520] =?UTF-8?q?=E5=8E=BB=E9=99=A4=E5=9B=9E=E8=B0=83sta?= =?UTF-8?q?tus=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../inner_kits/native_cpp/src/notify/device_manager_notify.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 8c01f8b90..1846d19fc 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 @@ -823,7 +823,7 @@ void DeviceManagerNotify::OnBindResult(const std::string &pkgName, const PeerTar return; } tempCbk = iter->second; - if (result != DM_OK || status < STATUS_DM_SHOW_AUTHORIZE_UI) { + if (result != DM_OK || status == STATUS_DM_AUTH_FINISH || status == STATUS_DM_AUTH_DEFAULT) { LOGI("notify end, result: %{public}d, status: %{public}d", result, status); bindCallback_[pkgName].erase(targetId); if (bindCallback_[pkgName].empty()) { -- Gitee From b42f7ab66645954ed6b5c6b93bde2fdacb623ed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 10 Oct 2024 21:53:48 +0800 Subject: [PATCH 271/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=B6=85=E5=A4=A7?= =?UTF-8?q?=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../kits/js/include/native_devicemanager_js.h | 1 + .../kits/js/src/native_devicemanager_js.cpp | 33 ++++++++++++++----- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index d50a45f65..496f0b47b 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -320,6 +320,7 @@ public: static void JsObjectToInt(const napi_env &env, const napi_value &object, const std::string &fieldStr, int32_t &fieldRef); static std::string JsObjectToString(const napi_env &env, const napi_value ¶m); + static bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, std::string &strValue); static int32_t JsToDmSubscribeInfo(const napi_env &env, const napi_value &object, OHOS::DistributedHardware::DmSubscribeInfo &info); static void JsToDmPublishInfo(const napi_env &env, const napi_value &object, diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 45d485c91..32670450a 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -3087,6 +3087,27 @@ void DeviceManagerNapi::DeviceInfotoJsByNetworkId(const napi_env &env, const DmD SetValueInt32(env, "deviceType", (int)nidDevInfo.deviceTypeId, result); } +bool DeviceManagerNapi::JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, std::string &strValue) +{ + napi_valuetype deviceIdType = napi_undefined; + napi_typeof(env, value, &deviceIdType); + if (!CheckArgsType(env, deviceIdType == napi_string, valueName, "string")) { + return false; + } + size_t valueLen = 0; + napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen); + if (!CheckArgsVal(env, valueLen > 0, valueName, "len == 0")) { + return false; + } + if (!CheckArgsVal(env, valueLen < DM_NAPI_BUF_LENGTH, valueName, "len >= MAXLEN")) { + return false; + } + char temp[DM_NAPI_BUF_LENGTH] = {0}; + napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + strValue = temp; + return true; +} + napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info info) { if (!IsSystemApp()) { @@ -3101,16 +3122,10 @@ napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info inf NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); NAPI_ASSERT(env, ((argc >= DM_NAPI_ARGS_ONE) && (argc <= DM_NAPI_ARGS_TWO)), "requires 1 or 2 parameter"); - napi_valuetype networkIdValueType = napi_undefined; - napi_typeof(env, argv[0], &networkIdValueType); - if (!CheckArgsType(env, networkIdValueType == napi_string, "networkId", "string")) { + std::string networkId; + if (!JsToStringAndCheck(env, argv[0], "networkId", networkId)) { return nullptr; } - size_t networkIdLen = 0; - napi_get_value_string_utf8(env, argv[0], nullptr, 0, &networkIdLen); - NAPI_ASSERT(env, networkIdLen < DM_NAPI_BUF_LENGTH, "typeLen >= MAXLEN"); - char networkIdValue[DM_NAPI_BUF_LENGTH] = {0}; - napi_get_value_string_utf8(env, argv[0], networkIdValue, networkIdLen + 1, &networkIdLen); DeviceManagerNapi *deviceManagerWrapper = nullptr; if (IsDeviceManagerNapiNull(env, thisVar, &deviceManagerWrapper)) { napi_create_uint32(env, ERR_DM_POINT_NULL, &result); @@ -3120,7 +3135,7 @@ napi_value DeviceManagerNapi::GetDeviceInfo(napi_env env, napi_callback_info inf networkIdAsyncCallbackInfo->env = env; networkIdAsyncCallbackInfo->deviceInfo = deviceInfo; networkIdAsyncCallbackInfo->bundleName = deviceManagerWrapper->bundleName_; - networkIdAsyncCallbackInfo->networkId = std::string(networkIdValue); + networkIdAsyncCallbackInfo->networkId = networkId; if (argc == DM_NAPI_ARGS_ONE) { // promise napi_deferred deferred; -- Gitee From a8bc543d043a5d6e4387c8e24aaa42647ef9f354 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 10 Oct 2024 22:20:01 +0800 Subject: [PATCH 272/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=A1=8C=E5=AE=BD?= 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 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 32670450a..d4b2aec90 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -3087,7 +3087,8 @@ void DeviceManagerNapi::DeviceInfotoJsByNetworkId(const napi_env &env, const DmD SetValueInt32(env, "deviceType", (int)nidDevInfo.deviceTypeId, result); } -bool DeviceManagerNapi::JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, std::string &strValue) +bool DeviceManagerNapi::JsToStringAndCheck(napi_env env, napi_value value, const std::string &valueName, + std::string &strValue) { napi_valuetype deviceIdType = napi_undefined; napi_typeof(env, value, &deviceIdType); -- Gitee From ead1afa184087f8b4bee1e934ca1d8b7e4a05f4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 11 Oct 2024 11:00:41 +0800 Subject: [PATCH 273/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0DM=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=E5=92=8C=E7=9B=91=E5=90=AC=E8=AE=BE=E5=A4=87=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- bundle.json | 1 + sa_profile/device_manager.cfg | 1 + .../dependency/softbus/softbus_session.cpp | 3 +- services/service/BUILD.gn | 7 + .../devicenamemgr/account_boot_listener.h | 40 +++ .../devicenamemgr/local_device_name_mgr.h | 55 ++++ .../settings_data_event_monitor.h | 43 +++ .../include/ipc/standard/ipc_server_stub.h | 5 +- .../devicenamemgr/account_boot_listener.cpp | 98 +++++++ .../devicenamemgr/local_device_name_mgr.cpp | 259 ++++++++++++++++++ .../settings_data_event_monitor.cpp | 50 ++++ .../src/ipc/standard/ipc_server_stub.cpp | 12 +- .../ipcserverstub_fuzzer/BUILD.gn | 2 + test/unittest/BUILD.gn | 16 ++ 14 files changed, 585 insertions(+), 7 deletions(-) create mode 100644 services/service/include/devicenamemgr/account_boot_listener.h create mode 100644 services/service/include/devicenamemgr/local_device_name_mgr.h create mode 100644 services/service/include/devicenamemgr/settings_data_event_monitor.h create mode 100644 services/service/src/devicenamemgr/account_boot_listener.cpp create mode 100644 services/service/src/devicenamemgr/local_device_name_mgr.cpp create mode 100644 services/service/src/devicenamemgr/settings_data_event_monitor.cpp diff --git a/bundle.json b/bundle.json index 8e193b87c..014692de8 100644 --- a/bundle.json +++ b/bundle.json @@ -36,6 +36,7 @@ "cJSON", "c_utils", "common_event_service", + "data_share", "device_auth", "device_info_manager", "dsoftbus", diff --git a/sa_profile/device_manager.cfg b/sa_profile/device_manager.cfg index 0550cd7b9..2d24a868d 100644 --- a/sa_profile/device_manager.cfg +++ b/sa_profile/device_manager.cfg @@ -26,6 +26,7 @@ "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", "ohos.permission.ENABLE_DISTRIBUTED_HARDWARE", "ohos.permission.MANAGE_LOCAL_ACCOUNTS", + "ohos.permission.MANAGE_SECURE_SETTINGS", "ohos.permission.ACCESS_BLUETOOTH", "ohos.permission.MANAGE_BLUETOOTH", "ohos.permission.MANAGE_SETTINGS", diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 30ded78bf..808872474 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -27,6 +27,7 @@ namespace OHOS { namespace DistributedHardware { std::shared_ptr SoftbusSession::sessionCallback_ = nullptr; constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; +constexpr int32_t DATA_LEN = 65535; static void OnShutdown(int32_t socket, ShutdownReason reason) { @@ -179,7 +180,7 @@ void SoftbusSession::OnSessionClosed(int sessionId) void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - if (sessionId < 0 || data == nullptr || dataLen <= 0) { + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > DATA_LEN) { LOGI("[SOFTBUS]fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); return; diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index 60a6c439a..b05125f26 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -119,6 +119,7 @@ if (defined(ohos_lite)) { include_dirs = [ "include", "include/advertise", + "include/devicenamemgr", "include/discovery", "include/ipc", "include/ipc/standard", @@ -163,6 +164,9 @@ if (defined(ohos_lite)) { "src/advertise/advertise_manager.cpp", "src/device_manager_service.cpp", "src/device_manager_service_listener.cpp", + "src/devicenamemgr/account_boot_listener.cpp", + "src/devicenamemgr/local_device_name_mgr.cpp", + "src/devicenamemgr/settings_data_event_monitor.cpp", "src/discovery/discovery_filter.cpp", "src/discovery/discovery_manager.cpp", "src/ipc/standard/ipc_cmd_parser.cpp", @@ -204,6 +208,8 @@ if (defined(ohos_lite)) { "c_utils:utils", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", "dsoftbus:softbus_client", @@ -217,6 +223,7 @@ if (defined(ohos_lite)) { "ipc:ipc_single", "openssl:libcrypto_shared", "os_account:libaccountkits", + "os_account:os_account_innerkits", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h new file mode 100644 index 000000000..d6e18ec38 --- /dev/null +++ b/services/service/include/devicenamemgr/account_boot_listener.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_ACCOUNT_BOOT_LISTENER_H +#define OHOS_ACCOUNT_BOOT_LISTENER_H +#include + +#include "local_device_name_mgr.h" +namespace OHOS { +namespace DistributedHardware { +class AccountBootListener { +public: + AccountBootListener(); + ~AccountBootListener(); + void RegisterAccountBootCb(); + void DoAccountBootProc(); +private: + /** + * @brief flag for is registered callback for account boot event + * true: has register the callback + * false: NOT register the callback + */ + std::atomic isRegAccountBootCb_; + std::shared_ptr localDeviceMgr_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_ACCOUNT_BOOT_LISTENER_H \ No newline at end of file diff --git a/services/service/include/devicenamemgr/local_device_name_mgr.h b/services/service/include/devicenamemgr/local_device_name_mgr.h new file mode 100644 index 000000000..28630fc4a --- /dev/null +++ b/services/service/include/devicenamemgr/local_device_name_mgr.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DEVICE_NAME_MGR_H +#define OHOS_DEVICE_NAME_MGR_H + +#include +#include +#include + +#include "datashare_helper.h" + +namespace OHOS { +namespace DistributedHardware { +class LocalDeviceNameMgr : public std::enable_shared_from_this { +public: + LocalDeviceNameMgr(); + virtual ~LocalDeviceNameMgr(); + int32_t QueryLocalDeviceName(); + void RegisterDeviceNameChangeCb(); + int32_t QueryLocalDisplayName(); + void RegisterDisplayNameChangeCb(); + +private: + std::shared_ptr GetDataShareHelper(); + int32_t GetDeviceNameFromDataShareHelper(std::shared_ptr dataShareHelper, + std::shared_ptr uri, const char *key, std::string &deviceName); + int32_t GetDefaultDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName); + int32_t GetUserDefinedDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName); + int32_t GetDisplayDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName); + int32_t GetActiveOsAccountIds(); +private: + std::mutex devNameMtx_; + std::string localDeviceName_; + std::string localDisplayName_; +}; +} // DistributedHardware +} // OHOS + +#endif // OHOS_DEVICE_NAME_MGR_H \ No newline at end of file diff --git a/services/service/include/devicenamemgr/settings_data_event_monitor.h b/services/service/include/devicenamemgr/settings_data_event_monitor.h new file mode 100644 index 000000000..b1be98102 --- /dev/null +++ b/services/service/include/devicenamemgr/settings_data_event_monitor.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_SETTINGS_DATA_EVENT_MONITOR_H +#define OHOS_SETTINGS_DATA_EVENT_MONITOR_H + +#include "data_ability_observer_stub.h" +#include + +#include "local_device_name_mgr.h" + +namespace OHOS { +namespace DistributedHardware { +class LocalDeviceNameMgr; +enum class SettingsDataMonitorType : int32_t { + USER_DEFINED_DEVICE_NAME_MONITOR = 0, + DISPLAY_DEVICE_NAME_MONITOR = 1 +}; + +class SettingsDataEventMonitor : public AAFwk::DataAbilityObserverStub { +public: + SettingsDataEventMonitor(std::shared_ptr localDeviceNameMgr, + SettingsDataMonitorType monitorType); + void OnChange() override; +private: + std::weak_ptr localDeviceNameMgrWPtr_; + SettingsDataMonitorType monitorType_; +}; +} // DistributedHardware +} // OHOS +#endif // OHOS_SETTINGS_DATA_EVENT_MONITOR_H \ No newline at end of file diff --git a/services/service/include/ipc/standard/ipc_server_stub.h b/services/service/include/ipc/standard/ipc_server_stub.h index 77a83b211..6c3f819f2 100644 --- a/services/service/include/ipc/standard/ipc_server_stub.h +++ b/services/service/include/ipc/standard/ipc_server_stub.h @@ -27,9 +27,11 @@ #include "ipc_req.h" #include "ipc_rsp.h" #include "iremote_stub.h" -#include "dm_single_instance.h" #include "system_ability.h" +#include "account_boot_listener.h" +#include "dm_single_instance.h" + namespace OHOS { namespace DistributedHardware { enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING }; @@ -160,6 +162,7 @@ private: mutable std::mutex listenerLock_; std::map> appRecipient_; std::map> dmListener_; + std::shared_ptr accountBootListener_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp new file mode 100644 index 000000000..3c5bd1bc7 --- /dev/null +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "account_boot_listener.h" + +#include + +#include "parameter.h" + +#include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif + +namespace OHOS { +namespace DistributedHardware { +namespace { + const char * const BOOTEVENT_ACCOUNT_READY = "bootevent.account.ready"; + const char * const ACCOUNT_BOOT_EVENT = "account_boot_event"; +} + +static void AccountBootCb(const char *key, const char *value, void *context) +{ + if (strcmp(key, BOOTEVENT_ACCOUNT_READY) != 0 || strcmp(value, "true") != 0) { + return; + } + AccountBootListener *accountBootListener = static_cast(context); + + if (accountBootListener == nullptr) { + LOGE("accountBootListener is null"); + return; + } + LOGI("Trigger"); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { accountBootListener->DoAccountBootProc(); }); +#else + std::thread dealThread([=]() { + accountBootListener->DoAccountBootProc(); + }); + int32_t ret = pthread_setname_np(dealThread.native_handle(), ACCOUNT_BOOT_EVENT); + if (ret != DM_OK) { + LOGE("dealThread setname failed."); + } + dealThread.detach(); +#endif + +} + +AccountBootListener::AccountBootListener() : isRegAccountBootCb_(false), + localDeviceMgr_(std::make_shared()) +{ + LOGI("Ctor AccountBootListener"); +} + +AccountBootListener::~AccountBootListener() +{ + LOGI("Dtor AccountBootListener"); +} + +void AccountBootListener::RegisterAccountBootCb() +{ + if (isRegAccountBootCb_) { + return; + } + LOGI("start"); + int32_t ret = WatchParameter(BOOTEVENT_ACCOUNT_READY, AccountBootCb, this); + if (ret != 0) { + LOGE("watch account boot event fail"); + } + isRegAccountBootCb_ = true; +} + +void AccountBootListener::DoAccountBootProc() +{ + LOGI("start"); + if (localDeviceMgr_ == nullptr) { + LOGE("localDeviceMgr_ is null"); + return; + } + localDeviceMgr_->RegisterDeviceNameChangeCb(); + localDeviceMgr_->RegisterDisplayNameChangeCb(); + localDeviceMgr_->QueryLocalDeviceName(); + localDeviceMgr_->QueryLocalDisplayName(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp new file mode 100644 index 000000000..58b80f376 --- /dev/null +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "local_device_name_mgr.h" + +#include "data_ability_observer_stub.h" +#include "datashare_helper.h" +#include "datashare_predicates.h" +#include "datashare_result_set.h" +#include "ohos_account_kits.h" +#include "os_account_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "uri.h" + +#include "dm_constants.h" +#include "dm_log.h" +#include "settings_data_event_monitor.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const std::string SETTINGS_DATA_BASE_URI = + "datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true"; + const std::string SETTINGS_DATA_SECURE_URI = + "datashare:///com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE_"; + constexpr const char *SETTINGS_DATA_EXT_URI = "datashare:///com.ohos.settingsdata.DataAbility"; + constexpr const char *SETTINGS_DATA_FIELD_KEYWORD = "KEYWORD"; + constexpr const char *SETTINGS_DATA_FIELD_VALUE = "VALUE"; + constexpr const char *PREDICATES_STRING = "settings.general.device_name"; + constexpr const char *USER_DEFINED_STRING = "settings.general.user_defined_device_name"; + constexpr const char *DISPLAY_DEVICE_NAME_STRING = "settings.general.display_device_name"; +} +LocalDeviceNameMgr::LocalDeviceNameMgr() : localDeviceName_(""), localDisplayName_("") +{ + LOGI("Ctor LocalDeviceNameMgr"); +} + +LocalDeviceNameMgr::~LocalDeviceNameMgr() +{ + std::lock_guard lock(devNameMtx_); + localDeviceName_ = ""; + localDisplayName_ = ""; + LOGI("Dtor LocalDeviceNameMgr"); +} + +std::shared_ptr LocalDeviceNameMgr::GetDataShareHelper() +{ + sptr saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saManager == nullptr) { + LOGE("saManager NULL"); + return nullptr; + } + + sptr remoteObject = saManager->GetSystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + if (remoteObject == nullptr) { + LOGE("remoteObject NULL"); + return nullptr; + } + return DataShare::DataShareHelper::Creator(remoteObject, SETTINGS_DATA_BASE_URI, SETTINGS_DATA_EXT_URI); +} + +int32_t LocalDeviceNameMgr::GetDeviceNameFromDataShareHelper( + std::shared_ptr dataShareHelper, std::shared_ptr uri, + const char *key, std::string &deviceName) +{ + int32_t numRows = 0; + std::string val; + std::vector columns; + columns.emplace_back(SETTINGS_DATA_FIELD_VALUE); + DataShare::DataSharePredicates predicates; + predicates.EqualTo(SETTINGS_DATA_FIELD_KEYWORD, key); + + auto resultSet = dataShareHelper->Query(*uri, predicates, columns); + if (resultSet == nullptr) { + LOGE("query fail."); + return ERR_DM_FAILED; + } + resultSet->GetRowCount(numRows); + if (numRows <= 0) { + LOGE("row zero."); + resultSet->Close(); + return ERR_DM_FAILED; + } + + int columnIndex; + resultSet->GoToFirstRow(); + resultSet->GetColumnIndex(SETTINGS_DATA_FIELD_VALUE, columnIndex); + if (resultSet->GetString(columnIndex, val) != DM_OK) { + LOGE("GetString val fail"); + resultSet->Close(); + return ERR_DM_FAILED; + } + deviceName = val; + LOGI("deviceName=%{public}s.", deviceName.c_str()); + resultSet->Close(); + return DM_OK; +} + +int32_t LocalDeviceNameMgr::GetDefaultDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName) +{ + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); + LOGI("get default deviceName"); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, PREDICATES_STRING, deviceName); +} + +int32_t LocalDeviceNameMgr::GetUserDefinedDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName) +{ + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + return ERR_DM_FAILED; + } + std::string accountIdStr = std::to_string(osAccountId); + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + + USER_DEFINED_STRING); + LOGI("get user defined deviceName, accountId=%{public}s", accountIdStr.c_str()); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, USER_DEFINED_STRING, deviceName); +} + +int32_t LocalDeviceNameMgr::GetDisplayDeviceName(std::shared_ptr dataShareHelper, + std::string &deviceName) +{ + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + return ERR_DM_FAILED; + } + std::string accountIdStr = std::to_string(osAccountId); + std::shared_ptr uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + "?Proxy=true&key=" + + DISPLAY_DEVICE_NAME_STRING); + LOGI("get user defined deviceName, accountId=%{public}s", accountIdStr.c_str()); + return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, DISPLAY_DEVICE_NAME_STRING, deviceName); +} + +int32_t LocalDeviceNameMgr::GetActiveOsAccountIds() +{ + std::vector accountId; + int32_t ret = OHOS::AccountSA::OsAccountManager::QueryActiveOsAccountIds(accountId); + if (ret != DM_OK || accountId.empty()) { + LOGE("QueryActiveOsAccountIds failed"); + return ERR_DM_FAILED; + } + LOGI("account id=%{public}d", accountId[0]); + return accountId[0]; +} + +int32_t LocalDeviceNameMgr::QueryLocalDeviceName() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return ERR_DM_FAILED; + } + std::string localDeviceName = ""; + int32_t ret = GetUserDefinedDeviceName(dataShareHelper, localDeviceName); + if (ret == DM_OK && !localDeviceName.empty()) { + std::lock_guard lock(devNameMtx_); + localDeviceName_ = localDeviceName; + dataShareHelper->Release(); + LOGI("get user defined deviceName=%{public}s", localDeviceName.c_str()); + return DM_OK; + } + ret = GetDefaultDeviceName(dataShareHelper, localDeviceName); + LOGI("get default deviceName=%{public}s", localDeviceName.c_str()); + dataShareHelper->Release(); + return DM_OK; +} + +void LocalDeviceNameMgr::RegisterDeviceNameChangeCb() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return; + } + + auto uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); + sptr settingDataObserver = + sptr(new SettingsDataEventMonitor(shared_from_this(), + SettingsDataMonitorType::USER_DEFINED_DEVICE_NAME_MONITOR)); + dataShareHelper->RegisterObserver(*uri, settingDataObserver); + + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + LOGE("Get OsAccountId error"); + return; + } + std::string accountIdStr = std::to_string(osAccountId); + uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + + "?Proxy=true&key=" + USER_DEFINED_STRING); + + dataShareHelper->RegisterObserver(*uri, settingDataObserver); + dataShareHelper->Release(); + LOGI("register device name change cb success"); +} + +int32_t LocalDeviceNameMgr::QueryLocalDisplayName() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return ERR_DM_FAILED; + } + std::string localDisplayName = ""; + int32_t ret = GetDisplayDeviceName(dataShareHelper, localDisplayName); + if (ret != DM_OK || localDisplayName.empty()) { + LOGE("get display device name failed"); + return ERR_DM_FAILED; + } + std::lock_guard lock(devNameMtx_); + localDisplayName_ = localDisplayName; + dataShareHelper->Release(); + LOGI("get display deviceName=%{public}s", localDisplayName.c_str()); + return DM_OK; +} + +void LocalDeviceNameMgr::RegisterDisplayNameChangeCb() +{ + LOGI("start"); + auto dataShareHelper = GetDataShareHelper(); + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null"); + return; + } + + int32_t osAccountId = GetActiveOsAccountIds(); + if (osAccountId == ERR_DM_FAILED) { + LOGE("Get OsAccountId error"); + return; + } + std::string accountIdStr = std::to_string(osAccountId); + auto uri = std::make_shared(SETTINGS_DATA_SECURE_URI + accountIdStr + + "?Proxy=true&key=" + DISPLAY_DEVICE_NAME_STRING); + sptr settingDataObserver = + sptr(new SettingsDataEventMonitor(shared_from_this(), + SettingsDataMonitorType::DISPLAY_DEVICE_NAME_MONITOR)); + dataShareHelper->RegisterObserver(*uri, settingDataObserver); + dataShareHelper->Release(); + LOGI("register display device name change cb success"); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/settings_data_event_monitor.cpp b/services/service/src/devicenamemgr/settings_data_event_monitor.cpp new file mode 100644 index 000000000..4dbf931a8 --- /dev/null +++ b/services/service/src/devicenamemgr/settings_data_event_monitor.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "settings_data_event_monitor.h" + +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +SettingsDataEventMonitor::SettingsDataEventMonitor(std::shared_ptr localDeviceNameMgr, + SettingsDataMonitorType monitorType) + : localDeviceNameMgrWPtr_(localDeviceNameMgr), monitorType_(monitorType) +{ + LOGI("Ctor SettingsDataEventMonitor, monitorType: %{public}d", (int32_t)monitorType); +} + +void SettingsDataEventMonitor::OnChange() +{ + if (localDeviceNameMgrWPtr_.expired()) { + LOGE("localDeviceNameMgrWPtr_ expired"); + return; + } + LOGI("Settings OnChange type: %{public}d", (int32_t)monitorType_); + std::shared_ptr localDevNameSPtr = localDeviceNameMgrWPtr_.lock(); + switch (monitorType_) { + case SettingsDataMonitorType::USER_DEFINED_DEVICE_NAME_MONITOR: + localDevNameSPtr->QueryLocalDeviceName(); + break; + case SettingsDataMonitorType::DISPLAY_DEVICE_NAME_MONITOR: + localDevNameSPtr->QueryLocalDisplayName(); + break; + default: + LOGE("unknwon monitor type"); + break; + } +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 40a4db53d..a35726888 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -15,10 +15,6 @@ #include "ipc_server_stub.h" -#include "device_manager_ipc_interface_code.h" -#include "device_manager_service.h" -#include "dm_constants.h" -#include "dm_log.h" #include "if_system_ability_manager.h" #include "ipc_cmd_register.h" #include "ipc_skeleton.h" @@ -31,9 +27,13 @@ #include "mem_mgr_client.h" #include "mem_mgr_proxy.h" #endif // SUPPORT_MEMMGR + #include "string_ex.h" #include "system_ability_definition.h" - +#include "device_manager_ipc_interface_code.h" +#include "device_manager_service.h" +#include "dm_constants.h" +#include "dm_log.h" #include "multiple_user_connector.h" namespace OHOS { @@ -47,6 +47,7 @@ IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGE { registerToService_ = false; state_ = ServiceRunningState::STATE_NOT_START; + accountBootListener_ = std::make_shared(); } void IpcServerStub::OnStart() @@ -85,6 +86,7 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; + accountBootListener_->RegisterAccountBootCb(); return; } diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn b/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn index 8f0bce417..0b4a67247 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn @@ -69,6 +69,8 @@ ohos_fuzztest("IpcServerStubFuzzTest") { external_deps = [ "c_utils:utils", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "ipc:ipc_core", "ipc:ipc_single", diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 3641dee2f..9c17755be 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -93,6 +93,8 @@ ohos_unittest("UTTest_pin_auth") { deps = [ ":device_manager_test_common" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -174,6 +176,8 @@ ohos_unittest("UTTest_ipc_cmd_parser_service") { deps = [ ":device_manager_test_common" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -672,6 +676,8 @@ ohos_unittest("UTTest_ipc_server_client_proxy") { deps = [ ":device_manager_test_common" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -692,6 +698,8 @@ ohos_unittest("UTTest_ipc_server_listener") { deps = [ ":device_manager_test_common" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "googletest:gmock", ] @@ -708,6 +716,8 @@ ohos_unittest("UTTest_ipc_server_stub") { deps = [ ":device_manager_test_common" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -1150,6 +1160,8 @@ ohos_unittest("UTTest_discovery_filter") { deps = [ ":device_manager_test_common" ] external_deps = [ + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -1368,6 +1380,8 @@ ohos_unittest("UTTest_dm_publish_manager") { external_deps = [ "cJSON:cjson", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -1472,6 +1486,8 @@ ohos_static_library("device_manager_test_common") { "c_utils:utils", "common_event_service:cesfwk_core", "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", -- Gitee From 74fb1070147b109c54da7d4b3fc89637abf33936 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 11 Oct 2024 11:35:49 +0800 Subject: [PATCH 274/520] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=9A=84=E7=A9=BA=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/src/devicenamemgr/account_boot_listener.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 3c5bd1bc7..860a7d198 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -55,7 +55,6 @@ static void AccountBootCb(const char *key, const char *value, void *context) } dealThread.detach(); #endif - } AccountBootListener::AccountBootListener() : isRegAccountBootCb_(false), -- Gitee From 77688075b1cf8d618af45e81dbba40047cef9a7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sat, 12 Oct 2024 11:57:17 +0800 Subject: [PATCH 275/520] =?UTF-8?q?=E6=9E=84=E5=BB=BA=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/src/devicenamemgr/account_boot_listener.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 860a7d198..60b56ad35 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -28,7 +28,9 @@ namespace OHOS { namespace DistributedHardware { namespace { const char * const BOOTEVENT_ACCOUNT_READY = "bootevent.account.ready"; +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) const char * const ACCOUNT_BOOT_EVENT = "account_boot_event"; +#endif } static void AccountBootCb(const char *key, const char *value, void *context) -- Gitee From 8b08e88db52d7d465c8f478cf31f5e42f218e04c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 14 Oct 2024 11:39:39 +0800 Subject: [PATCH 276/520] =?UTF-8?q?=E8=AE=A4=E8=AF=81=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E7=9B=91=E5=90=AC=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../device_manager_ipc_interface_code.h | 1 + .../native_cpp/include/device_manager.h | 3 ++ .../include/device_manager_callback.h | 8 ++++ .../native_cpp/include/device_manager_impl.h | 3 ++ .../include/notify/device_manager_notify.h | 6 +++ .../native_cpp/src/device_manager_impl.cpp | 23 ++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 10 +++++ .../src/notify/device_manager_notify.cpp | 44 +++++++++++++++++++ .../include/device_manager_service_impl.h | 1 + .../device_manager_service_impl_lite.h | 1 + .../src/device_manager_service_impl.cpp | 5 +++ .../src/device_manager_service_impl_lite.cpp | 6 +++ .../service/include/device_manager_service.h | 1 + .../include/idevice_manager_service_impl.h | 1 + .../include/softbus/softbus_listener.h | 2 + .../service/src/device_manager_service.cpp | 7 +++ .../src/device_manager_service_listener.cpp | 19 ++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 30 +++++++++++++ .../service/src/softbus/softbus_listener.cpp | 22 ++++++++++ 19 files changed, 193 insertions(+) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index f45c99b44..5a4fd679b 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -96,6 +96,7 @@ enum DMIpcCmdInterfaceCode { SERVER_DEVICE_SCREEN_STATE_NOTIFY, GET_DEVICE_SCREEN_STATUS, GET_NETWORKID_BY_UDID, + SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index d62cd9a21..28b9c99bf 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -625,6 +625,9 @@ public: virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) = 0; + virtual int32_t RegisterImportCredentialStatusCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterImportCredentialStatusCallback(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index c8e4ee522..e4cd94380 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -148,6 +148,14 @@ public: } virtual void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) = 0; }; + +class ImportCredentialStatusCallback { +public: + virtual ~ImportCredentialStatusCallback() + { + } + virtual void OnImportCredentialStatus(int32_t result) = 0; +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_CALLBACK_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 52d0c67f2..8144e50d9 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -397,6 +397,9 @@ public: virtual int32_t StopAuthenticateDevice(const std::string &pkgName) override; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) override; + virtual int32_t RegisterImportCredentialStatusCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterImportCredentialStatusCallback(const std::string &pkgName) override; private: DeviceManagerImpl() = default; 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 4721c7fc9..b6c9c8860 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 @@ -70,6 +70,9 @@ public: void RegisterDeviceScreenStatusCallback(const std::string &pkgName, std::shared_ptr callback); void UnRegisterDeviceScreenStatusCallback(const std::string &pkgName); + void RegisterImportCredentialStatusCallback(const std::string &pkgName, + std::shared_ptr callback); + void UnRegisterImportCredentialStatusCallback(const std::string &pkgName); public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -116,6 +119,8 @@ public: void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); + void OnImportCredentialStatus(const std::string &pkgName, int32_t result); + private: #if !defined(__LITEOS_M__) std::mutex lock_; @@ -133,6 +138,7 @@ private: std::map> pinHolderCallback_; std::map> devTrustChangeCallback_; std::map> deviceScreenStatusCallback_; + std::map> importCredentialStatusCallback_; std::mutex bindLock_; }; } // namespace DistributedHardware 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 b0e3bb30c..27ff5e0f3 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2436,5 +2436,28 @@ int32_t DeviceManagerImpl::GetNetworkIdByUdid(const std::string &pkgName, const networkId = rsp->GetNetWorkId(); return DM_OK; } + +int32_t DeviceManagerImpl::RegisterImportCredentialStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().RegisterImportCredentialStatusCallback(pkgName, callback); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterImportCredentialStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().UnRegisterImportCredentialStatusCallback(pkgName); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 c2ed4d06a..3d08455de 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 @@ -1732,5 +1732,15 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt pRsp->SetNetWorkId(reply.ReadString()); return DM_OK; } + +ON_IPC_CMD(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + int32_t result = data.ReadInt32(); + DeviceManagerNotify::GetInstance().OnImportCredentialStatus(pkgName, result); + + reply.WriteInt32(DM_OK); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 1846d19fc..3a94d7967 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 @@ -1147,5 +1147,49 @@ void DeviceManagerNotify::OnDeviceScreenStatus(const std::string &pkgName, const } tempCbk->OnDeviceScreenStatus(deviceInfo); } + +void RegisterImportCredentialStatusCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + importCredentialStatusCallback_[pkgName] = callback; +} + +void UnRegisterImportCredentialStatusCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::lock_guard autoLock(lock_); + importCredentialStatusCallback_.erase(pkgName); +} + +void OnImportCredentialStatus(const std::string &pkgName, int32_t result) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + LOGI("In, pkgName:%{public}s", pkgName.c_str()); + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + if (importCredentialStatusCallback_.find(pkgName) == importCredentialStatusCallback_.end()) { + LOGE("error, import credential status not register."); + return; + } + tempCbk = importCredentialStatusCallback_[pkgName]; + } + if (tempCbk == nullptr) { + LOGE("error, registered import credential status callback is nullptr."); + return; + } + tempCbk->OnImportCredentialStatus(result); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 8fcd1502f..d965b561d 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -131,6 +131,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); + void HandleImportCredentialStatus(int32_t result); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 788447f84..168b64f7f 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -137,6 +137,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); + void HandleImportCredentialStatus(int32_t result); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index dc6d1df62..f9e310a22 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -853,6 +853,11 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } +void DeviceManagerServiceImpl::HandleImportCredentialStatus(int32_t result) +{ + +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index de163f557..c546cec43 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -524,6 +524,12 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } +void DeviceManagerServiceImpl::HandleImportCredentialStatus(int32_t result) +{ + (void)result; + return; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 1a46cc713..e1900a6ee 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,6 +201,7 @@ public: int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); + void HandleImportCredentialStatus(int32_t result); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 90e35e986..7890bdbc2 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -273,6 +273,7 @@ public: virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; + virtual void HandleImportCredentialStatus(int32_t result) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index cdc8643d0..0c7c04748 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -58,6 +58,8 @@ public: static void DeviceTrustedChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); + static void OnImportCredentialStatus(int32_t result); + static void ImportCredentialStatus(int32_t result); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f7b5d0ff2..bbe56eae6 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1993,5 +1993,12 @@ void DeviceManagerService::SubscribePackageCommonEvent() } #endif } + +void DeviceManagerService::HandleImportCredentialStatus(int32_t result) +{ + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleImportCredentialStatus(result); + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 62ee556a1..ce0bd5057 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -543,5 +543,24 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string & } } } + +void DeviceManagerServiceListener::OnImportCredentialStateChange(const std::string &pkgName, int32_t result) +{ + LOGI("In, pkgName = %{public}s", pkgName.c_str()); + if (pkgName == std::string(DM_PKG_NAME)) { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + pReq->SetResult(result); + std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); + for (const auto &it : PkgNameVec) { + pReq->SetPkgName(it); + ipcServerListener_.SendRequest(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, pReq, pRsp); + } + } else { + pReq->SetPkgName(pkgName); + pReq->SetResult(result); + ipcServerListener_.SendRequest(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, pReq, pRsp); + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index be34d4daf..a389fdd8e 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1571,5 +1571,35 @@ ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) } return DM_OK; } + +ON_IPC_SET_REQUEST(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t result = pReq->GetResult(); + + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 356f5d2f5..5107c334b 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -48,6 +48,7 @@ constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; +constexpr const char* IMPORT_CREDENTIAL_STATUS = "importCredentialStatus"; #endif constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; @@ -66,6 +67,7 @@ static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; static std::mutex g_lockDeviceIdSet; static std::mutex g_lockDevScreenStatusChange; +static std::mutex g_lockImportCredentialStatus; static std::map>>> discoveredDeviceMap; static std::map> lnnOpsCbkMap; @@ -162,6 +164,26 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); } +void SoftbusListener::ImportCredentialStatus(int32_t result) +{ + std::lock_guard lock(g_lockImportCredentialStatus); + DeviceManagerService::GetInstance().HandleImportCredentialStatus(result); +} + +void SoftbusListener::OnImportCredentialStatus(int32_t result) +{ + LOGI("received import credential status callback from softbus."); + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { ImportCredentialStatus(result); }); + #else + std::thread importStatusChange([=]() { ImportCredentialStatus(result); }); + if (pthread_setname_np(importStatusChange.native_handle(), IMPORT_CREDENTIAL_STATUS) != DM_OK) { + LOGE("devImportStatusChange setname failed."); + } + importStatusChange.detach(); + #endif +} + void SoftbusListener::OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status) { LOGI("received device screen status change callback from softbus."); -- Gitee From cbaea4d50ea1faa78c4eedb3d9ee5cc9249302ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 14 Oct 2024 17:03:32 +0800 Subject: [PATCH 277/520] =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../ipc_notify_candidaterestrict_status_req.h | 94 +++++++++++++++++++ .../native_cpp/include/device_manager.h | 6 +- .../include/device_manager_callback.h | 7 +- .../native_cpp/include/device_manager_impl.h | 6 +- .../include/notify/device_manager_notify.h | 11 ++- .../native_cpp/src/device_manager_impl.cpp | 10 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 6 +- .../src/notify/device_manager_notify.cpp | 21 +++-- .../include/device_manager_service_impl.h | 3 +- .../device_manager_service_impl_lite.h | 3 +- .../devicestate/dm_device_state_manager.h | 2 + .../src/device_manager_service_impl.cpp | 6 +- .../src/device_manager_service_impl_lite.cpp | 3 +- .../devicestate/dm_device_state_manager.cpp | 17 ++++ .../service/include/device_manager_service.h | 3 +- .../include/device_manager_service_listener.h | 2 + .../include/idevice_manager_service_impl.h | 3 +- .../idevice_manager_service_listener.h | 8 ++ .../include/softbus/softbus_listener.h | 4 +- .../service/src/device_manager_service.cpp | 5 +- .../src/device_manager_service_listener.cpp | 14 ++- .../src/ipc/standard/ipc_cmd_parser.cpp | 20 +++- .../service/src/softbus/softbus_listener.cpp | 16 ++-- 23 files changed, 212 insertions(+), 58 deletions(-) create mode 100644 common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h diff --git a/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h b/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h new file mode 100644 index 000000000..6360402f0 --- /dev/null +++ b/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_NOTIFY_CANDIDATERESTRICT_STATUS_REQ_H +#define OHOS_DM_IPC_NOTIFY_CANDIDATERESTRICT_STATUS_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcNotifyCandidateRestrictStatusReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyCandidateRestrictStatusReq); + +public: + /** + * @tc.name: IpcNotifyCandidateRestrictStatusReq::GetPublishId + * @tc.desc: Get deviceId of the Ipc Notify Candidate Restrict Status Request + * @tc.type: FUNC + */ + std::string GetDeviceId() const + { + return deviceId_; + } + + /** + * @tc.name: IpcNotifyCandidateRestrictStatusReq::SetPublishId + * @tc.desc: Set deviceId of the Ipc Notify Candidate Restrict Status Request + * @tc.type: FUNC + */ + void SetDeviceId(const std::string &deviceId) + { + deviceId_ = deviceId; + } + + /** + * @tc.name: IpcNotifyCandidateRestrictStatusReq::GetResult + * @tc.desc: Get DeviceType of the Ipc Notify Candidate Restrict Status Request + * @tc.type: FUNC + */ + uint16_t GetDeviceTypeId() const + { + return deviceTypeId_; + } + + /** + * @tc.name: IpcNotifyCandidateRestrictStatusReq::SetResult + * @tc.desc: Set DeviceType of the Ipc Notify Candidate Restrict Status Request + * @tc.type: FUNC + */ + void SetDeviceTypeId(uint16_t deviceTypeId) + { + deviceTypeId_ = deviceTypeId; + } + + /** + * @tc.name: IpcNotifyCandidateRestrictStatusReq::GetErrCode + * @tc.desc: Get ErrCode of the Ipc Notify Candidate Restrict Status Request + * @tc.type: FUNC + */ + int32_t GetErrCode() const + { + return errcode_; + } + + /** + * @tc.name: IpcNotifyCandidateRestrictStatusReq::SetErrCode + * @tc.desc: Set ErrCode of the Ipc Notify Candidate Restrict Status Request + * @tc.type: FUNC + */ + void SetErrCode(int32_t errcode) + { + errcode_ = errcode; + } + +private: + std::string deviceId_; + uint16_t deviceTypeId_ = 0; + int32_t errcode_ = 0 +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_NOTIFY_CANDIDATERESTRICT_STATUS_REQ_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 28b9c99bf..956d59bd4 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -625,9 +625,9 @@ public: virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) = 0; - virtual int32_t RegisterImportCredentialStatusCallback(const std::string &pkgName, - std::shared_ptr callback) = 0; - virtual int32_t UnRegisterImportCredentialStatusCallback(const std::string &pkgName) = 0; + virtual int32_t RegisterCandidateRestrictStatusCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index e4cd94380..904ecde11 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -149,12 +149,13 @@ public: virtual void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) = 0; }; -class ImportCredentialStatusCallback { +class CandidateRestrictStatusCallback { public: - virtual ~ImportCredentialStatusCallback() + virtual ~CandidateRestrictStatusCallback() { } - virtual void OnImportCredentialStatus(int32_t result) = 0; + virtual void OnCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 8144e50d9..c0ce27860 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -397,9 +397,9 @@ public: virtual int32_t StopAuthenticateDevice(const std::string &pkgName) override; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) override; - virtual int32_t RegisterImportCredentialStatusCallback(const std::string &pkgName, - std::shared_ptr callback) override; - virtual int32_t UnRegisterImportCredentialStatusCallback(const std::string &pkgName) override; + virtual int32_t RegisterCandidateRestrictStatusCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) override; private: DeviceManagerImpl() = default; 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 b6c9c8860..9c227802b 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 @@ -70,9 +70,9 @@ public: void RegisterDeviceScreenStatusCallback(const std::string &pkgName, std::shared_ptr callback); void UnRegisterDeviceScreenStatusCallback(const std::string &pkgName); - void RegisterImportCredentialStatusCallback(const std::string &pkgName, - std::shared_ptr callback); - void UnRegisterImportCredentialStatusCallback(const std::string &pkgName); + void RegisterCandidateRestrictStatusCallback(const std::string &pkgName, + std::shared_ptr callback); + void UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName); public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -119,7 +119,8 @@ public: void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnImportCredentialStatus(const std::string &pkgName, int32_t result); + void OnCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode); private: #if !defined(__LITEOS_M__) @@ -138,7 +139,7 @@ private: std::map> pinHolderCallback_; std::map> devTrustChangeCallback_; std::map> deviceScreenStatusCallback_; - std::map> importCredentialStatusCallback_; + std::map> candidateRestrictStatusCallback_; std::mutex bindLock_; }; } // namespace DistributedHardware 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 27ff5e0f3..e636c4498 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2437,25 +2437,25 @@ int32_t DeviceManagerImpl::GetNetworkIdByUdid(const std::string &pkgName, const return DM_OK; } -int32_t DeviceManagerImpl::RegisterImportCredentialStatusCallback(const std::string &pkgName, - std::shared_ptr callback) +int32_t DeviceManagerImpl::RegisterCandidateRestrictStatusCallback(const std::string &pkgName, + std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - DeviceManagerNotify::GetInstance().RegisterImportCredentialStatusCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterCandidateRestrictStatusCallback(pkgName, callback); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } -int32_t DeviceManagerImpl::UnRegisterImportCredentialStatusCallback(const std::string &pkgName) +int32_t DeviceManagerImpl::UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - DeviceManagerNotify::GetInstance().UnRegisterImportCredentialStatusCallback(pkgName); + DeviceManagerNotify::GetInstance().UnRegisterCandidateRestrictStatusCallback(pkgName); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index 3d08455de..8f24fa8b9 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 @@ -1736,8 +1736,10 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt ON_IPC_CMD(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); - int32_t result = data.ReadInt32(); - DeviceManagerNotify::GetInstance().OnImportCredentialStatus(pkgName, result); + std::string deviceId = data.ReadString(); + uint16_t deviceTypeId = data.ReadUint16(); + int32_t errCode = data.ReadInt32(); + DeviceManagerNotify::GetInstance().OnCandidateRestrictStatus(pkgName, deviceId, deviceTypeId, errCode); reply.WriteInt32(DM_OK); return DM_OK; diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 3a94d7967..1cc7198c7 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 @@ -1148,48 +1148,49 @@ void DeviceManagerNotify::OnDeviceScreenStatus(const std::string &pkgName, const tempCbk->OnDeviceScreenStatus(deviceInfo); } -void RegisterImportCredentialStatusCallback(const std::string &pkgName, - std::shared_ptr callback) +void RegisterCandidateRestrictStatusCallback(const std::string &pkgName, + std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); return; } std::lock_guard autoLock(lock_); - importCredentialStatusCallback_[pkgName] = callback; + candidateRestrictStatusCallback_[pkgName] = callback; } -void UnRegisterImportCredentialStatusCallback(const std::string &pkgName) +void UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } std::lock_guard autoLock(lock_); - importCredentialStatusCallback_.erase(pkgName); + candidateRestrictStatusCallback_.erase(pkgName); } -void OnImportCredentialStatus(const std::string &pkgName, int32_t result) +void OnCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } LOGI("In, pkgName:%{public}s", pkgName.c_str()); - std::shared_ptr tempCbk; + std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); - if (importCredentialStatusCallback_.find(pkgName) == importCredentialStatusCallback_.end()) { + if (candidateRestrictStatusCallback_.find(pkgName) == candidateRestrictStatusCallback_.end()) { LOGE("error, import credential status not register."); return; } - tempCbk = importCredentialStatusCallback_[pkgName]; + tempCbk = candidateRestrictStatusCallback_[pkgName]; } if (tempCbk == nullptr) { LOGE("error, registered import credential status callback is nullptr."); return; } - tempCbk->OnImportCredentialStatus(result); + tempCbk->OnCandidateRestrictStatus(deviceId, deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index d965b561d..c06cd04a8 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -131,7 +131,8 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HandleImportCredentialStatus(int32_t result); + void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 168b64f7f..afab36b3d 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -137,7 +137,8 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HandleImportCredentialStatus(int32_t result); + void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 8e6806ef4..bb8ab0da4 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,6 +96,8 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); + private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index f9e310a22..4976e8262 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -853,9 +853,11 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } -void DeviceManagerServiceImpl::HandleImportCredentialStatus(int32_t result) +void DeviceManagerServiceImpl::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) { - + CHECK_NULL_VOID(deviceStateMgr_); + deviceStateMgr_-> } extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index c546cec43..f52355b18 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -524,7 +524,8 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } -void DeviceManagerServiceImpl::HandleImportCredentialStatus(int32_t result) +void DeviceManagerServiceImpl::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) { (void)result; return; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index ad0ddca1e..f49c98948 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -526,5 +526,22 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) } softbusConnector_->ClearPkgName(); } + +void DmDeviceStateManager::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) +{ + if (softbusConnector_ == nullptr || listener_ == nullptr) { + LOGE("Failed, callback_ptr is null."); + return; + } + std::vector pkgName = softbusConnector_->GetPkgName(); + if (pkgName.size() == 0) { + listener_->OnHandleCandidateRestrictStatus(std::string(DM_PKG_NAME), deviceId, deviceTypeId, errcode); + } else { + for (auto item : pkgName) { + listener_->OnHandleCandidateRestrictStatus(item, deviceId, deviceTypeId, errcode); + } + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index e1900a6ee..e3e5557b6 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,7 +201,8 @@ public: int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); - void HandleImportCredentialStatus(int32_t result); + void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 9bad1b561..6dd9176ff 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -73,6 +73,8 @@ public: const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; + void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode); private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 7890bdbc2..633654913 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -273,7 +273,8 @@ public: virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; - virtual void HandleImportCredentialStatus(int32_t result) = 0; + virtual void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 57ab0697f..2d84314d3 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -158,6 +158,14 @@ public: * @tc.type: FUNC */ virtual void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) = 0; + + /** + * @tc.name: IDeviceManagerServiceListener::OnHandleCandidateRestrictStatus + * @tc.desc: Device Screen State Change of the DeviceManager Service Listener + * @tc.type: FUNC + */ + virtual void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 0c7c04748..26802ef21 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -58,8 +58,8 @@ public: static void DeviceTrustedChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); - static void OnImportCredentialStatus(int32_t result); - static void ImportCredentialStatus(int32_t result); + static void OnCandidateRestrict(char *deviceId, uint16_t deviceTypeId, int32_t errcode); + static void CandidateRestrict(std::string deviceId, uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index bbe56eae6..e42ae4059 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1994,10 +1994,11 @@ void DeviceManagerService::SubscribePackageCommonEvent() #endif } -void DeviceManagerService::HandleImportCredentialStatus(int32_t result) +void DeviceManagerService::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) { if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleImportCredentialStatus(result); + dmServiceImpl_->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); } } } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index ce0bd5057..6b588e22d 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -26,6 +26,7 @@ #include "ipc_destroy_pin_holder_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" +#include "ipc_notify_candidaterestrict_status_req.h" #include "ipc_notify_credential_req.h" #include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_device_found_req.h" @@ -544,13 +545,17 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string & } } -void DeviceManagerServiceListener::OnImportCredentialStateChange(const std::string &pkgName, int32_t result) +void DeviceManagerServiceListener::OnHandleCandidateRestrictStatus(const std::string &pkgName, + const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { LOGI("In, pkgName = %{public}s", pkgName.c_str()); + std::shared_ptr pReq = + std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + pReq->SetDeviceId(deviceId); + pReq->SetDeviceTypeId(deviceTypeId); + pReq->SetErrCode(errcode); if (pkgName == std::string(DM_PKG_NAME)) { - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - pReq->SetResult(result); std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); for (const auto &it : PkgNameVec) { pReq->SetPkgName(it); @@ -558,7 +563,6 @@ void DeviceManagerServiceListener::OnImportCredentialStateChange(const std::stri } } else { pReq->SetPkgName(pkgName); - pReq->SetResult(result); ipcServerListener_.SendRequest(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, pReq, pRsp); } } diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index a389fdd8e..de8f21b4c 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -33,6 +33,7 @@ #include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" +#include "ipc_notify_candidaterestrict_status_req.h" #include "ipc_notify_credential_req.h" #include "ipc_notify_device_found_req.h" #include "ipc_notify_device_discovery_req.h" @@ -1577,16 +1578,27 @@ ON_IPC_SET_REQUEST(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); - int32_t result = pReq->GetResult(); + std::string deviceId = pReq->GetDeviceId(); + uint16_t deviceTypeId = pReq->GetDeviceTypeId(); + int32_t errCode = pReq->GetErrCode(); if (!data.WriteString(pkgName)) { LOGE("write pkgName failed"); return ERR_DM_IPC_WRITE_FAILED; } - if (!data.WriteInt32(result)) { - LOGE("write result failed"); + if (!data.WriteString(deviceId)) { + LOGE("write deviceId failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteUint16(deviceTypeId)) { + LOGE("write deviceTypeId failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(errCode)) { + LOGE("write errCode failed"); return ERR_DM_IPC_WRITE_FAILED; } return DM_OK; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 5107c334b..eb764ee10 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -67,7 +67,7 @@ static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; static std::mutex g_lockDeviceIdSet; static std::mutex g_lockDevScreenStatusChange; -static std::mutex g_lockImportCredentialStatus; +static std::mutex g_lockCandidateRestrictStatus; static std::map>>> discoveredDeviceMap; static std::map> lnnOpsCbkMap; @@ -121,6 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, + .onCandidateRestrict = SoftbusListener::OnCandidateRestrict, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -164,19 +165,20 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); } -void SoftbusListener::ImportCredentialStatus(int32_t result) +void SoftbusListener::CandidateRestrict(std::string deviceId, uint16_t deviceTypeId, int32_t errcode) { - std::lock_guard lock(g_lockImportCredentialStatus); - DeviceManagerService::GetInstance().HandleImportCredentialStatus(result); + std::lock_guard lock(g_lockCandidateRestrictStatus); + DeviceManagerService::GetInstance().HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); } -void SoftbusListener::OnImportCredentialStatus(int32_t result) +void SoftbusListener::OnCandidateRestrict(char *deviceId, uint16_t deviceTypeId, int32_t errcode) { LOGI("received import credential status callback from softbus."); + std::string deviceIdStr(deviceId); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { ImportCredentialStatus(result); }); + ffrt::submit([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); #else - std::thread importStatusChange([=]() { ImportCredentialStatus(result); }); + std::thread importStatusChange([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); if (pthread_setname_np(importStatusChange.native_handle(), IMPORT_CREDENTIAL_STATUS) != DM_OK) { LOGE("devImportStatusChange setname failed."); } -- Gitee From cb258e0402566ddd3f33b3d87e0470a3658c8943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 14 Oct 2024 17:12:46 +0800 Subject: [PATCH 278/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../inner_kits/native_cpp/include/device_manager_callback.h | 2 +- .../native_cpp/include/notify/device_manager_notify.h | 2 +- services/service/include/device_manager_service_listener.h | 4 ++-- services/service/include/idevice_manager_service_listener.h | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) 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 904ecde11..7bf34045b 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -155,7 +155,7 @@ public: { } virtual void OnCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) = 0; + int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 9c227802b..2a311e267 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 @@ -120,7 +120,7 @@ public: int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); void OnCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + int32_t errcode); private: #if !defined(__LITEOS_M__) diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 6dd9176ff..f58eb0e52 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -73,8 +73,8 @@ public: const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; - void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, + uint16_t deviceTypeId, int32_t errcode); private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 2d84314d3..36c2cdb01 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -161,11 +161,11 @@ public: /** * @tc.name: IDeviceManagerServiceListener::OnHandleCandidateRestrictStatus - * @tc.desc: Device Screen State Change of the DeviceManager Service Listener + * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) = 0; + virtual void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, + uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From a9ca29dce47eb6435330f577714866accb7e3103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 14 Oct 2024 19:12:42 +0800 Subject: [PATCH 279/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../ipc/model/ipc_notify_candidaterestrict_status_req.h | 2 +- .../native_cpp/src/notify/device_manager_notify.cpp | 8 ++++---- .../implementation/src/device_manager_service_impl.cpp | 2 +- .../service/include/device_manager_service_listener.h | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h b/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h index 6360402f0..ab91e0c49 100644 --- a/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h +++ b/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h @@ -87,7 +87,7 @@ public: private: std::string deviceId_; uint16_t deviceTypeId_ = 0; - int32_t errcode_ = 0 + int32_t errcode_ = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 1cc7198c7..4a3a9e470 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 @@ -1148,7 +1148,7 @@ void DeviceManagerNotify::OnDeviceScreenStatus(const std::string &pkgName, const tempCbk->OnDeviceScreenStatus(deviceInfo); } -void RegisterCandidateRestrictStatusCallback(const std::string &pkgName, +void DeviceManagerNotify::RegisterCandidateRestrictStatusCallback(const std::string &pkgName, std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { @@ -1159,7 +1159,7 @@ void RegisterCandidateRestrictStatusCallback(const std::string &pkgName, candidateRestrictStatusCallback_[pkgName] = callback; } -void UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) +void DeviceManagerNotify::UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -1169,8 +1169,8 @@ void UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) candidateRestrictStatusCallback_.erase(pkgName); } -void OnCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) +void DeviceManagerNotify::OnCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, + uint16_t deviceTypeId, int32_t errcode) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 4976e8262..1dd8bc6f9 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -857,7 +857,7 @@ void DeviceManagerServiceImpl::HandleCandidateRestrictStatus(const std::string & int32_t errcode) { CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_-> + deviceStateMgr_->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); } extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index f58eb0e52..a4ed0f5aa 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -74,7 +74,7 @@ public: void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode); + uint16_t deviceTypeId, int32_t errcode) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); -- Gitee From 5f2510a53ab4a8ce59e0f7d98f76406ae0d236bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 14 Oct 2024 19:55:19 +0800 Subject: [PATCH 280/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0UT=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/device_manager_service_impl_lite.cpp | 4 +- .../service/src/softbus/softbus_listener.cpp | 3 ++ .../UTTest_softbus_listener.cpp | 7 ++++ test/unittest/UTTest_device_manager_impl.h | 9 +++++ .../UTTest_device_manager_impl_three.cpp | 39 +++++++++++++++++++ 5 files changed, 61 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index f52355b18..6c19072c9 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -527,7 +527,9 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN void DeviceManagerServiceImpl::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { - (void)result; + (void)deviceId; + (void)deviceTypeId; + (void)errcode; return; } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index eb764ee10..8c124eff4 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -174,6 +174,9 @@ void SoftbusListener::CandidateRestrict(std::string deviceId, uint16_t deviceTyp void SoftbusListener::OnCandidateRestrict(char *deviceId, uint16_t deviceTypeId, int32_t errcode) { LOGI("received import credential status callback from softbus."); + if (deviceId == nullptr) { + return; + } std::string deviceIdStr(deviceId); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 6d33dca16..378a5bac9 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -731,6 +731,13 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener->OnDeviceTrustedChange(type, msg1, msgLen2); softbusListener->OnDeviceTrustedChange(type, msg2, msgLen2); softbusListener->SendAclChangedBroadcast(msg); + char deviceId[DM_MAX_DEVICE_ID_LEN] = "XXX"; + uint16_t deviceTypeId = 0; + int32_t errcode = -1; + softbusListener->OnCandidateRestrict(deviceId, deviceTypeId, errcode); + std::string deviceId2 = "1234567890"; + deviceTypeId = 0xA2F; + softbusListener->CandidateRestrict(deviceId2, deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index a5c007ca5..a40965ea3 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -117,6 +117,15 @@ public: } void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override {} }; + +class CandidateRestrictStatusCallbackTest : public CandidateRestrictStatusCallback { +public: + virtual ~CandidateRestrictStatusCallbackTest() + { + } + void OnCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + int32_t errcode) override {} +}; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 2bf9fb04c..7854577ca 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1344,6 +1344,45 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_003, testing::ext::TestSiz ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); DeviceManager::GetInstance().UnInitDeviceManager(packName); } + + +HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterCandidateRestrictStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.candidateRestrict01"; + std::shared_ptr callback = nullptr; + int32_t ret = DeviceManager::GetInstance().RegisterCandidateRestrictStatusCallback(packName, callback); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_003, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.scandidateRestrict02"; + std::shared_ptr callback = std::make_shared(); + int32_t ret = DeviceManager::GetInstance().RegisterCandidateRestrictStatusCallback(packName, callback); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterCandidateRestrictStatusCallback_001, testing::ext::TestSize.Level0) +{ + std::string packName = "com.ohos.candidateRestrict03"; + int32_t ret = DeviceManager::GetInstance().UnRegisterCandidateRestrictStatusCallback(packName); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerImplTest, UnRegisterCandidateRestrictStatusCallback_002, testing::ext::TestSize.Level0) +{ + std::string packName = ""; + int32_t ret = DeviceManager::GetInstance().UnRegisterCandidateRestrictStatusCallback(packName); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From f20602f9413d0fdee0c307f8d43bee2d93228e19 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Mon, 14 Oct 2024 20:48:59 +0800 Subject: [PATCH 281/520] =?UTF-8?q?=E9=97=AE=E9=A2=98=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- interfaces/kits/js/src/native_devicemanager_js.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index d4b2aec90..037ef23a5 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -853,6 +853,7 @@ void DeviceManagerNapi::OnCredentialResult(int32_t &action, const std::string &c if (handler != nullptr) { napi_call_function(env_, nullptr, handler, DM_NAPI_ARGS_ONE, &result, &callResult); napi_delete_reference(env_, creAsyncCallbackInfo_.callback); + creAsyncCallbackInfo_.callback = nullptr; } else { LOGE("handler is nullptr"); } -- Gitee From 116977fd7a1412efbcf7dd82a1c5611da13e8074 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 15 Oct 2024 10:41:02 +0800 Subject: [PATCH 282/520] =?UTF-8?q?=E8=A7=A3=E5=86=B2=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/device_manager_service_listener.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 6b588e22d..a1166e9fa 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -545,6 +545,21 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string & } } +void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) +{ + LOGI("udidHash: %{public}s.", GetAnonyString(info.deviceId).c_str()); + { + std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + for (auto item = alreadyOnlinePkgName_.begin(); item != alreadyOnlinePkgName_.end();) { + if (std::string(item->second.deviceId) == std::string(info.deviceId)) { + item = alreadyOnlinePkgName_.erase(item); + } else { + ++item; + } + } + } +} + void DeviceManagerServiceListener::OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { -- Gitee From 028e9195d13364068024ccf4e9573783588c2ad6 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 15 Oct 2024 11:44:04 +0800 Subject: [PATCH 283/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_softbus_listener.cpp | 57 +++++++++++++++++++ .../UTTest_device_manager_service.cpp | 8 +-- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 6d33dca16..6da2a59ac 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -117,10 +117,46 @@ HWTEST_F(SoftbusListenerTest, ShiftLNNGear_001, testing::ext::TestSize.Level0) if (softbusListener == nullptr) { softbusListener = std::make_shared(); } + NodeBasicInfo *info = nullptr; + softbusListener->OnSoftbusDeviceOnline(info); std::string callerId = "callerId"; EXPECT_NE(softbusListener->ShiftLNNGear(false, callerId), DM_OK); } +HWTEST_F(SoftbusListenerTest, ShiftLNNGear_001, testing::ext::TestSize.Level0) +{ + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + std::string callerId; + EXPECT_EQ(softbusListener->ShiftLNNGear(false, callerId), ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(SoftbusListenerTest, ConvertScreenStatusToDmDevice_001, testing::ext::TestSize.Level0) +{ + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + NodeBasicInfo nodeInfo = { + .networkId = "123456", + .deviceName = "123456", + .deviceTypeId = 1 + }; + int32_t devScreenStatus = 1; + DmDeviceInfo devInfo = { + .deviceId = {"45688"}, + .deviceName = {"device_001"}, + .deviceTypeId = 12, + .extraData = "dsasweadwe65164654", + .networkId = {"8885665"}, + .networkType = 21, + .range = 2, + .authForm = DmAuthForm::ACROSS_ACCOUNT + }; + int ret = softbusListener->ConvertScreenStatusToDmDevice(nodeInfo, devScreenStatus, devInfo); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + HWTEST_F(SoftbusListenerTest, DeviceOnLine_001, testing::ext::TestSize.Level0) { DmDeviceInfo deviceInf = { @@ -705,6 +741,27 @@ HWTEST_F(SoftbusListenerTest, RefreshSoftbusLNN_001, testing::ext::TestSize.Leve if (softbusListener == nullptr) { softbusListener = std::make_shared(); } + NodeStatusType type = NodeStatusType::TYPE_SCREEN_STATUS; + NodeStatus *status = nullptr; + softbusListener->OnDeviceScreenStatusChanged(type, status); + NodeBasicInfo nodeBasicInfo = { + .deviceName = {"device_001"}, + .networkId = {"network_001"}, + .deviceTypeId = 16789, + .osType = 24, + .osVersion = {1} + }; + NodeStatus nodeStatus = { + .authStatus = 0, + .dataBaseStatus = 1, + .meshType = 2, + .reserved = {1}, + .basicInfo = nodeBasicInfo + }; + status = &nodeStatus; + softbusListener->OnDeviceScreenStatusChanged(type, status); + type = NodeStatusType::TYPE_AUTH_STATUS; + softbusListener->OnDeviceScreenStatusChanged(type, status); int32_t ret = softbusListener->RefreshSoftbusLNN(pkgName.c_str(), dmSubInfo, customData); EXPECT_EQ(true, checkSoftbusRes(ret)); } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index e7344fe2a..7d5177de3 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1506,7 +1506,7 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_001, testing::ext::TestSize.Level { "authType" : 1, "userId" : "123", - "credentialData" : + "credentialData" : "cryptosupportData", "CRYPTOSUPPORT" : "cryptosupportTest", "credentialType" : 1, "credentialId" : "104", @@ -2230,7 +2230,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level EXPECT_NE(ret, DM_OK); } -/** +/**ll * @tc.name: StartDeviceDiscovery_007 * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return * ERR_DM_DISCOVERY_REPEATED @@ -2240,10 +2240,10 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_007, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test7"; - DmSubscribeInfo subscribeInfo; + uint16_t subscribeId = 1; std::string extra = "test"; DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); + int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, extra); EXPECT_NE(ret, DM_OK); DeviceManagerService::GetInstance().UninitDMServiceListener(); } -- Gitee From d2174e4bf4308d7b22c4f4ea917ffbea30e9a46b Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 15 Oct 2024 11:48:55 +0800 Subject: [PATCH 284/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/softbusunittest/UTTest_softbus_listener.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 6da2a59ac..fe620dd00 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -123,7 +123,7 @@ HWTEST_F(SoftbusListenerTest, ShiftLNNGear_001, testing::ext::TestSize.Level0) EXPECT_NE(softbusListener->ShiftLNNGear(false, callerId), DM_OK); } -HWTEST_F(SoftbusListenerTest, ShiftLNNGear_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusListenerTest, ShiftLNNGear_002, testing::ext::TestSize.Level0) { if (softbusListener == nullptr) { softbusListener = std::make_shared(); -- Gitee From 76c3a07e409348840afd9e1f32345dbacec71b95 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 15 Oct 2024 13:48:54 +0800 Subject: [PATCH 285/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/softbusunittest/UTTest_softbus_listener.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index fe620dd00..b2c03f046 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -154,7 +154,7 @@ HWTEST_F(SoftbusListenerTest, ConvertScreenStatusToDmDevice_001, testing::ext::T .authForm = DmAuthForm::ACROSS_ACCOUNT }; int ret = softbusListener->ConvertScreenStatusToDmDevice(nodeInfo, devScreenStatus, devInfo); - EXPECT_EQ(ret, ERR_DM_FAILED); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(SoftbusListenerTest, DeviceOnLine_001, testing::ext::TestSize.Level0) -- Gitee From 3bf65868987c457c5b91988267867ea5a5507686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 15 Oct 2024 15:51:01 +0800 Subject: [PATCH 286/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 12 ++++++------ test/unittest/UTTest_dm_pin_holder.h | 9 +++++++++ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 8c124eff4..c8b5d6a2d 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -48,7 +48,7 @@ constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; -constexpr const char* IMPORT_CREDENTIAL_STATUS = "importCredentialStatus"; +constexpr const char* CANDIDATE_RESTRICT_STATUS = "candidateRestrictStatus"; #endif constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; @@ -173,7 +173,7 @@ void SoftbusListener::CandidateRestrict(std::string deviceId, uint16_t deviceTyp void SoftbusListener::OnCandidateRestrict(char *deviceId, uint16_t deviceTypeId, int32_t errcode) { - LOGI("received import credential status callback from softbus."); + LOGI("received candidate restrict status callback from softbus."); if (deviceId == nullptr) { return; } @@ -181,11 +181,11 @@ void SoftbusListener::OnCandidateRestrict(char *deviceId, uint16_t deviceTypeId, #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); #else - std::thread importStatusChange([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); - if (pthread_setname_np(importStatusChange.native_handle(), IMPORT_CREDENTIAL_STATUS) != DM_OK) { - LOGE("devImportStatusChange setname failed."); + std::thread candidateRestrictStatus([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); + if (pthread_setname_np(candidateRestrictStatus.native_handle(), CANDIDATE_RESTRICT_STATUS) != DM_OK) { + LOGE("devcandidateRestrictStatus setname failed."); } - importStatusChange.detach(); + candidateRestrictStatus.detach(); #endif } diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 3a249b3a9..1b59834b9 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -192,6 +192,15 @@ public: (void)pkgName; (void)devInfo; } + + void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, + uint16_t deviceTypeId, int32_t errcode) override + { + (void)pkgName; + (void)deviceId; + (void)deviceTypeId; + (void)errcode; + } }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 98184d7e44978ebfbbc58ee68eea46868674c712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 15 Oct 2024 16:48:14 +0800 Subject: [PATCH 287/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- common/include/device_manager_ipc_interface_code.h | 2 +- .../inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp | 2 +- services/service/src/device_manager_service_listener.cpp | 4 ++-- services/service/src/ipc/standard/ipc_cmd_parser.cpp | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index 5a4fd679b..8defae362 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -96,7 +96,7 @@ enum DMIpcCmdInterfaceCode { SERVER_DEVICE_SCREEN_STATE_NOTIFY, GET_DEVICE_SCREEN_STATUS, GET_NETWORKID_BY_UDID, - SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, + SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, // Add ipc msg here IPC_MSG_BUTT }; 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 8f24fa8b9..568a738db 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 @@ -1733,7 +1733,7 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt return DM_OK; } -ON_IPC_CMD(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); std::string deviceId = data.ReadString(); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index fcd057df2..d3978c37e 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -566,11 +566,11 @@ void DeviceManagerServiceListener::OnHandleCandidateRestrictStatus(const std::st std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); for (const auto &it : PkgNameVec) { pReq->SetPkgName(it); - ipcServerListener_.SendRequest(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, pReq, pRsp); + ipcServerListener_.SendRequest(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, pReq, pRsp); } } else { pReq->SetPkgName(pkgName); - ipcServerListener_.SendRequest(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, pReq, pRsp); + ipcServerListener_.SendRequest(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, pReq, pRsp); } } } // namespace DistributedHardware diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index de8f21b4c..3b2dc7b87 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1573,7 +1573,7 @@ ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +ON_IPC_SET_REQUEST(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) { if (pBaseReq == nullptr) { return ERR_DM_FAILED; @@ -1604,7 +1604,7 @@ ON_IPC_SET_REQUEST(SERVER_IMPORT_CREDENTIAL_STATE_NOTIFY, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) { if (pBaseRsp == nullptr) { LOGE("pBaseRsp is null"); -- Gitee From ca3aa1066bc31d0f0839d4fe07923b3642957db6 Mon Sep 17 00:00:00 2001 From: kangchongtao Date: Tue, 15 Oct 2024 08:55:04 +0000 Subject: [PATCH 288/520] =?UTF-8?q?=E7=A7=BB=E9=99=A4=E5=AF=B9node?= =?UTF-8?q?=E7=9A=84=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: kangchongtao Change-Id: Id8d175744c943ed211d8e16772f1f13a6e7074f7 --- bundle.json | 1 - interfaces/kits/js/BUILD.gn | 1 - interfaces/kits/js4.0/BUILD.gn | 1 - 3 files changed, 3 deletions(-) diff --git a/bundle.json b/bundle.json index 8e193b87c..e6e75bf4d 100644 --- a/bundle.json +++ b/bundle.json @@ -51,7 +51,6 @@ "kv_store", "memmgr", "napi", - "node", "openssl", "os_account", "power_manager", diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index a1419e45c..c10dbe0a2 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -58,7 +58,6 @@ ohos_shared_library("devicemanager") { "ipc:ipc_core", "json:nlohmann_json_static", "napi:ace_napi", - "node:node_header_notice", ] subsystem_name = "distributedhardware" diff --git a/interfaces/kits/js4.0/BUILD.gn b/interfaces/kits/js4.0/BUILD.gn index 07a13f4c8..7e7875902 100644 --- a/interfaces/kits/js4.0/BUILD.gn +++ b/interfaces/kits/js4.0/BUILD.gn @@ -60,7 +60,6 @@ ohos_shared_library("distributeddevicemanager") { "ipc:ipc_core", "json:nlohmann_json_static", "napi:ace_napi", - "node:node_header_notice", ] subsystem_name = "distributedhardware" -- Gitee From 6a9f804bc34065b74fc5b7f4661553470ec11e69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 15 Oct 2024 17:46:37 +0800 Subject: [PATCH 289/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/commonunittest/UTTest_dm_device_state_manager.cpp | 9 +++++++++ test/unittest/UTTest_device_manager_service_impl.cpp | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 80aaf0bbf..9f68b230f 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -252,6 +252,15 @@ HWTEST_F(DmDeviceStateManagerTest, ProcNotifyEvent_001, testing::ext::TestSize.L dmDeviceStateManager->ChangeDeviceInfo(info); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) +{ + std::string deviceId = "1234567890"; + uint16_t deviceTypeId = "0x00"; + int32_t errcode = -1; + dmDeviceStateManager->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 5865aac98..78e85d6f8 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1501,6 +1501,15 @@ HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::e DmAuthForm authForm = deviceManagerServiceImpl_->ConvertBindTypeToAuthForm(bindType); EXPECT_EQ(authForm, DmAuthForm::ACROSS_ACCOUNT); } + +HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::ext::TestSize.Level0) +{ + std::string deviceId = "0123456789"; + uint16_t deviceTypeId = "0x00"; + int32_t errcode = -1; + deviceManagerServiceImpl_->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From 093fd2b80d4816ca4d501cf8e7130d3c99889314 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 15 Oct 2024 19:13:34 +0800 Subject: [PATCH 290/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 7d5177de3..2dc430ada 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2230,7 +2230,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level EXPECT_NE(ret, DM_OK); } -/**ll +/** * @tc.name: StartDeviceDiscovery_007 * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return * ERR_DM_DISCOVERY_REPEATED -- Gitee From 17fca5a9a8afcfd040409594e3338e888d9f5607 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 15 Oct 2024 19:44:26 +0800 Subject: [PATCH 291/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../include/softbus/softbus_listener.h | 5 +-- .../service/src/softbus/softbus_listener.cpp | 16 +++++---- .../UTTest_dm_device_state_manager.cpp | 2 +- .../UTTest_softbus_listener.cpp | 4 +-- .../UTTest_device_manager_service_impl.cpp | 4 +-- ...UTTest_device_manager_service_listener.cpp | 11 ++++++ .../UTTest_ipc_cmd_parser_service.cpp | 34 +++++++++++++++++++ 7 files changed, 62 insertions(+), 14 deletions(-) diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 26802ef21..bf46430e7 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -58,8 +58,9 @@ public: static void DeviceTrustedChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); - static void OnCandidateRestrict(char *deviceId, uint16_t deviceTypeId, int32_t errcode); - static void CandidateRestrict(std::string deviceId, uint16_t deviceTypeId, int32_t errcode); + static void OnHichainProofException(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, + int32_t errcode); + static void HichainProofException(std::string deviceId, uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index c8b5d6a2d..adf0d3476 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -121,7 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, - .onCandidateRestrict = SoftbusListener::OnCandidateRestrict, + .onHichainProofException = SoftbusListener::OnHichainProofException, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -165,23 +165,25 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); } -void SoftbusListener::CandidateRestrict(std::string deviceId, uint16_t deviceTypeId, int32_t errcode) +void SoftbusListener::HichainProofException(std::string deviceId, uint16_t deviceTypeId, int32_t errcode) { std::lock_guard lock(g_lockCandidateRestrictStatus); DeviceManagerService::GetInstance().HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); } -void SoftbusListener::OnCandidateRestrict(char *deviceId, uint16_t deviceTypeId, int32_t errcode) +void SoftbusListener::OnHichainProofException(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, + int32_t errcode) { LOGI("received candidate restrict status callback from softbus."); - if (deviceId == nullptr) { + if (deviceId == nullptr || deviceIdLen == 0) { + LOGE("received invaild deviceId."); return; } - std::string deviceIdStr(deviceId); + std::string deviceIdStr(deviceId, deviceIdLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); + ffrt::submit([=]() { HichainProofException(deviceIdStr, deviceTypeId, errcode); }); #else - std::thread candidateRestrictStatus([=]() { CandidateRestrict(deviceIdStr, deviceTypeId, errcode); }); + std::thread candidateRestrictStatus([=]() { HichainProofException(deviceIdStr, deviceTypeId, errcode); }); if (pthread_setname_np(candidateRestrictStatus.native_handle(), CANDIDATE_RESTRICT_STATUS) != DM_OK) { LOGE("devcandidateRestrictStatus setname failed."); } diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 9f68b230f..7a8b446ab 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -256,7 +256,7 @@ HWTEST_F(DmDeviceStateManagerTest, ProcNotifyEvent_001, testing::ext::TestSize.L HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) { std::string deviceId = "1234567890"; - uint16_t deviceTypeId = "0x00"; + uint16_t deviceTypeId = 0x00; int32_t errcode = -1; dmDeviceStateManager->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 378a5bac9..d15a0c3fd 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -734,10 +734,10 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. char deviceId[DM_MAX_DEVICE_ID_LEN] = "XXX"; uint16_t deviceTypeId = 0; int32_t errcode = -1; - softbusListener->OnCandidateRestrict(deviceId, deviceTypeId, errcode); + softbusListener->OnHichainProofException(deviceId, deviceTypeId, errcode); std::string deviceId2 = "1234567890"; deviceTypeId = 0xA2F; - softbusListener->CandidateRestrict(deviceId2, deviceTypeId, errcode); + softbusListener->HichainProofException(deviceId2, deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 78e85d6f8..8ebaad220 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1502,10 +1502,10 @@ HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::e EXPECT_EQ(authForm, DmAuthForm::ACROSS_ACCOUNT); } -HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceImplTest, HandleCandidateRestrictStatus_101, testing::ext::TestSize.Level0) { std::string deviceId = "0123456789"; - uint16_t deviceTypeId = "0x00"; + uint16_t deviceTypeId = 0x00; int32_t errcode = -1; deviceManagerServiceImpl_->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 77a8944df..67055b273 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -432,6 +432,17 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::T listener_->OnPinHolderEvent(pkgName, event, result, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } + +HWTEST_F(DeviceManagerServiceListenerTest, OnHandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + std::string pkgName = "com.ohos.helloworld"; + std::string deviceId = "0123456789"; + uint16_t deviceTypeId = 0x00; + int32_t errcode = -1; + listener_->OnHandleCandidateRestrictStatus(pkgName, deviceId, deviceTypeId, errcode); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index f47931e5b..1db55b97d 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -32,6 +32,7 @@ #include "ipc_get_trustdevice_rsp.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" +#include "ipc_notify_candidaterestrict_status_req.h" #include "ipc_notify_credential_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_dmfa_result_req.h" @@ -1528,6 +1529,39 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_055, testing::ext::TestSize.Level } ASSERT_EQ(ret, DM_OK); } + +HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY; + MessageParcel data; + std::shared_ptr req = nullptr; + int ret = ERR_DM_FAILED; + SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, ERR_DM_FAILED); + + req = std::make_shared(); + std::string pkgName = "com.ohos.test"; + std::string deviceId = "012345678"; + uint16_t deviceTypeId = 0x00; + int32_t errcode = -1; + req->SetPkgName(pkgName); + req->SetDeviceId(deviceId); + req->SetDeviceTypeId(deviceTypeId); + req->SetErrCode(errcode); + if (ptr) { + ret = ptr(req, data); + } + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_030, testing::ext::TestSize.Level0) +{ + int32_t cmdCode = SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY; + ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 875f025f0adaf3d0e7022b77f71d28b5ece5709b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 15 Oct 2024 20:33:51 +0800 Subject: [PATCH 292/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../device_manager_ipc_interface_code.h | 2 +- .../ipc_notify_candidaterestrict_status_req.h | 16 ++++++------- .../native_cpp/include/device_manager.h | 6 ++--- .../include/device_manager_callback.h | 6 ++--- .../native_cpp/include/device_manager_impl.h | 6 ++--- .../include/notify/device_manager_notify.h | 10 ++++---- .../native_cpp/src/device_manager_impl.cpp | 10 ++++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 4 ++-- .../src/notify/device_manager_notify.cpp | 24 +++++++++---------- .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../devicestate/dm_device_state_manager.h | 2 +- .../src/device_manager_service_impl.cpp | 4 ++-- .../src/device_manager_service_impl_lite.cpp | 2 +- .../devicestate/dm_device_state_manager.cpp | 6 ++--- .../service/include/device_manager_service.h | 2 +- .../include/device_manager_service_listener.h | 2 +- .../include/idevice_manager_service_impl.h | 2 +- .../idevice_manager_service_listener.h | 4 ++-- .../include/softbus/softbus_listener.h | 4 ++-- .../service/src/device_manager_service.cpp | 4 ++-- .../src/device_manager_service_listener.cpp | 10 ++++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 8 +++---- .../service/src/softbus/softbus_listener.cpp | 20 ++++++++-------- .../UTTest_dm_device_state_manager.cpp | 2 +- .../UTTest_softbus_listener.cpp | 4 ++-- test/unittest/UTTest_device_manager_impl.h | 4 ++-- .../UTTest_device_manager_impl_three.cpp | 10 ++++---- .../UTTest_device_manager_service_impl.cpp | 2 +- ...UTTest_device_manager_service_listener.cpp | 2 +- test/unittest/UTTest_dm_pin_holder.h | 2 +- .../UTTest_ipc_cmd_parser_service.cpp | 8 +++---- 32 files changed, 96 insertions(+), 96 deletions(-) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index 8defae362..3f2fd7cd0 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -96,7 +96,7 @@ enum DMIpcCmdInterfaceCode { SERVER_DEVICE_SCREEN_STATE_NOTIFY, GET_DEVICE_SCREEN_STATUS, GET_NETWORKID_BY_UDID, - SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, + SERVER_HICHAIN_PROOF_STATUS_NOTIFY, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h b/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h index ab91e0c49..dcd4b8ce4 100644 --- a/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h +++ b/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h @@ -20,12 +20,12 @@ namespace OHOS { namespace DistributedHardware { -class IpcNotifyCandidateRestrictStatusReq : public IpcReq { - DECLARE_IPC_MODEL(IpcNotifyCandidateRestrictStatusReq); +class IpcNotifyHichainProofExceptionStatusReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyHichainProofExceptionStatusReq); public: /** - * @tc.name: IpcNotifyCandidateRestrictStatusReq::GetPublishId + * @tc.name: IpcNotifyHichainProofExceptionStatusReq::GetPublishId * @tc.desc: Get deviceId of the Ipc Notify Candidate Restrict Status Request * @tc.type: FUNC */ @@ -35,7 +35,7 @@ public: } /** - * @tc.name: IpcNotifyCandidateRestrictStatusReq::SetPublishId + * @tc.name: IpcNotifyHichainProofExceptionStatusReq::SetPublishId * @tc.desc: Set deviceId of the Ipc Notify Candidate Restrict Status Request * @tc.type: FUNC */ @@ -45,7 +45,7 @@ public: } /** - * @tc.name: IpcNotifyCandidateRestrictStatusReq::GetResult + * @tc.name: IpcNotifyHichainProofExceptionStatusReq::GetResult * @tc.desc: Get DeviceType of the Ipc Notify Candidate Restrict Status Request * @tc.type: FUNC */ @@ -55,7 +55,7 @@ public: } /** - * @tc.name: IpcNotifyCandidateRestrictStatusReq::SetResult + * @tc.name: IpcNotifyHichainProofExceptionStatusReq::SetResult * @tc.desc: Set DeviceType of the Ipc Notify Candidate Restrict Status Request * @tc.type: FUNC */ @@ -65,7 +65,7 @@ public: } /** - * @tc.name: IpcNotifyCandidateRestrictStatusReq::GetErrCode + * @tc.name: IpcNotifyHichainProofExceptionStatusReq::GetErrCode * @tc.desc: Get ErrCode of the Ipc Notify Candidate Restrict Status Request * @tc.type: FUNC */ @@ -75,7 +75,7 @@ public: } /** - * @tc.name: IpcNotifyCandidateRestrictStatusReq::SetErrCode + * @tc.name: IpcNotifyHichainProofExceptionStatusReq::SetErrCode * @tc.desc: Set ErrCode of the Ipc Notify Candidate Restrict Status Request * @tc.type: FUNC */ diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 956d59bd4..b0bd9aede 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -625,9 +625,9 @@ public: virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) = 0; - virtual int32_t RegisterCandidateRestrictStatusCallback(const std::string &pkgName, - std::shared_ptr callback) = 0; - virtual int32_t UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) = 0; + virtual int32_t RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 7bf34045b..3c1380e2d 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -149,12 +149,12 @@ public: virtual void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) = 0; }; -class CandidateRestrictStatusCallback { +class HichainProofExceptionStatusCallback { public: - virtual ~CandidateRestrictStatusCallback() + virtual ~HichainProofExceptionStatusCallback() { } - virtual void OnCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + virtual void OnHichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index c0ce27860..5bab59f73 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -397,9 +397,9 @@ public: virtual int32_t StopAuthenticateDevice(const std::string &pkgName) override; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) override; - virtual int32_t RegisterCandidateRestrictStatusCallback(const std::string &pkgName, - std::shared_ptr callback) override; - virtual int32_t UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) override; + virtual int32_t RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) override; private: DeviceManagerImpl() = default; 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 2a311e267..f33bd48e8 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 @@ -70,9 +70,9 @@ public: void RegisterDeviceScreenStatusCallback(const std::string &pkgName, std::shared_ptr callback); void UnRegisterDeviceScreenStatusCallback(const std::string &pkgName); - void RegisterCandidateRestrictStatusCallback(const std::string &pkgName, - std::shared_ptr callback); - void UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName); + void RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, + std::shared_ptr callback); + void UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName); public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -119,7 +119,7 @@ public: void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, + void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); private: @@ -139,7 +139,7 @@ private: std::map> pinHolderCallback_; std::map> devTrustChangeCallback_; std::map> deviceScreenStatusCallback_; - std::map> candidateRestrictStatusCallback_; + std::map> hichainProofExceptionStatusCallback_; std::mutex bindLock_; }; } // namespace DistributedHardware 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 e636c4498..6b1a237d8 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2437,25 +2437,25 @@ int32_t DeviceManagerImpl::GetNetworkIdByUdid(const std::string &pkgName, const return DM_OK; } -int32_t DeviceManagerImpl::RegisterCandidateRestrictStatusCallback(const std::string &pkgName, - std::shared_ptr callback) +int32_t DeviceManagerImpl::RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, + std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - DeviceManagerNotify::GetInstance().RegisterCandidateRestrictStatusCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterHichainProofExceptionStatusCallback(pkgName, callback); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } -int32_t DeviceManagerImpl::UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) +int32_t DeviceManagerImpl::UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - DeviceManagerNotify::GetInstance().UnRegisterCandidateRestrictStatusCallback(pkgName); + DeviceManagerNotify::GetInstance().UnRegisterHichainProofExceptionStatusCallback(pkgName); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index 568a738db..7ed4c9a42 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 @@ -1733,13 +1733,13 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt return DM_OK; } -ON_IPC_CMD(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); std::string deviceId = data.ReadString(); uint16_t deviceTypeId = data.ReadUint16(); int32_t errCode = data.ReadInt32(); - DeviceManagerNotify::GetInstance().OnCandidateRestrictStatus(pkgName, deviceId, deviceTypeId, errCode); + DeviceManagerNotify::GetInstance().OnHichainProofExceptionStatus(pkgName, deviceId, deviceTypeId, errCode); reply.WriteInt32(DM_OK); return DM_OK; diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 4a3a9e470..7aba869b5 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 @@ -1148,28 +1148,28 @@ void DeviceManagerNotify::OnDeviceScreenStatus(const std::string &pkgName, const tempCbk->OnDeviceScreenStatus(deviceInfo); } -void DeviceManagerNotify::RegisterCandidateRestrictStatusCallback(const std::string &pkgName, - std::shared_ptr callback) +void DeviceManagerNotify::RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, + std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); return; } std::lock_guard autoLock(lock_); - candidateRestrictStatusCallback_[pkgName] = callback; + hichainProofExceptionStatusCallback_[pkgName] = callback; } -void DeviceManagerNotify::UnRegisterCandidateRestrictStatusCallback(const std::string &pkgName) +void DeviceManagerNotify::UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } std::lock_guard autoLock(lock_); - candidateRestrictStatusCallback_.erase(pkgName); + hichainProofExceptionStatusCallback_.erase(pkgName); } -void DeviceManagerNotify::OnCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, +void DeviceManagerNotify::OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { if (pkgName.empty()) { @@ -1177,20 +1177,20 @@ void DeviceManagerNotify::OnCandidateRestrictStatus(const std::string &pkgName, return; } LOGI("In, pkgName:%{public}s", pkgName.c_str()); - std::shared_ptr tempCbk; + std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); - if (candidateRestrictStatusCallback_.find(pkgName) == candidateRestrictStatusCallback_.end()) { - LOGE("error, import credential status not register."); + if (hichainProofExceptionStatusCallback_.find(pkgName) == hichainProofExceptionStatusCallback_.end()) { + LOGE("error, hichain proof exception status not register."); return; } - tempCbk = candidateRestrictStatusCallback_[pkgName]; + tempCbk = hichainProofExceptionStatusCallback_[pkgName]; } if (tempCbk == nullptr) { - LOGE("error, registered import credential status callback is nullptr."); + LOGE("error, registered hichain proof exception status callback is nullptr."); return; } - tempCbk->OnCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + tempCbk->OnHichainProofExceptionStatus(deviceId, deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index c06cd04a8..84936abf5 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -131,7 +131,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index afab36b3d..97fd49541 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -137,7 +137,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); private: diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index bb8ab0da4..77d876ea0 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,7 +96,7 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); + void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); private: void StartEventThread(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 1dd8bc6f9..d0fced130 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -853,11 +853,11 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } -void DeviceManagerServiceImpl::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, +void DeviceManagerServiceImpl::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + deviceStateMgr_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); } extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 6c19072c9..37addb9db 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -524,7 +524,7 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } -void DeviceManagerServiceImpl::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, +void DeviceManagerServiceImpl::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { (void)deviceId; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index f49c98948..29889c99b 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -527,7 +527,7 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) softbusConnector_->ClearPkgName(); } -void DmDeviceStateManager::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, +void DmDeviceStateManager::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { if (softbusConnector_ == nullptr || listener_ == nullptr) { @@ -536,10 +536,10 @@ void DmDeviceStateManager::HandleCandidateRestrictStatus(const std::string &devi } std::vector pkgName = softbusConnector_->GetPkgName(); if (pkgName.size() == 0) { - listener_->OnHandleCandidateRestrictStatus(std::string(DM_PKG_NAME), deviceId, deviceTypeId, errcode); + listener_->OnHichainProofExceptionStatus(std::string(DM_PKG_NAME), deviceId, deviceTypeId, errcode); } else { for (auto item : pkgName) { - listener_->OnHandleCandidateRestrictStatus(item, deviceId, deviceTypeId, errcode); + listener_->OnHichainProofExceptionStatus(item, deviceId, deviceTypeId, errcode); } } } diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index e3e5557b6..5626e2c64 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,7 +201,7 @@ public: int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); - void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); private: bool IsDMServiceImplReady(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 3abd50b23..fe2cc3dfe 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -73,7 +73,7 @@ public: const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; - void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, + void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 633654913..f9ef5abaf 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -273,7 +273,7 @@ public: virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; - virtual void HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + virtual void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) = 0; }; diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 36c2cdb01..0387c420a 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -160,11 +160,11 @@ public: virtual void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) = 0; /** - * @tc.name: IDeviceManagerServiceListener::OnHandleCandidateRestrictStatus + * @tc.name: IDeviceManagerServiceListener::OnHichainProofExceptionStatus * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, + virtual void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index bf46430e7..d02847b52 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -58,9 +58,9 @@ public: static void DeviceTrustedChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); - static void OnHichainProofException(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, + static void OnHichainProofStatus(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, int32_t errcode); - static void HichainProofException(std::string deviceId, uint16_t deviceTypeId, int32_t errcode); + static void HichainProofExceptionProcess(std::string deviceId, uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index e42ae4059..1535fad42 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1994,11 +1994,11 @@ void DeviceManagerService::SubscribePackageCommonEvent() #endif } -void DeviceManagerService::HandleCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, +void DeviceManagerService::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + dmServiceImpl_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); } } } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index d3978c37e..1eb98c1f9 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -552,12 +552,12 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) } } -void DeviceManagerServiceListener::OnHandleCandidateRestrictStatus(const std::string &pkgName, +void DeviceManagerServiceListener::OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { LOGI("In, pkgName = %{public}s", pkgName.c_str()); - std::shared_ptr pReq = - std::make_shared(); + std::shared_ptr pReq = + std::make_shared(); std::shared_ptr pRsp = std::make_shared(); pReq->SetDeviceId(deviceId); pReq->SetDeviceTypeId(deviceTypeId); @@ -566,11 +566,11 @@ void DeviceManagerServiceListener::OnHandleCandidateRestrictStatus(const std::st std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); for (const auto &it : PkgNameVec) { pReq->SetPkgName(it); - ipcServerListener_.SendRequest(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, pReq, pRsp); + ipcServerListener_.SendRequest(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, pReq, pRsp); } } else { pReq->SetPkgName(pkgName); - ipcServerListener_.SendRequest(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, pReq, pRsp); + ipcServerListener_.SendRequest(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, pReq, pRsp); } } } // namespace DistributedHardware diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 3b2dc7b87..3995a96b1 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1573,13 +1573,13 @@ ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) { if (pBaseReq == nullptr) { return ERR_DM_FAILED; } - std::shared_ptr pReq = - std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string deviceId = pReq->GetDeviceId(); uint16_t deviceTypeId = pReq->GetDeviceTypeId(); @@ -1604,7 +1604,7 @@ ON_IPC_SET_REQUEST(SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) { if (pBaseRsp == nullptr) { LOGE("pBaseRsp is null"); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index adf0d3476..2c437b0ce 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -48,7 +48,7 @@ constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; -constexpr const char* CANDIDATE_RESTRICT_STATUS = "candidateRestrictStatus"; +constexpr const char* HICHAIN_PROOF_STATUS = "hichainProofStatus"; #endif constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; @@ -121,7 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, - .onHichainProofException = SoftbusListener::OnHichainProofException, + .OnHichainProofStatus = SoftbusListener::OnHichainProofStatus, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -165,13 +165,13 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); } -void SoftbusListener::HichainProofException(std::string deviceId, uint16_t deviceTypeId, int32_t errcode) +void SoftbusListener::HichainProofExceptionProcess(std::string deviceId, uint16_t deviceTypeId, int32_t errcode) { std::lock_guard lock(g_lockCandidateRestrictStatus); - DeviceManagerService::GetInstance().HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + DeviceManagerService::GetInstance().HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); } -void SoftbusListener::OnHichainProofException(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, +void SoftbusListener::OnHichainProofStatus(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, int32_t errcode) { LOGI("received candidate restrict status callback from softbus."); @@ -181,13 +181,13 @@ void SoftbusListener::OnHichainProofException(const char *deviceId, uint32_t dev } std::string deviceIdStr(deviceId, deviceIdLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { HichainProofException(deviceIdStr, deviceTypeId, errcode); }); + ffrt::submit([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); #else - std::thread candidateRestrictStatus([=]() { HichainProofException(deviceIdStr, deviceTypeId, errcode); }); - if (pthread_setname_np(candidateRestrictStatus.native_handle(), CANDIDATE_RESTRICT_STATUS) != DM_OK) { - LOGE("devcandidateRestrictStatus setname failed."); + std::thread hichainProofStatus([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); + if (pthread_setname_np(hichainProofStatus.native_handle(), HICHAIN_PROOF_STATUS) != DM_OK) { + LOGE("hichainProofStatus setname failed."); } - candidateRestrictStatus.detach(); + hichainProofStatus.detach(); #endif } diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 7a8b446ab..08e87b283 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -258,7 +258,7 @@ HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::e std::string deviceId = "1234567890"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - dmDeviceStateManager->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + dmDeviceStateManager->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); } } // namespace diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index d15a0c3fd..0c9c2d1ae 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -734,10 +734,10 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. char deviceId[DM_MAX_DEVICE_ID_LEN] = "XXX"; uint16_t deviceTypeId = 0; int32_t errcode = -1; - softbusListener->OnHichainProofException(deviceId, deviceTypeId, errcode); + softbusListener->OnHichainProofStatus(deviceId, DM_MAX_DEVICE_ID_LEN, deviceTypeId, errcode); std::string deviceId2 = "1234567890"; deviceTypeId = 0xA2F; - softbusListener->HichainProofException(deviceId2, deviceTypeId, errcode); + softbusListener->HichainProofExceptionProcess(deviceId2, deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index a40965ea3..fb0b65417 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -118,12 +118,12 @@ public: void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override {} }; -class CandidateRestrictStatusCallbackTest : public CandidateRestrictStatusCallback { +class CandidateRestrictStatusCallbackTest : public HichainProofExceptionStatusCallback { public: virtual ~CandidateRestrictStatusCallbackTest() { } - void OnCandidateRestrictStatus(const std::string &deviceId, uint16_t deviceTypeId, + void OnHichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) override {} }; } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 7854577ca..570461fe0 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1350,7 +1350,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_001, tes { std::string packName = ""; std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().RegisterCandidateRestrictStatusCallback(packName, callback); + int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1358,7 +1358,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_002, tes { std::string packName = "com.ohos.candidateRestrict01"; std::shared_ptr callback = nullptr; - int32_t ret = DeviceManager::GetInstance().RegisterCandidateRestrictStatusCallback(packName, callback); + int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1366,21 +1366,21 @@ HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_003, tes { std::string packName = "com.ohos.scandidateRestrict02"; std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().RegisterCandidateRestrictStatusCallback(packName, callback); + int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); ASSERT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerImplTest, UnRegisterCandidateRestrictStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.candidateRestrict03"; - int32_t ret = DeviceManager::GetInstance().UnRegisterCandidateRestrictStatusCallback(packName); + int32_t ret = DeviceManager::GetInstance().UnRegisterHichainProofExceptionStatusCallback(packName); ASSERT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerImplTest, UnRegisterCandidateRestrictStatusCallback_002, testing::ext::TestSize.Level0) { std::string packName = ""; - int32_t ret = DeviceManager::GetInstance().UnRegisterCandidateRestrictStatusCallback(packName); + int32_t ret = DeviceManager::GetInstance().UnRegisterHichainProofExceptionStatusCallback(packName); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 8ebaad220..1ee369bc8 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1507,7 +1507,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleCandidateRestrictStatus_101, testin std::string deviceId = "0123456789"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - deviceManagerServiceImpl_->HandleCandidateRestrictStatus(deviceId, deviceTypeId, errcode); + deviceManagerServiceImpl_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 67055b273..e8abba6df 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -440,7 +440,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnHandleCandidateRestrictStatus_001, std::string deviceId = "0123456789"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - listener_->OnHandleCandidateRestrictStatus(pkgName, deviceId, deviceTypeId, errcode); + listener_->OnHichainProofExceptionStatus(pkgName, deviceId, deviceTypeId, errcode); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } } // namespace diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 1b59834b9..a293ec66b 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -193,7 +193,7 @@ public: (void)devInfo; } - void OnHandleCandidateRestrictStatus(const std::string &pkgName, const std::string &deviceId, + void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) override { (void)pkgName; diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 1db55b97d..db81d1f05 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -1532,9 +1532,9 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_055, testing::ext::TestSize.Level HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize.Level0) { - int32_t cmdCode = SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY; + int32_t cmdCode = SERVER_HICHAIN_PROOF_STATUS_NOTIFY; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -1542,7 +1542,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; std::string deviceId = "012345678"; uint16_t deviceTypeId = 0x00; @@ -1559,7 +1559,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_030, testing::ext::TestSize.Level0) { - int32_t cmdCode = SERVER_CANDIDATE_RESTRICT_STATUS_NOTIFY; + int32_t cmdCode = SERVER_HICHAIN_PROOF_STATUS_NOTIFY; ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); } } // namespace -- Gitee From 6431c10843097117ff70801275a1b8b6d422af2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Tue, 15 Oct 2024 22:04:00 +0800 Subject: [PATCH 293/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0COMMON=5FEVENT=5FDATA?= =?UTF-8?q?=5FSHARE=5FREADY=E7=9B=91=E5=90=AC=EF=BC=8C=E7=A1=AE=E4=BF=9Dda?= =?UTF-8?q?ta=5Fshare=E6=88=90=E5=8A=9F=E5=90=AF=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/BUILD.gn | 1 + .../devicenamemgr/account_boot_listener.h | 12 ++ .../dm_data_share_common_event.h | 83 ++++++++ .../devicenamemgr/account_boot_listener.cpp | 59 +++++- .../src/ipc/standard/ipc_server_stub.cpp | 3 +- .../dm_data_share_common_event.cpp | 180 ++++++++++++++++++ 6 files changed, 336 insertions(+), 2 deletions(-) create mode 100644 services/service/include/publishcommonevent/dm_data_share_common_event.h create mode 100644 services/service/src/publishcommonevent/dm_data_share_common_event.cpp diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index b05125f26..a00da9fff 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -179,6 +179,7 @@ if (defined(ohos_lite)) { "src/publishcommonevent/dm_account_common_event.cpp", "src/publishcommonevent/dm_package_common_event.cpp", "src/publishcommonevent/dm_screen_common_event.cpp", + "src/publishcommonevent/dm_data_share_common_event.cpp", "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h index d6e18ec38..8c894c6f9 100644 --- a/services/service/include/devicenamemgr/account_boot_listener.h +++ b/services/service/include/devicenamemgr/account_boot_listener.h @@ -17,15 +17,23 @@ #define OHOS_ACCOUNT_BOOT_LISTENER_H #include +#include "dm_data_share_common_event.h" #include "local_device_name_mgr.h" namespace OHOS { namespace DistributedHardware { +typedef enum SaTriggerFlag { + DM_SA_READY, + DATA_SHARE_SA_REDDY +} SaTriggerFlag; class AccountBootListener { public: AccountBootListener(); ~AccountBootListener(); void RegisterAccountBootCb(); void DoAccountBootProc(); + void SetSaTriggerFlag(SaTriggerFlag triggerFlag); + void InitDataShareEvent(); + void DataShareCallback(); private: /** * @brief flag for is registered callback for account boot event @@ -34,6 +42,10 @@ private: */ std::atomic isRegAccountBootCb_; std::shared_ptr localDeviceMgr_; + std::atomic isDmSaReady_; + std::atomic isDataShareReady_; + static std::mutex lock_; + std::shared_ptr dataShareCommonEventManager_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/publishcommonevent/dm_data_share_common_event.h b/services/service/include/publishcommonevent/dm_data_share_common_event.h new file mode 100644 index 000000000..f861486a9 --- /dev/null +++ b/services/service/include/publishcommonevent/dm_data_share_common_event.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DATA_SHARE_COMMON_EVENT_H +#define OHOS_DATA_SHARE_COMMON_EVENT_H + +#include +#include +#include +#include + +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "matching_skills.h" +#include "system_ability_status_change_stub.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::CommonEventData; +using OHOS::EventFwk::CommonEventSubscriber; +using OHOS::EventFwk::CommonEventSubscribeInfo; +using DataShareEventCallback = std::function; + +class DmDataShareEventSubscriber : public CommonEventSubscriber { +public: + DmDataShareEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo, const DataShareEventCallback &callback, + const std::vector &eventNameVec) : CommonEventSubscriber(subscribeInfo), + eventNameVec_(eventNameVec), callback_(callback) {} + ~DmDataShareEventSubscriber() override = default; + std::vector GetSubscriberEventNameVec() const; + void OnReceiveEvent(const CommonEventData &data) override; + +private: + std::vector eventNameVec_; + DataShareEventCallback callback_; +}; + +class DmDataShareCommonEventManager { +public: + DmDataShareCommonEventManager() = default; + ~DmDataShareCommonEventManager(); + bool SubscribeDataShareCommonEvent(const std::vector &eventNameVec, + const DataShareEventCallback &callback); + bool UnsubscribeDataShareCommonEvent(); + +private: + std::vector eventNameVec_; + bool eventValidFlag_ = false; + std::mutex evenSubscriberMutex_; + std::shared_ptr subscriber_ = nullptr; + sptr statusChangeListener_ = nullptr; + int32_t counter_ = 0; + +private: + class SystemAbilityStatusChangeListener : public SystemAbilityStatusChangeStub { + public: + explicit SystemAbilityStatusChangeListener(std::shared_ptr DataShareSubscriber) + : changeSubscriber_(DataShareSubscriber) {} + ~SystemAbilityStatusChangeListener() = default; + void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + + private: + std::shared_ptr changeSubscriber_; + }; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DATA_SHARE_COMMON_EVENT_H diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 60b56ad35..fec2dc7bc 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -17,6 +17,8 @@ #include +#include "common_event_support.h" +#include "device_manager_service.h" #include "parameter.h" #include "dm_log.h" @@ -33,6 +35,8 @@ namespace { #endif } +std::mutex AccountBootListener::lock_; + static void AccountBootCb(const char *key, const char *value, void *context) { if (strcmp(key, BOOTEVENT_ACCOUNT_READY) != 0 || strcmp(value, "true") != 0) { @@ -60,7 +64,8 @@ static void AccountBootCb(const char *key, const char *value, void *context) } AccountBootListener::AccountBootListener() : isRegAccountBootCb_(false), - localDeviceMgr_(std::make_shared()) + localDeviceMgr_(std::make_shared()), isDmSaReady_(false), isDataShareReady_(false), + dataShareCommonEventManager_(std::make_shared()) { LOGI("Ctor AccountBootListener"); } @@ -95,5 +100,57 @@ void AccountBootListener::DoAccountBootProc() localDeviceMgr_->QueryLocalDeviceName(); localDeviceMgr_->QueryLocalDisplayName(); } + +void AccountBootListener::SetSaTriggerFlag(SaTriggerFlag triggerFlag) +{ + LOGI("start"); + std::lock_guard lock(lock_); + switch (triggerFlag) { + case DM_SA_READY: + isDmSaReady_ = true; + LOGI("DM SA ready!"); + break; + case DATA_SHARE_SA_REDDY: + LOGI("DATA SHARE SA ready!"); + this->InitDataShareEvent(); + break; + default: + break; + } + if (isDmSaReady_ && isDataShareReady_) { + LOGI("dm and data_share is ready!"); + this->RegisterAccountBootCb(); + } +} + +void AccountBootListener::InitDataShareEvent() +{ + LOGI("Start"); + if (dataShareCommonEventManager_ == nullptr) { + dataShareCommonEventManager_ = std::make_shared(); + } + DataShareEventCallback callback = [=]() { + this->DataShareCallback(); + }; + std::vector dataShareEventVec; + dataShareEventVec.emplace_back(EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY); + if (dataShareCommonEventManager_->SubscribeDataShareCommonEvent(dataShareEventVec, callback)) { + LOGI("Success"); + } + return; +} + +void AccountBootListener::DataShareCallback() +{ + LOGI("Start"); + std::lock_guard lock(lock_); + isDataShareReady_ = true; + LOGI("isDmSaReady_:%{public}d", std::atomic_load(&isDmSaReady_)); + LOGI("isDataShareReady_:%{public}d", std::atomic_load(&isDataShareReady_)); + if (isDmSaReady_ && isDataShareReady_) { + LOGI("dm and data_share is ready!"); + this->RegisterAccountBootCb(); + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index a35726888..0ad5e7f8f 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -86,7 +86,7 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; - accountBootListener_->RegisterAccountBootCb(); + accountBootListener_->SetSaTriggerFlag(SaTriggerFlag::DM_SA_READY); return; } @@ -114,6 +114,7 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) { KVAdapterManager::GetInstance().ReInit(); + accountBootListener_->SetSaTriggerFlag(SaTriggerFlag::DATA_SHARE_SA_REDDY); return; } #endif diff --git a/services/service/src/publishcommonevent/dm_data_share_common_event.cpp b/services/service/src/publishcommonevent/dm_data_share_common_event.cpp new file mode 100644 index 000000000..c7e43b10f --- /dev/null +++ b/services/service/src/publishcommonevent/dm_data_share_common_event.cpp @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_data_share_common_event.h" + +#include +#include + +#include "common_event_support.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif +#include "iservice_registry.h" +#include "multiple_user_connector.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace DistributedHardware { +using OHOS::EventFwk::MatchingSkills; +using OHOS::EventFwk::CommonEventManager; + +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) +constexpr const char* DEAL_THREAD = "data_share"; +#endif +constexpr int32_t MAX_TRY_TIMES = 3; + +std::vector DmDataShareEventSubscriber::GetSubscriberEventNameVec() const +{ + return eventNameVec_; +} + +DmDataShareCommonEventManager::~DmDataShareCommonEventManager() +{ + DmDataShareCommonEventManager::UnsubscribeDataShareCommonEvent(); +} + +bool DmDataShareCommonEventManager::SubscribeDataShareCommonEvent(const std::vector &eventNameVec, + const DataShareEventCallback &callback) +{ + LOGI("start"); + if (eventNameVec.empty() || callback == nullptr) { + LOGE("eventNameVec is empty or callback is nullptr."); + return false; + } + std::lock_guard locker(evenSubscriberMutex_); + if (eventValidFlag_) { + LOGE("failed to subscribe data share commom eventName size: %{public}zu", eventNameVec.size()); + return false; + } + + MatchingSkills matchingSkills; + for (auto &item : eventNameVec) { + matchingSkills.AddEvent(item); + } + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + subscriber_ = std::make_shared(subscriberInfo, callback, eventNameVec); + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + subscriber_ = nullptr; + return false; + } + statusChangeListener_ = new (std::nothrow) SystemAbilityStatusChangeListener(subscriber_); + if (statusChangeListener_ == nullptr) { + LOGE("statusChangeListener_ is nullptr"); + subscriber_ = nullptr; + return false; + } + while (counter_ != MAX_TRY_TIMES) { + if (samgrProxy->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_) == ERR_OK) { + LOGI("SubscribeDataShareEvent success."); + counter_ = 0; + break; + } + if (++counter_ == MAX_TRY_TIMES) { + LOGI("SubscribeDataShareEvent failed."); + } + sleep(1); + } + eventNameVec_ = eventNameVec; + eventValidFlag_ = true; + LOGI("success to subscribe data share commom event name size: %{public}zu", eventNameVec.size()); + return true; +} + +bool DmDataShareCommonEventManager::UnsubscribeDataShareCommonEvent() +{ + std::lock_guard locker(evenSubscriberMutex_); + if (!eventValidFlag_) { + LOGE("failed to unsubscribe data share commom event name size: %{public}zu because event is invalid.", + eventNameVec_.size()); + return false; + } + if (subscriber_ != nullptr) { + LOGI("start to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + if (!CommonEventManager::UnSubscribeCommonEvent(subscriber_)) { + LOGE("failed to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + return false; + } + LOGI("success to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + subscriber_ = nullptr; + } + if (statusChangeListener_ != nullptr) { + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + LOGE("samgrProxy is nullptr"); + return false; + } + int32_t ret = samgrProxy->UnSubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, statusChangeListener_); + if (ret != ERR_OK) { + LOGE("failed to unsubscribe system ability COMMON_EVENT_SERVICE_ID ret:%{public}d", ret); + return false; + } + statusChangeListener_ = nullptr; + } + + LOGI("success to unsubscribe data share commom event name size: %{public}zu", eventNameVec_.size()); + eventValidFlag_ = false; + return true; +} + +void DmDataShareEventSubscriber::OnReceiveEvent(const CommonEventData &data) +{ + std::string receiveEvent = data.GetWant().GetAction(); + LOGI("Received data share event: %{public}s", receiveEvent.c_str()); + if (receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_DATA_SHARE_READY) { + return; + } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { callback_();}); +#else + std::thread dealThread(callback_); + int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); + if (ret != DM_OK) { + LOGE("dealThread setname failed."); + } + dealThread.detach(); +#endif +} + +void DmDataShareCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is added with said: %{public}d.", systemAbilityId); + if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { + return; + } + if (changeSubscriber_ == nullptr) { + LOGE("failed to subscribe data share commom event because changeSubscriber_ is nullptr."); + return; + } + std::vector eventNameVec = changeSubscriber_->GetSubscriberEventNameVec(); + LOGI("start to subscribe data share commom eventName: %{public}zu", eventNameVec.size()); + if (!CommonEventManager::SubscribeCommonEvent(changeSubscriber_)) { + LOGE("failed to subscribe data share commom event: %{public}zu", eventNameVec.size()); + } +} + +void DmDataShareCommonEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + LOGI("systemAbility is removed with said: %{public}d.", systemAbilityId); +} +} // namespace DistributedHardware +} \ No newline at end of file -- Gitee From b04d473106fad102e8408f595b3ea2e6dd633475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Wed, 16 Oct 2024 11:03:51 +0800 Subject: [PATCH 294/520] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E8=A7=84=E8=8C=83?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../service/include/devicenamemgr/settings_data_event_monitor.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/include/devicenamemgr/settings_data_event_monitor.h b/services/service/include/devicenamemgr/settings_data_event_monitor.h index b1be98102..1ba6591bb 100644 --- a/services/service/include/devicenamemgr/settings_data_event_monitor.h +++ b/services/service/include/devicenamemgr/settings_data_event_monitor.h @@ -16,9 +16,9 @@ #ifndef OHOS_SETTINGS_DATA_EVENT_MONITOR_H #define OHOS_SETTINGS_DATA_EVENT_MONITOR_H -#include "data_ability_observer_stub.h" #include +#include "data_ability_observer_stub.h" #include "local_device_name_mgr.h" namespace OHOS { -- Gitee From 5ccd0045199a06533e19e96b5b1660c34ef42e9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 16 Oct 2024 11:29:36 +0800 Subject: [PATCH 295/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp | 2 ++ services/service/src/ipc/standard/ipc_cmd_parser.cpp | 2 ++ 2 files changed, 4 insertions(+) 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 7ed4c9a42..cd70bc97e 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 @@ -1735,6 +1735,7 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt ON_IPC_CMD(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) { + LOGI("In."); std::string pkgName = data.ReadString(); std::string deviceId = data.ReadString(); uint16_t deviceTypeId = data.ReadUint16(); @@ -1742,6 +1743,7 @@ ON_IPC_CMD(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &data, MessageParce DeviceManagerNotify::GetInstance().OnHichainProofExceptionStatus(pkgName, deviceId, deviceTypeId, errCode); reply.WriteInt32(DM_OK); + LOGI("End."); return DM_OK; } } // namespace DistributedHardware diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 3995a96b1..51947fc36 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1575,6 +1575,7 @@ ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) { + LOGI("In"); if (pBaseReq == nullptr) { return ERR_DM_FAILED; } @@ -1601,6 +1602,7 @@ ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr p LOGE("write errCode failed"); return ERR_DM_IPC_WRITE_FAILED; } + LOGI("End."); return DM_OK; } -- Gitee From 1d012d9e4953eb64c99da220af7fa2ab0bfbba55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Wed, 16 Oct 2024 12:04:35 +0800 Subject: [PATCH 296/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9build.gn=E5=AD=97?= =?UTF-8?q?=E5=85=B8=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index a00da9fff..ee1da5e34 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -177,9 +177,9 @@ if (defined(ohos_lite)) { "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", "src/publishcommonevent/dm_account_common_event.cpp", + "src/publishcommonevent/dm_data_share_common_event.cpp", "src/publishcommonevent/dm_package_common_event.cpp", "src/publishcommonevent/dm_screen_common_event.cpp", - "src/publishcommonevent/dm_data_share_common_event.cpp", "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", -- Gitee From 5343a8639a4d4c8e65a7d0f83f290110c35ce362 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Tue, 15 Oct 2024 11:40:39 +0800 Subject: [PATCH 297/520] add dadian Signed-off-by: gaoqiang_strong --- .../native_cpp/src/device_manager_impl.cpp | 6 +++ radar/BUILD.gn | 4 ++ radar/include/dm_radar_helper.h | 7 +++ radar/src/dm_radar_helper.cpp | 46 ++++++++++++++++++- services/service/src/pinholder/pin_holder.cpp | 1 + 5 files changed, 62 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index b0e3bb30c..5b8851055 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2245,14 +2245,17 @@ bool DeviceManagerImpl::CheckAccessControl(const DmAccessCaller &caller, const D req->SetAccessCallee(callee); int32_t ret = ipcClientProxy_->SendRequest(CHECK_ACCESS_CONTROL, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckAccessControl", ret); LOGE("CheckAccessControl Send Request failed ret: %{public}d", ret); return false; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckAccessControl", ret); LOGE("CheckAccessControl Failed with ret: %{public}d", ret); return false; } + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckAccessControl", DM_OK); return true; } @@ -2265,14 +2268,17 @@ bool DeviceManagerImpl::CheckIsSameAccount(const DmAccessCaller &caller, const D req->SetAccessCallee(callee); int32_t ret = ipcClientProxy_->SendRequest(CHECK_SAME_ACCOUNT, req, rsp); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckIsSameAccount", ret); LOGE("CheckIsSameAccount Send Request failed ret: %{public}d", ret); return false; } ret = rsp->GetErrCode(); if (ret != DM_OK) { + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckIsSameAccount", ret); LOGE("CheckIsSameAccount Failed with ret: %{public}d", ret); return false; } + DmRadarHelper::GetInstance().ReportDmBehavior(caller.pkgName, "CheckIsSameAccount", DM_OK); return true; } diff --git a/radar/BUILD.gn b/radar/BUILD.gn index b93d77b96..4df9d2608 100644 --- a/radar/BUILD.gn +++ b/radar/BUILD.gn @@ -61,11 +61,15 @@ if (defined(ohos_lite)) { ] external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "cJSON:cjson", "c_utils:utils", "hilog:libhilog", "hisysevent:libhisysevent", "init:libbegetutil", + "ipc:ipc_core", + "ipc:ipc_single", ] subsystem_name = "distributedhardware" diff --git a/radar/include/dm_radar_helper.h b/radar/include/dm_radar_helper.h index 91de34ac7..66060c2ca 100644 --- a/radar/include/dm_radar_helper.h +++ b/radar/include/dm_radar_helper.h @@ -109,6 +109,12 @@ enum class TrustStatus : int32_t { IS_TRUST = 0x1, }; +enum class ApiType : int32_t { + API_UNKNOW = 0x0, + API_JS = 0x1, + API_NATIVE = 0x2, +}; + enum class CommServ : int32_t { NOT_USE_SOFTBUS = 0x0, USE_SOFTBUS = 0x1, @@ -219,6 +225,7 @@ public: private: std::string GetAnonyUdid(std::string udid); std::string GetAnonyLocalUdid(); + int32_t GetApiType(); }; extern "C" IDmRadarHelper *CreateDmRadarInstance(); diff --git a/radar/src/dm_radar_helper.cpp b/radar/src/dm_radar_helper.cpp index 792ec11a6..e2e2c32d2 100644 --- a/radar/src/dm_radar_helper.cpp +++ b/radar/src/dm_radar_helper.cpp @@ -21,12 +21,17 @@ #include #include #include - #include "hisysevent.h" #include "dm_constants.h" #include "dm_log.h" #include "parameter.h" - +#include "accesstoken_kit.h" +#include "access_token.h" +#include "hap_token_info.h" +#include "ipc_skeleton.h" +#include "native_token_info.h" +#include "tokenid_kit.h" +using namespace OHOS::Security::AccessToken; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DmRadarHelper); @@ -41,6 +46,7 @@ bool DmRadarHelper::ReportDiscoverRegCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", info.stageRes, @@ -54,6 +60,7 @@ bool DmRadarHelper::ReportDiscoverRegCallback(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", info.stageRes, @@ -80,6 +87,7 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", SOFTBUSNAME, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -95,6 +103,7 @@ bool DmRadarHelper::ReportDiscoverResCallback(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", SOFTBUSNAME, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_REGISTER_CALLBACK), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), @@ -123,6 +132,7 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, @@ -135,6 +145,7 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "ORG_PKG", ORGPKGNAME, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, @@ -147,6 +158,7 @@ bool DmRadarHelper::ReportDiscoverUserRes(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_DISCOVER), "BIZ_STAGE", static_cast(DisCoverStage::DISCOVER_USER_DEAL_RES), "STAGE_RES", info.stageRes, @@ -170,6 +182,7 @@ bool DmRadarHelper::ReportAuthStart(const std::string &peerUdid, const std::stri "ORG_PKG", ORGPKGNAME, "FUNC", "AuthenticateDevice", "HOST_PKG", pkgName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(AuthScene::DM_AUTHCATION), "BIZ_STAGE", static_cast(AuthStage::AUTH_START), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -577,6 +590,7 @@ bool DmRadarHelper::ReportDeleteTrustRelation(struct RadarInfo &info) "ORG_PKG", ORGPKGNAME, "HOST_PKG", info.hostName, "FUNC", info.funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(AuthScene::DM_DELET_TRUST_RELATION), "BIZ_STAGE", static_cast(DeleteTrust::DELETE_TRUST), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -604,6 +618,7 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "CreatePinHolder", + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::CREATE_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -624,6 +639,7 @@ void DmRadarHelper::ReportCreatePinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "CreatePinHolder", + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::CREATE_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), @@ -653,6 +669,7 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "DestroyPinHolder", + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -671,6 +688,7 @@ void DmRadarHelper::ReportDestroyPinHolder(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", "DestroyPinHolder", + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(AuthScene::DM_PIN_HOLDER), "BIZ_STAGE", static_cast(PinHolderStage::DESTROY_PIN_HOLDER), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), @@ -746,6 +764,7 @@ void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_TRUST_DEVICE_LIST), "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -761,6 +780,7 @@ void DmRadarHelper::ReportGetTrustDeviceList(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_TRUST_DEVICE_LIST), "BIZ_STAGE", static_cast(GetTrustDeviceList::GET_TRUST_DEVICE_LIST), "STAGE_RES", static_cast(StageRes::STAGE_FAIL), @@ -786,6 +806,7 @@ void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_BEHAVIOR), "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -799,6 +820,7 @@ void DmRadarHelper::ReportDmBehavior(std::string hostName, std::string funcName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_BEHAVIOR), "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_FAIL), @@ -827,6 +849,7 @@ void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_LOCAL_DEVICE_INFO), "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -842,6 +865,7 @@ void DmRadarHelper::ReportGetLocalDevInfo(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_LOCAL_DEVICE_INFO), "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_FAIL), @@ -873,6 +897,7 @@ void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_DEVICE_INFO), "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_SUCC), @@ -889,6 +914,7 @@ void DmRadarHelper::ReportGetDeviceInfo(std::string hostName, "ORG_PKG", ORGPKGNAME, "HOST_PKG", hostName, "FUNC", funcName, + "API_TYPE", GetApiType(), "BIZ_SCENE", static_cast(DiscoverScene::DM_GET_DEVICE_INFO), "BIZ_STAGE", DEFAULT_STAGE, "STAGE_RES", static_cast(StageRes::STAGE_FAIL), @@ -970,6 +996,22 @@ int32_t DmRadarHelper::GetErrCode(int32_t errCode) return flag->second; } +int32_t DmRadarHelper::GetApiType() +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("GetApiType GetCallingTokenID error."); + return static_cast(ApiType::API_UNKNOW); + } + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_HAP) { + return static_cast(ApiType::API_JS); + } else if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + return static_cast(ApiType::API_NATIVE); + } + return static_cast(ApiType::API_UNKNOW); +} + IDmRadarHelper *CreateDmRadarInstance() { return &DmRadarHelper::GetInstance(); diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 23108f10c..8b86a63d2 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -476,6 +476,7 @@ void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t if (ret != DM_OK) { LOGE("[SOFTBUS]GetPeerDeviceId failed for session: %{public}d.", sessionId); } + LOGI("OnSessionOpened, peerDeviceId: %{public}s.", GetAnonyString(peerDeviceId).c_str()); DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(static_cast(PinHolderStage::SESSION_OPENED), std::string("OnSessionOpened"), std::string(peerDeviceId)); sessionId_ = sessionId; -- Gitee From 484104151dfc293670de9cacbe25667376aa207b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 16 Oct 2024 16:25:35 +0800 Subject: [PATCH 298/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- ... => ipc_notify_hichain_proof_status_req.h} | 34 +++++++++---------- .../include/device_manager_callback.h | 2 +- .../include/notify/device_manager_notify.h | 2 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 2 -- .../src/device_manager_service_impl.cpp | 2 +- .../src/device_manager_service_impl_lite.cpp | 2 +- .../service/include/device_manager_service.h | 2 +- .../include/device_manager_service_listener.h | 2 +- .../include/idevice_manager_service_impl.h | 2 +- .../idevice_manager_service_listener.h | 2 +- .../include/softbus/softbus_listener.h | 2 +- .../service/src/device_manager_service.cpp | 2 +- .../src/device_manager_service_listener.cpp | 6 ++-- .../src/ipc/standard/ipc_cmd_parser.cpp | 8 ++--- .../service/src/softbus/softbus_listener.cpp | 28 +++++++-------- ...UTTest_device_manager_service_listener.cpp | 11 ------ .../UTTest_ipc_cmd_parser_service.cpp | 6 ++-- 17 files changed, 50 insertions(+), 65 deletions(-) rename common/include/ipc/model/{ipc_notify_candidaterestrict_status_req.h => ipc_notify_hichain_proof_status_req.h} (56%) diff --git a/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h b/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h similarity index 56% rename from common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h rename to common/include/ipc/model/ipc_notify_hichain_proof_status_req.h index dcd4b8ce4..7cfb36a55 100644 --- a/common/include/ipc/model/ipc_notify_candidaterestrict_status_req.h +++ b/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef OHOS_DM_IPC_NOTIFY_CANDIDATERESTRICT_STATUS_REQ_H -#define OHOS_DM_IPC_NOTIFY_CANDIDATERESTRICT_STATUS_REQ_H +#ifndef OHOS_DM_IPC_NOTIFY_HICHAIN_PROOF_STATUS_REQ_H +#define OHOS_DM_IPC_NOTIFY_HICHAIN_PROOF_STATUS_REQ_H #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { -class IpcNotifyHichainProofExceptionStatusReq : public IpcReq { - DECLARE_IPC_MODEL(IpcNotifyHichainProofExceptionStatusReq); +class IpcNotifyHichainProofStatusReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyHichainProofStatusReq); public: /** - * @tc.name: IpcNotifyHichainProofExceptionStatusReq::GetPublishId - * @tc.desc: Get deviceId of the Ipc Notify Candidate Restrict Status Request + * @tc.name: IpcNotifyHichainProofStatusReq::GetPublishId + * @tc.desc: Get deviceId of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ std::string GetDeviceId() const @@ -35,8 +35,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofExceptionStatusReq::SetPublishId - * @tc.desc: Set deviceId of the Ipc Notify Candidate Restrict Status Request + * @tc.name: IpcNotifyHichainProofStatusReq::SetPublishId + * @tc.desc: Set deviceId of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ void SetDeviceId(const std::string &deviceId) @@ -45,8 +45,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofExceptionStatusReq::GetResult - * @tc.desc: Get DeviceType of the Ipc Notify Candidate Restrict Status Request + * @tc.name: IpcNotifyHichainProofStatusReq::GetResult + * @tc.desc: Get DeviceType of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ uint16_t GetDeviceTypeId() const @@ -55,8 +55,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofExceptionStatusReq::SetResult - * @tc.desc: Set DeviceType of the Ipc Notify Candidate Restrict Status Request + * @tc.name: IpcNotifyHichainProofStatusReq::SetResult + * @tc.desc: Set DeviceType of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ void SetDeviceTypeId(uint16_t deviceTypeId) @@ -65,8 +65,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofExceptionStatusReq::GetErrCode - * @tc.desc: Get ErrCode of the Ipc Notify Candidate Restrict Status Request + * @tc.name: IpcNotifyHichainProofStatusReq::GetErrCode + * @tc.desc: Get ErrCode of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ int32_t GetErrCode() const @@ -75,8 +75,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofExceptionStatusReq::SetErrCode - * @tc.desc: Set ErrCode of the Ipc Notify Candidate Restrict Status Request + * @tc.name: IpcNotifyHichainProofStatusReq::SetErrCode + * @tc.desc: Set ErrCode of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ void SetErrCode(int32_t errcode) @@ -91,4 +91,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IPC_NOTIFY_CANDIDATERESTRICT_STATUS_REQ_H +#endif // OHOS_DM_IPC_NOTIFY_HICHAIN_PROOF_STATUS_REQ_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 3c1380e2d..0a5ab50fa 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -155,7 +155,7 @@ public: { } virtual void OnHichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) = 0; + int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index f33bd48e8..4c270cb49 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 @@ -120,7 +120,7 @@ public: int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + int32_t errcode); private: #if !defined(__LITEOS_M__) 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 cd70bc97e..7ed4c9a42 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 @@ -1735,7 +1735,6 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt ON_IPC_CMD(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) { - LOGI("In."); std::string pkgName = data.ReadString(); std::string deviceId = data.ReadString(); uint16_t deviceTypeId = data.ReadUint16(); @@ -1743,7 +1742,6 @@ ON_IPC_CMD(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &data, MessageParce DeviceManagerNotify::GetInstance().OnHichainProofExceptionStatus(pkgName, deviceId, deviceTypeId, errCode); reply.WriteInt32(DM_OK); - LOGI("End."); return DM_OK; } } // namespace DistributedHardware diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index d0fced130..5aa9cc97b 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -854,7 +854,7 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI } void DeviceManagerServiceImpl::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) + int32_t errcode) { CHECK_NULL_VOID(deviceStateMgr_); deviceStateMgr_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 37addb9db..9045b1076 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -525,7 +525,7 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN } void DeviceManagerServiceImpl::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) + int32_t errcode) { (void)deviceId; (void)deviceTypeId; diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 5626e2c64..85861a162 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -202,7 +202,7 @@ public: void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + int32_t errcode); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index fe2cc3dfe..2f383c4c6 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -74,7 +74,7 @@ public: void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) override; + uint16_t deviceTypeId, int32_t errcode) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index f9ef5abaf..14c38d769 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -274,7 +274,7 @@ public: virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) = 0; + int32_t errcode) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 0387c420a..e2444c3dc 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -165,7 +165,7 @@ public: * @tc.type: FUNC */ virtual void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) = 0; + uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index d02847b52..bb23cfa59 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -59,7 +59,7 @@ public: static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); static void OnHichainProofStatus(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, - int32_t errcode); + int32_t errcode); static void HichainProofExceptionProcess(std::string deviceId, uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 1535fad42..0abcb8086 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1995,7 +1995,7 @@ void DeviceManagerService::SubscribePackageCommonEvent() } void DeviceManagerService::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) + int32_t errcode) { if (IsDMServiceImplReady()) { dmServiceImpl_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 1eb98c1f9..f374d2830 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -26,13 +26,13 @@ #include "ipc_destroy_pin_holder_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" -#include "ipc_notify_candidaterestrict_status_req.h" #include "ipc_notify_credential_req.h" #include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_device_found_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_device_state_req.h" #include "ipc_notify_discover_result_req.h" +#include "ipc_notify_hichain_proof_status_req.h" #include "ipc_notify_pin_holder_event_req.h" #include "ipc_notify_publish_result_req.h" #include "ipc_server_stub.h" @@ -556,8 +556,8 @@ void DeviceManagerServiceListener::OnHichainProofExceptionStatus(const std::stri const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { LOGI("In, pkgName = %{public}s", pkgName.c_str()); - std::shared_ptr pReq = - std::make_shared(); + std::shared_ptr pReq = + std::make_shared(); std::shared_ptr pRsp = std::make_shared(); pReq->SetDeviceId(deviceId); pReq->SetDeviceTypeId(deviceTypeId); diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 51947fc36..069bf939a 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -33,12 +33,12 @@ #include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" -#include "ipc_notify_candidaterestrict_status_req.h" #include "ipc_notify_credential_req.h" #include "ipc_notify_device_found_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_device_state_req.h" #include "ipc_notify_discover_result_req.h" +#include "ipc_notify_hichain_proof_status_req.h" #include "ipc_notify_publish_result_req.h" #include "ipc_notify_pin_holder_event_req.h" #include "ipc_server_client_proxy.h" @@ -1575,12 +1575,11 @@ ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) { - LOGI("In"); if (pBaseReq == nullptr) { return ERR_DM_FAILED; } - std::shared_ptr pReq = - std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string deviceId = pReq->GetDeviceId(); uint16_t deviceTypeId = pReq->GetDeviceTypeId(); @@ -1602,7 +1601,6 @@ ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr p LOGE("write errCode failed"); return ERR_DM_IPC_WRITE_FAILED; } - LOGI("End."); return DM_OK; } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 2c437b0ce..f95f08f64 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -67,7 +67,7 @@ static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; static std::mutex g_lockDeviceIdSet; static std::mutex g_lockDevScreenStatusChange; -static std::mutex g_lockCandidateRestrictStatus; +static std::mutex g_lockHichainProofStatus; static std::map>>> discoveredDeviceMap; static std::map> lnnOpsCbkMap; @@ -121,7 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, - .OnHichainProofStatus = SoftbusListener::OnHichainProofStatus, + .onHichainProofException = SoftbusListener::OnHichainProofStatus, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -167,28 +167,28 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) void SoftbusListener::HichainProofExceptionProcess(std::string deviceId, uint16_t deviceTypeId, int32_t errcode) { - std::lock_guard lock(g_lockCandidateRestrictStatus); + std::lock_guard lock(g_lockHichainProofStatus); DeviceManagerService::GetInstance().HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); } void SoftbusListener::OnHichainProofStatus(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, - int32_t errcode) + int32_t errcode) { - LOGI("received candidate restrict status callback from softbus."); + LOGI("received hichain proof status callback from softbus."); if (deviceId == nullptr || deviceIdLen == 0) { LOGE("received invaild deviceId."); return; } std::string deviceIdStr(deviceId, deviceIdLen); - #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); - #else - std::thread hichainProofStatus([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); - if (pthread_setname_np(hichainProofStatus.native_handle(), HICHAIN_PROOF_STATUS) != DM_OK) { - LOGE("hichainProofStatus setname failed."); - } - hichainProofStatus.detach(); - #endif +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); +#else + std::thread hichainProofStatus([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); + if (pthread_setname_np(hichainProofStatus.native_handle(), HICHAIN_PROOF_STATUS) != DM_OK) { + LOGE("hichainProofStatus setname failed."); + } + hichainProofStatus.detach(); +#endif } void SoftbusListener::OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status) diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index e8abba6df..77a8944df 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -432,17 +432,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::T listener_->OnPinHolderEvent(pkgName, event, result, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } - -HWTEST_F(DeviceManagerServiceListenerTest, OnHandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - std::string deviceId = "0123456789"; - uint16_t deviceTypeId = 0x00; - int32_t errcode = -1; - listener_->OnHichainProofExceptionStatus(pkgName, deviceId, deviceTypeId, errcode); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index db81d1f05..3aaa244dc 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -32,10 +32,10 @@ #include "ipc_get_trustdevice_rsp.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" -#include "ipc_notify_candidaterestrict_status_req.h" #include "ipc_notify_credential_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_dmfa_result_req.h" +#include "ipc_notify_hichain_proof_status_req.h" #include "ipc_notify_event_req.h" #include "ipc_notify_pin_holder_event_req.h" #include "ipc_notify_publish_result_req.h" @@ -1534,7 +1534,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. { int32_t cmdCode = SERVER_HICHAIN_PROOF_STATUS_NOTIFY; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -1542,7 +1542,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; std::string deviceId = "012345678"; uint16_t deviceTypeId = 0x00; -- Gitee From baed13b8288a856da0e09a9fd4059505e4a423ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 16 Oct 2024 17:04:51 +0800 Subject: [PATCH 299/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/implementation/include/device_manager_service_impl.h | 2 +- .../implementation/include/device_manager_service_impl_lite.h | 2 +- .../include/devicestate/dm_device_state_manager.h | 1 - test/unittest/UTTest_device_manager_impl_three.cpp | 1 - 4 files changed, 2 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 84936abf5..369ee46af 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -132,7 +132,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + int32_t errcode); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 97fd49541..33d40b410 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -138,7 +138,7 @@ public: void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + int32_t errcode); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 77d876ea0..f39f4714a 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -97,7 +97,6 @@ public: void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); - private: void StartEventThread(); void StopEventThread(); diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 570461fe0..fddaad999 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1345,7 +1345,6 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_003, testing::ext::TestSiz DeviceManager::GetInstance().UnInitDeviceManager(packName); } - HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = ""; -- Gitee From ba665d31da8a84c89f9e0709981e58e2699f1d6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 16 Oct 2024 17:15:25 +0800 Subject: [PATCH 300/520] =?UTF-8?q?=E5=B1=8F=E8=94=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index f95f08f64..6a3352f95 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -121,7 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, - .onHichainProofException = SoftbusListener::OnHichainProofStatus, + // .onHichainProofException = SoftbusListener::OnHichainProofStatus, }; static IRefreshCallback softbusRefreshCallback_ = { -- Gitee From cc2eb43e05a55336a6edb4f1511c75fcff977d5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 16 Oct 2024 17:19:24 +0800 Subject: [PATCH 301/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../implementation/src/devicestate/dm_device_state_manager.cpp | 2 +- test/unittest/UTTest_device_manager_impl.h | 2 +- test/unittest/UTTest_dm_pin_holder.h | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 29889c99b..f7c0176c6 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -528,7 +528,7 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) } void DmDeviceStateManager::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) + int32_t errcode) { if (softbusConnector_ == nullptr || listener_ == nullptr) { LOGE("Failed, callback_ptr is null."); diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index fb0b65417..1db483efe 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -124,7 +124,7 @@ public: { } void OnHichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) override {} + int32_t errcode) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index a293ec66b..8a1030752 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -194,7 +194,7 @@ public: } void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) override + uint16_t deviceTypeId, int32_t errcode) override { (void)pkgName; (void)deviceId; -- Gitee From e5887256cb30859fb6027e3b476282dc730baef9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Wed, 16 Oct 2024 17:27:27 +0800 Subject: [PATCH 302/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0fuzz=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn b/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn index 0b4a67247..737b7b187 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/BUILD.gn @@ -68,6 +68,7 @@ ohos_fuzztest("IpcServerStubFuzzTest") { ] external_deps = [ + "ability_base:want", "c_utils:utils", "data_share:datashare_common", "data_share:datashare_consumer", -- Gitee From a0af8fafb77a142c69930d2488a8473830c062ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 17 Oct 2024 09:01:56 +0800 Subject: [PATCH 303/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9codecheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/src/notify/device_manager_notify.cpp | 2 +- test/unittest/UTTest_device_manager_impl_three.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 7aba869b5..cee27cb69 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 @@ -1170,7 +1170,7 @@ void DeviceManagerNotify::UnRegisterHichainProofExceptionStatusCallback(const st } void DeviceManagerNotify::OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) + uint16_t deviceTypeId, int32_t errcode) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index fddaad999..1a8ffc306 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1348,7 +1348,8 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_003, testing::ext::TestSiz HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = ""; - std::shared_ptr callback = std::make_shared(); + std::shared_ptr callback = + std::make_shared(); int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1364,7 +1365,8 @@ HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_002, tes HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_003, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.scandidateRestrict02"; - std::shared_ptr callback = std::make_shared(); + std::shared_ptr callback = + std::make_shared(); int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); ASSERT_EQ(ret, DM_OK); } -- Gitee From c6d29fe4ca007546eae114d827d99d15c33e3b9a Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 15 Oct 2024 14:19:00 +0800 Subject: [PATCH 304/520] =?UTF-8?q?=E7=BB=91=E5=AE=9A=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- interfaces/kits/js/include/native_devicemanager_js.h | 2 +- services/implementation/src/authentication/dm_auth_manager.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/js/include/native_devicemanager_js.h b/interfaces/kits/js/include/native_devicemanager_js.h index 496f0b47b..ebe81431f 100644 --- a/interfaces/kits/js/include/native_devicemanager_js.h +++ b/interfaces/kits/js/include/native_devicemanager_js.h @@ -32,7 +32,7 @@ #include "napi/native_node_api.h" #include "nlohmann/json.hpp" #define DM_NAPI_BUF_LENGTH (256) -#define DM_NAPI_CREDENTIAL_BUF_LENGTH (12000) +#define DM_NAPI_CREDENTIAL_BUF_LENGTH (64000) #define DM_NAPI_DESCRIPTION_BUF_LENGTH (16384) struct AsyncCallbackInfo { diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index f5fb9c185..1fabdfe0b 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2304,6 +2304,7 @@ int32_t DmAuthManager::CheckTrustState() CompatiblePutAcl(); } softbusConnector_->JoinLnn(authResponseContext_->deviceId); + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return ALREADY_BIND; } -- Gitee From 69bf08db438b32c37a4092de7c42a3bcc4c7c0c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 17 Oct 2024 10:22:30 +0800 Subject: [PATCH 305/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../ipc/model/ipc_notify_hichain_proof_status_req.h | 8 ++++---- services/service/src/softbus/softbus_listener.cpp | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h b/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h index 7cfb36a55..613cc2030 100644 --- a/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h +++ b/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h @@ -25,7 +25,7 @@ class IpcNotifyHichainProofStatusReq : public IpcReq { public: /** - * @tc.name: IpcNotifyHichainProofStatusReq::GetPublishId + * @tc.name: IpcNotifyHichainProofStatusReq::GetDeviceId * @tc.desc: Get deviceId of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ @@ -35,7 +35,7 @@ public: } /** - * @tc.name: IpcNotifyHichainProofStatusReq::SetPublishId + * @tc.name: IpcNotifyHichainProofStatusReq::SetDeviceId * @tc.desc: Set deviceId of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ @@ -45,7 +45,7 @@ public: } /** - * @tc.name: IpcNotifyHichainProofStatusReq::GetResult + * @tc.name: IpcNotifyHichainProofStatusReq::GetDeviceTypeId * @tc.desc: Get DeviceType of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ @@ -55,7 +55,7 @@ public: } /** - * @tc.name: IpcNotifyHichainProofStatusReq::SetResult + * @tc.name: IpcNotifyHichainProofStatusReq::SetDeviceTypeId * @tc.desc: Set DeviceType of the Ipc Notify Hichain proof Status Request * @tc.type: FUNC */ diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 6a3352f95..f95f08f64 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -121,7 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, - // .onHichainProofException = SoftbusListener::OnHichainProofStatus, + .onHichainProofException = SoftbusListener::OnHichainProofStatus, }; static IRefreshCallback softbusRefreshCallback_ = { -- Gitee From e9e6f6e0e21384f9b51f557e898358ec9ed85710 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 17 Oct 2024 10:37:53 +0800 Subject: [PATCH 306/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_impl_three.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 1a8ffc306..6f5239d62 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1345,7 +1345,7 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_003, testing::ext::TestSiz DeviceManager::GetInstance().UnInitDeviceManager(packName); } -HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = ""; std::shared_ptr callback = @@ -1354,7 +1354,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_001, tes ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } -HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_002, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.candidateRestrict01"; std::shared_ptr callback = nullptr; @@ -1362,7 +1362,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_002, tes ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } -HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_003, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.scandidateRestrict02"; std::shared_ptr callback = @@ -1371,14 +1371,14 @@ HWTEST_F(DeviceManagerImplTest, RegisterCandidateRestrictStatusCallback_003, tes ASSERT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, UnRegisterCandidateRestrictStatusCallback_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, UnRegisterHichainProofExceptionStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.candidateRestrict03"; int32_t ret = DeviceManager::GetInstance().UnRegisterHichainProofExceptionStatusCallback(packName); ASSERT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, UnRegisterCandidateRestrictStatusCallback_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, UnRegisterHichainProofExceptionStatusCallback_002, testing::ext::TestSize.Level0) { std::string packName = ""; int32_t ret = DeviceManager::GetInstance().UnRegisterHichainProofExceptionStatusCallback(packName); -- Gitee From df9c8bbc2e700bdfe9eccc7e5bda95168e32de68 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 15 Oct 2024 11:03:21 +0800 Subject: [PATCH 307/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=8F=98=E9=87=8F?= =?UTF-8?q?=E7=AE=A1=E6=8E=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../include/ipc/standard/ipc_cmd_register.h | 7 ++ common/src/ipc/standard/ipc_cmd_register.cpp | 64 +++++++++++-------- 2 files changed, 45 insertions(+), 26 deletions(-) diff --git a/common/include/ipc/standard/ipc_cmd_register.h b/common/include/ipc/standard/ipc_cmd_register.h index 650a69950..885abc550 100644 --- a/common/include/ipc/standard/ipc_cmd_register.h +++ b/common/include/ipc/standard/ipc_cmd_register.h @@ -18,6 +18,7 @@ #include #include +#include #include #include "device_manager_ipc_interface_code.h" @@ -76,6 +77,7 @@ public: */ void RegisterSetRequestFunc(int32_t cmdCode, SetIpcRequestFunc setIpcRequestFunc) { + std::lock_guard autoLock(setIpcRequestFuncMapLock_); setIpcRequestFuncMap_.emplace(cmdCode, setIpcRequestFunc); }; @@ -86,6 +88,7 @@ public: */ void RegisterReadResponseFunc(int32_t cmdCode, ReadResponseFunc readResponseFunc) { + std::lock_guard autoLock(readResponseFuncMapLock_); readResponseFuncMap_.emplace(cmdCode, readResponseFunc); }; @@ -96,6 +99,7 @@ public: */ void RegisterCmdProcessFunc(int32_t cmdCode, OnIpcCmdFunc onIpcCmdFunc) { + std::lock_guard autoLock(onIpcCmdFuncMapLock_); onIpcCmdFuncMap_.emplace(cmdCode, onIpcCmdFunc); }; @@ -121,8 +125,11 @@ public: int32_t OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply); private: + std::mutex setIpcRequestFuncMapLock_; std::unordered_map setIpcRequestFuncMap_; + std::mutex readResponseFuncMapLock_; std::unordered_map readResponseFuncMap_; + std::mutex onIpcCmdFuncMapLock_; std::unordered_map onIpcCmdFuncMap_; }; } // namespace DistributedHardware diff --git a/common/src/ipc/standard/ipc_cmd_register.cpp b/common/src/ipc/standard/ipc_cmd_register.cpp index 4f18a43bb..082a4e8d4 100644 --- a/common/src/ipc/standard/ipc_cmd_register.cpp +++ b/common/src/ipc/standard/ipc_cmd_register.cpp @@ -41,21 +41,21 @@ int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBas LOGE("IpcCmdRegister::SetRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - - if (setIpcRequestFuncMap_.count(cmdCode) == 0) { - LOGE("cmdCode:%{public}d not register SetRequestFunc", cmdCode); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - - auto setRequestMapIter = setIpcRequestFuncMap_.find(cmdCode); - if (setRequestMapIter != setIpcRequestFuncMap_.end()) { - SetIpcRequestFunc ptr = setRequestMapIter->second; + SetIpcRequestFunc ptr = nullptr; + { + std::lock_guard autoLock(setIpcRequestFuncMapLock_); + auto setRequestMapIter = setIpcRequestFuncMap_.find(cmdCode); + if (setRequestMapIter == setIpcRequestFuncMap_.end()) { + LOGE("cmdCode:%{public}d not register SetRequestFunc", cmdCode); + return ERR_DM_UNSUPPORTED_IPC_COMMAND; + } + ptr = setRequestMapIter->second; if (ptr == nullptr) { LOGE("IpcCmdRegister::SetRequest setRequestMapIter->second is null"); return ERR_DM_POINT_NULL; } - ret = (setRequestMapIter->second)(pBaseReq, data); } + ret = (ptr)(pBaseReq, data); return ret; } @@ -65,15 +65,21 @@ int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std: LOGE("IpcCmdRegister::ReadResponse cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - auto readResponseMapIter = readResponseFuncMap_.find(cmdCode); - if (readResponseMapIter == readResponseFuncMap_.end()) { - LOGE("cmdCode:%{public}d not register ReadResponseFunc", cmdCode); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - if (readResponseMapIter->second == nullptr) { - return ERR_DM_POINT_NULL; + ReadResponseFunc ptr = nullptr; + { + std::lock_guard autoLock(readResponseFuncMapLock_); + auto readResponseMapIter = readResponseFuncMap_.find(cmdCode); + if (readResponseMapIter == readResponseFuncMap_.end()) { + LOGE("cmdCode:%{public}d not register ReadResponseFunc", cmdCode); + return ERR_DM_UNSUPPORTED_IPC_COMMAND; + } + ptr = readResponseMapIter->second; + if (ptr == nullptr) { + LOGE("IpcCmdRegister::ReadResponse readResponseMapIter->second is null"); + return ERR_DM_POINT_NULL; + } } - return (readResponseMapIter->second)(reply, pBaseRsp); + return (ptr)(reply, pBaseRsp); } int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply) @@ -82,15 +88,21 @@ int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessagePa LOGE("IpcCmdRegister::OnIpcCmd cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - auto onIpcCmdMapIter = onIpcCmdFuncMap_.find(cmdCode); - if (onIpcCmdMapIter == onIpcCmdFuncMap_.end()) { - LOGE("cmdCode:%{public}d not register OnIpcCmdFunc", cmdCode); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - if (onIpcCmdMapIter->second == nullptr) { - return ERR_DM_POINT_NULL; + OnIpcCmdFunc ptr = nullptr; + { + std::lock_guard autoLock(onIpcCmdFuncMapLock_); + auto onIpcCmdMapIter = onIpcCmdFuncMap_.find(cmdCode); + if (onIpcCmdMapIter == onIpcCmdFuncMap_.end()) { + LOGE("cmdCode:%{public}d not register OnIpcCmdFunc", cmdCode); + return ERR_DM_UNSUPPORTED_IPC_COMMAND; + } + ptr = onIpcCmdMapIter->second; + if (ptr == nullptr) { + LOGE("IpcCmdRegister::OnIpcCmd onIpcCmdMapIter->second is null"); + return ERR_DM_POINT_NULL; + } } - return (onIpcCmdMapIter->second)(data, reply); + return (ptr)(data, reply); } } // namespace DistributedHardware } // namespace OHOS -- Gitee From 40c3a078dba2d3888fc3396e791a429dff1fb869 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 17 Oct 2024 15:18:59 +0800 Subject: [PATCH 308/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/devicestate/dm_device_state_manager.cpp | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index f7c0176c6..6b191f6b3 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -530,18 +530,11 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) void DmDeviceStateManager::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) { - if (softbusConnector_ == nullptr || listener_ == nullptr) { - LOGE("Failed, callback_ptr is null."); + if (listener_ == nullptr) { + LOGE("Failed, listener_ is null."); return; } - std::vector pkgName = softbusConnector_->GetPkgName(); - if (pkgName.size() == 0) { - listener_->OnHichainProofExceptionStatus(std::string(DM_PKG_NAME), deviceId, deviceTypeId, errcode); - } else { - for (auto item : pkgName) { - listener_->OnHichainProofExceptionStatus(item, deviceId, deviceTypeId, errcode); - } - } + listener_->OnHichainProofExceptionStatus(std::string(DM_PKG_NAME), deviceId, deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 53493b038e5884173064013892f32d34a6d2a2ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Thu, 17 Oct 2024 15:55:35 +0800 Subject: [PATCH 309/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../src/devicenamemgr/account_boot_listener.cpp | 10 ++++++++-- .../src/devicenamemgr/local_device_name_mgr.cpp | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index fec2dc7bc..87947975b 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -39,6 +39,10 @@ std::mutex AccountBootListener::lock_; static void AccountBootCb(const char *key, const char *value, void *context) { + if (key == nullptr || value == nullptr) { + LOGE("key or value is null, param is error!"); + return; + } if (strcmp(key, BOOTEVENT_ACCOUNT_READY) != 0 || strcmp(value, "true") != 0) { return; } @@ -117,6 +121,8 @@ void AccountBootListener::SetSaTriggerFlag(SaTriggerFlag triggerFlag) default: break; } + LOGI("isDmSaReady_:%{public}d,isDataShareReady_:%{public}d", + std::atomic_load(&isDmSaReady_),std::atomic_load(&isDataShareReady_)); if (isDmSaReady_ && isDataShareReady_) { LOGI("dm and data_share is ready!"); this->RegisterAccountBootCb(); @@ -145,8 +151,8 @@ void AccountBootListener::DataShareCallback() LOGI("Start"); std::lock_guard lock(lock_); isDataShareReady_ = true; - LOGI("isDmSaReady_:%{public}d", std::atomic_load(&isDmSaReady_)); - LOGI("isDataShareReady_:%{public}d", std::atomic_load(&isDataShareReady_)); + LOGI("isDmSaReady_:%{public}d,isDataShareReady_:%{public}d", + std::atomic_load(&isDmSaReady_),std::atomic_load(&isDataShareReady_)); if (isDmSaReady_ && isDataShareReady_) { LOGI("dm and data_share is ready!"); this->RegisterAccountBootCb(); diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp index 58b80f376..8f2c803ee 100644 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -76,6 +76,10 @@ int32_t LocalDeviceNameMgr::GetDeviceNameFromDataShareHelper( std::shared_ptr dataShareHelper, std::shared_ptr uri, const char *key, std::string &deviceName) { + if (uri == nullptr || key == nullptr) { + LOGE("uri or key is null, param is error!"); + return ERR_DM_FAILED; + } int32_t numRows = 0; std::string val; std::vector columns; @@ -122,6 +126,7 @@ int32_t LocalDeviceNameMgr::GetUserDefinedDeviceName(std::shared_ptr Date: Thu, 17 Oct 2024 20:00:09 +0800 Subject: [PATCH 310/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=99=BD=E5=90=8D?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 11 ++++++++++- .../src/permission/standard/permission_manager.cpp | 3 ++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f7b5d0ff2..72f4f9569 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1751,10 +1751,19 @@ void DeviceManagerService::HandleDeviceNotTrust(const std::string &msg) int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::map &policy) { - if (!PermissionManager::GetInstance().CheckNewPermission()) { + if (!PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } + std::string processName = ""; + if (PermissionManager::GetInstance().GetCallerProcessName(processName) != DM_OK) { + LOGE("Get caller process name failed, pkgname: %{public}s.", pkgName.c_str()); + return ERR_DM_FAILED; + } + if (!PermissionManager::GetInstance().CheckSystemSA(processName)) { + LOGE("The caller: %{public}s is not in white list.", processName.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } LOGI("Start for pkgName = %{public}s", pkgName.c_str()); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 23fc34d23..aa35eea84 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -49,7 +49,7 @@ constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_ "CollaborationFwk", }; -constexpr int32_t SYSTEM_SA_WHITE_LIST_NUM = 7; +constexpr int32_t SYSTEM_SA_WHITE_LIST_NUM = 8; constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", @@ -58,6 +58,7 @@ constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME "distributed_bundle_framework", "ohos.dhardware", "ohos.security.distributed_access_token", + "collaboration_service", }; } -- Gitee From 909813eaef61284aa19ae84676ac41486125a191 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 18 Oct 2024 10:08:35 +0800 Subject: [PATCH 311/520] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../ipc_notify_hichain_proof_status_req.h | 21 ------------------- .../include/device_manager_callback.h | 3 +-- .../include/notify/device_manager_notify.h | 3 +-- .../src/ipc/standard/ipc_cmd_parser.cpp | 3 +-- .../src/notify/device_manager_notify.cpp | 6 +++--- .../include/device_manager_service_impl.h | 3 +-- .../device_manager_service_impl_lite.h | 3 +-- .../devicestate/dm_device_state_manager.h | 2 +- .../src/device_manager_service_impl.cpp | 5 ++--- .../src/device_manager_service_impl_lite.cpp | 4 +--- .../devicestate/dm_device_state_manager.cpp | 5 ++--- .../service/include/device_manager_service.h | 3 +-- .../include/device_manager_service_listener.h | 3 +-- .../include/idevice_manager_service_impl.h | 3 +-- .../idevice_manager_service_listener.h | 4 ++-- .../include/softbus/softbus_listener.h | 5 ++--- .../service/src/device_manager_service.cpp | 5 ++--- .../src/device_manager_service_listener.cpp | 3 +-- .../src/ipc/standard/ipc_cmd_parser.cpp | 5 ----- .../service/src/softbus/softbus_listener.cpp | 16 +++++--------- .../UTTest_dm_device_state_manager.cpp | 3 +-- .../UTTest_softbus_listener.cpp | 6 ++---- test/unittest/UTTest_device_manager_impl.h | 3 +-- .../UTTest_device_manager_service_impl.cpp | 3 +-- test/unittest/UTTest_dm_pin_holder.h | 4 +--- 25 files changed, 35 insertions(+), 89 deletions(-) diff --git a/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h b/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h index 613cc2030..bb82802ec 100644 --- a/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h +++ b/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h @@ -24,26 +24,6 @@ class IpcNotifyHichainProofStatusReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyHichainProofStatusReq); public: - /** - * @tc.name: IpcNotifyHichainProofStatusReq::GetDeviceId - * @tc.desc: Get deviceId of the Ipc Notify Hichain proof Status Request - * @tc.type: FUNC - */ - std::string GetDeviceId() const - { - return deviceId_; - } - - /** - * @tc.name: IpcNotifyHichainProofStatusReq::SetDeviceId - * @tc.desc: Set deviceId of the Ipc Notify Hichain proof Status Request - * @tc.type: FUNC - */ - void SetDeviceId(const std::string &deviceId) - { - deviceId_ = deviceId; - } - /** * @tc.name: IpcNotifyHichainProofStatusReq::GetDeviceTypeId * @tc.desc: Get DeviceType of the Ipc Notify Hichain proof Status Request @@ -85,7 +65,6 @@ public: } private: - std::string deviceId_; uint16_t deviceTypeId_ = 0; int32_t errcode_ = 0; }; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 0a5ab50fa..9a4bc834a 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -154,8 +154,7 @@ public: virtual ~HichainProofExceptionStatusCallback() { } - virtual void OnHichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) = 0; + virtual void OnHichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 4c270cb49..690855131 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 @@ -119,8 +119,7 @@ public: void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode); private: #if !defined(__LITEOS_M__) 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 7ed4c9a42..d2721d8bf 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 @@ -1736,10 +1736,9 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt ON_IPC_CMD(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); - std::string deviceId = data.ReadString(); uint16_t deviceTypeId = data.ReadUint16(); int32_t errCode = data.ReadInt32(); - DeviceManagerNotify::GetInstance().OnHichainProofExceptionStatus(pkgName, deviceId, deviceTypeId, errCode); + DeviceManagerNotify::GetInstance().OnHichainProofExceptionStatus(pkgName, deviceTypeId, errCode); reply.WriteInt32(DM_OK); return DM_OK; diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index cee27cb69..98437e78a 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 @@ -1169,8 +1169,8 @@ void DeviceManagerNotify::UnRegisterHichainProofExceptionStatusCallback(const st hichainProofExceptionStatusCallback_.erase(pkgName); } -void DeviceManagerNotify::OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerNotify::OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, + int32_t errcode) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -1190,7 +1190,7 @@ void DeviceManagerNotify::OnHichainProofExceptionStatus(const std::string &pkgNa LOGE("error, registered hichain proof exception status callback is nullptr."); return; } - tempCbk->OnHichainProofExceptionStatus(deviceId, deviceTypeId, errcode); + tempCbk->OnHichainProofExceptionStatus(deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 369ee46af..29e027379 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -131,8 +131,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 33d40b410..76787058d 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -137,8 +137,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index f39f4714a..3c6a08d04 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,7 +96,7 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode); + void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 5aa9cc97b..768d37586 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -853,11 +853,10 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } -void DeviceManagerServiceImpl::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) +void DeviceManagerServiceImpl::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) { CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); + deviceStateMgr_->HichainProofExceptionStatus(deviceTypeId, errcode); } extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 9045b1076..2da689667 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -524,10 +524,8 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } -void DeviceManagerServiceImpl::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) +void DeviceManagerServiceImpl::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) { - (void)deviceId; (void)deviceTypeId; (void)errcode; return; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 6b191f6b3..6f3732e1a 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -527,14 +527,13 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) softbusConnector_->ClearPkgName(); } -void DmDeviceStateManager::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) +void DmDeviceStateManager::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) { if (listener_ == nullptr) { LOGE("Failed, listener_ is null."); return; } - listener_->OnHichainProofExceptionStatus(std::string(DM_PKG_NAME), deviceId, deviceTypeId, errcode); + listener_->OnHichainProofExceptionStatus(std::string(DM_PKG_NAME), deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 85861a162..ce13ac1d7 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,8 +201,7 @@ public: int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); - void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode); + void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 2f383c4c6..eb3b965c2 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -73,8 +73,7 @@ public: const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; - void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) override; + void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 14c38d769..4f505ad5f 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -273,8 +273,7 @@ public: virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; - virtual void HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) = 0; + virtual void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index e2444c3dc..ddf2ebc53 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -164,8 +164,8 @@ public: * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, + int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index bb23cfa59..82bcfc93a 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -58,9 +58,8 @@ public: static void DeviceTrustedChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); - static void OnHichainProofStatus(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, - int32_t errcode); - static void HichainProofExceptionProcess(std::string deviceId, uint16_t deviceTypeId, int32_t errcode); + static void OnHichainProofStatus(uint16_t deviceTypeId, int32_t errcode); + static void HichainProofExceptionProcess(uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0abcb8086..5bbd98a0a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1994,11 +1994,10 @@ void DeviceManagerService::SubscribePackageCommonEvent() #endif } -void DeviceManagerService::HichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) +void DeviceManagerService::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) { if (IsDMServiceImplReady()) { - dmServiceImpl_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); + dmServiceImpl_->HichainProofExceptionStatus(deviceTypeId, errcode); } } } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index f374d2830..a07a51c93 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -553,13 +553,12 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) } void DeviceManagerServiceListener::OnHichainProofExceptionStatus(const std::string &pkgName, - const std::string &deviceId, uint16_t deviceTypeId, int32_t errcode) + uint16_t deviceTypeId, int32_t errcode) { LOGI("In, pkgName = %{public}s", pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetDeviceId(deviceId); pReq->SetDeviceTypeId(deviceTypeId); pReq->SetErrCode(errcode); if (pkgName == std::string(DM_PKG_NAME)) { diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 069bf939a..6c03e6254 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1581,7 +1581,6 @@ ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr p std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); - std::string deviceId = pReq->GetDeviceId(); uint16_t deviceTypeId = pReq->GetDeviceTypeId(); int32_t errCode = pReq->GetErrCode(); @@ -1589,10 +1588,6 @@ ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr p LOGE("write pkgName failed"); return ERR_DM_IPC_WRITE_FAILED; } - if (!data.WriteString(deviceId)) { - LOGE("write deviceId failed"); - return ERR_DM_IPC_WRITE_FAILED; - } if (!data.WriteUint16(deviceTypeId)) { LOGE("write deviceTypeId failed"); return ERR_DM_IPC_WRITE_FAILED; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index f95f08f64..fba3915bf 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -165,25 +165,19 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); } -void SoftbusListener::HichainProofExceptionProcess(std::string deviceId, uint16_t deviceTypeId, int32_t errcode) +void SoftbusListener::HichainProofExceptionProcess(uint16_t deviceTypeId, int32_t errcode) { std::lock_guard lock(g_lockHichainProofStatus); - DeviceManagerService::GetInstance().HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); + DeviceManagerService::GetInstance().HichainProofExceptionStatus(deviceTypeId, errcode); } -void SoftbusListener::OnHichainProofStatus(const char *deviceId, uint32_t deviceIdLen, uint16_t deviceTypeId, - int32_t errcode) +void SoftbusListener::OnHichainProofStatus(uint16_t deviceTypeId, int32_t errcode) { LOGI("received hichain proof status callback from softbus."); - if (deviceId == nullptr || deviceIdLen == 0) { - LOGE("received invaild deviceId."); - return; - } - std::string deviceIdStr(deviceId, deviceIdLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); + ffrt::submit([=]() { HichainProofExceptionProcess(deviceTypeId, errcode); }); #else - std::thread hichainProofStatus([=]() { HichainProofExceptionProcess(deviceIdStr, deviceTypeId, errcode); }); + std::thread hichainProofStatus([=]() { HichainProofExceptionProcess(deviceTypeId, errcode); }); if (pthread_setname_np(hichainProofStatus.native_handle(), HICHAIN_PROOF_STATUS) != DM_OK) { LOGE("hichainProofStatus setname failed."); } diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 08e87b283..38dae6eca 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -255,10 +255,9 @@ HWTEST_F(DmDeviceStateManagerTest, ProcNotifyEvent_001, testing::ext::TestSize.L HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) { - std::string deviceId = "1234567890"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - dmDeviceStateManager->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); + dmDeviceStateManager->HichainProofExceptionStatus(deviceTypeId, errcode); EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); } } // namespace diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 0c9c2d1ae..c553b1c17 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -731,13 +731,11 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener->OnDeviceTrustedChange(type, msg1, msgLen2); softbusListener->OnDeviceTrustedChange(type, msg2, msgLen2); softbusListener->SendAclChangedBroadcast(msg); - char deviceId[DM_MAX_DEVICE_ID_LEN] = "XXX"; uint16_t deviceTypeId = 0; int32_t errcode = -1; - softbusListener->OnHichainProofStatus(deviceId, DM_MAX_DEVICE_ID_LEN, deviceTypeId, errcode); - std::string deviceId2 = "1234567890"; + softbusListener->OnHichainProofStatus(deviceTypeId, errcode); deviceTypeId = 0xA2F; - softbusListener->HichainProofExceptionProcess(deviceId2, deviceTypeId, errcode); + softbusListener->HichainProofExceptionProcess(deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index 1db483efe..51c1d10e6 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -123,8 +123,7 @@ public: virtual ~CandidateRestrictStatusCallbackTest() { } - void OnHichainProofExceptionStatus(const std::string &deviceId, uint16_t deviceTypeId, - int32_t errcode) override {} + void OnHichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 1ee369bc8..08e9c1a9d 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1504,10 +1504,9 @@ HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::e HWTEST_F(DeviceManagerServiceImplTest, HandleCandidateRestrictStatus_101, testing::ext::TestSize.Level0) { - std::string deviceId = "0123456789"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - deviceManagerServiceImpl_->HichainProofExceptionStatus(deviceId, deviceTypeId, errcode); + deviceManagerServiceImpl_->HichainProofExceptionStatus(deviceTypeId, errcode); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } } // namespace diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 8a1030752..31b3d89e6 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -193,11 +193,9 @@ public: (void)devInfo; } - void OnHichainProofExceptionStatus(const std::string &pkgName, const std::string &deviceId, - uint16_t deviceTypeId, int32_t errcode) override + void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override { (void)pkgName; - (void)deviceId; (void)deviceTypeId; (void)errcode; } -- Gitee From db3cd12f4105b15930d33aa86364b58e9f38bae5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 18 Oct 2024 10:17:48 +0800 Subject: [PATCH 312/520] =?UTF-8?q?=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_ipc_cmd_parser_service.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 3aaa244dc..060c4b115 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -1544,11 +1544,9 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. req = std::make_shared(); std::string pkgName = "com.ohos.test"; - std::string deviceId = "012345678"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; req->SetPkgName(pkgName); - req->SetDeviceId(deviceId); req->SetDeviceTypeId(deviceTypeId); req->SetErrCode(errcode); if (ptr) { -- Gitee From 200fcf3cd0a38ebb0fee92ab734130b81c45499e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 18 Oct 2024 11:50:13 +0800 Subject: [PATCH 313/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../permission/lite/permission_manager.h | 1 + .../permission/standard/permission_manager.h | 1 + .../service/src/device_manager_service.cpp | 2 +- .../permission/lite/permission_manager.cpp | 6 +++++ .../standard/permission_manager.cpp | 24 ++++++++++++++++++- 5 files changed, 32 insertions(+), 2 deletions(-) diff --git a/services/service/include/permission/lite/permission_manager.h b/services/service/include/permission/lite/permission_manager.h index 9d8d2cce5..4d41f71db 100644 --- a/services/service/include/permission/lite/permission_manager.h +++ b/services/service/include/permission/lite/permission_manager.h @@ -34,6 +34,7 @@ public: bool CheckProcessNameValidOnPinHolder(const std::string &processName); bool CheckSystemSA(const std::string &pkgName); std::unordered_set GetSystemSA(); + bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index b62f81ea5..6b3716507 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -35,6 +35,7 @@ public: bool CheckProcessNameValidOnPinHolder(const std::string &processName); bool CheckSystemSA(const std::string &pkgName); std::unordered_set GetSystemSA(); + bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 72f4f9569..1b6740e96 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1760,7 +1760,7 @@ int32_t DeviceManagerService::SetDnPolicy(const std::string &pkgName, std::map PermissionManager::GetSystemSA() { return std::unordered_set{}; } + +bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) +{ + (void)processName; + return true; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index aa35eea84..ab7359501 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -49,7 +49,7 @@ constexpr const static char g_pinHolderWhiteList[PIN_HOLDER_WHITE_LIST_NUM][PKG_ "CollaborationFwk", }; -constexpr int32_t SYSTEM_SA_WHITE_LIST_NUM = 8; +constexpr int32_t SYSTEM_SA_WHITE_LIST_NUM = 7; constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "Samgr_Networking", "ohos.distributeddata.service", @@ -58,6 +58,10 @@ constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME "distributed_bundle_framework", "ohos.dhardware", "ohos.security.distributed_access_token", +}; + +constexpr int32_t SETDNPOLICY_WHITE_LIST_NUM = 1; +constexpr const static char g_setDnPolicyWhiteList[SETDNPOLICY_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "collaboration_service", }; } @@ -213,5 +217,23 @@ std::unordered_set PermissionManager::GetSystemSA() } return systemSA; } + +bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) +{ + if (processName.empty()) { + LOGE("ProcessName is empty"); + return false; + } + uint16_t index = 0; + for (; index < SETDNPOLICY_WHITE_LIST_NUM; ++index) { + std::string tmp(g_setDnPolicyWhiteList[index]); + if (processName == tmp) { + return true; + } + } + + LOGE("Process name: %{public}s invalid.", processName.c_str()); + return false; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 9e09f77310ccbf00490957fb7fe47ca71fe841a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 18 Oct 2024 12:29:49 +0800 Subject: [PATCH 314/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=87=BD=E6=95=B0?= =?UTF-8?q?=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../device_manager_ipc_interface_code.h | 2 +- ...req.h => ipc_credential_auth_status_req.h} | 26 +++++++++---------- .../native_cpp/include/device_manager.h | 6 ++--- .../include/device_manager_callback.h | 6 ++--- .../native_cpp/include/device_manager_impl.h | 6 ++--- .../include/notify/device_manager_notify.h | 10 +++---- .../native_cpp/src/device_manager_impl.cpp | 10 +++---- .../src/ipc/standard/ipc_cmd_parser.cpp | 4 +-- .../src/notify/device_manager_notify.cpp | 24 ++++++++--------- .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../devicestate/dm_device_state_manager.h | 2 +- .../src/device_manager_service_impl.cpp | 4 +-- .../src/device_manager_service_impl_lite.cpp | 2 +- .../devicestate/dm_device_state_manager.cpp | 4 +-- .../service/include/device_manager_service.h | 2 +- .../include/device_manager_service_listener.h | 2 +- .../include/idevice_manager_service_impl.h | 2 +- .../idevice_manager_service_listener.h | 4 +-- .../include/softbus/softbus_listener.h | 4 +-- .../service/src/device_manager_service.cpp | 4 +-- .../src/device_manager_service_listener.cpp | 12 ++++----- .../src/ipc/standard/ipc_cmd_parser.cpp | 10 +++---- .../service/src/softbus/softbus_listener.cpp | 26 +++++++++---------- .../UTTest_dm_device_state_manager.cpp | 2 +- .../UTTest_softbus_listener.cpp | 4 +-- test/unittest/UTTest_device_manager_impl.h | 4 +-- .../UTTest_device_manager_impl_three.cpp | 10 +++---- .../UTTest_device_manager_service_impl.cpp | 2 +- test/unittest/UTTest_dm_pin_holder.h | 2 +- .../UTTest_ipc_cmd_parser_service.cpp | 10 +++---- 31 files changed, 105 insertions(+), 105 deletions(-) rename common/include/ipc/model/{ipc_notify_hichain_proof_status_req.h => ipc_credential_auth_status_req.h} (59%) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index 3f2fd7cd0..82f3b6251 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -96,7 +96,7 @@ enum DMIpcCmdInterfaceCode { SERVER_DEVICE_SCREEN_STATE_NOTIFY, GET_DEVICE_SCREEN_STATUS, GET_NETWORKID_BY_UDID, - SERVER_HICHAIN_PROOF_STATUS_NOTIFY, + SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h b/common/include/ipc/model/ipc_credential_auth_status_req.h similarity index 59% rename from common/include/ipc/model/ipc_notify_hichain_proof_status_req.h rename to common/include/ipc/model/ipc_credential_auth_status_req.h index bb82802ec..008d79020 100644 --- a/common/include/ipc/model/ipc_notify_hichain_proof_status_req.h +++ b/common/include/ipc/model/ipc_credential_auth_status_req.h @@ -13,20 +13,20 @@ * limitations under the License. */ -#ifndef OHOS_DM_IPC_NOTIFY_HICHAIN_PROOF_STATUS_REQ_H -#define OHOS_DM_IPC_NOTIFY_HICHAIN_PROOF_STATUS_REQ_H +#ifndef OHOS_DM_IPC_NOTIFY_CREDENTIAL_AUTH_STATUS_REQ_H +#define OHOS_DM_IPC_NOTIFY_CREDENTIAL_AUTH_STATUS_REQ_H #include "ipc_req.h" namespace OHOS { namespace DistributedHardware { -class IpcNotifyHichainProofStatusReq : public IpcReq { - DECLARE_IPC_MODEL(IpcNotifyHichainProofStatusReq); +class IpcNotifyCredentialAuthStatusReq : public IpcReq { + DECLARE_IPC_MODEL(IpcNotifyCredentialAuthStatusReq); public: /** - * @tc.name: IpcNotifyHichainProofStatusReq::GetDeviceTypeId - * @tc.desc: Get DeviceType of the Ipc Notify Hichain proof Status Request + * @tc.name: IpcNotifyCredentialAuthStatusReq::GetDeviceTypeId + * @tc.desc: Get DeviceType of the Ipc Notify Credential Auth Status Request * @tc.type: FUNC */ uint16_t GetDeviceTypeId() const @@ -35,8 +35,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofStatusReq::SetDeviceTypeId - * @tc.desc: Set DeviceType of the Ipc Notify Hichain proof Status Request + * @tc.name: IpcNotifyCredentialAuthStatusReq::SetDeviceTypeId + * @tc.desc: Set DeviceType of the Ipc Notify Credential Auth Status Request * @tc.type: FUNC */ void SetDeviceTypeId(uint16_t deviceTypeId) @@ -45,8 +45,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofStatusReq::GetErrCode - * @tc.desc: Get ErrCode of the Ipc Notify Hichain proof Status Request + * @tc.name: IpcNotifyCredentialAuthStatusReq::GetErrCode + * @tc.desc: Get ErrCode of the Ipc Notify Credential Auth Status Request * @tc.type: FUNC */ int32_t GetErrCode() const @@ -55,8 +55,8 @@ public: } /** - * @tc.name: IpcNotifyHichainProofStatusReq::SetErrCode - * @tc.desc: Set ErrCode of the Ipc Notify Hichain proof Status Request + * @tc.name: IpcNotifyCredentialAuthStatusReq::SetErrCode + * @tc.desc: Set ErrCode of the Ipc Notify Credential Auth Status Request * @tc.type: FUNC */ void SetErrCode(int32_t errcode) @@ -70,4 +70,4 @@ private: }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_IPC_NOTIFY_HICHAIN_PROOF_STATUS_REQ_H +#endif // OHOS_DM_IPC_NOTIFY_CREDENTIAL_AUTH_STATUS_REQ_H diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index b0bd9aede..6ecb472ab 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -625,9 +625,9 @@ public: virtual int32_t SetDnPolicy(const std::string &pkgName, std::map &policy) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) = 0; - virtual int32_t RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, - std::shared_ptr callback) = 0; - virtual int32_t UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) = 0; + virtual int32_t RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 9a4bc834a..010c94228 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -149,12 +149,12 @@ public: virtual void OnDeviceScreenStatus(const DmDeviceInfo &deviceInfo) = 0; }; -class HichainProofExceptionStatusCallback { +class CredentialAuthStatusCallback { public: - virtual ~HichainProofExceptionStatusCallback() + virtual ~CredentialAuthStatusCallback() { } - virtual void OnHichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 5bab59f73..ca18f9e29 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -397,9 +397,9 @@ public: virtual int32_t StopAuthenticateDevice(const std::string &pkgName) override; virtual int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId) override; - virtual int32_t RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, - std::shared_ptr callback) override; - virtual int32_t UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) override; + virtual int32_t RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) override; private: DeviceManagerImpl() = default; 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 690855131..70f50b5e2 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 @@ -70,9 +70,9 @@ public: void RegisterDeviceScreenStatusCallback(const std::string &pkgName, std::shared_ptr callback); void UnRegisterDeviceScreenStatusCallback(const std::string &pkgName); - void RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, - std::shared_ptr callback); - void UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName); + void RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback); + void UnRegisterCredentialAuthStatusCallback(const std::string &pkgName); public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -119,7 +119,7 @@ public: void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode); + void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode); private: #if !defined(__LITEOS_M__) @@ -138,7 +138,7 @@ private: std::map> pinHolderCallback_; std::map> devTrustChangeCallback_; std::map> deviceScreenStatusCallback_; - std::map> hichainProofExceptionStatusCallback_; + std::map> credentialAuthStatusCallback_; std::mutex bindLock_; }; } // namespace DistributedHardware 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 6b1a237d8..eb8ad73f9 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2437,25 +2437,25 @@ int32_t DeviceManagerImpl::GetNetworkIdByUdid(const std::string &pkgName, const return DM_OK; } -int32_t DeviceManagerImpl::RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, - std::shared_ptr callback) +int32_t DeviceManagerImpl::RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - DeviceManagerNotify::GetInstance().RegisterHichainProofExceptionStatusCallback(pkgName, callback); + DeviceManagerNotify::GetInstance().RegisterCredentialAuthStatusCallback(pkgName, callback); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } -int32_t DeviceManagerImpl::UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) +int32_t DeviceManagerImpl::UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } - DeviceManagerNotify::GetInstance().UnRegisterHichainProofExceptionStatusCallback(pkgName); + DeviceManagerNotify::GetInstance().UnRegisterCredentialAuthStatusCallback(pkgName); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index d2721d8bf..ce9976e29 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 @@ -1733,12 +1733,12 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt return DM_OK; } -ON_IPC_CMD(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); uint16_t deviceTypeId = data.ReadUint16(); int32_t errCode = data.ReadInt32(); - DeviceManagerNotify::GetInstance().OnHichainProofExceptionStatus(pkgName, deviceTypeId, errCode); + DeviceManagerNotify::GetInstance().OnCredentialAuthStatus(pkgName, deviceTypeId, errCode); reply.WriteInt32(DM_OK); return DM_OK; diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 98437e78a..74c58c006 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 @@ -1148,28 +1148,28 @@ void DeviceManagerNotify::OnDeviceScreenStatus(const std::string &pkgName, const tempCbk->OnDeviceScreenStatus(deviceInfo); } -void DeviceManagerNotify::RegisterHichainProofExceptionStatusCallback(const std::string &pkgName, - std::shared_ptr callback) +void DeviceManagerNotify::RegisterCredentialAuthStatusCallback(const std::string &pkgName, + std::shared_ptr callback) { if (pkgName.empty() || callback == nullptr) { LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); return; } std::lock_guard autoLock(lock_); - hichainProofExceptionStatusCallback_[pkgName] = callback; + credentialAuthStatusCallback_[pkgName] = callback; } -void DeviceManagerNotify::UnRegisterHichainProofExceptionStatusCallback(const std::string &pkgName) +void DeviceManagerNotify::UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } std::lock_guard autoLock(lock_); - hichainProofExceptionStatusCallback_.erase(pkgName); + credentialAuthStatusCallback_.erase(pkgName); } -void DeviceManagerNotify::OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, +void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) { if (pkgName.empty()) { @@ -1177,20 +1177,20 @@ void DeviceManagerNotify::OnHichainProofExceptionStatus(const std::string &pkgNa return; } LOGI("In, pkgName:%{public}s", pkgName.c_str()); - std::shared_ptr tempCbk; + std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); - if (hichainProofExceptionStatusCallback_.find(pkgName) == hichainProofExceptionStatusCallback_.end()) { - LOGE("error, hichain proof exception status not register."); + if (credentialAuthStatusCallback_.find(pkgName) == credentialAuthStatusCallback_.end()) { + LOGE("error, credential auth statusnot register."); return; } - tempCbk = hichainProofExceptionStatusCallback_[pkgName]; + tempCbk = credentialAuthStatusCallback_[pkgName]; } if (tempCbk == nullptr) { - LOGE("error, registered hichain proof exception status callback is nullptr."); + LOGE("error, registered credential auth status callback is nullptr."); return; } - tempCbk->OnHichainProofExceptionStatus(deviceTypeId, errcode); + tempCbk->OnCredentialAuthStatus(deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 29e027379..12cb14c52 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -131,7 +131,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); + void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 76787058d..f22c7407b 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -137,7 +137,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); + void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 3c6a08d04..9bf0db227 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,7 +96,7 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); + void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 768d37586..022875e10 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -853,10 +853,10 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } -void DeviceManagerServiceImpl::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerServiceImpl::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->HichainProofExceptionStatus(deviceTypeId, errcode); + deviceStateMgr_->CredentialAuthStatus(deviceTypeId, errcode); } extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 2da689667..83fff1d37 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -524,7 +524,7 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } -void DeviceManagerServiceImpl::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerServiceImpl::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { (void)deviceTypeId; (void)errcode; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 6f3732e1a..876d01c5e 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -527,13 +527,13 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) softbusConnector_->ClearPkgName(); } -void DmDeviceStateManager::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) +void DmDeviceStateManager::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { if (listener_ == nullptr) { LOGE("Failed, listener_ is null."); return; } - listener_->OnHichainProofExceptionStatus(std::string(DM_PKG_NAME), deviceTypeId, errcode); + listener_->OnCredentialAuthStatus(std::string(DM_PKG_NAME), deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index ce13ac1d7..bd89dcbe4 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,7 +201,7 @@ public: int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); - void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode); + void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index eb3b965c2..53040f5a0 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -73,7 +73,7 @@ public: const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; - void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override; + void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 4f505ad5f..1a72c967a 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -273,7 +273,7 @@ public: virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; - virtual void HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index ddf2ebc53..f727c8a52 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -160,11 +160,11 @@ public: virtual void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) = 0; /** - * @tc.name: IDeviceManagerServiceListener::OnHichainProofExceptionStatus + * @tc.name: IDeviceManagerServiceListener::OnCredentialAuthStatus * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, + virtual void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 82bcfc93a..9cfe41426 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -58,8 +58,8 @@ public: static void DeviceTrustedChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); - static void OnHichainProofStatus(uint16_t deviceTypeId, int32_t errcode); - static void HichainProofExceptionProcess(uint16_t deviceTypeId, int32_t errcode); + static void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + static void CredentialAuthStatusProcess(uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 5bbd98a0a..f0956b74a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1994,10 +1994,10 @@ void DeviceManagerService::SubscribePackageCommonEvent() #endif } -void DeviceManagerService::HichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerService::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { if (IsDMServiceImplReady()) { - dmServiceImpl_->HichainProofExceptionStatus(deviceTypeId, errcode); + dmServiceImpl_->CredentialAuthStatus(deviceTypeId, errcode); } } } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index a07a51c93..c50cb8277 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -23,6 +23,7 @@ #include "dm_log.h" #include "dm_softbus_cache.h" #include "ipc_create_pin_holder_req.h" +#include "ipc_credential_auth_status_req.h" #include "ipc_destroy_pin_holder_req.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_bind_result_req.h" @@ -32,7 +33,6 @@ #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_device_state_req.h" #include "ipc_notify_discover_result_req.h" -#include "ipc_notify_hichain_proof_status_req.h" #include "ipc_notify_pin_holder_event_req.h" #include "ipc_notify_publish_result_req.h" #include "ipc_server_stub.h" @@ -552,12 +552,12 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) } } -void DeviceManagerServiceListener::OnHichainProofExceptionStatus(const std::string &pkgName, +void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) { LOGI("In, pkgName = %{public}s", pkgName.c_str()); - std::shared_ptr pReq = - std::make_shared(); + std::shared_ptr pReq = + std::make_shared(); std::shared_ptr pRsp = std::make_shared(); pReq->SetDeviceTypeId(deviceTypeId); pReq->SetErrCode(errcode); @@ -565,11 +565,11 @@ void DeviceManagerServiceListener::OnHichainProofExceptionStatus(const std::stri std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); for (const auto &it : PkgNameVec) { pReq->SetPkgName(it); - ipcServerListener_.SendRequest(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, pReq, pRsp); + ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } } else { pReq->SetPkgName(pkgName); - ipcServerListener_.SendRequest(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, pReq, pRsp); + ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } } } // namespace DistributedHardware diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 6c03e6254..64b21766b 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -29,6 +29,7 @@ #include "ipc_cmd_register.h" #include "ipc_def.h" #include "ipc_create_pin_holder_req.h" +#include "ipc_credential_auth_status_req.h" #include "ipc_destroy_pin_holder_req.h" #include "ipc_notify_devicetrustchange_req.h" #include "ipc_notify_auth_result_req.h" @@ -38,7 +39,6 @@ #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_device_state_req.h" #include "ipc_notify_discover_result_req.h" -#include "ipc_notify_hichain_proof_status_req.h" #include "ipc_notify_publish_result_req.h" #include "ipc_notify_pin_holder_event_req.h" #include "ipc_server_client_proxy.h" @@ -1573,13 +1573,13 @@ ON_IPC_CMD(GET_NETWORKID_BY_UDID, MessageParcel &data, MessageParcel &reply) return DM_OK; } -ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) +ON_IPC_SET_REQUEST(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, std::shared_ptr pBaseReq, MessageParcel &data) { if (pBaseReq == nullptr) { return ERR_DM_FAILED; } - std::shared_ptr pReq = - std::static_pointer_cast(pBaseReq); + std::shared_ptr pReq = + std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); uint16_t deviceTypeId = pReq->GetDeviceTypeId(); int32_t errCode = pReq->GetErrCode(); @@ -1599,7 +1599,7 @@ ON_IPC_SET_REQUEST(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, std::shared_ptr p return DM_OK; } -ON_IPC_READ_RESPONSE(SERVER_HICHAIN_PROOF_STATUS_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) +ON_IPC_READ_RESPONSE(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &reply, std::shared_ptr pBaseRsp) { if (pBaseRsp == nullptr) { LOGE("pBaseRsp is null"); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index fba3915bf..9c176a1b8 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -48,7 +48,7 @@ constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; -constexpr const char* HICHAIN_PROOF_STATUS = "hichainProofStatus"; +constexpr const char* HICHAIN_PROOF_STATUS = "credentialAuthStatus"; #endif constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; @@ -67,7 +67,7 @@ static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; static std::mutex g_lockDeviceIdSet; static std::mutex g_lockDevScreenStatusChange; -static std::mutex g_lockHichainProofStatus; +static std::mutex g_credentialAuthStatus; static std::map>>> discoveredDeviceMap; static std::map> lnnOpsCbkMap; @@ -121,7 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, - .onHichainProofException = SoftbusListener::OnHichainProofStatus, + .onHichainProofException = SoftbusListener::OnCredentialAuthStatus, }; static IRefreshCallback softbusRefreshCallback_ = { @@ -165,23 +165,23 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); } -void SoftbusListener::HichainProofExceptionProcess(uint16_t deviceTypeId, int32_t errcode) +void SoftbusListener::CredentialAuthStatusProcess(uint16_t deviceTypeId, int32_t errcode) { - std::lock_guard lock(g_lockHichainProofStatus); - DeviceManagerService::GetInstance().HichainProofExceptionStatus(deviceTypeId, errcode); + std::lock_guard lock(g_credentialAuthStatus); + DeviceManagerService::GetInstance().CredentialAuthStatus(deviceTypeId, errcode); } -void SoftbusListener::OnHichainProofStatus(uint16_t deviceTypeId, int32_t errcode) +void SoftbusListener::OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { - LOGI("received hichain proof status callback from softbus."); + LOGI("received credential auth status callback from softbus."); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { HichainProofExceptionProcess(deviceTypeId, errcode); }); + ffrt::submit([=]() { CredentialAuthStatusProcess(deviceTypeId, errcode); }); #else - std::thread hichainProofStatus([=]() { HichainProofExceptionProcess(deviceTypeId, errcode); }); - if (pthread_setname_np(hichainProofStatus.native_handle(), HICHAIN_PROOF_STATUS) != DM_OK) { - LOGE("hichainProofStatus setname failed."); + std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceTypeId, errcode); }); + if (pthread_setname_np(credentialAuthStatus.native_handle(), HICHAIN_PROOF_STATUS) != DM_OK) { + LOGE("credentialAuthStatus setname failed."); } - hichainProofStatus.detach(); + credentialAuthStatus.detach(); #endif } diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 38dae6eca..0a894cebc 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -257,7 +257,7 @@ HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::e { uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - dmDeviceStateManager->HichainProofExceptionStatus(deviceTypeId, errcode); + dmDeviceStateManager->CredentialAuthStatus(deviceTypeId, errcode); EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); } } // namespace diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index c553b1c17..c715a0cbd 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -733,9 +733,9 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener->SendAclChangedBroadcast(msg); uint16_t deviceTypeId = 0; int32_t errcode = -1; - softbusListener->OnHichainProofStatus(deviceTypeId, errcode); + softbusListener->OnCredentialAuthStatus(deviceTypeId, errcode); deviceTypeId = 0xA2F; - softbusListener->HichainProofExceptionProcess(deviceTypeId, errcode); + softbusListener->CredentialAuthStatusProcess(deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index 51c1d10e6..fa15d0b6f 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -118,12 +118,12 @@ public: void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override {} }; -class CandidateRestrictStatusCallbackTest : public HichainProofExceptionStatusCallback { +class CandidateRestrictStatusCallbackTest : public CredentialAuthStatusCallback { public: virtual ~CandidateRestrictStatusCallbackTest() { } - void OnHichainProofExceptionStatus(uint16_t deviceTypeId, int32_t errcode) override {} + void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 6f5239d62..a6393f387 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1350,7 +1350,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_001, std::string packName = ""; std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); + int32_t ret = DeviceManager::GetInstance().RegisterCredentialAuthStatusCallback(packName, callback); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1358,7 +1358,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_002, { std::string packName = "com.ohos.candidateRestrict01"; std::shared_ptr callback = nullptr; - int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); + int32_t ret = DeviceManager::GetInstance().RegisterCredentialAuthStatusCallback(packName, callback); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -1367,21 +1367,21 @@ HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_003, std::string packName = "com.ohos.scandidateRestrict02"; std::shared_ptr callback = std::make_shared(); - int32_t ret = DeviceManager::GetInstance().RegisterHichainProofExceptionStatusCallback(packName, callback); + int32_t ret = DeviceManager::GetInstance().RegisterCredentialAuthStatusCallback(packName, callback); ASSERT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerImplTest, UnRegisterHichainProofExceptionStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.candidateRestrict03"; - int32_t ret = DeviceManager::GetInstance().UnRegisterHichainProofExceptionStatusCallback(packName); + int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); ASSERT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerImplTest, UnRegisterHichainProofExceptionStatusCallback_002, testing::ext::TestSize.Level0) { std::string packName = ""; - int32_t ret = DeviceManager::GetInstance().UnRegisterHichainProofExceptionStatusCallback(packName); + int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 08e9c1a9d..bab97cf2b 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1506,7 +1506,7 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleCandidateRestrictStatus_101, testin { uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - deviceManagerServiceImpl_->HichainProofExceptionStatus(deviceTypeId, errcode); + deviceManagerServiceImpl_->CredentialAuthStatus(deviceTypeId, errcode); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } } // namespace diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 31b3d89e6..9a90655b0 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -193,7 +193,7 @@ public: (void)devInfo; } - void OnHichainProofExceptionStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override + void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override { (void)pkgName; (void)deviceTypeId; diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 060c4b115..8bcddad18 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -24,6 +24,7 @@ #include "ipc_client_manager.h" #include "ipc_cmd_register.h" #include "ipc_create_pin_holder_req.h" +#include "ipc_credential_auth_status_req.h" #include "ipc_destroy_pin_holder_req.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_info_by_network_rsp.h" @@ -35,7 +36,6 @@ #include "ipc_notify_credential_req.h" #include "ipc_notify_device_discovery_req.h" #include "ipc_notify_dmfa_result_req.h" -#include "ipc_notify_hichain_proof_status_req.h" #include "ipc_notify_event_req.h" #include "ipc_notify_pin_holder_event_req.h" #include "ipc_notify_publish_result_req.h" @@ -1532,9 +1532,9 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_055, testing::ext::TestSize.Level HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize.Level0) { - int32_t cmdCode = SERVER_HICHAIN_PROOF_STATUS_NOTIFY; + int32_t cmdCode = SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY; MessageParcel data; - std::shared_ptr req = nullptr; + std::shared_ptr req = nullptr; int ret = ERR_DM_FAILED; SetIpcRequestFunc ptr = GetIpcRequestFunc(cmdCode); if (ptr) { @@ -1542,7 +1542,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. } ASSERT_EQ(ret, ERR_DM_FAILED); - req = std::make_shared(); + req = std::make_shared(); std::string pkgName = "com.ohos.test"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; @@ -1557,7 +1557,7 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. HWTEST_F(IpcCmdParserServiceTest, ReadResponseFunc_030, testing::ext::TestSize.Level0) { - int32_t cmdCode = SERVER_HICHAIN_PROOF_STATUS_NOTIFY; + int32_t cmdCode = SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY; ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); } } // namespace -- Gitee From cd40d76052f8fdaca4fa35063830efc98e71861f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 18 Oct 2024 14:18:42 +0800 Subject: [PATCH 315/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 4 ++-- test/unittest/UTTest_device_manager_impl_three.cpp | 10 +++++----- test/unittest/UTTest_device_manager_service_impl.cpp | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 9c176a1b8..116fdc04c 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -48,7 +48,7 @@ constexpr const char* DEVICE_OFFLINE = "deviceOffLine"; constexpr const char* DEVICE_NAME_CHANGE = "deviceNameChange"; constexpr const char* DEVICE_NOT_TRUST = "deviceNotTrust"; constexpr const char* DEVICE_SCREEN_STATUS_CHANGE = "deviceScreenStatusChange"; -constexpr const char* HICHAIN_PROOF_STATUS = "credentialAuthStatus"; +constexpr const char* CREDENTIAL_AUTH_STATUS = "credentialAuthStatus"; #endif constexpr const char* LIB_RADAR_NAME = "libdevicemanagerradar.z.so"; constexpr static char HEX_ARRAY[] = "0123456789ABCDEF"; @@ -178,7 +178,7 @@ void SoftbusListener::OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errc ffrt::submit([=]() { CredentialAuthStatusProcess(deviceTypeId, errcode); }); #else std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceTypeId, errcode); }); - if (pthread_setname_np(credentialAuthStatus.native_handle(), HICHAIN_PROOF_STATUS) != DM_OK) { + if (pthread_setname_np(credentialAuthStatus.native_handle(), CREDENTIAL_AUTH_STATUS) != DM_OK) { LOGE("credentialAuthStatus setname failed."); } credentialAuthStatus.detach(); diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index a6393f387..3d5eb2410 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1345,7 +1345,7 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_003, testing::ext::TestSiz DeviceManager::GetInstance().UnInitDeviceManager(packName); } -HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, RegisterCredentialAuthStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = ""; std::shared_ptr callback = @@ -1354,7 +1354,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_001, ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } -HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, RegisterCredentialAuthStatusCallback_002, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.candidateRestrict01"; std::shared_ptr callback = nullptr; @@ -1362,7 +1362,7 @@ HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_002, ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } -HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, RegisterCredentialAuthStatusCallback_003, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.scandidateRestrict02"; std::shared_ptr callback = @@ -1371,14 +1371,14 @@ HWTEST_F(DeviceManagerImplTest, RegisterHichainProofExceptionStatusCallback_003, ASSERT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, UnRegisterHichainProofExceptionStatusCallback_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_001, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.candidateRestrict03"; int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); ASSERT_EQ(ret, DM_OK); } -HWTEST_F(DeviceManagerImplTest, UnRegisterHichainProofExceptionStatusCallback_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_002, testing::ext::TestSize.Level0) { std::string packName = ""; int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index bab97cf2b..06f488105 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1502,7 +1502,7 @@ HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::e EXPECT_EQ(authForm, DmAuthForm::ACROSS_ACCOUNT); } -HWTEST_F(DeviceManagerServiceImplTest, HandleCandidateRestrictStatus_101, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceImplTest, CredentialAuthStatus_101, testing::ext::TestSize.Level0) { uint16_t deviceTypeId = 0x00; int32_t errcode = -1; -- Gitee From edf9b589ce6316a32bacc2feb1dba5a09b03a921 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 18 Oct 2024 14:42:36 +0800 Subject: [PATCH 316/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/src/notify/device_manager_notify.cpp | 2 +- services/implementation/include/device_manager_service_impl.h | 2 +- .../implementation/include/device_manager_service_impl_lite.h | 2 +- .../include/devicestate/dm_device_state_manager.h | 2 +- services/implementation/src/device_manager_service_impl.cpp | 4 ++-- .../implementation/src/device_manager_service_impl_lite.cpp | 2 +- .../src/devicestate/dm_device_state_manager.cpp | 2 +- services/service/include/device_manager_service.h | 2 +- services/service/include/idevice_manager_service_impl.h | 2 +- services/service/src/device_manager_service.cpp | 4 ++-- services/service/src/softbus/softbus_listener.cpp | 2 +- test/commonunittest/UTTest_dm_device_state_manager.cpp | 2 +- test/unittest/UTTest_device_manager_service_impl.cpp | 2 +- 13 files changed, 15 insertions(+), 15 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 74c58c006..93a06ad7a 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 @@ -1170,7 +1170,7 @@ void DeviceManagerNotify::UnRegisterCredentialAuthStatusCallback(const std::stri } void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, - int32_t errcode) + int32_t errcode) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 12cb14c52..52c3a2478 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -131,7 +131,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); - void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index f22c7407b..accb95b68 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -137,7 +137,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); - void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 9bf0db227..68fb531a4 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,7 +96,7 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 022875e10..23127a238 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -853,10 +853,10 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } -void DeviceManagerServiceImpl::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->CredentialAuthStatus(deviceTypeId, errcode); + deviceStateMgr_->HandleCredentialAuthStatus(deviceTypeId, errcode); } extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 83fff1d37..24cf8559b 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -524,7 +524,7 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } -void DeviceManagerServiceImpl::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { (void)deviceTypeId; (void)errcode; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 876d01c5e..18e6b2bef 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -527,7 +527,7 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) softbusConnector_->ClearPkgName(); } -void DmDeviceStateManager::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DmDeviceStateManager::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { if (listener_ == nullptr) { LOGE("Failed, listener_ is null."); diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index bd89dcbe4..59cd724f9 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,7 +201,7 @@ public: int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); - void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 1a72c967a..cb63dc1b2 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -273,7 +273,7 @@ public: virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; - virtual void CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f0956b74a..557a0304d 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1994,10 +1994,10 @@ void DeviceManagerService::SubscribePackageCommonEvent() #endif } -void DeviceManagerService::CredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerService::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { if (IsDMServiceImplReady()) { - dmServiceImpl_->CredentialAuthStatus(deviceTypeId, errcode); + dmServiceImpl_->HandleCredentialAuthStatus(deviceTypeId, errcode); } } } // namespace DistributedHardware diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 116fdc04c..1bdcc4ebc 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -168,7 +168,7 @@ void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) void SoftbusListener::CredentialAuthStatusProcess(uint16_t deviceTypeId, int32_t errcode) { std::lock_guard lock(g_credentialAuthStatus); - DeviceManagerService::GetInstance().CredentialAuthStatus(deviceTypeId, errcode); + DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceTypeId, errcode); } void SoftbusListener::OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 0a894cebc..9d7bec6bf 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -257,7 +257,7 @@ HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::e { uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - dmDeviceStateManager->CredentialAuthStatus(deviceTypeId, errcode); + dmDeviceStateManager->HandleCredentialAuthStatus(deviceTypeId, errcode); EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 06f488105..5042479b1 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1506,7 +1506,7 @@ HWTEST_F(DeviceManagerServiceImplTest, CredentialAuthStatus_101, testing::ext::T { uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - deviceManagerServiceImpl_->CredentialAuthStatus(deviceTypeId, errcode); + deviceManagerServiceImpl_->HandleCredentialAuthStatus(deviceTypeId, errcode); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } } // namespace -- Gitee From 4f9750d05bc648a17dce3325a29b5e5baf19b88b Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Fri, 18 Oct 2024 17:32:28 +0800 Subject: [PATCH 317/520] =?UTF-8?q?=E6=97=A5=E8=90=BD=E7=BE=A4=E7=BB=84?= =?UTF-8?q?=E5=92=8C=E5=8D=B8=E8=BD=BDapp=E5=88=A0=E9=99=A4=E5=8F=AF?= =?UTF-8?q?=E4=BF=A1=E5=85=B3=E7=B3=BB=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/deviceprofile_connector.h | 2 + .../src/deviceprofile_connector.cpp | 14 +++ .../include/authentication/dm_auth_manager.h | 3 + .../dependency/hichain/hichain_connector.h | 11 +- .../include/device_manager_service_impl.h | 2 + .../device_manager_service_impl_lite.h | 1 + .../src/authentication/dm_auth_manager.cpp | 51 ++++++++- .../dependency/hichain/hichain_connector.cpp | 104 ++++++++++++------ .../src/device_manager_service_impl.cpp | 37 +++++++ .../src/device_manager_service_impl_lite.cpp | 7 ++ .../include/device_manager_service_listener.h | 2 + .../include/idevice_manager_service_impl.h | 1 + .../idevice_manager_service_listener.h | 1 + .../dm_package_common_event.h | 2 +- .../service/src/device_manager_service.cpp | 8 +- .../src/device_manager_service_listener.cpp | 12 ++ .../dm_package_common_event.cpp | 4 +- .../UTTest_device_manager_service.cpp | 2 +- test/unittest/UTTest_dm_pin_holder.h | 5 + utils/include/appInfo/lite/app_manager.h | 1 + utils/include/appInfo/standard/app_manager.h | 1 + utils/src/appInfo/lite/app_manager.cpp | 5 + utils/src/appInfo/standard/app_manager.cpp | 14 +++ 23 files changed, 247 insertions(+), 43 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index cf3c8e51f..fb95f058b 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -134,6 +134,8 @@ public: int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid); + std::vector GetAllAccessControlProfile(); + void DeleteAccessControlById(int64_t accessControlId); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index ee5930d8c..58803d67e 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -979,6 +979,20 @@ std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, c return pkgName; } +std::vector DeviceProfileConnector::GetAllAccessControlProfile() +{ + std::vector profiles; + if (DistributedDeviceProfileClient::GetInstance().GetAllAccessControlProfile(profiles) != DM_OK) { + LOGE("DP failed."); + } + return profiles; +} + +void DeviceProfileConnector::DeleteAccessControlById(int64_t accessControlId) +{ + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(accessControlId); +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index c9716d65a..bbea5de22 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -464,6 +464,7 @@ public: private: int32_t CheckAuthParamVaild(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra); + int32_t CheckAuthParamVaildExtra(const std::string &extra); void ProcessSourceMsg(); void ProcessSinkMsg(); std::string GetAccountGroupIdHash(); @@ -528,6 +529,8 @@ private: int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); void GetPeerUdidHash(int32_t sessionId, std::string &peerUdidHash); void DeleteOffLineTimer(int32_t sessionId); + bool IsAllowDeviceBind(); + int32_t GetBindLevel(int32_t bindLevel); private: std::shared_ptr softbusConnector_; diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index 13ce9b5c1..37c1dbecd 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -166,8 +166,12 @@ public: * @tc.desc: Get GroupInfo of the HiChain Connector * @tc.type: FUNC */ - int32_t GetGroupInfo(const int32_t userId, const std::string &queryParams, std::vector &groupList); + bool GetGroupInfo(const int32_t userId, const std::string &queryParams, std::vector &groupList); + + bool GetGroupInfoExt(const int32_t userId, const std::string &queryParams, std::vector &groupList); + bool GetGroupInfoCommon(const int32_t userId, const std::string &queryParams, const char* pkgName, + std::vector &groupList); /** * @tc.name: HiChainConnector::GetGroupType * @tc.desc: Get GroupType of the HiChain Connector @@ -237,6 +241,11 @@ public: std::vector &groupList); void DeleteAllGroupByUdid(const std::string &udid); void DeleteP2PGroup(int32_t switchUserId); + int32_t DeleteGroupByACL(std::vector> &delACLInfoVec, + std::vector &userIdVec); + bool IsNeedDelete(std::string &groupName, int32_t userId, + std::vector> &delACLInfoVec); + private: int64_t GenRequestId(); int32_t SyncGroups(std::string deviceId, std::vector &remoteGroupIdList); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 52c3a2478..c7f35e4a8 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -132,6 +132,8 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); + private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index accb95b68..c561b19e6 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -138,6 +138,7 @@ public: void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 1fabdfe0b..23041ff9d 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -26,6 +26,7 @@ #endif #include "system_ability_definition.h" +#include "app_manager.h" #include "auth_message_processor.h" #include "common_event_support.h" #include "dm_ability_manager.h" @@ -164,6 +165,25 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a return DM_OK; } +int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra) +{ + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (!jsonObject.is_discarded()) { + if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { + int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + if (bindLevel > APP || bindLevel < INVALID_TYPE) { + LOGE("bindlevel error %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + if (bindLevel == DEVICE && !IsAllowDeviceBind()) { + LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + } + } + return DM_OK; +} + void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { @@ -207,6 +227,7 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { authRequestContext_->bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } + authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); } authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); } @@ -247,6 +268,11 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild."); return ret; } + ret = CheckAuthParamVaildExtra(extra); + if (ret != DM_OK) { + LOGE("CheckAuthParamVaildExtra failed, param is invaild."); + return ret; + } isAuthenticateDevice_ = true; if (authType == AUTH_TYPE_CRE) { LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly."); @@ -1229,8 +1255,7 @@ void DmAuthManager::AuthenticateFinish() } if (DeviceProfileConnector::GetInstance().GetTrustNumber(remoteDeviceId_) >= 1 && CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && - authResponseContext_->bindLevel == INVALIED_TYPE && softbusConnector_->CheckIsOnline(remoteDeviceId_) && - authResponseContext_->isFinish) { + softbusConnector_->CheckIsOnline(remoteDeviceId_) && authResponseContext_->isFinish) { softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } @@ -2451,5 +2476,27 @@ int32_t DmAuthManager::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) } return taskTimeOut; } + +bool DmAuthManager::IsAllowDeviceBind() +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) +{ + if (IsAllowDeviceBind()) { + if (bindLevel == INVALIED_TYPE || bindLevel > APP || bindLevel < DEVICE) { + return DEVICE; + } + return bindLevel; + } + if (bindLevel == INVALIED_TYPE || (bindLevel != APP && bindLevel != SERVICE)) { + return APP; + } + return bindLevel; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 035330be9..08045a9b4 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -40,6 +40,7 @@ const int32_t CREDENTIAL_NETWORK = 1; const int32_t DELAY_TIME_MS = 10000; // 10ms const int32_t FIELD_EXPIRE_TIME_VALUE = 7; const int32_t SAME_ACCOUNT = 1; +const int32_t DEVICE_ID_HALF = 2; constexpr const char* DEVICE_ID = "DEVICE_ID"; constexpr const char* FIELD_CREDENTIAL = "credential"; @@ -211,53 +212,36 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth bool HiChainConnector::GetGroupInfo(const std::string &queryParams, std::vector &groupList) { - char *groupVec = nullptr; - uint32_t num = 0; int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); return false; } - int32_t ret = deviceGroupManager_->getGroupInfo(userId, DM_PKG_NAME, queryParams.c_str(), &groupVec, &num); - if (ret != 0) { - LOGE("[HICHAIN]fail to get group info with ret:%{public}d.", ret); - return false; - } - if (groupVec == nullptr) { - LOGE("[HICHAIN]return groups info point is nullptr"); - return false; - } - if (num == 0) { - LOGE("[HICHAIN]return groups info number is zero."); - return false; - } - LOGI("HiChainConnector::GetGroupInfo groupNum(%{public}u)", num); - std::string relatedGroups = std::string(groupVec); - deviceGroupManager_->destroyInfo(&groupVec); - nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups, nullptr, false); - if (jsonObject.is_discarded()) { - LOGE("returnGroups parse error"); - return false; - } - if (!jsonObject.is_array()) { - LOGE("json string is not array."); - return false; - } - std::vector groupInfos = jsonObject.get>(); - if (groupInfos.size() == 0) { - LOGE("HiChainConnector::GetGroupInfo group failed, groupInfos is empty."); - return false; - } - groupList = groupInfos; - return true; + return GetGroupInfo(userId, queryParams, groupList); +} + +bool HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &queryParams, + std::vector &groupList) +{ + return GetGroupInfoCommon(userId, queryParams, DM_PKG_NAME, groupList); } -int32_t HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &queryParams, +bool HiChainConnector::GetGroupInfoExt(const int32_t userId, const std::string &queryParams, + std::vector &groupList) +{ + return GetGroupInfoCommon(userId, queryParams, DM_PKG_NAME_EXT, groupList); +} + +bool HiChainConnector::GetGroupInfoCommon(const int32_t userId, const std::string &queryParams, const char* pkgName, std::vector &groupList) { char *groupVec = nullptr; uint32_t num = 0; - int32_t ret = deviceGroupManager_->getGroupInfo(userId, DM_PKG_NAME, queryParams.c_str(), &groupVec, &num); + if (deviceGroupManager_ == nullptr) { + LOGE("deviceGroupManager_ is null"); + return false; + } + int32_t ret = deviceGroupManager_->getGroupInfo(userId, pkgName, queryParams.c_str(), &groupVec, &num); if (ret != 0) { LOGE("[HICHAIN]fail to get group info with ret:%{public}d.", ret); return false; @@ -1223,5 +1207,53 @@ void HiChainConnector::DeleteP2PGroup(int32_t switchUserId) } } } + +int32_t HiChainConnector::DeleteGroupByACL(std::vector> &delACLInfoVec, + std::vector &userIdVec) +{ + if (delACLInfoVec.size() == 0) { + LOGI("delACLInfoVec is empty"); + return DM_OK; + } + if (userIdVec.size() == 0) { + LOGI("userIdVec is empty"); + return DM_OK; + } + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; + std::string queryParams = jsonObj.dump(); + for (int32_t userId : userIdVec) { + std::vector groupList; + if (!GetGroupInfo(userId, queryParams, groupList)) { + continue; + } + for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { + if (!IsNeedDelete(iter->groupName, userId, delACLInfoVec)) { + continue; + } + if (DeleteGroup(userId, iter->groupId) != DM_OK) { + LOGE("failed to delete group %{public}s", GetAnonyString(iter->groupId).c_str()); + } + } + } + return DM_OK; +} + +bool HiChainConnector::IsNeedDelete(std::string &groupName, int32_t userId, + std::vector> &delACLInfoVec) +{ + if (delACLInfoVec.size() == 0 || groupName.empty()) { + LOGI("delACLInfoVec or groupName is empty"); + return false; + } + for (auto item : delACLInfoVec) { + uint32_t interceptLength = item.second.size() / DEVICE_ID_HALF; + std::string interceptUdid = item.second.substr(0, interceptLength); + if (groupName.find(interceptUdid) != std::string::npos && userId == item.first) { + return true; + } + } + return false; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 23127a238..a5efd68a5 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -859,6 +859,43 @@ void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, deviceStateMgr_->HandleCredentialAuthStatus(deviceTypeId, errcode); } +int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) +{ + CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL); + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + LOGI("delete ACL size is %{public}zu, appId %{public}s", profiles.size(), GetAnonyString(appId).c_str()); + if (profiles.size() == 0) { + return DM_OK; + } + std::vector> delACLInfoVec; + std::vector userIdVec; + for (auto &item : profiles) { + int64_t tokenId = item.GetAccesser().GetAccesserTokenId(); + if (accessTokenId != static_cast(tokenId)) { + continue; + } + DeviceProfileConnector::GetInstance().DeleteAccessControlById(item.GetAccessControlId()); + listener_->OnAppUnintall(item.GetAccesser().GetAccesserBundleName()); + if (item.GetBindLevel() == DEVICE) { + userIdVec.push_back(item.GetAccesser().GetAccesserUserId()); + delACLInfoVec.push_back(std::pair(item.GetAccesser().GetAccesserUserId(), + item.GetAccessee().GetAccesseeDeviceId())); + } + } + if (delACLInfoVec.size() == 0) { + LOGI("delACLInfoVec is empty"); + return DM_OK; + } + if (userIdVec.size() == 0) { + LOGI("userIdVec is empty"); + return DM_OK; + } + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); + hiChainConnector_->DeleteGroupByACL(delACLInfoVec, userIdVec); + return DM_OK; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 24cf8559b..28b66e4e1 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -531,6 +531,13 @@ void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, return; } +int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) +{ + (void)appId; + (void)accessTokenId; + return 0; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 53040f5a0..e3df75866 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -74,6 +74,8 @@ public: void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override; + void OnAppUnintall(const std::string &pkgName) override; + private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index cb63dc1b2..eb17b1511 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -274,6 +274,7 @@ public: virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; + virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index f727c8a52..a1d276dca 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -166,6 +166,7 @@ public: */ virtual void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void OnAppUnintall(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/publishcommonevent/dm_package_common_event.h b/services/service/include/publishcommonevent/dm_package_common_event.h index fec36d16c..f0964d173 100644 --- a/services/service/include/publishcommonevent/dm_package_common_event.h +++ b/services/service/include/publishcommonevent/dm_package_common_event.h @@ -33,7 +33,7 @@ namespace DistributedHardware { using OHOS::EventFwk::CommonEventData; using OHOS::EventFwk::CommonEventSubscriber; using OHOS::EventFwk::CommonEventSubscribeInfo; -using PackageEventCallback = std::function; +using PackageEventCallback = std::function; class DmPackageEventSubscriber : public CommonEventSubscriber { public: diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 557a0304d..fc07f1c03 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -948,6 +948,9 @@ bool DeviceManagerService::IsDMServiceImplReady() } dmServiceImpl_ = std::shared_ptr(func()); + if (listener_ == nullptr) { + listener_ = std::make_shared(); + } if (dmServiceImpl_->Initialize(listener_) != DM_OK) { dlclose(so_handle); dmServiceImpl_ = nullptr; @@ -1982,7 +1985,10 @@ void DeviceManagerService::SubscribePackageCommonEvent() if (packageCommonEventManager_ == nullptr) { packageCommonEventManager_ = std::make_shared(); } - PackageEventCallback callback = [=](const auto &arg1, const auto &arg2) { + PackageEventCallback callback = [=](const auto &arg1, const auto &arg2, const auto &arg3) { + if (IsDMServiceImplReady()) { + dmServiceImpl_->ProcessAppUnintall(arg1, arg3); + } KVAdapterManager::GetInstance().AppUnintall(arg1); }; std::vector commonEventVec; diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index c50cb8277..7478a10bf 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -572,5 +572,17 @@ void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkg ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } } + +void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) +{ + std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { + if (it->first.find(pkgName) == 0) { + it = alreadyOnlinePkgName_.erase(it); + } else { + ++it; + } + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/publishcommonevent/dm_package_common_event.cpp b/services/service/src/publishcommonevent/dm_package_common_event.cpp index f394e5f4a..d49a5d8fa 100644 --- a/services/service/src/publishcommonevent/dm_package_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_package_common_event.cpp @@ -36,6 +36,7 @@ using OHOS::EventFwk::CommonEventManager; constexpr const char* DEAL_THREAD = "package_common_event"; #endif const std::string APP_ID = "appId"; +const std::string ACCESS_TOKEN_ID = "accessTokenId"; constexpr int32_t MAX_TRY_TIMES = 3; std::vector DmPackageEventSubscriber::GetSubscriberEventNameVec() const @@ -136,6 +137,7 @@ void DmPackageEventSubscriber::OnReceiveEvent(const CommonEventData &data) { std::string receiveEvent = data.GetWant().GetAction(); std::string appId = data.GetWant().GetStringParam(APP_ID); + int32_t accessTokenId = static_cast(data.GetWant().GetIntParam(ACCESS_TOKEN_ID, 0)); LOGI("Received package event: %{public}s", receiveEvent.c_str()); if (receiveEvent != EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED && @@ -144,7 +146,7 @@ void DmPackageEventSubscriber::OnReceiveEvent(const CommonEventData &data) return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { callback_(appId, receiveEvent); }); + ffrt::submit([=]() { callback_(appId, receiveEvent, accessTokenId); }); #else std::thread dealThread([=]() { callback_(appId, receiveEvent); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 2dc430ada..cfe307aa1 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1187,7 +1187,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterCallerAppId_001, testing::ext::TestSi { std::string pkgName; DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); - EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); + EXPECT_NE(DeviceManagerService::GetInstance().listener_, nullptr); } /** diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 9a90655b0..1434de194 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -199,6 +199,11 @@ public: (void)deviceTypeId; (void)errcode; } + + void OnAppUnintall(const std::string &pkgName) override + { + (void)pkgName; + } }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index a97d1a3ef..33927be8e 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -29,6 +29,7 @@ public: void RegisterCallerAppId(const std::string &pkgName); void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); + bool IsSystemSA(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 2ee9069b7..684337867 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -35,6 +35,7 @@ public: void RegisterCallerAppId(const std::string &pkgName); void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); + bool IsSystemSA(); private: bool GetBundleManagerProxy(sptr &bundleManager); std::mutex appIdMapLock_; diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index 72a9ac465..ea3ab90cc 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -41,5 +41,10 @@ int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &a (void)appId; return DM_OK; } + +bool AppManager::IsSystemSA() +{ + return true; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 0d6eddab4..63935cd2b 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -137,5 +137,19 @@ bool AppManager::GetBundleManagerProxy(sptr &bundleManag } return true; } + +bool AppManager::IsSystemSA() +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("IsSystemSA GetCallingTokenID error."); + return false; + } + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + return true; + } + return false; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 9f27efc468b2fb434262d457442c8d5357b505dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sat, 19 Oct 2024 16:00:33 +0800 Subject: [PATCH 318/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../dependency/softbus/softbus_session.cpp | 4 ++-- .../devicenamemgr/account_boot_listener.h | 11 +++++----- .../devicenamemgr/account_boot_listener.cpp | 22 +++++++++---------- .../devicenamemgr/local_device_name_mgr.cpp | 17 ++++++++++++-- .../settings_data_event_monitor.cpp | 4 ++++ 5 files changed, 38 insertions(+), 20 deletions(-) diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 808872474..9730b6861 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -27,7 +27,7 @@ namespace OHOS { namespace DistributedHardware { std::shared_ptr SoftbusSession::sessionCallback_ = nullptr; constexpr const char* DM_HITRACE_AUTH_TO_OPPEN_SESSION = "DM_HITRACE_AUTH_TO_OPPEN_SESSION"; -constexpr int32_t DATA_LEN = 65535; +constexpr int32_t MAX_DATA_LEN = 65535; static void OnShutdown(int32_t socket, ShutdownReason reason) { @@ -180,7 +180,7 @@ void SoftbusSession::OnSessionClosed(int sessionId) void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > DATA_LEN) { + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { LOGI("[SOFTBUS]fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); return; diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h index 8c894c6f9..341dcd8db 100644 --- a/services/service/include/devicenamemgr/account_boot_listener.h +++ b/services/service/include/devicenamemgr/account_boot_listener.h @@ -21,10 +21,11 @@ #include "local_device_name_mgr.h" namespace OHOS { namespace DistributedHardware { -typedef enum SaTriggerFlag { - DM_SA_READY, - DATA_SHARE_SA_REDDY -} SaTriggerFlag; +enum class SaTriggerFlag : int32_t { + DM_SA_READY = 0, + DATA_SHARE_SA_REDDY = 1 +}; + class AccountBootListener { public: AccountBootListener(); @@ -44,7 +45,7 @@ private: std::shared_ptr localDeviceMgr_; std::atomic isDmSaReady_; std::atomic isDataShareReady_; - static std::mutex lock_; + static std::mutex depSaStatelock_; std::shared_ptr dataShareCommonEventManager_; }; } // namespace DistributedHardware diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 87947975b..50de621fb 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -35,12 +35,12 @@ namespace { #endif } -std::mutex AccountBootListener::lock_; +std::mutex AccountBootListener::depSaStatelock_; static void AccountBootCb(const char *key, const char *value, void *context) { - if (key == nullptr || value == nullptr) { - LOGE("key or value is null, param is error!"); + if (key == nullptr || value == nullptr || context == nullptr) { + LOGE("key or value or context is null, param is error!"); return; } if (strcmp(key, BOOTEVENT_ACCOUNT_READY) != 0 || strcmp(value, "true") != 0) { @@ -108,21 +108,21 @@ void AccountBootListener::DoAccountBootProc() void AccountBootListener::SetSaTriggerFlag(SaTriggerFlag triggerFlag) { LOGI("start"); - std::lock_guard lock(lock_); + std::lock_guard lock(depSaStatelock_); switch (triggerFlag) { - case DM_SA_READY: + case SaTriggerFlag::DM_SA_READY: isDmSaReady_ = true; LOGI("DM SA ready!"); break; - case DATA_SHARE_SA_REDDY: + case SaTriggerFlag::DATA_SHARE_SA_REDDY: LOGI("DATA SHARE SA ready!"); this->InitDataShareEvent(); break; default: break; } - LOGI("isDmSaReady_:%{public}d,isDataShareReady_:%{public}d", - std::atomic_load(&isDmSaReady_),std::atomic_load(&isDataShareReady_)); + LOGI("isDmSaReady_: %{public}d, isDataShareReady_: %{public}d", + std::atomic_load(&isDmSaReady_), std::atomic_load(&isDataShareReady_)); if (isDmSaReady_ && isDataShareReady_) { LOGI("dm and data_share is ready!"); this->RegisterAccountBootCb(); @@ -149,10 +149,10 @@ void AccountBootListener::InitDataShareEvent() void AccountBootListener::DataShareCallback() { LOGI("Start"); - std::lock_guard lock(lock_); + std::lock_guard lock(depSaStatelock_); isDataShareReady_ = true; - LOGI("isDmSaReady_:%{public}d,isDataShareReady_:%{public}d", - std::atomic_load(&isDmSaReady_),std::atomic_load(&isDataShareReady_)); + LOGI("isDmSaReady_: %{public}d, isDataShareReady_: %{public}d", + std::atomic_load(&isDmSaReady_), std::atomic_load(&isDataShareReady_)); if (isDmSaReady_ && isDataShareReady_) { LOGI("dm and data_share is ready!"); this->RegisterAccountBootCb(); diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp index 8f2c803ee..84db17a39 100644 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -43,6 +43,7 @@ namespace { constexpr const char *USER_DEFINED_STRING = "settings.general.user_defined_device_name"; constexpr const char *DISPLAY_DEVICE_NAME_STRING = "settings.general.display_device_name"; } + LocalDeviceNameMgr::LocalDeviceNameMgr() : localDeviceName_(""), localDisplayName_("") { LOGI("Ctor LocalDeviceNameMgr"); @@ -76,8 +77,8 @@ int32_t LocalDeviceNameMgr::GetDeviceNameFromDataShareHelper( std::shared_ptr dataShareHelper, std::shared_ptr uri, const char *key, std::string &deviceName) { - if (uri == nullptr || key == nullptr) { - LOGE("uri or key is null, param is error!"); + if (dataShareHelper == nullptr || uri == nullptr || key == nullptr) { + LOGE("dataShareHelper or uri or key is null, param is error!"); return ERR_DM_FAILED; } int32_t numRows = 0; @@ -116,6 +117,10 @@ int32_t LocalDeviceNameMgr::GetDeviceNameFromDataShareHelper( int32_t LocalDeviceNameMgr::GetDefaultDeviceName(std::shared_ptr dataShareHelper, std::string &deviceName) { + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null, param is error!"); + return ERR_DM_FAILED; + } std::shared_ptr uri = std::make_shared(SETTINGS_DATA_BASE_URI + "&key=" + PREDICATES_STRING); LOGI("get default deviceName"); return GetDeviceNameFromDataShareHelper(dataShareHelper, uri, PREDICATES_STRING, deviceName); @@ -124,6 +129,10 @@ int32_t LocalDeviceNameMgr::GetDefaultDeviceName(std::shared_ptr dataShareHelper, std::string &deviceName) { + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null, param is error!"); + return ERR_DM_FAILED; + } int32_t osAccountId = GetActiveOsAccountIds(); if (osAccountId == ERR_DM_FAILED) { LOGE("osAccountId acquire fail!"); @@ -139,6 +148,10 @@ int32_t LocalDeviceNameMgr::GetUserDefinedDeviceName(std::shared_ptr dataShareHelper, std::string &deviceName) { + if (dataShareHelper == nullptr) { + LOGE("dataShareHelper is null, param is error!"); + return ERR_DM_FAILED; + } int32_t osAccountId = GetActiveOsAccountIds(); if (osAccountId == ERR_DM_FAILED) { LOGE("osAccountId acquire fail!"); diff --git a/services/service/src/devicenamemgr/settings_data_event_monitor.cpp b/services/service/src/devicenamemgr/settings_data_event_monitor.cpp index 4dbf931a8..421acfc7b 100644 --- a/services/service/src/devicenamemgr/settings_data_event_monitor.cpp +++ b/services/service/src/devicenamemgr/settings_data_event_monitor.cpp @@ -34,6 +34,10 @@ void SettingsDataEventMonitor::OnChange() } LOGI("Settings OnChange type: %{public}d", (int32_t)monitorType_); std::shared_ptr localDevNameSPtr = localDeviceNameMgrWPtr_.lock(); + if (localDevNameSPtr == nullptr) { + LOGE("localDevNameSPtr is null!"); + return; + } switch (monitorType_) { case SettingsDataMonitorType::USER_DEFINED_DEVICE_NAME_MONITOR: localDevNameSPtr->QueryLocalDeviceName(); -- Gitee From b30636b727209e8b738acc49bd2bde057c2b4e11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 21 Oct 2024 12:00:39 +0800 Subject: [PATCH 319/520] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E5=A5=97=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- commondependency/src/deviceprofile_connector.cpp | 2 +- services/service/src/device_manager_service.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 58803d67e..c90af6e5f 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -842,7 +842,7 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccessee().GetAccesseeDeviceId() == udid) { tokenId = static_cast(item.GetAccesser().GetAccesserTokenId()); - bindLevel = item.GetBindLevel(); + bindLevel = static_cast(item.GetBindLevel()); LOGI("Src get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); continue; } diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fc07f1c03..3a7094da9 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -555,7 +555,7 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c std::string udid = ""; if (SoftbusListener::GetUdidByNetworkId(networkId.c_str(), udid) != DM_OK) { LOGE("UnAuthenticateDevice GetUdidByNetworkId error: udid: %{public}s", GetAnonyString(udid).c_str()); - return ERR_DM_INPUT_PARA_INVALID; + return ERR_DM_FAILED; } char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); -- Gitee From 90d35f73e895621f1c3da50da5b8521b81fdc58c Mon Sep 17 00:00:00 2001 From: ding_dong_dong Date: Tue, 22 Oct 2024 15:07:39 +0800 Subject: [PATCH 320/520] modify kvdb corrupt code Signed-off-by: ding_dong_dong --- utils/src/kvadapter/kv_adapter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/src/kvadapter/kv_adapter.cpp b/utils/src/kvadapter/kv_adapter.cpp index 61ad40f14..3ecb6e2a2 100644 --- a/utils/src/kvadapter/kv_adapter.cpp +++ b/utils/src/kvadapter/kv_adapter.cpp @@ -63,7 +63,7 @@ int32_t KVAdapter::Init() LOGE("CheckKvStore, left times: %{public}d, status: %{public}d", tryTimes, status); if (status == DistributedKv::Status::STORE_META_CHANGED || status == DistributedKv::Status::SECURITY_LEVEL_ERROR || - status == DistributedKv::Status::CRYPT_ERROR) { + status == DistributedKv::Status::DATA_CORRUPTED) { LOGE("init db error, remove and rebuild it"); DeleteKvStore(); } -- Gitee From 993e84ab2f9edb3052879d54b0fed03436b978bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 22 Oct 2024 16:29:59 +0800 Subject: [PATCH 321/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9ut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../UTTest_device_manager_impl_three.cpp | 23 +++++++++++++++++++ .../UTTest_device_manager_service_two.cpp | 23 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 2bf9fb04c..c1a4852c2 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1096,8 +1096,31 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialCallback002, testing::ext::T DeviceManagerImpl::GetInstance().ipcClientProxy_->ipcClientManager_ = std::make_shared(); } +void SetSetDnPolicyPermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.ACCESS_SERVICE_DM"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "collaboration_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + HWTEST_F(DeviceManagerImplTest, SetDnPolicy001, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index e24249309..59da5684a 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -50,6 +50,28 @@ void DeletePermission() OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); } +void SetSetDnPolicyPermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.ACCESS_SERVICE_DM"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "collaboration_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + /** * @tc.name: GetTrustedDeviceList_201 * @tc.type: FUNC @@ -281,6 +303,7 @@ HWTEST_F(DeviceManagerServiceTest, SubscribeAccountCommonEvent_201, testing::ext */ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; -- Gitee From c10788421222e7272467e503bfe6a3f2f361ee7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 22 Oct 2024 17:22:29 +0800 Subject: [PATCH 322/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9ut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_impl.cpp | 2 +- test/unittest/UTTest_device_manager_service.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index 243184706..8e236a814 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -1057,7 +1057,7 @@ HWTEST_F(DeviceManagerImplTest, UnAuthenticateDevice_101, testing::ext::TestSize // 3. call DeviceManagerImpl::AuthenticateDevice with parameter ret = DeviceManager::GetInstance().UnAuthenticateDevice(packName, deviceInfo); // 4. check ret is ERR_DM_FAILED - ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ASSERT_EQ(ret, ERR_DM_FAILED); DeviceManager::GetInstance().UnInitDeviceManager(packName); } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index cfe307aa1..db40dd891 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -664,7 +664,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_004, testing::ext::TestS std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, ERR_DM_FAILED); } /** -- Gitee From 7754b3b2fe5bd8e89dc9de2c7fcc00fb7baf5792 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 22 Oct 2024 17:52:26 +0800 Subject: [PATCH 323/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9ut?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/unittest/UTTest_device_manager_impl_three.cpp | 5 +++++ test/unittest/UTTest_device_manager_service_two.cpp | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index c1a4852c2..b9384ddd1 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1138,6 +1138,7 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy001, testing::ext::TestSize.Level0) HWTEST_F(DeviceManagerImplTest, SetDnPolicy002, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; @@ -1150,6 +1151,7 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy002, testing::ext::TestSize.Level0) HWTEST_F(DeviceManagerImplTest, SetDnPolicy003, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; std::shared_ptr callback = std::make_shared(); @@ -1161,6 +1163,7 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy003, testing::ext::TestSize.Level0) HWTEST_F(DeviceManagerImplTest, SetDnPolicy004, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName; std::map policy; std::shared_ptr callback = std::make_shared(); @@ -1172,6 +1175,7 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy004, testing::ext::TestSize.Level0) HWTEST_F(DeviceManagerImplTest, SetDnPolicy005, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; @@ -1185,6 +1189,7 @@ HWTEST_F(DeviceManagerImplTest, SetDnPolicy005, testing::ext::TestSize.Level0) HWTEST_F(DeviceManagerImplTest, SetDnPolicy006, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 59da5684a..95700ddb8 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -322,6 +322,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level */ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_202, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; @@ -337,6 +338,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_202, testing::ext::TestSize.Level HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_203, testing::ext::TestSize.Level0) { std::string packName = "com.ohos.test"; + SetSetDnPolicyPermission(); std::map policy; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); @@ -349,6 +351,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_203, testing::ext::TestSize.Level */ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; @@ -362,6 +365,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level */ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_205, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; @@ -376,6 +380,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_205, testing::ext::TestSize.Level */ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_206, testing::ext::TestSize.Level0) { + SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100a"; -- Gitee From 6828332ce5d19df6645ffa80ce38946418b4e153 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Tue, 22 Oct 2024 14:14:23 +0800 Subject: [PATCH 324/520] =?UTF-8?q?=E8=B0=83=E6=95=B4unbind=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../src/authentication/dm_auth_manager.cpp | 28 ++----------------- 1 file changed, 3 insertions(+), 25 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 23041ff9d..5734f3c58 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -291,18 +291,6 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_FAILED; } - if (authRequestState_!= nullptr || authResponseContext_ != nullptr) { - if (isAuthenticateDevice_) { - LOGI("Stop previous AuthenticateDevice."); - authRequestContext_->reason = STOP_BIND; - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestState_->TransitionTo(std::make_shared()); - return DM_OK; - } else { - LOGE("UnAuthenticateDevice is syncchronizing sink acl data."); - return ERR_DM_FAILED; - } - } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); struct RadarInfo info = { @@ -327,7 +315,9 @@ int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_FAILED; } - if ((authRequestState_!= nullptr || authResponseContext_ != nullptr) && isAuthenticateDevice_) { + if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) || + (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) && + isAuthenticateDevice_) { LOGI("Stop previous AuthenticateDevice."); authRequestContext_->reason = STOP_BIND; authResponseContext_->state = authRequestState_->GetStateType(); @@ -377,18 +367,6 @@ int32_t DmAuthManager::UnBindDevice(const std::string &pkgName, const std::strin LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_FAILED; } - if (authRequestState_!= nullptr || authResponseContext_ != nullptr) { - if (isAuthenticateDevice_) { - LOGI("Stop previous AuthenticateDevice."); - authRequestContext_->reason = STOP_BIND; - authResponseContext_->state = authRequestState_->GetStateType(); - authRequestState_->TransitionTo(std::make_shared()); - return DM_OK; - } else { - LOGE("UnBindDevice is syncchronizing sink acl data."); - return ERR_DM_FAILED; - } - } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); if (bindLevel == DEVICE) { -- Gitee From 58db5f4e8da77f77c30c768519a86bac6d7405c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 23 Oct 2024 15:41:18 +0800 Subject: [PATCH 325/520] =?UTF-8?q?=E5=87=AD=E6=8D=AE=E5=9B=9E=E8=B0=83?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../model/ipc_credential_auth_status_req.h | 21 +++++++++++++++++++ .../include/device_manager_callback.h | 2 +- .../include/notify/device_manager_notify.h | 3 ++- .../src/ipc/standard/ipc_cmd_parser.cpp | 3 ++- .../src/notify/device_manager_notify.cpp | 6 +++--- .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../devicestate/dm_device_state_manager.h | 2 +- .../src/device_manager_service_impl.cpp | 5 +++-- .../src/device_manager_service_impl_lite.cpp | 4 +++- .../devicestate/dm_device_state_manager.cpp | 5 +++-- .../service/include/device_manager_service.h | 2 +- .../include/device_manager_service_listener.h | 3 ++- .../include/idevice_manager_service_impl.h | 3 ++- .../idevice_manager_service_listener.h | 4 ++-- .../include/softbus/softbus_listener.h | 2 +- .../service/src/device_manager_service.cpp | 5 +++-- .../src/device_manager_service_listener.cpp | 3 ++- .../src/ipc/standard/ipc_cmd_parser.cpp | 5 +++++ .../service/src/softbus/softbus_listener.cpp | 9 ++++---- .../UTTest_dm_device_state_manager.cpp | 3 ++- .../UTTest_softbus_listener.cpp | 3 ++- test/unittest/UTTest_device_manager_impl.h | 2 +- .../UTTest_device_manager_service_impl.cpp | 3 ++- test/unittest/UTTest_dm_pin_holder.h | 4 +++- 25 files changed, 74 insertions(+), 32 deletions(-) diff --git a/common/include/ipc/model/ipc_credential_auth_status_req.h b/common/include/ipc/model/ipc_credential_auth_status_req.h index 008d79020..730d077bf 100644 --- a/common/include/ipc/model/ipc_credential_auth_status_req.h +++ b/common/include/ipc/model/ipc_credential_auth_status_req.h @@ -24,6 +24,26 @@ class IpcNotifyCredentialAuthStatusReq : public IpcReq { DECLARE_IPC_MODEL(IpcNotifyCredentialAuthStatusReq); public: + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::GetDeviceList + * @tc.desc: Get DeviceList of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + std::string GetDeviceList() const + { + return deviceList_; + } + + /** + * @tc.name: IpcNotifyCredentialAuthStatusReq::SetDeviceList + * @tc.desc: Set DeviceList of the Ipc Notify Credential Auth Status Request + * @tc.type: FUNC + */ + void SetDeviceList(const std::string &deviceList) + { + deviceList_ = deviceList; + } + /** * @tc.name: IpcNotifyCredentialAuthStatusReq::GetDeviceTypeId * @tc.desc: Get DeviceType of the Ipc Notify Credential Auth Status Request @@ -65,6 +85,7 @@ public: } private: + std::string deviceList_; uint16_t deviceTypeId_ = 0; int32_t errcode_ = 0; }; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h index 010c94228..61989ccf3 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_callback.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_callback.h @@ -154,7 +154,7 @@ public: virtual ~CredentialAuthStatusCallback() { } - virtual void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void OnCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 70f50b5e2..ed39e630a 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 @@ -119,7 +119,8 @@ public: void OnDeviceTrustChange(const std::string &pkgName, const std::string &udid, const std::string &uuid, int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); - void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode); + void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, + uint16_t deviceTypeId, int32_t errcode); private: #if !defined(__LITEOS_M__) 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 ce9976e29..eee8b4acb 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 @@ -1736,9 +1736,10 @@ ON_IPC_READ_RESPONSE(GET_NETWORKID_BY_UDID, MessageParcel &reply, std::shared_pt ON_IPC_CMD(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); + std::string deviceList = data.ReadString(); uint16_t deviceTypeId = data.ReadUint16(); int32_t errCode = data.ReadInt32(); - DeviceManagerNotify::GetInstance().OnCredentialAuthStatus(pkgName, deviceTypeId, errCode); + DeviceManagerNotify::GetInstance().OnCredentialAuthStatus(pkgName, deviceList, deviceTypeId, errCode); reply.WriteInt32(DM_OK); return DM_OK; diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 93a06ad7a..f2072b0a0 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 @@ -1169,8 +1169,8 @@ void DeviceManagerNotify::UnRegisterCredentialAuthStatusCallback(const std::stri credentialAuthStatusCallback_.erase(pkgName); } -void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, - int32_t errcode) +void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, + uint16_t deviceTypeId, int32_t errcode) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -1190,7 +1190,7 @@ void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, uin LOGE("error, registered credential auth status callback is nullptr."); return; } - tempCbk->OnCredentialAuthStatus(deviceTypeId, errcode); + tempCbk->OnCredentialAuthStatus(deviceList, deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index c7f35e4a8..551f91518 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -131,7 +131,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); private: diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index c561b19e6..67c30b863 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -137,7 +137,7 @@ public: void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); - void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); private: diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 68fb531a4..e1343283e 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,7 +96,7 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a5efd68a5..f24af10f6 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -853,10 +853,11 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } -void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) { CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->HandleCredentialAuthStatus(deviceTypeId, errcode); + deviceStateMgr_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 28b66e4e1..d8b73f856 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -524,8 +524,10 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN return 0; } -void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) { + (void)deviceList; (void)deviceTypeId; (void)errcode; return; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 18e6b2bef..1848fc3b1 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -527,13 +527,14 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) softbusConnector_->ClearPkgName(); } -void DmDeviceStateManager::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DmDeviceStateManager::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) { if (listener_ == nullptr) { LOGE("Failed, listener_ is null."); return; } - listener_->OnCredentialAuthStatus(std::string(DM_PKG_NAME), deviceTypeId, errcode); + listener_->OnCredentialAuthStatus(std::string(DM_PKG_NAME), deviceList, deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 59cd724f9..eabc5a957 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,7 +201,7 @@ public: int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); - void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index e3df75866..ba2641f5c 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -73,7 +73,8 @@ public: const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; - void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override; + void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) override; void OnAppUnintall(const std::string &pkgName) override; private: diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index eb17b1511..7c8a691a6 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -273,7 +273,8 @@ public: virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; - virtual void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; + virtual void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; }; diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index a1d276dca..e611b3b5f 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -164,8 +164,8 @@ public: * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, - int32_t errcode) = 0; + virtual void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, + uint16_t deviceTypeId, int32_t errcode) = 0; virtual void OnAppUnintall(const std::string &pkgName) = 0; }; } // namespace DistributedHardware diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 9cfe41426..c49532bfb 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -59,7 +59,7 @@ public: static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); static void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); - static void CredentialAuthStatusProcess(uint16_t deviceTypeId, int32_t errcode); + static void CredentialAuthStatusProcess(std::string deviceList, uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); static void ClearDiscoveredDevice(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fc07f1c03..2f6dfe193 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2000,10 +2000,11 @@ void DeviceManagerService::SubscribePackageCommonEvent() #endif } -void DeviceManagerService::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) { if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleCredentialAuthStatus(deviceTypeId, errcode); + dmServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } } } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 7478a10bf..7f2cbea34 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -553,12 +553,13 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) } void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkgName, - uint16_t deviceTypeId, int32_t errcode) + const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) { LOGI("In, pkgName = %{public}s", pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); + pReq->SetDeviceList(deviceList); pReq->SetDeviceTypeId(deviceTypeId); pReq->SetErrCode(errcode); if (pkgName == std::string(DM_PKG_NAME)) { diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 64b21766b..27416f7a0 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1581,6 +1581,7 @@ ON_IPC_SET_REQUEST(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); + std::string deviceList = pReq->GetDeviceList(); uint16_t deviceTypeId = pReq->GetDeviceTypeId(); int32_t errCode = pReq->GetErrCode(); @@ -1588,6 +1589,10 @@ ON_IPC_SET_REQUEST(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, std::shared_ptr lock(g_credentialAuthStatus); - DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceTypeId, errcode); + DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } void SoftbusListener::OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { LOGI("received credential auth status callback from softbus."); + std::string deviceList(); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { CredentialAuthStatusProcess(deviceTypeId, errcode); }); + ffrt::submit([=]() { CredentialAuthStatusProcess(deviceList, deviceTypeId, errcode); }); #else - std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceTypeId, errcode); }); + std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceList, deviceTypeId, errcode); }); if (pthread_setname_np(credentialAuthStatus.native_handle(), CREDENTIAL_AUTH_STATUS) != DM_OK) { LOGE("credentialAuthStatus setname failed."); } diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 9d7bec6bf..9980b61b7 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -255,9 +255,10 @@ HWTEST_F(DmDeviceStateManagerTest, ProcNotifyEvent_001, testing::ext::TestSize.L HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) { + std::string deviceList; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - dmDeviceStateManager->HandleCredentialAuthStatus(deviceTypeId, errcode); + dmDeviceStateManager->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); } } // namespace diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index d3b965d4b..2de5e29a0 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -791,8 +791,9 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. uint16_t deviceTypeId = 0; int32_t errcode = -1; softbusListener->OnCredentialAuthStatus(deviceTypeId, errcode); + std::string deviceList; deviceTypeId = 0xA2F; - softbusListener->CredentialAuthStatusProcess(deviceTypeId, errcode); + softbusListener->CredentialAuthStatusProcess(deviceList, deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace diff --git a/test/unittest/UTTest_device_manager_impl.h b/test/unittest/UTTest_device_manager_impl.h index fa15d0b6f..bb1de8da2 100644 --- a/test/unittest/UTTest_device_manager_impl.h +++ b/test/unittest/UTTest_device_manager_impl.h @@ -123,7 +123,7 @@ public: virtual ~CandidateRestrictStatusCallbackTest() { } - void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) override {} + void OnCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 5042479b1..195b962a7 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1504,9 +1504,10 @@ HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_104, testing::e HWTEST_F(DeviceManagerServiceImplTest, CredentialAuthStatus_101, testing::ext::TestSize.Level0) { + std::string deviceList; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; - deviceManagerServiceImpl_->HandleCredentialAuthStatus(deviceTypeId, errcode); + deviceManagerServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } } // namespace diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 1434de194..3c1668837 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -193,9 +193,11 @@ public: (void)devInfo; } - void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override + void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) override { (void)pkgName; + (void)deviceList; (void)deviceTypeId; (void)errcode; } -- Gitee From 4107171c5a1f72746a3e11c5a96c7694788ad82c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 23 Oct 2024 15:48:17 +0800 Subject: [PATCH 326/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/include/idevice_manager_service_impl.h | 2 +- services/service/src/device_manager_service.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 7c8a691a6..f447e2ebc 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -274,7 +274,7 @@ public: virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, - int32_t errcode) = 0; + int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; }; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 2f6dfe193..1cb08de36 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2001,7 +2001,7 @@ void DeviceManagerService::SubscribePackageCommonEvent() } void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, - int32_t errcode) + int32_t errcode) { if (IsDMServiceImplReady()) { dmServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); -- Gitee From db3422016453a72da76d6d396fade0159a2fcf13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 23 Oct 2024 16:32:19 +0800 Subject: [PATCH 327/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/include/softbus/softbus_listener.h | 3 ++- services/service/src/softbus/softbus_listener.cpp | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index c49532bfb..b1186db61 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -58,7 +58,8 @@ public: static void DeviceTrustedChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); - static void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + static void OnCredentialAuthStatus(const char *deviceList, uint32_t deviceListLen, uint16_t deviceTypeId, + int32_t errcode); static void CredentialAuthStatusProcess(std::string deviceList, uint16_t deviceTypeId, int32_t errcode); static void CacheDiscoveredDevice(const DeviceInfo *device); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index fefaf4f9f..41e342b73 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -171,10 +171,15 @@ void SoftbusListener::CredentialAuthStatusProcess(std::string deviceList, uint16 DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } -void SoftbusListener::OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +void SoftbusListener::OnCredentialAuthStatus(const char *deviceList, uint32_t deviceListLen, + uint16_t deviceTypeId, int32_t errcode) { LOGI("received credential auth status callback from softbus."); - std::string deviceList(); + if (deviceList == nullptr || deviceListLen == 0) { + LOGE("[SOFTBUS]received invaild deviceList value."); + return; + } + std::string deviceList(deviceList, deviceListLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([=]() { CredentialAuthStatusProcess(deviceList, deviceTypeId, errcode); }); #else -- Gitee From f74de75927e0d7c2b122d4d0fea4181115b8c517 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 23 Oct 2024 17:07:58 +0800 Subject: [PATCH 328/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 41e342b73..8b32e9956 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -175,7 +175,7 @@ void SoftbusListener::OnCredentialAuthStatus(const char *deviceList, uint32_t de uint16_t deviceTypeId, int32_t errcode) { LOGI("received credential auth status callback from softbus."); - if (deviceList == nullptr || deviceListLen == 0) { + if (deviceList == nullptr || deviceListLen > MAX_SOFTBUS_MSG_LEN) { LOGE("[SOFTBUS]received invaild deviceList value."); return; } -- Gitee From d0cb1ecec44ffb806eab7f57d39839dcdc5f7e03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 23 Oct 2024 17:35:36 +0800 Subject: [PATCH 329/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- test/softbusunittest/UTTest_softbus_listener.cpp | 7 ++++--- test/unittest/UTTest_ipc_cmd_parser_service.cpp | 2 ++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 2de5e29a0..3a987096e 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -788,12 +788,13 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener->OnDeviceTrustedChange(type, msg1, msgLen2); softbusListener->OnDeviceTrustedChange(type, msg2, msgLen2); softbusListener->SendAclChangedBroadcast(msg); + char devicelist[msgLen] = {0}; uint16_t deviceTypeId = 0; int32_t errcode = -1; - softbusListener->OnCredentialAuthStatus(deviceTypeId, errcode); - std::string deviceList; + softbusListener->OnCredentialAuthStatus(devicelist, msgLen, deviceTypeId, errcode); + std::string deviceList2; deviceTypeId = 0xA2F; - softbusListener->CredentialAuthStatusProcess(deviceList, deviceTypeId, errcode); + softbusListener->CredentialAuthStatusProcess(deviceList2, deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } } // namespace diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 8bcddad18..71e2f2b7d 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -1544,9 +1544,11 @@ HWTEST_F(IpcCmdParserServiceTest, SetIpcRequestFunc_022, testing::ext::TestSize. req = std::make_shared(); std::string pkgName = "com.ohos.test"; + std::string deviceList = "test"; uint16_t deviceTypeId = 0x00; int32_t errcode = -1; req->SetPkgName(pkgName); + req->SetDeviceList(deviceList); req->SetDeviceTypeId(deviceTypeId); req->SetErrCode(errcode); if (ptr) { -- Gitee From ce12044438daa299fb6c02b5f359e22bcefa84d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 23 Oct 2024 18:11:09 +0800 Subject: [PATCH 330/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 8b32e9956..f60475eec 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -114,7 +114,7 @@ static IPublishCb softbusPublishCallback_ = { static INodeStateCb softbusNodeStateCb_ = { .events = EVENT_NODE_STATE_ONLINE | EVENT_NODE_STATE_OFFLINE | EVENT_NODE_STATE_INFO_CHANGED | - EVENT_NODE_STATUS_CHANGED, + EVENT_NODE_STATUS_CHANGED | EVENT_NODE_HICHAIN_PROOF_EXCEPTION, .onNodeOnline = SoftbusListener::OnSoftbusDeviceOnline, .onNodeOffline = SoftbusListener::OnSoftbusDeviceOffline, .onNodeBasicInfoChanged = SoftbusListener::OnSoftbusDeviceInfoChanged, -- Gitee From 3a65a0df171a15123075df72c831bfbb5df39475 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 23 Oct 2024 18:31:38 +0800 Subject: [PATCH 331/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index f60475eec..0f46b712e 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -179,11 +179,11 @@ void SoftbusListener::OnCredentialAuthStatus(const char *deviceList, uint32_t de LOGE("[SOFTBUS]received invaild deviceList value."); return; } - std::string deviceList(deviceList, deviceListLen); + std::string deviceListStr(deviceList, deviceListLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { CredentialAuthStatusProcess(deviceList, deviceTypeId, errcode); }); + ffrt::submit([=]() { CredentialAuthStatusProcess(deviceListStr, deviceTypeId, errcode); }); #else - std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceList, deviceTypeId, errcode); }); + std::thread credentialAuthStatus([=]() { CredentialAuthStatusProcess(deviceListStr, deviceTypeId, errcode); }); if (pthread_setname_np(credentialAuthStatus.native_handle(), CREDENTIAL_AUTH_STATUS) != DM_OK) { LOGE("credentialAuthStatus setname failed."); } -- Gitee From d7a32f10a90787df24fb29e2490b2dc9efa53130 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 24 Oct 2024 15:12:20 +0800 Subject: [PATCH 332/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 0f46b712e..3bbb0cb70 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -175,11 +175,14 @@ void SoftbusListener::OnCredentialAuthStatus(const char *deviceList, uint32_t de uint16_t deviceTypeId, int32_t errcode) { LOGI("received credential auth status callback from softbus."); - if (deviceList == nullptr || deviceListLen > MAX_SOFTBUS_MSG_LEN) { + if (deviceListLen > MAX_SOFTBUS_MSG_LEN) { LOGE("[SOFTBUS]received invaild deviceList value."); return; } - std::string deviceListStr(deviceList, deviceListLen); + std::string deviceListStr; + if (deviceList != nullptr) { + deviceListStr = std::string(deviceList, deviceListLen); + } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([=]() { CredentialAuthStatusProcess(deviceListStr, deviceTypeId, errcode); }); #else -- Gitee From a34315973c421d2ab8286d68dae15cd9afa990e9 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Thu, 24 Oct 2024 15:48:26 +0800 Subject: [PATCH 333/520] =?UTF-8?q?=E7=8A=B6=E6=80=81=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- services/implementation/src/authentication/dm_auth_manager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 23041ff9d..f0f59ac7c 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -969,6 +969,7 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) if (authResponseContext_->isOnline && authResponseContext_->authed) { authRequestContext_->reason = DM_OK; + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return; } @@ -977,6 +978,7 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) (authResponseContext_->authed && !authResponseContext_->isOnline)) { softbusConnector_->JoinLnn(authRequestContext_->addr); authRequestContext_->reason = DM_OK; + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return; } -- Gitee From 990e8fbdc91aa2ff5d752157458341364073966d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 25 Oct 2024 17:30:23 +0800 Subject: [PATCH 334/520] =?UTF-8?q?deviceName=E9=80=9A=E7=9F=A5=E6=80=BB?= =?UTF-8?q?=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../service/include/device_manager_service.h | 1 + .../service/include/softbus/softbus_listener.h | 1 + services/service/src/device_manager_service.cpp | 17 +++++++++++++++++ .../src/devicenamemgr/local_device_name_mgr.cpp | 2 ++ .../service/src/softbus/softbus_listener.cpp | 15 +++++++++++++++ 5 files changed, 36 insertions(+) diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index eabc5a957..b735cfd55 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -202,6 +202,7 @@ public: void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + int32_t SetLocalDeviceName(const std::string &localDeviceName); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index b1186db61..52ee84058 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -102,6 +102,7 @@ public: void SendAclChangedBroadcast(const std::string &msg); int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); static int32_t GetNetworkIdByUdid(const std::string &udid, std::string &networkId); + int32_t SetLocalDeviceName(const std::string &localDeviceName); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0689a3bd6..5ffc46393 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2007,5 +2007,22 @@ void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceL dmServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } } + +int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceName) +{ + LOGI("Start"); + if (localDeviceName.empty()) { + LOGE("Invalid parameter, parameter is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); + int32_t ret = softbusListener_->SetLocalDeviceName(localDeviceName); + if (ret != DM_OK) { + LOGE("SetLocalDeviceName error, failed ret: %{public}d", ret); + return ret; + } + return DM_OK; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp index 84db17a39..20b548d70 100644 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -25,6 +25,7 @@ #include "system_ability_definition.h" #include "uri.h" +#include "device_manager_service.h" #include "dm_constants.h" #include "dm_log.h" #include "settings_data_event_monitor.h" @@ -246,6 +247,7 @@ int32_t LocalDeviceNameMgr::QueryLocalDisplayName() localDisplayName_ = localDisplayName; dataShareHelper->Release(); LOGI("get display deviceName=%{public}s", localDisplayName.c_str()); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDisplayName); return DM_OK; } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 3bbb0cb70..a4a380db0 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -688,6 +688,21 @@ int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId); } +int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName) +{ + LOGI("Start"); + if (localDeviceName.empty()) { + LOGE("Invalid parameter, callerId is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t ret = ::SetLocalDeviceName(DM_PKG_NAME, localDeviceName.c_str()); + if (ret != DM_OK) { + LOGE("[SOFTBUS]SetLocalDeviceName error, failed ret: %{public}d", ret); + return ret; + } + return DM_OK; +} + int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId) { if (callerId.empty()) { -- Gitee From 86474af428349e1ca49e049efc1874ee2edb8e99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 28 Oct 2024 10:20:59 +0800 Subject: [PATCH 335/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- common/src/ipc/standard/ipc_cmd_register.cpp | 4 +--- commondependency/src/deviceprofile_connector.cpp | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/common/src/ipc/standard/ipc_cmd_register.cpp b/common/src/ipc/standard/ipc_cmd_register.cpp index 082a4e8d4..f6e23e205 100644 --- a/common/src/ipc/standard/ipc_cmd_register.cpp +++ b/common/src/ipc/standard/ipc_cmd_register.cpp @@ -32,7 +32,6 @@ constexpr int32_t ERR_DM_POINT_NULL = 96929748; int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) { - int32_t ret = DM_OK; if (pBaseReq == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } @@ -55,8 +54,7 @@ int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBas return ERR_DM_POINT_NULL; } } - ret = (ptr)(pBaseReq, data); - return ret; + return (ptr)(pBaseReq, data); } int32_t IpcCmdRegister::ReadResponse(int32_t cmdCode, MessageParcel &reply, std::shared_ptr pBaseRsp) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index c90af6e5f..c581a8224 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -849,7 +849,7 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s if (item.GetAccessee().GetAccesseeBundleName() == pkgName && item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccesser().GetAccesserDeviceId() == udid) { - tokenId = item.GetAccessee().GetAccesseeTokenId(); + tokenId = static_cast(item.GetAccessee().GetAccesseeTokenId()); bindLevel = static_cast(item.GetBindLevel()); LOGI("Sink get bindLevel %{public}d, tokenid %{public}" PRId64".", bindLevel, tokenId); continue; -- Gitee From 96fc5fefb2ebb4603b1aad82769dfcb66d7e77dd Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Mon, 28 Oct 2024 11:25:18 +0800 Subject: [PATCH 336/520] =?UTF-8?q?=E5=88=A0=E9=99=A4input=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../src/authentication/dm_auth_manager.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index f0f59ac7c..e137796a9 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -55,7 +55,6 @@ const int32_t WAIT_REQUEST_TIMEOUT = 10; const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; const int32_t CLONE_CONFIRM_TIMEOUT = 5; const int32_t CLONE_NEGOTIATE_TIMEOUT = 5; -const int32_t CLONE_INPUT_TIMEOUT = 5; const int32_t CLONE_ADD_TIMEOUT = 5; const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 5; const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 5; @@ -81,7 +80,6 @@ const std::map TASK_TIME_OUT_MAP = { { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, - { std::string(INPUT_TIMEOUT_TASK), CLONE_INPUT_TIMEOUT }, { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, @@ -1510,10 +1508,13 @@ int32_t DmAuthManager::AuthDevice(int32_t pinCode) } isAuthDevice_ = true; int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT, - [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + timer_->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), AUTH_DEVICE_TIMEOUT, + [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } if (hiChainAuthConnector_->AuthDevice(pinCode, osAccountId, remoteDeviceId_, authResponseContext_->requestId) != DM_OK) { LOGE("DmAuthManager::AuthDevice failed."); -- Gitee From 5dce7cd77bfa941ce6500176fbe1aaa49c6eb3fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 28 Oct 2024 20:31:33 +0800 Subject: [PATCH 337/520] =?UTF-8?q?=E6=95=B4=E6=94=B9log=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 2 +- services/service/src/device_manager_service_listener.cpp | 2 +- services/softbuscache/src/dm_softbus_cache.cpp | 2 +- utils/src/appInfo/standard/app_manager.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0689a3bd6..c564ba144 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -326,7 +326,7 @@ int32_t DeviceManagerService::GetDeviceInfo(const std::string &networkId, DmDevi int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) { - LOGI("Begin."); + LOGD("Begin."); bool isOnlyShowNetworkId = false; if (!PermissionManager::GetInstance().CheckNewPermission()) { LOGE("The caller does not have permission to call GetLocalDeviceInfo."); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 7f2cbea34..56e05b4d7 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -437,7 +437,7 @@ void DeviceManagerServiceListener::OnPinHolderEvent(const std::string &pkgName, #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoyAndSave(const std::string &pkgName, DmDeviceInfo &deviceInfo) { - LOGI("pkgName %{public}s.", pkgName.c_str()); + LOGD("pkgName %{public}s.", pkgName.c_str()); std::string appId = ""; if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { LOGD("GetAppIdByPkgName failed"); diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index faec235e8..c1027d74c 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -62,7 +62,7 @@ int32_t SoftbusCache::GetLocalDeviceInfo(DmDeviceInfo &nodeInfo) std::lock_guard mutexLock(localDevInfoMutex_); if (g_getLocalDevInfo) { nodeInfo = localDeviceInfo_; - LOGI("SoftbusCache::GetLocalDeviceInfo from dm cache."); + LOGD("SoftbusCache::GetLocalDeviceInfo from dm cache."); return DM_OK; } NodeBasicInfo nodeBasicInfo; diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 63935cd2b..a1311654d 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -106,7 +106,7 @@ int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &a LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("PkgName %{public}s.", pkgName.c_str()); + LOGD("PkgName %{public}s.", pkgName.c_str()); std::lock_guard lock(appIdMapLock_); if (appIdMap_.find(pkgName) == appIdMap_.end()) { LOGE("AppIdMap not find pkgName."); -- Gitee From ea75fae987bebe913522cbc71ffee522cde65163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 29 Oct 2024 15:18:20 +0800 Subject: [PATCH 338/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/permission/standard/permission_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index ab7359501..f49d5fcf7 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -60,7 +60,7 @@ constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME "ohos.security.distributed_access_token", }; -constexpr int32_t SETDNPOLICY_WHITE_LIST_NUM = 1; +constexpr uint16_t SETDNPOLICY_WHITE_LIST_NUM = 1; constexpr const static char g_setDnPolicyWhiteList[SETDNPOLICY_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "collaboration_service", }; -- Gitee From 04fb8a0d915eebe887bf9363f30fb2b2b90d1dc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 29 Oct 2024 15:48:41 +0800 Subject: [PATCH 339/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=A3=80=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../implementation/src/credential/dm_credential_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 043d2dd32..14f16e395 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -383,7 +383,7 @@ void to_json(nlohmann::json &jsonObject, const CredentialDataInfo &credentialDat int32_t DmCredentialManager::GetAddDeviceList(const nlohmann::json &jsonObject, nlohmann::json &jsonDeviceList) { - if (!jsonObject.contains(FIELD_CREDENTIAL_DATA) || !jsonObject[FIELD_CREDENTIAL_DATA].is_object() || + if (!jsonObject.contains(FIELD_CREDENTIAL_DATA) || !jsonObject[FIELD_CREDENTIAL_DATA].is_array() || !IsInt32(jsonObject, FIELD_AUTH_TYPE)) { LOGE("credentaildata or authType string key not exist!"); return ERR_DM_FAILED; -- Gitee From f954003898643bb7138efac31cf61e956e5a2fd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 29 Oct 2024 20:25:02 +0800 Subject: [PATCH 340/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/ipc/standard/ipc_server_stub.cpp | 2 +- utils/src/appInfo/standard/app_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 0ad5e7f8f..b384a77e3 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -232,7 +232,7 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< } dmListener_[pkgName] = listener; appRecipient_[pkgName] = appRecipient; - LOGI("Register listener complete."); + LOGD("Register listener complete."); return DM_OK; } diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index a1311654d..07a8099db 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -37,7 +37,7 @@ const std::string AppManager::GetAppId() std::string appId = ""; AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) { - LOGI("The caller is not token_hap."); + LOGD("The caller is not token_hap."); return appId; } sptr bundleManager = nullptr; -- Gitee From 8ed74afaf69adce24dfbc99366332ad809e234ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 30 Oct 2024 09:59:57 +0800 Subject: [PATCH 341/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/softbus_listener.cpp | 1 + utils/src/appInfo/standard/app_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 3bbb0cb70..8a44a0b78 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -758,6 +758,7 @@ int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nod extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType; extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN); devInfo.extraData = to_string(extraJson); + LOGI("OsType %{public}d.", nodeInfo.osType); return DM_OK; } diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 07a8099db..cb2c61ec9 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -109,7 +109,7 @@ int32_t AppManager::GetAppIdByPkgName(const std::string &pkgName, std::string &a LOGD("PkgName %{public}s.", pkgName.c_str()); std::lock_guard lock(appIdMapLock_); if (appIdMap_.find(pkgName) == appIdMap_.end()) { - LOGE("AppIdMap not find pkgName."); + LOGD("AppIdMap not find pkgName."); return ERR_DM_FAILED; } appId = appIdMap_[pkgName]; -- Gitee From bc4fed35ab3a4cdaf695246e52a5d220e1eb35dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Thu, 31 Oct 2024 11:30:18 +0800 Subject: [PATCH 342/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=80=BB=E7=BA=BF?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../service/include/devicenamemgr/account_boot_listener.h | 2 ++ .../service/include/devicenamemgr/local_device_name_mgr.h | 1 + services/service/src/device_manager_service.cpp | 2 +- .../service/src/devicenamemgr/account_boot_listener.cpp | 5 +++++ .../service/src/devicenamemgr/local_device_name_mgr.cpp | 4 ++++ services/service/src/ipc/standard/ipc_server_stub.cpp | 7 +++++++ services/service/src/softbus/softbus_listener.cpp | 2 +- 7 files changed, 21 insertions(+), 2 deletions(-) diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h index 341dcd8db..7ea76627c 100644 --- a/services/service/include/devicenamemgr/account_boot_listener.h +++ b/services/service/include/devicenamemgr/account_boot_listener.h @@ -35,6 +35,8 @@ public: void SetSaTriggerFlag(SaTriggerFlag triggerFlag); void InitDataShareEvent(); void DataShareCallback(); + std::shared_ptr GetLocalDeviceMgr() const; + private: /** * @brief flag for is registered callback for account boot event diff --git a/services/service/include/devicenamemgr/local_device_name_mgr.h b/services/service/include/devicenamemgr/local_device_name_mgr.h index 28630fc4a..2c03f786f 100644 --- a/services/service/include/devicenamemgr/local_device_name_mgr.h +++ b/services/service/include/devicenamemgr/local_device_name_mgr.h @@ -32,6 +32,7 @@ public: void RegisterDeviceNameChangeCb(); int32_t QueryLocalDisplayName(); void RegisterDisplayNameChangeCb(); + std::string GetLocalDisplayName() const; private: std::shared_ptr GetDataShareHelper(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 5ffc46393..61ddeb5d4 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2010,7 +2010,7 @@ void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceL int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceName) { - LOGI("Start"); + LOGI("DeviceManagerService Start SetLocalDeviceName!"); if (localDeviceName.empty()) { LOGE("Invalid parameter, parameter is empty."); return ERR_DM_INPUT_PARA_INVALID; diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 50de621fb..48b2338bd 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -158,5 +158,10 @@ void AccountBootListener::DataShareCallback() this->RegisterAccountBootCb(); } } + +std::shared_ptr AccountBootListener::GetLocalDeviceMgr() const +{ + return localDeviceMgr_; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp index 20b548d70..a3213d641 100644 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -276,5 +276,9 @@ void LocalDeviceNameMgr::RegisterDisplayNameChangeCb() LOGI("register display device name change cb success"); } +std::string LocalDeviceNameMgr::GetLocalDisplayName() const +{ + return localDisplayName_; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 0ad5e7f8f..446ee9a2d 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -86,6 +86,13 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; + if (!accountBootListener_->GetLocalDeviceMgr()->GetLocalDisplayName().empty()) { + LOGI("Already have display deviceName=%{public}s", + accountBootListener_->GetLocalDeviceMgr()->GetLocalDisplayName().c_str()); + DeviceManagerService::GetInstance() + .SetLocalDeviceName(accountBootListener_->GetLocalDeviceMgr()->GetLocalDisplayName()); + return; + } accountBootListener_->SetSaTriggerFlag(SaTriggerFlag::DM_SA_READY); return; } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a4a380db0..64e27b70b 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -690,7 +690,7 @@ int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName) { - LOGI("Start"); + LOGI("SoftbusListener Start SetLocalDeviceName!"); if (localDeviceName.empty()) { LOGE("Invalid parameter, callerId is empty."); return ERR_DM_INPUT_PARA_INVALID; -- Gitee From a9c63628bd39bad8018927b145635534a668b5ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 31 Oct 2024 14:21:12 +0800 Subject: [PATCH 343/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/dependency/softbus/softbus_connector.cpp | 1 + services/service/src/softbus/softbus_listener.cpp | 3 ++- services/softbuscache/src/dm_softbus_cache.cpp | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 0cb6a149d..29248f6a8 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -790,6 +790,7 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo) { + LOGI("Begin, osType : %{public}d", nodeBasicInfo.osType); if (memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 8a44a0b78..d4177f97d 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -711,6 +711,7 @@ int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, DmDeviceInfo &devInfo) { + LOGI("Begin, osType : %{public}d", nodeInfo.osType); if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); return ERR_DM_FAILED; @@ -737,6 +738,7 @@ int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &node int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { + LOGI("Begin, osType : %{public}d", nodeInfo.osType); if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return ERR_DM_FAILED; @@ -758,7 +760,6 @@ int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nod extraJson[PARAM_KEY_OS_TYPE] = nodeInfo.osType; extraJson[PARAM_KEY_OS_VERSION] = ConvertCharArray2String(nodeInfo.osVersion, OS_VERSION_BUF_LEN); devInfo.extraData = to_string(extraJson); - LOGI("OsType %{public}d.", nodeInfo.osType); return DM_OK; } diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index c1027d74c..eaa0c5cdf 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -255,6 +255,7 @@ int32_t SoftbusCache::GetUuidFromCache(const char *networkId, std::string &uuid) int32_t SoftbusCache::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { + LOGI("Begin, osType : %{public}d", nodeInfo.osType); if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return ERR_DM_FAILED; -- Gitee From 492094e04089a2f0bf32442d9809fe8e77961769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 31 Oct 2024 14:26:51 +0800 Subject: [PATCH 344/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 3343bcbae..d6d95efdb 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -94,6 +94,7 @@ if (defined(ohos_lite)) { "${common_path}/src/dfx/lite/dm_hisysevent.cpp", "${common_path}/src/dfx/lite/dm_hitrace.cpp", "${common_path}/src/dm_anonymous.cpp", + "${devicemanager_path}/radar/src/lite/dm_radar_helper.cpp", "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", -- Gitee From abba22dc8ab1bd45c9b2631771507136bc3b86ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 31 Oct 2024 15:34:25 +0800 Subject: [PATCH 345/520] =?UTF-8?q?=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/BUILD.gn | 1 - .../implementation/src/dependency/softbus/softbus_connector.cpp | 1 - services/service/src/softbus/softbus_listener.cpp | 1 - services/softbuscache/src/dm_softbus_cache.cpp | 1 - 4 files changed, 4 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index d6d95efdb..3343bcbae 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -94,7 +94,6 @@ if (defined(ohos_lite)) { "${common_path}/src/dfx/lite/dm_hisysevent.cpp", "${common_path}/src/dfx/lite/dm_hitrace.cpp", "${common_path}/src/dm_anonymous.cpp", - "${devicemanager_path}/radar/src/lite/dm_radar_helper.cpp", "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 29248f6a8..0cb6a149d 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -790,7 +790,6 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device void SoftbusConnector::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeBasicInfo, DmDeviceInfo &dmDeviceInfo) { - LOGI("Begin, osType : %{public}d", nodeBasicInfo.osType); if (memset_s(&dmDeviceInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index d4177f97d..899a18fda 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -711,7 +711,6 @@ int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &nodeInfo, const int32_t devScreenStatus, DmDeviceInfo &devInfo) { - LOGI("Begin, osType : %{public}d", nodeInfo.osType); if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); return ERR_DM_FAILED; diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index eaa0c5cdf..c1027d74c 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -255,7 +255,6 @@ int32_t SoftbusCache::GetUuidFromCache(const char *networkId, std::string &uuid) int32_t SoftbusCache::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { - LOGI("Begin, osType : %{public}d", nodeInfo.osType); if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); return ERR_DM_FAILED; -- Gitee From fb79d7dad7f66331b5efb0826501e5f9106694e2 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 31 Oct 2024 19:03:05 +0800 Subject: [PATCH 346/520] =?UTF-8?q?=E9=87=8D=E7=BD=AE=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- services/implementation/src/authentication/dm_auth_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index e137796a9..99fd7faef 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1250,6 +1250,7 @@ void DmAuthManager::AuthenticateFinish() LOGI("DmAuthManager::AuthenticateFinish start"); isAddingMember_ = false; isAuthenticateDevice_ = false; + isAuthDevice_ = false; if (authResponseContext_->isFinish) { CompatiblePutAcl(); } -- Gitee From 96cf1ec190959e3e2b01da105c3610e5ac139380 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 1 Nov 2024 10:54:07 +0800 Subject: [PATCH 347/520] =?UTF-8?q?=E8=8E=B7=E5=8F=96pinCode=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E9=80=BB=E8=BE=91=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../implementation/src/authentication/dm_auth_manager.cpp | 1 - .../src/dependency/hichain/hichain_auth_connector.cpp | 4 ++-- .../src/dependency/hichain/hichain_connector.cpp | 6 +++--- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 3e4f8aa35..3ca7517df 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1354,7 +1354,6 @@ int32_t DmAuthManager::GetPinCode(int32_t &code) { if (authResponseContext_ == nullptr) { LOGE("failed to GetPinCode because authResponseContext_ is nullptr"); - code = ERR_DM_AUTH_NOT_START; return ERR_DM_FAILED; } LOGI("ShowConfigDialog start add member pin code."); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index c7887c985..155846b3d 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -101,8 +101,8 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons return nullptr; } nlohmann::json jsonObj; - int32_t pinCode = 0; - if (dmDeviceAuthCallback_->GetPinCode(pinCode) == ERR_DM_FAILED) { + int32_t pinCode = -1; + if (dmDeviceAuthCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == -1) { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 08045a9b4..4f4a5ab3f 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -476,13 +476,13 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch return nullptr; } nlohmann::json jsonObj; - int32_t pinCode = 0; - if (hiChainConnectorCallback_->GetPinCode(pinCode) == ERR_DM_FAILED) { + int32_t pinCode = -1; + if (hiChainConnectorCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == -1) { jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str(); } - 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; -- Gitee From 32dbe27fa7b4997fad5a7cd6c3907dd24d882c43 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 31 Oct 2024 21:21:15 +0800 Subject: [PATCH 348/520] add lock Signed-off-by: gaoqiang_strong --- .../native_cpp/src/ipc/standard/ipc_client_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index fac75fe60..7745c5f46 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -147,6 +147,7 @@ int32_t IpcClientManager::SendRequest(int32_t cmdCode, std::shared_ptr r if (req == nullptr || rsp == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } + std::lock_guard autoLock(lock_); if (dmInterface_ != nullptr) { LOGD("IpcClientManager::SendRequest cmdCode: %{public}d", cmdCode); return dmInterface_->SendCmd(cmdCode, req, rsp); -- Gitee From 02d276dde9abf583ae45e3f652dcc328389d5da1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 1 Nov 2024 14:53:00 +0800 Subject: [PATCH 349/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../src/dependency/hichain/hichain_auth_connector.cpp | 2 +- .../implementation/src/dependency/hichain/hichain_connector.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 155846b3d..427b94a36 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -106,10 +106,10 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); } std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; std::string jsonStr = jsonObj.dump(); char *buffer = strdup(jsonStr.c_str()); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 4f4a5ab3f..dbef716ee 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -481,7 +481,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch jsonObj[FIELD_CONFIRMATION] = REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode).c_str(); + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); -- Gitee From 50443370d65322f962057a127f73c0782477d7cd Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 1 Nov 2024 15:12:57 +0800 Subject: [PATCH 350/520] add sink bind callback Signed-off-by: gaoqiang_strong --- .../device_manager_ipc_interface_code.h | 1 + .../native_cpp/include/device_manager.h | 3 ++ .../native_cpp/include/device_manager_impl.h | 3 ++ .../include/notify/device_manager_notify.h | 5 +++ .../native_cpp/src/device_manager_impl.cpp | 23 ++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 14 ++++++ .../src/notify/device_manager_notify.cpp | 45 +++++++++++++++++++ .../src/authentication/dm_auth_manager.cpp | 17 +++++++ .../include/device_manager_service_listener.h | 2 + .../idevice_manager_service_listener.h | 2 + .../src/device_manager_service_listener.cpp | 25 +++++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 45 +++++++++++++++++++ test/unittest/UTTest_dm_pin_holder.h | 10 +++++ 13 files changed, 195 insertions(+) diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index 82f3b6251..cd6dee5cd 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -97,6 +97,7 @@ enum DMIpcCmdInterfaceCode { GET_DEVICE_SCREEN_STATUS, GET_NETWORKID_BY_UDID, SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, + SINK_BIND_TARGET_RESULT, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/interfaces/inner_kits/native_cpp/include/device_manager.h b/interfaces/inner_kits/native_cpp/include/device_manager.h index 6ecb472ab..d9abc7351 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager.h @@ -628,6 +628,9 @@ public: virtual int32_t RegisterCredentialAuthStatusCallback(const std::string &pkgName, std::shared_ptr callback) = 0; virtual int32_t UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) = 0; + virtual int32_t RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) = 0; + virtual int32_t UnRegisterSinkBindCallback(const std::string &pkgName) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index ca18f9e29..f701b5540 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -400,6 +400,9 @@ public: virtual int32_t RegisterCredentialAuthStatusCallback(const std::string &pkgName, std::shared_ptr callback) override; virtual int32_t UnRegisterCredentialAuthStatusCallback(const std::string &pkgName) override; + virtual int32_t RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) override; + virtual int32_t UnRegisterSinkBindCallback(const std::string &pkgName) override; private: DeviceManagerImpl() = default; 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 ed39e630a..10ffd05cd 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 @@ -73,6 +73,8 @@ public: void RegisterCredentialAuthStatusCallback(const std::string &pkgName, std::shared_ptr callback); void UnRegisterCredentialAuthStatusCallback(const std::string &pkgName); + void RegisterSinkBindCallback(const std::string &pkgName, std::shared_ptr callback); + void UnRegisterSinkBindCallback(const std::string &pkgName); public: static void DeviceInfoOnline(const DmDeviceInfo &deviceInfo, std::shared_ptr tempCbk); @@ -121,6 +123,8 @@ public: void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, + std::string content); private: #if !defined(__LITEOS_M__) @@ -140,6 +144,7 @@ private: std::map> devTrustChangeCallback_; std::map> deviceScreenStatusCallback_; std::map> credentialAuthStatusCallback_; + std::map> sinkBindTargetCallback_; std::mutex bindLock_; }; } // namespace DistributedHardware 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 9b163893a..42e3e6086 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -2465,5 +2465,28 @@ int32_t DeviceManagerImpl::UnRegisterCredentialAuthStatusCallback(const std::str LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } + +int32_t DeviceManagerImpl::RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().RegisterSinkBindCallback(pkgName, callback); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} + +int32_t DeviceManagerImpl::UnRegisterSinkBindCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Error: Invalid para"); + return ERR_DM_INPUT_PARA_INVALID; + } + DeviceManagerNotify::GetInstance().UnRegisterSinkBindCallback(pkgName); + LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 eee8b4acb..a18aa8327 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 @@ -1744,5 +1744,19 @@ ON_IPC_CMD(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &data, MessagePa reply.WriteInt32(DM_OK); return DM_OK; } + +ON_IPC_CMD(SINK_BIND_TARGET_RESULT, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + PeerTargetId targetId; + DecodePeerTargetId(data, targetId); + int32_t result = data.ReadInt32(); + int32_t status = data.ReadInt32(); + std::string content = data.ReadString(); + + DeviceManagerNotify::GetInstance().OnSinkBindResult(pkgName, targetId, result, status, content); + reply.WriteInt32(DM_OK); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 f2072b0a0..046090539 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 @@ -1192,5 +1192,50 @@ void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, con } tempCbk->OnCredentialAuthStatus(deviceList, deviceTypeId, errcode); } + +void DeviceManagerNotify::RegisterSinkBindCallback(const std::string &pkgName, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("Invalid parameter, pkgName is empty or callback is nullptr."); + return; + } + std::lock_guard autoLock(lock_); + sinkBindTargetCallback_[pkgName] = callback; +} + +void DeviceManagerNotify::UnRegisterSinkBindCallback(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::lock_guard autoLock(lock_); + sinkBindTargetCallback_.erase(pkgName); +} + +void DeviceManagerNotify::OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, + int32_t result, int32_t status, std::string content) +{ + if (pkgName.empty()) { + LOGE("Invalid para, pkgName: %{public}s.", pkgName.c_str()); + return; + } + LOGI("DeviceManagerNotify::OnSinkBindResult in, pkgName:%{public}s, result:%{public}d", pkgName.c_str(), result); + std::shared_ptr tempCbk; + { + std::lock_guard autoLock(lock_); + if (sinkBindTargetCallback_.find(pkgName) == sinkBindTargetCallback_.end()) { + LOGE("error, sink bind callback not register."); + return; + } + tempCbk = sinkBindTargetCallback_[pkgName]; + } + if (tempCbk == nullptr) { + LOGE("error, registered sink bind callback is nullptr."); + return; + } + tempCbk->OnBindResult(targetId, result, status, content); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 3e4f8aa35..427e01c42 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -321,6 +321,7 @@ int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) LOGI("Stop previous AuthenticateDevice."); authRequestContext_->reason = STOP_BIND; authResponseContext_->state = authRequestState_->GetStateType(); + authResponseContext_->reply = STOP_BIND; authRequestState_->TransitionTo(std::make_shared()); } return DM_OK; @@ -639,6 +640,7 @@ void DmAuthManager::MemberJoinAuthRequest(int64_t requestId, int32_t status) if (status != DM_OK || authResponseContext_->requestId != requestId) { if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authResponseContext_->reply = ERR_DM_BIND_PIN_CODE_ERROR; authRequestContext_->reason = ERR_DM_BIND_PIN_CODE_ERROR; authRequestState_->TransitionTo(std::make_shared()); return; @@ -662,6 +664,7 @@ void DmAuthManager::HandleMemberJoinImportAuthCode(const int64_t requestId, cons { if (status != DM_OK || authResponseContext_->requestId != requestId) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; + authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; authRequestState_->TransitionTo(std::make_shared()); } else { @@ -678,6 +681,7 @@ void DmAuthManager::HandleAuthenticateTimeout(std::string name) } authResponseContext_->state = authRequestState_->GetStateType(); authRequestContext_->reason = ERR_DM_TIME_OUT; + authResponseContext_->reply = ERR_DM_TIME_OUT; authRequestState_->TransitionTo(std::make_shared()); } @@ -715,6 +719,7 @@ int32_t DmAuthManager::EstablishAuthChannel(const std::string &deviceId) authResponseContext_ = std::make_shared(); } authResponseContext_->state = AuthState::AUTH_REQUEST_NEGOTIATE; + authResponseContext_->reply = sessionId; if (authRequestContext_ == nullptr) { authRequestContext_ = std::make_shared(); } @@ -947,6 +952,7 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) if (authResponseContext_->isOnline && authResponseContext_->authed) { authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return; @@ -957,6 +963,7 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) softbusConnector_->JoinLnn(authRequestContext_->addr); authRequestContext_->reason = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); return; } @@ -1090,6 +1097,7 @@ void DmAuthManager::StartRespAuthProcess() LOGE("do not accept"); authResponseContext_->state = AuthState::AUTH_REQUEST_REPLY; authRequestContext_->reason = ERR_DM_AUTH_PEER_REJECT; + authResponseContext_->reply = ERR_DM_AUTH_PEER_REJECT; authRequestState_->TransitionTo(std::make_shared()); } } @@ -1175,6 +1183,7 @@ int32_t DmAuthManager::JoinNetwork() authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authResponseContext_->isFinish = true; authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); return DM_OK; } @@ -1182,6 +1191,8 @@ int32_t DmAuthManager::JoinNetwork() void DmAuthManager::SinkAuthenticateFinish() { LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); + listener_->OnSinkBindResult(authResponseContext_->hostPkgName, peerTargetId_, authResponseContext_->reply, + authResponseContext_->state, GenerateBindResultContent()); if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && authPtr_ != nullptr) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_CONFIRM_SHOW); @@ -1871,6 +1882,7 @@ void DmAuthManager::RequestCredentialDone() softbusConnector_->JoinLnn(authRequestContext_->addr); authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); } @@ -1929,6 +1941,7 @@ void DmAuthManager::SrcAuthDeviceFinish() softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return; @@ -1949,6 +1962,7 @@ void DmAuthManager::SrcAuthDeviceFinish() softbusConnector_->JoinLnn(authRequestContext_->addr); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); return; @@ -2001,6 +2015,7 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; + authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; authRequestState_->TransitionTo(std::make_shared()); return; } @@ -2010,6 +2025,7 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = ERR_DM_INPUT_PARA_INVALID; + authResponseContext_->reply = ERR_DM_INPUT_PARA_INVALID; authRequestState_->TransitionTo(std::make_shared()); } else { timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), @@ -2297,6 +2313,7 @@ int32_t DmAuthManager::CheckTrustState() softbusConnector_->JoinLnn(authResponseContext_->deviceId); authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestContext_->reason = DM_OK; + authResponseContext_->reply = DM_OK; authRequestState_->TransitionTo(std::make_shared()); return ALREADY_BIND; } diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index ba2641f5c..a175c8525 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -76,6 +76,8 @@ public: void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) override; void OnAppUnintall(const std::string &pkgName) override; + void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + int32_t status, std::string content) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index e611b3b5f..9e39d2440 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -167,6 +167,8 @@ public: virtual void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; virtual void OnAppUnintall(const std::string &pkgName) = 0; + virtual void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + int32_t status, std::string content) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 7f2cbea34..41cc15c66 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -585,5 +585,30 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) } } } + +void DeviceManagerServiceListener::OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, + int32_t result, int32_t status, std::string content) +{ + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + if (status < STATUS_DM_AUTH_FINISH && status > STATUS_DM_AUTH_DEFAULT) { + status = STATUS_DM_AUTH_DEFAULT; + } + PeerTargetId returnTargetId = targetId; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::string deviceIdTemp = ""; + DmKVValue kvValue; + if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { + returnTargetId.deviceId = deviceIdTemp; + } +#endif + pReq->SetPkgName(pkgName); + pReq->SetPeerTargetId(returnTargetId); + pReq->SetResult(result); + pReq->SetStatus(status); + pReq->SetContent(content); + ipcServerListener_.SendRequest(SINK_BIND_TARGET_RESULT, pReq, pRsp); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 27416f7a0..2bb2369b3 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1102,6 +1102,51 @@ ON_IPC_READ_RESPONSE(BIND_TARGET_RESULT, MessageParcel &reply, std::shared_ptr pBaseReq, MessageParcel &data) +{ + if (pBaseReq == nullptr) { + return ERR_DM_FAILED; + } + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + PeerTargetId targetId = pReq->GetPeerTargetId(); + int32_t result = pReq->GetResult(); + int32_t status = pReq->GetStatus(); + std::string content = pReq->GetContent(); + + if (!data.WriteString(pkgName)) { + LOGE("write bind pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!EncodePeerTargetId(targetId, data)) { + LOGE("write bind peer target id failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(result)) { + LOGE("write bind result code failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(status)) { + LOGE("write bind result status failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteString(content)) { + LOGE("write bind result content failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SINK_BIND_TARGET_RESULT, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + if (pBaseRsp == nullptr) { + LOGE("pBaseRsp is null"); + return ERR_DM_FAILED; + } + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} + ON_IPC_SET_REQUEST(UNBIND_TARGET_RESULT, std::shared_ptr pBaseReq, MessageParcel &data) { if (pBaseReq == nullptr) { diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 3c1668837..d8acbce6f 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -206,6 +206,16 @@ public: { (void)pkgName; } + + void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + int32_t status, std::string content) override + { + (void)pkgName; + (void)targetId; + (void)result; + (void)status; + (void)content; + } }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From f6844ee2b67993e36d54eb1787f63a04ddf2dd47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 1 Nov 2024 18:06:25 +0800 Subject: [PATCH 351/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../include/devicenamemgr/account_boot_listener.h | 2 +- .../service/src/devicenamemgr/account_boot_listener.cpp | 4 ++-- services/service/src/ipc/standard/ipc_server_stub.cpp | 9 ++++----- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h index 7ea76627c..a2df48e8e 100644 --- a/services/service/include/devicenamemgr/account_boot_listener.h +++ b/services/service/include/devicenamemgr/account_boot_listener.h @@ -35,7 +35,7 @@ public: void SetSaTriggerFlag(SaTriggerFlag triggerFlag); void InitDataShareEvent(); void DataShareCallback(); - std::shared_ptr GetLocalDeviceMgr() const; + std::string GetLocalDisplayName() const; private: /** diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 48b2338bd..0d2b77a7e 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -159,9 +159,9 @@ void AccountBootListener::DataShareCallback() } } -std::shared_ptr AccountBootListener::GetLocalDeviceMgr() const +std::string AccountBootListener::GetLocalDisplayName() const { - return localDeviceMgr_; + return localDeviceMgr_->GetLocalDisplayName(); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 446ee9a2d..b720748e1 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -86,11 +86,10 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; - if (!accountBootListener_->GetLocalDeviceMgr()->GetLocalDisplayName().empty()) { - LOGI("Already have display deviceName=%{public}s", - accountBootListener_->GetLocalDeviceMgr()->GetLocalDisplayName().c_str()); - DeviceManagerService::GetInstance() - .SetLocalDeviceName(accountBootListener_->GetLocalDeviceMgr()->GetLocalDisplayName()); + std::string localDisplayName = accountBootListener_->GetLocalDisplayName(); + if (!localDisplayName.empty()) { + LOGI("Already have display deviceName=%{public}s", localDisplayName.c_str()); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDisplayName); return; } accountBootListener_->SetSaTriggerFlag(SaTriggerFlag::DM_SA_READY); -- Gitee From 05c087c6a047923ca0418db40f65c7cc4d255502 Mon Sep 17 00:00:00 2001 From: li-tiangang4 Date: Sat, 2 Nov 2024 15:03:04 +0800 Subject: [PATCH 352/520] =?UTF-8?q?=E4=BF=9D=E6=B4=BBdhardware=E8=BF=9B?= =?UTF-8?q?=E7=A8=8B=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: li-tiangang4 --- services/service/src/device_manager_service.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 641331f7c..af482fe23 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1015,9 +1015,9 @@ int32_t DeviceManagerService::NotifyEvent(const std::string &pkgName, const int3 void DeviceManagerService::LoadHardwareFwkService() { - std::string extra; std::vector deviceList; - int32_t ret = GetTrustedDeviceList(DM_PKG_NAME, extra, deviceList); + CHECK_NULL_VOID(softbusListener_); + int32_t ret = softbusListener_->GetTrustedDeviceList(deviceList); if (ret != DM_OK) { LOGE("LoadHardwareFwkService failed, get trusted devicelist failed."); return; -- Gitee From 0868b349c2082f07d0bfa2871bf8c53dee9bcc8d Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Mon, 4 Nov 2024 19:03:40 +0800 Subject: [PATCH 353/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=B6=85=E6=97=B6?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- common/include/dm_constants.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 3a933cd29..932dc0562 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -116,6 +116,9 @@ enum { ERR_DM_SOFTBUS_STOP_DISCOVERY_DEVICE = 96929815, ERR_DM_INVALID_JSON_STRING = 96929816, ERR_DM_GET_DATA_SHA256_HASH = 96929817, + ERR_DM_CHANNLE_OPEN_TIMEOUT = 96929818, + ERR_DM_ADD_GOUTP_TIMEOUT = 96929819, + ERR_DM_INPUT_TIMEOUT = 96929820, }; constexpr const char* TAG_GROUP_ID = "groupId"; -- Gitee From 72749dbc19c3920acb6db4747c61d5e1e141de27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 4 Nov 2024 20:33:28 +0800 Subject: [PATCH 354/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 0689a3bd6..476a1fa41 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -952,7 +952,6 @@ bool DeviceManagerService::IsDMServiceImplReady() listener_ = std::make_shared(); } if (dmServiceImpl_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImpl_ = nullptr; isImplsoLoaded_ = false; return false; @@ -1199,7 +1198,6 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() dmServiceImplExt_ = std::shared_ptr(func()); if (dmServiceImplExt_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImplExt_ = nullptr; isAdapterSoLoaded_ = false; LOGE("dm service adapter impl ext init failed."); -- Gitee From 981a8e568a9861c4fc61ed1d77f7d746799e1266 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 5 Nov 2024 15:21:31 +0800 Subject: [PATCH 355/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../dependency/hichain/hichain_connector.cpp | 21 ++ .../hichain_connector_fuzzer.cpp | 140 +++++++++++ .../UTTest_dm_discovery_manager.cpp | 12 +- .../UTTest_dm_publish_manager.cpp | 7 +- .../UTTest_mine_softbus_listener.cpp | 11 +- .../UTTest_softbus_connector.cpp | 17 +- .../UTTest_softbus_listener.cpp | 3 +- test/unittest/BUILD.gn | 16 +- .../UTTest_device_manager_service.cpp | 227 +++++++++++++++++- test/unittest/UTTest_device_manager_service.h | 18 ++ .../UTTest_device_manager_service_impl.cpp | 125 +++++++++- .../UTTest_device_manager_service_impl.h | 4 + .../UTTest_device_manager_service_two.cpp | 2 +- test/unittest/mock/app_manager_mock.cpp | 28 +++ test/unittest/mock/app_manager_mock.h | 40 +++ .../mock/device_manager_service_impl_mock.cpp | 27 +++ .../mock/device_manager_service_impl_mock.h | 40 +++ .../mock/deviceprofile_connector_mock.cpp | 28 +++ .../mock/deviceprofile_connector_mock.h | 40 +++ .../unittest/mock/kv_adapter_manager_mock.cpp | 29 +++ test/unittest/mock/kv_adapter_manager_mock.h | 40 +++ .../unittest/mock/permission_manager_mock.cpp | 28 +++ test/unittest/mock/permission_manager_mock.h | 40 +++ test/unittest/mock/softbus_listener_mock.cpp | 47 ++++ test/unittest/mock/softbus_listener_mock.h | 48 ++++ 25 files changed, 1005 insertions(+), 33 deletions(-) create mode 100644 test/unittest/mock/app_manager_mock.cpp create mode 100644 test/unittest/mock/app_manager_mock.h create mode 100644 test/unittest/mock/device_manager_service_impl_mock.cpp create mode 100644 test/unittest/mock/device_manager_service_impl_mock.h create mode 100644 test/unittest/mock/deviceprofile_connector_mock.cpp create mode 100644 test/unittest/mock/deviceprofile_connector_mock.h create mode 100644 test/unittest/mock/kv_adapter_manager_mock.cpp create mode 100644 test/unittest/mock/kv_adapter_manager_mock.h create mode 100644 test/unittest/mock/permission_manager_mock.cpp create mode 100644 test/unittest/mock/permission_manager_mock.h create mode 100644 test/unittest/mock/softbus_listener_mock.cpp create mode 100644 test/unittest/mock/softbus_listener_mock.h diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index dbef716ee..d4423017b 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -15,6 +15,7 @@ #include "hichain_connector.h" +#include #include #include #include @@ -155,6 +156,16 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou return ERR_DM_FAILED; } + try + { + jsonObj.dump(); + } + catch(nlohmann::json::type_error& e) + { + LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); + return ERR_DM_FAILED; + } + int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); struct RadarInfo info = { .funcName = "CreateGroup", @@ -801,6 +812,16 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const return ERR_DM_FAILED; } + try + { + jsonObj.dump(); + } + catch(nlohmann::json::type_error& e) + { + LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); + return ERR_DM_FAILED; + } + int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 433615553..550dad6e1 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include "device_manager_service_listener.h" @@ -53,6 +54,31 @@ public: } }; +void AddGroupInfo(std::vector &groupList) +{ + GroupInfo groupInfo1; + groupInfo1.groupId = "234"; + groupInfo1.groupType = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; + groupList.push_back(groupInfo1); + GroupInfo groupInfo2; + groupInfo2.groupId = "1485"; + groupInfo2.groupOwner = DM_PKG_NAME; + groupList.push_back(groupInfo2); +} + +void AddAclInfo(std::vector> &delACLInfoVec) +{ + int32_t key = 12; + std::string value = "acl_info1"; + delACLInfoVec.push_back(std::make_pair(key, value)); + key = 23; + value = "acl_info2"; + delACLInfoVec.push_back(std::make_pair(key, value)); + key = 25; + value = "acl_info3"; + delACLInfoVec.push_back(std::make_pair(key, value)); +} + void HiChainConnectorFuzzTest(const uint8_t* data, size_t size) { if ((data == nullptr) || (size < sizeof(int32_t))) { @@ -115,6 +141,118 @@ void HiChainConnectorSecondFuzzTest(const uint8_t* data, size_t size) hichainConnector->UnRegisterHiChainGroupCallback(); hichainConnector->GetJsonStr(jsonDeviceList, "key"); } + +void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + + int64_t requestId = *(reinterpret_cast(data)); + std::string groupName(reinterpret_cast(data), size); + GroupInfo groupInfo; + std::string userId(reinterpret_cast(data), size); + int32_t usersId = *(reinterpret_cast(data)); + int32_t authType = *(reinterpret_cast(data)); + std::vector groupList; + std::string queryParams(reinterpret_cast(data), size); + std::string pkgName(reinterpret_cast(data), size); + std::string groupId(reinterpret_cast(data), size); + std::string deviceId(reinterpret_cast(data), size); + std::string reqDeviceId(reinterpret_cast(data), size); + nlohmann::json jsonOutObj; + std::shared_ptr callback; + std::string jsonStr(reinterpret_cast(data), size); + nlohmann::json jsonDeviceList; + int32_t groupType = *(reinterpret_cast(data)); + std::string udid(reinterpret_cast(data), size); + int32_t switchUserId = *(reinterpret_cast(data)); + std::string reqParams(reinterpret_cast(data), size); + int operationCode = GroupOperationCode::MEMBER_JOIN; + hichainConnector->deviceGroupManager_ = nullptr; + hichainConnector->AddMember(deviceId, queryParams); + hichainConnector->CreateGroup(requestId, groupName); + hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); + hichainConnector->getRegisterInfo(queryParams, jsonStr); + hichainConnector->addMultiMembers(groupType, userId, jsonDeviceList); + hichainConnector->deleteMultiMembers(groupType, userId, jsonDeviceList); + hichainConnector->GetGroupInfoCommon(usersId, queryParams, pkgName.c_str(), groupList); + hichainConnector->hiChainResCallback_ = nullptr; + hichainConnector->GetConnectPara(deviceId, reqDeviceId); + hichainConnector->onRequest(requestId, operationCode, reqParams.c_str()); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + if (hichainConnector->deviceGroupManager_ == nullptr) { + hichainConnector->deviceGroupManager_ = GetGmInstance(); + } + hichainConnector->CreateGroup(requestId, groupName); + hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); + hichainConnector->IsGroupCreated(groupName ,groupInfo); + hichainConnector->GetGroupInfoExt(usersId, queryParams, groupList); + hichainConnector->GetGroupInfoCommon(usersId, queryParams, pkgName.c_str(), groupList); + hichainConnector->RegisterHiChainGroupCallback(callback); + hichainConnector->GetJsonInt(jsonDeviceList, "key"); + hichainConnector->deleteMultiMembers(groupType, userId, jsonDeviceList); + hichainConnector->DeleteAllGroupByUdid(udid); + hichainConnector->DeleteP2PGroup(switchUserId); +} + +void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + + int64_t requestId = *(reinterpret_cast(data)); + std::string groupName(reinterpret_cast(data), size); + std::string groupId(reinterpret_cast(data), size); + std::string deviceId(reinterpret_cast(data), size); + std::string returnData(reinterpret_cast(data), size); + std::string userId(reinterpret_cast(data), size); + int32_t authType = *(reinterpret_cast(data)); + int operationCode = GroupOperationCode::MEMBER_JOIN; + int errCode = 102; + std::vector syncGroupList; + std::vector> delACLInfoVec; + std::vector userIdVec; + AddAclInfo(delACLInfoVec); + hichainConnector->DeleteGroupByACL(delACLInfoVec, userIdVec); + userIdVec.push_back(key); + key = 32; + userIdVec.push_back(key); + std::vector groupList; + AddGroupInfo(groupList); + hichainConnector->DeleteGroup(groupId); + hichainConnector->DeleteGroupExt(groupId); + hichainConnector->DeleteGroup(authType, groupId); + hichainConnector->DeleteGroup(requestId, userId, authType); + hichainConnector->DelMemberFromGroup(groupId, deviceId); + hichainConnector->DeleteRedundanceGroup(userId); + hichainConnector->DealRedundanceGroup(userId, authType); + hichainConnector->DeleteGroupByACL(delACLInfoVec, userIdVec); + hichainConnector->IsNeedDelete(groupName, userId, delACLInfoVec); + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + hichainConnector->onRequest(requestId, operationCode, returnData.c_str()); + operationCode = GroupOperationCode::GROUP_CREATE; + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + operationCode == GroupOperationCode::MEMBER_DELETE + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + operationCode == GroupOperationCode::GROUP_DISBAND; + hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); + hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); + hichainConnector->GenRequestId(); + hichainConnector->GetRelatedGroups(deviceId, groupList); + hichainConnector->GetRelatedGroupsExt(deviceId, groupList); + hichainConnector->GetSyncGroupList(groupList, syncGroupList); + hichainConnector->GetGroupId(userId, authType, userId); +} } } @@ -124,5 +262,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) /* Run your code on data */ OHOS::DistributedHardware::HiChainConnectorFuzzTest(data, size); OHOS::DistributedHardware::HiChainConnectorSecondFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorThirdFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorForthFuzzTest(data, size); return 0; } \ No newline at end of file diff --git a/test/commonunittest/UTTest_dm_discovery_manager.cpp b/test/commonunittest/UTTest_dm_discovery_manager.cpp index 895b74e2e..73299f1a8 100644 --- a/test/commonunittest/UTTest_dm_discovery_manager.cpp +++ b/test/commonunittest/UTTest_dm_discovery_manager.cpp @@ -53,6 +53,12 @@ std::shared_ptr hiChainConnector_ = std::make_shared discoveryMgr_ = std::make_shared(softbusConnector_, listener_, hiChainConnector_); +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR + || ret == SOFTBUS_IPC_ERR; +} + /** * @tc.name: DmDiscoveryManager_001 * @tc.desc: Test whether the DmDiscoveryManager function can generate a new pointer @@ -135,7 +141,7 @@ HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_003, testing::ext::TestSiz std::queue emptyQueue; discoveryMgr_->discoveryQueue_ = emptyQueue; int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - ASSERT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + ASSERT_TRUE(CheckSoftbusRes(ret)); discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeInfo.subscribeId); } @@ -174,7 +180,7 @@ HWTEST_F(DmDiscoveryManagerTest, StartDeviceDiscovery_005, testing::ext::TestSiz std::queue emptyQueue; discoveryMgr_->discoveryQueue_ = emptyQueue; int32_t ret = discoveryMgr_->StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - ASSERT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + ASSERT_TRUE(CheckSoftbusRes(ret)); discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); } @@ -203,7 +209,7 @@ HWTEST_F(DmDiscoveryManagerTest, StopDeviceDiscovery_002, testing::ext::TestSize std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; int32_t ret = discoveryMgr_->StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** diff --git a/test/commonunittest/UTTest_dm_publish_manager.cpp b/test/commonunittest/UTTest_dm_publish_manager.cpp index 70ec4cb32..7f50c30d2 100644 --- a/test/commonunittest/UTTest_dm_publish_manager.cpp +++ b/test/commonunittest/UTTest_dm_publish_manager.cpp @@ -47,6 +47,10 @@ std::shared_ptr softbusConnector_ = std::make_shared listener_ = std::make_shared(); std::shared_ptr publishMgr_ = std::make_shared(softbusConnector_, listener_); +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || ret == SOFTBUS_IPC_ERR; +} /** * @tc.name: DmPublishManager_001 * @tc.desc: Test whether the DmPublishManager function can generate a new pointer @@ -111,12 +115,13 @@ HWTEST_F(DmPublishManagerTest, PublishDeviceDiscovery_002, testing::ext::TestSiz publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); pkgName = "com.ohos.helloworld.new"; int32_t ret = publishMgr_->PublishDeviceDiscovery(pkgName, publishInfo); - ASSERT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + ASSERT_TRUE(CheckSoftbusRes(ret)); publishMgr_->UnPublishDeviceDiscovery(pkgName, publishInfo.publishId); } /** * @tc.name: OnPublishResult_001 + * * @tc.desc: The OnPublishFailed function takes the wrong case and emptying pkgName * @tc.type: FUNC * @tc.require: I5N1K3 diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 37f411872..ee2d19c81 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -45,6 +45,13 @@ void MineSoftbusListenerTest::TearDownTestCase() } namespace { + +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR + || ret == SOFTBUS_IPC_ERR; +} + HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_001, testing::ext::TestSize.Level0) { string pkgName; @@ -72,7 +79,7 @@ HWTEST_F(MineSoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestS uint16_t subscribeId = 1; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->StopRefreshSoftbusLNN(subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } HWTEST_F(MineSoftbusListenerTest, OnPublishResult_001, testing::ext::TestSize.Level0) @@ -755,7 +762,7 @@ HWTEST_F(MineSoftbusListenerTest, PublishDeviceDiscovery_001, testing::ext::Test { std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->PublishDeviceDiscovery(); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } HWTEST_F(MineSoftbusListenerTest, MatchSearchDealTask_001, testing::ext::TestSize.Level0) diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 8c467dd65..cc8c4fd78 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -100,14 +100,17 @@ void SoftbusConnectorTest::TearDownTestCase() { } -bool SoftbusConnectorTest::CheckReturnResult(int ret) -{ - return ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR; -} + namespace { std::shared_ptr listener = std::make_shared(); +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR + || ret == SOFTBUS_IPC_ERR; +} + /** * @tc.name: SoftbusConnector_001 * @tc.desc: set SoftbusConnector to new a pointer, and the pointer nou equal nullptr @@ -212,7 +215,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_001, testing::ext::TestSize.Level0 DmSubscribeInfo dmSubscribeInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(dmSubscribeInfo); - EXPECT_TRUE(CheckReturnResult(ret)); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** * @tc.name: StartDiscovery_002 @@ -225,7 +228,7 @@ HWTEST_F(SoftbusConnectorTest, StartDiscovery_002, testing::ext::TestSize.Level0 uint16_t subscribeId = 0; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->StartDiscovery(subscribeId); - EXPECT_TRUE(CheckReturnResult(ret)); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -253,7 +256,7 @@ HWTEST_F(SoftbusConnectorTest, PublishDiscovery_001, testing::ext::TestSize.Leve DmPublishInfo dmPublishInfo; std::shared_ptr softbusConnector = std::make_shared(); int ret = softbusConnector->PublishDiscovery(dmPublishInfo); - EXPECT_TRUE(CheckReturnResult(ret)); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 3a987096e..61e28df0a 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -50,7 +50,8 @@ namespace { bool checkSoftbusRes(int32_t ret) { - return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR; + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR + || ret == SOFTBUS_IPC_ERR; } /** diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 9c17755be..4aa296bc3 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -321,11 +321,19 @@ ohos_unittest("UTTest_device_manager_service") { module_out_path = module_out_path sources = [ + "mock/app_manager_mock.cpp", + "mock/device_manager_service_impl_mock.cpp", + "mock/kv_adapter_manager_mock.cpp", + "mock/permission_manager_mock.cpp", + "mock/softbus_listener_mock.cpp", "UTTest_device_manager_service.cpp", "UTTest_device_manager_service_two.cpp", ] - deps = [ ":device_manager_test_common" ] + deps = [ + ":device_manager_test_common", + "//third_party/googletest:gmock_main", + ] external_deps = [ "access_token:libaccesstoken_sdk", @@ -931,11 +939,15 @@ ohos_unittest("UTTest_device_manager_service_impl") { sources = [ "${devicemanager_path}/commondependency/src/multiple_user_connector.cpp", + "mock/deviceprofile_connector_mock.cpp", "${servicesimpl_path}/src/device_manager_service_impl.cpp", "UTTest_device_manager_service_impl.cpp", ] - deps = [ ":device_manager_test_common" ] + deps = [ + ":device_manager_test_common", + "//third_party/googletest:gmock_main", + ] external_deps = [ "device_auth:deviceauth_sdk", diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index db40dd891..4c8c67b5f 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -25,6 +25,8 @@ #include "softbus_error_code.h" using namespace OHOS::Security::AccessToken; +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); @@ -63,10 +65,20 @@ void DeviceManagerServiceTest::TearDown() void DeviceManagerServiceTest::SetUpTestCase() { + DmPermissionManager::dmPermissionManager = permissionManagerMock_; + DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; + DmKVAdapterManager::dmKVAdapterManager = kVAdapterManagerMock_; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; + DmAppManager::dmAppManager = appManagerMock_; } void DeviceManagerServiceTest::TearDownTestCase() { + permissionManagerMock_ = nullptr; + softbusListenerMock_ = nullptr; + kVAdapterManagerMock_ = nullptr; + deviceManagerServiceImplMock_ = nullptr; + appManagerMock_ = nullptr; } namespace { @@ -166,7 +178,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSi uint16_t subscribeId = 1; DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_ERR); + EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -311,7 +323,7 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_003, testing::ext::T int32_t publishId = 1; DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_ERR); + EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -538,9 +550,10 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_007, testing::ext::TestSize.Leve std::string callerId = "ShiftLNNGear_007"; bool isRefresh = true; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_,_)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); DeviceManagerService::GetInstance().softbusListener_ = nullptr; - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); } /** @@ -679,6 +692,7 @@ HWTEST_F(DeviceManagerServiceTest, GetUdidByNetworkId_001, testing::ext::TestSiz std::string pkgName = "com.ohos.test"; std::string netWorkId = "123"; std::string udid = "123"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(SOFTBUS_IPC_ERR)); int ret = DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, netWorkId, udid); EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } @@ -744,6 +758,7 @@ HWTEST_F(DeviceManagerServiceTest, GetUuidByNetworkId_001, testing::ext::TestSiz std::string pkgName = "com.ohos.test"; std::string netWorkId = "12"; std::string uuid = "12"; + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_,_)).WillOnce(Return(SOFTBUS_IPC_ERR)); int ret = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } @@ -1578,9 +1593,10 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); } + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_,_)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); DeviceManagerService::GetInstance().softbusListener_ = nullptr; - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DeviceManagerServiceTest, GenerateEncryptedUuid_001, testing::ext::TestSize.Level0) @@ -1694,8 +1710,9 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_002, testing::ext::TestSize.Le { std::string pkgName = "pkgName"; std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_001, testing::ext::TestSize.Level0) @@ -1709,8 +1726,9 @@ HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_001, testing::ext::TestSize.Le HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_002, testing::ext::TestSize.Level0) { std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, UnloadDMServiceImplSo_001, testing::ext::TestSize.Level0) @@ -1886,7 +1904,7 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::T std::map extraParam; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); - EXPECT_EQ(ret, SOFTBUS_ERR); + EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -1952,7 +1970,7 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_004, testing::ext::TestSize.L std::map advertiseParam; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_ERR); + EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -1963,6 +1981,9 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_005, testing::ext::TestSize.L std::string key = PARAM_KEY_META_TYPE; std::string value = "125"; advertiseParam.insert(std::make_pair(key, value)); + key = PARAM_KEY_PUBLISH_ID; + value = "128"; + advertiseParam.insert(std::make_pair(key, value)); DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); EXPECT_NE(ret, DM_OK); @@ -2149,6 +2170,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_005, testing::ext::Tes HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Level0) { std::string udid = ""; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -2156,6 +2178,7 @@ HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Lev HWTEST_F(DeviceManagerServiceTest, IsSameAccount_002, testing::ext::TestSize.Level0) { std::string udid = "udidTest"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); EXPECT_NE(ret, DM_OK); } @@ -2181,7 +2204,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_001, testing::ext::TestSiz DmAccessCaller caller; DmAccessCallee callee; DeletePermission(); - int ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); EXPECT_FALSE(ret); } @@ -2191,7 +2214,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_001, testing::ext::TestSiz DmAccessCaller caller; DmAccessCallee callee; DeletePermission(); - int ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_FALSE(ret); } @@ -2448,6 +2471,190 @@ HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_003, testing::ext::Tes int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_005"; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + DmPinType pinType = DmPinType::QR_CODE; + std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_003, testing::ext::TestSize.Level0) +{ + std::string pkgName; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: ShiftLNNGear_008 + * @tc.desc:Set the callerId and pkgNamenot not to null, and isRefresh to true; Return NOT DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_008, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ShiftLNNGear_008"; + std::string callerId = "ShiftLNNGear_008"; + bool isRefresh = true; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_,_)).WillOnce(Return(ERR_DM_FAILED)); + int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string authCode; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_003, testing::ext::TestSize.Level0) +{ + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, IsSameAccount_004, testing::ext::TestSize.Level0) +{ + std::string udid = "udidTest"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_006, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string invalidNetworkId; + int32_t securityLevel = 0; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceSecurityLevel(_,_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, invalidNetworkId, securityLevel); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_005, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkIdTest5"; + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_,_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string networkId = "network_id"; + std::string uuid = "13345689"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_,_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(ret, DM_OK); +} + +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoyDeviceId_001, testing::ext::TestSize.Level0) +{ + std::string udidHash; + std::string result; + int32_t ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); + ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, GetUdidHashByAnoyDeviceId_001, testing::ext::TestSize.Level0) +{ + std::string udidHash; + std::string anoyDeviceId = "anoyDeviceId"; + int32_t ret = DeviceManagerService::GetInstance().GetUdidHashByAnoyDeviceId(anoyDeviceId, udidHash); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*kVAdapterManagerMock_, Get(_,_)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().GetUdidHashByAnoyDeviceId(anoyDeviceId, udidHash); + EXPECT_EQ(ret, ERR_DM_FAILED); +} +#endif } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index 9c38a0936..f85349221 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -16,6 +16,7 @@ #define OHOS_UTTEST_DM_SERVICE_H #include +#include #include #include @@ -26,6 +27,11 @@ #include "device_manager_service_impl.h" #include "dm_single_instance.h" #include "common_event_support.h" +#include "permission_manager_mock.h" +#include "softbus_listener_mock.h" +#include "app_manager_mock.h" +#include "kv_adapter_manager_mock.h" +#include "device_manager_service_impl_mock.h" namespace OHOS { namespace DistributedHardware { class DeviceManagerServiceTest : public testing::Test { @@ -34,6 +40,18 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + + static inline std::shared_ptr permissionManagerMock_ = + std::make_shared(); + static inline std::shared_ptr softbusListenerMock_ = + std::make_shared(); + std::make_shared(); + static inline std::shared_ptr appManagerMock_ = + std::make_shared(); + static inline std::shared_ptr kVAdapterManagerMock_ = + std::make_shared(); + static inline std::shared_ptr deviceManagerServiceImplMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 195b962a7..50709091f 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -16,6 +16,12 @@ #include "UTTest_device_manager_service_impl.h" #include "softbus_error_code.h" #include "common_event_support.h" +#include "deviceprofile_connector.h" +#include "distributed_device_profile_client.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS::DistributedDeviceProfile; namespace OHOS { namespace DistributedHardware { void DeviceManagerServiceImplTest::SetUp() @@ -33,6 +39,7 @@ void DeviceManagerServiceImplTest::TearDown() void DeviceManagerServiceImplTest::SetUpTestCase() { + DmDeviceProfileConnector::dmDeviceProfileConnector = deviceProfileConnectorMock_; } void DeviceManagerServiceImplTest::TearDownTestCase() @@ -40,6 +47,62 @@ void DeviceManagerServiceImplTest::TearDownTestCase() } namespace { +bool CheckSoftbusRes(int32_t ret) +{ + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR + || ret == SOFTBUS_IPC_ERR; +} + +void AddAccessControlProfileFirst(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 4; + int32_t deviceIdType = 1; + uint32_t bindLevel = DEVICE; + uint32_t status = 0; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId_123"; + std::string newAccountId = "accountId_456"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFirst; + profileFirst.SetAccessControlId(accesserId); + profileFirst.SetAccesserId(accesserId); + profileFirst.SetAccesseeId(accesserId); + profileFirst.SetTrustDeviceId(trustDeviceId); + profileFirst.SetBindType(bindType); + profileFirst.SetAuthenticationType(authenticationType); + profileFirst.SetDeviceIdType(deviceIdType); + profileFirst.SetStatus(status); + profileFirst.SetBindLevel(bindLevel); + profileFirst.SetAccesser(accesser); + profileFirst.SetAccessee(accessee); + accessControlProfiles.push_back(profileFirst); +} /** * @tc.name: Initialize_001 @@ -863,7 +926,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_001, testing::ext::T uint16_t subscribeId = 0; std::string filterOptions; int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -897,7 +960,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StartDeviceDiscovery_003, testing::ext::T deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -946,7 +1009,7 @@ HWTEST_F(DeviceManagerServiceImplTest, StopDeviceDiscovery_002, testing::ext::Te deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -978,7 +1041,7 @@ HWTEST_F(DeviceManagerServiceImplTest, PublishDeviceDiscovery_002, testing::ext: deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->PublishDeviceDiscovery(pkgName, publishInfo); - EXPECT_TRUE(ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -1010,7 +1073,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnPublishDeviceDiscovery_002, testing::ex deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -1060,7 +1123,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetUdidHashByNetWorkId_003, testing::ext: deviceManagerServiceImpl_ = std::make_shared(); } int32_t ret = deviceManagerServiceImpl_->GetUdidHashByNetWorkId(networkId, deviceId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR); + EXPECT_TRUE(CheckSoftbusRes(ret)); } /** @@ -1510,6 +1573,56 @@ HWTEST_F(DeviceManagerServiceImplTest, CredentialAuthStatus_101, testing::ext::T deviceManagerServiceImpl_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } + +HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_101, testing::ext::TestSize.Level0) +{ + std::string appId; + int32_t accessTokenId = 101; + int ret = deviceManagerServiceImpl_->ProcessAppUnintall(appId, accessTokenId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_102, testing::ext::TestSize.Level0) +{ + std::string appId; + int32_t accessTokenId = 102; + std::vector profiles; + AddAccessControlProfileFirst(profiles); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + int ret = deviceManagerServiceImpl_->ProcessAppUnintall(appId, accessTokenId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_103, testing::ext::TestSize.Level0) +{ + std::string appId; + int32_t accessTokenId = 1001; + std::vector profiles; + AddAccessControlProfileFirst(profiles); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + if (deviceManagerServiceImpl_->hiChainConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + int ret = deviceManagerServiceImpl_->ProcessAppUnintall(appId, accessTokenId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, StopAuthenticateDevice_101, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int ret = deviceManagerServiceImpl_->StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, StopAuthenticateDevice_102, testing::ext::TestSize.Level0) +{ + std::string pkgName = "StopAuthenticateDevice_102"; + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + int ret = deviceManagerServiceImpl_->StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.h b/test/unittest/UTTest_device_manager_service_impl.h index cfd963d9e..a2e0f8e32 100644 --- a/test/unittest/UTTest_device_manager_service_impl.h +++ b/test/unittest/UTTest_device_manager_service_impl.h @@ -23,6 +23,7 @@ #include #include "device_manager_service_impl.h" +#include "deviceprofile_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -35,6 +36,9 @@ public: std::shared_ptr listener_ = std::make_shared(); std::shared_ptr deviceManagerServiceImpl_ = std::make_shared(); + static inline std::shared_ptr deviceProfileConnectorMock_ = + std::make_shared(); + }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 95700ddb8..55c9b29a4 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -313,7 +313,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD || ret == SOFTBUS_IPC_ERR) { bRet = true; } - ASSERT_EQ(bRet, true); + ASSERT_EQ(bRet, false); } /** diff --git a/test/unittest/mock/app_manager_mock.cpp b/test/unittest/mock/app_manager_mock.cpp new file mode 100644 index 000000000..0fc612b21 --- /dev/null +++ b/test/unittest/mock/app_manager_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(AppManager); +const std::string AppManager::GetAppId() +{ + return DmAppManager::dmAppManager->GetAppId(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/app_manager_mock.h b/test/unittest/mock/app_manager_mock.h new file mode 100644 index 000000000..5bbb89f11 --- /dev/null +++ b/test/unittest/mock/app_manager_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_APP_MANAGER_MOCK_H +#define OHOS_APP_MANAGER_MOCK_H + +#include +#include + +#include "app_manager.h" + +namespace OHOS{ +namespace DistributedHardware{ +class DmAppManager { +public: + virtual ~DmAppManager() = default; +public: + virtual std::string GetAppId() = 0; +public: + static inline std::shared_ptr dmAppManager = nullptr; +}; + +class AppManagerMock : public DmAppManager { +public: + MOCK_METHOD(std::string, GetAppId, ()); +}; +} +} +#endif diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp new file mode 100644 index 000000000..87b11676e --- /dev/null +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_service_impl.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->StopAuthenticateDevice(pkgName); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h new file mode 100644 index 000000000..52cc2d584 --- /dev/null +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICE_MANAGER_SERVICE_IMPL_MOCK_H +#define OHOS_DEVICE_MANAGER_SERVICE_IMPL_MOCK_H + +#include +#include + +#include "device_manager_service_impl.h" + +namespace OHOS{ +namespace DistributedHardware{ +class DmDeviceManagerServiceImpl { +public: + virtual ~DmDeviceManagerServiceImpl() = default; +public: + virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; +public: + static inline std::shared_ptr dmDeviceManagerServiceImpl = nullptr; +}; + +class DeviceManagerServiceImplMock : public DmDeviceManagerServiceImpl { +public: + MOCK_METHOD(int32_t, StopAuthenticateDevice, (const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp new file mode 100644 index 000000000..7aa1a95da --- /dev/null +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "deviceprofile_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DeviceProfileConnector); +std::vector DeviceProfileConnector::GetAllAccessControlProfile() +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->GetAllAccessControlProfile(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h new file mode 100644 index 000000000..e7826b9bd --- /dev/null +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICEPROFILE_CONNECTOR_MOCK_H +#define OHOS_DEVICEPROFILE_CONNECTOR_MOCK_H + +#include +#include + +#include "deviceprofile_connector.h" + +namespace OHOS{ +namespace DistributedHardware{ +class DmDeviceProfileConnector { +public: + virtual ~DmDeviceProfileConnector() = default; +public: + virtual std::vector GetAllAccessControlProfile() = 0; +public: + static inline std::shared_ptr dmDeviceProfileConnector = nullptr; +}; + +class DeviceProfileConnectorMock : public DmDeviceProfileConnector { +public: + MOCK_METHOD(std::vector, GetAllAccessControlProfile, ()); +}; +} +} +#endif diff --git a/test/unittest/mock/kv_adapter_manager_mock.cpp b/test/unittest/mock/kv_adapter_manager_mock.cpp new file mode 100644 index 000000000..05de0d040 --- /dev/null +++ b/test/unittest/mock/kv_adapter_manager_mock.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "kv_adapter_manager_mock.h" +#include "app_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(KVAdapterManager); +int32_t KVAdapterManager::Get(const std::string &key, DmKVValue &value) +{ + return DmKVAdapterManager::dmKVAdapterManager->Get(key, value); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/kv_adapter_manager_mock.h b/test/unittest/mock/kv_adapter_manager_mock.h new file mode 100644 index 000000000..ba5fb564d --- /dev/null +++ b/test/unittest/mock/kv_adapter_manager_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_KV_ADAPTER_MANAGER_MOCK_H +#define OHOS_KV_ADAPTER_MANAGER_MOCK_H + +#include +#include + +#include "kv_adapter_manager.h" + +namespace OHOS{ +namespace DistributedHardware{ +class DmKVAdapterManager { +public: + virtual ~DmKVAdapterManager() = default; +public: + virtual int32_t Get(const std::string &key, DmKVValue &value) = 0; +public: + static inline std::shared_ptr dmKVAdapterManager = nullptr; +}; + +class KVAdapterManagerMock : public DmKVAdapterManager { +public: + MOCK_METHOD(int32_t, Get, (const std::string &, DmKVValue &)); +}; +} +} +#endif diff --git a/test/unittest/mock/permission_manager_mock.cpp b/test/unittest/mock/permission_manager_mock.cpp new file mode 100644 index 000000000..02c0a9608 --- /dev/null +++ b/test/unittest/mock/permission_manager_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(PermissionManager); +bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &processName) +{ + return DmPermissionManager::dmPermissionManager->CheckProcessNameValidOnPinHolder(processName); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/permission_manager_mock.h b/test/unittest/mock/permission_manager_mock.h new file mode 100644 index 000000000..68c0cb2d4 --- /dev/null +++ b/test/unittest/mock/permission_manager_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_PERMISSION_MANAGER_MOCK_H +#define OHOS_PERMISSION_MANAGER_MOCK_H + +#include +#include + +#include "permission_manager.h" + +namespace OHOS{ +namespace DistributedHardware{ +class DmPermissionManager { +public: + virtual ~DmPermissionManager() = default; +public: + virtual bool CheckProcessNameValidOnPinHolder(const std::string &processName) = 0; +public: + static inline std::shared_ptr dmPermissionManager = nullptr; +}; + +class PermissionManagerMock : public DmPermissionManager { +public: + MOCK_METHOD(bool, CheckProcessNameValidOnPinHolder, (const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/softbus_listener_mock.cpp b/test/unittest/mock/softbus_listener_mock.cpp new file mode 100644 index 000000000..d5749586b --- /dev/null +++ b/test/unittest/mock/softbus_listener_mock.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_listener_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t SoftbusListener::ShiftLNNGear(bool isWakeUp, const std::string &callerId) +{ + return DmSoftbusListener::dmSoftbusListener->ShiftLNNGear(isWakeUp, callerId); +} + +int32_t SoftbusListener::GetUdidByNetworkId(const char *networkId, std::string &udid) +{ + return DmSoftbusListener::dmSoftbusListener->GetUdidByNetworkId(networkId, udid); +} + +int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) +{ + return DmSoftbusListener::dmSoftbusListener->GetDeviceSecurityLevel(networkId, securityLevel); +} + +int32_t SoftbusListener::GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info) +{ + return DmSoftbusListener::dmSoftbusListener->GetDeviceInfo(networkId, info); +} + +int32_t SoftbusListener::GetUuidByNetworkId(const char *networkId, std::string &uuid) +{ + return DmSoftbusListener::dmSoftbusListener->GetUuidByNetworkId(networkId, uuid); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h new file mode 100644 index 000000000..27a044b21 --- /dev/null +++ b/test/unittest/mock/softbus_listener_mock.h @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_SOFTBUS_LISTENER_MOCK_H +#define OHOS_SOFTBUS_LISTENER_MOCK_H + +#include +#include + +#include "softbus_listener.h" + +namespace OHOS{ +namespace DistributedHardware{ +class DmSoftbusListener { +public: + virtual ~DmSoftbusListener() = default; +public: + virtual int32_t ShiftLNNGear(bool isWakeUp, const std::string &callerId) = 0; + virtual int32_t GetUdidByNetworkId(const char *networkId, std::string &udid) = 0; + virtual int32_t GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) = 0; + virtual int32_t GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info) = 0; + virtual int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid) = 0; +public: + static inline std::shared_ptr dmSoftbusListener = nullptr; +}; + +class SoftbusListenerMock : public DmSoftbusListener { +public: + MOCK_METHOD(int32_t, ShiftLNNGear, (bool, const std::string &)); + MOCK_METHOD(int32_t, GetUdidByNetworkId, (const char *, std::string &)); + MOCK_METHOD(int32_t, GetDeviceSecurityLevel, (const char *, int32_t &)); + MOCK_METHOD(int32_t, GetDeviceInfo, (const std::string &, DmDeviceInfo &)); + MOCK_METHOD(int32_t, GetUuidByNetworkId, (const char *, std::string &)); +}; +} +} +#endif -- Gitee From 1103299ce23510550f3f2ac2a249767964cb67be Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 5 Nov 2024 15:33:42 +0800 Subject: [PATCH 356/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../src/dependency/hichain/hichain_connector.cpp | 1 - .../hichainconnector_fuzzer/hichain_connector_fuzzer.cpp | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index d4423017b..1f2093c4d 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -15,7 +15,6 @@ #include "hichain_connector.h" -#include #include #include #include diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 550dad6e1..a2c36d54e 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -234,14 +234,14 @@ void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) hichainConnector->DeleteRedundanceGroup(userId); hichainConnector->DealRedundanceGroup(userId, authType); hichainConnector->DeleteGroupByACL(delACLInfoVec, userIdVec); - hichainConnector->IsNeedDelete(groupName, userId, delACLInfoVec); + hichainConnector->IsNeedDelete(groupName, authType, delACLInfoVec); hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); hichainConnector->onRequest(requestId, operationCode, returnData.c_str()); operationCode = GroupOperationCode::GROUP_CREATE; hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); - operationCode == GroupOperationCode::MEMBER_DELETE + operationCode == GroupOperationCode::MEMBER_DELETE; hichainConnector->onFinish(requestId, operationCode, returnData.c_str()); hichainConnector->onError(requestId, operationCode, errCode, returnData.c_str()); operationCode == GroupOperationCode::GROUP_DISBAND; -- Gitee From b3f977dec6e8846b44144adbee31a91995cc6c9e Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Tue, 5 Nov 2024 15:34:24 +0800 Subject: [PATCH 357/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0udidhash=E8=A7=A6?= =?UTF-8?q?=E5=8F=91=E7=BB=84=E7=BD=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../include/dependency/softbus/softbus_connector.h | 1 + .../src/dependency/softbus/softbus_connector.cpp | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index ff406d11d..674002a71 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -163,6 +163,7 @@ private: ALLOW_BE_DISCOVERY = 1, NOT_ALLOW_BE_DISCOVERY = 2, }; + static std::string remoteUdidHash_; static PulishStatus publishStatus; static IRefreshCallback softbusDiscoveryCallback_; static IRefreshCallback softbusDiscoveryByIdCallback_; diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 0cb6a149d..e524c67d0 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -42,6 +42,7 @@ constexpr const char* BLE_MAC = "BLE_MAC"; constexpr const char* ETH_IP = "ETH_IP"; constexpr const char* ETH_PORT = "ETH_PORT"; +std::string SoftbusConnector::remoteUdidHash_ = ""; SoftbusConnector::PulishStatus SoftbusConnector::publishStatus = SoftbusConnector::STATUS_UNKNOWN; std::map> SoftbusConnector::discoveryDeviceInfoMap_ = {}; std::map> SoftbusConnector::discoveryCallbackMap_ = {}; @@ -264,6 +265,10 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId) LOGE("addrInfo is nullptr."); return; } + if (memcpy_s(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + remoteUdidHash_.c_str(), remoteUdidHash_.length()) != 0) { + LOGE("memcpy remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); + } int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult); if (ret != DM_OK) { LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); @@ -715,6 +720,7 @@ void SoftbusConnector::HandleDeviceOffline(std::string deviceId) void SoftbusConnector::DeleteOffLineTimer(std::string &udidHash) { LOGI("SoftbusConnector::DeleteOffLineTimer"); + remoteUdidHash_ = udidHash; if (deviceStateManagerCallback_ != nullptr) { deviceStateManagerCallback_->DeleteOffLineTimer(udidHash); } -- Gitee From 80767b51cb91c32d347f27ada62aa9a181fa8230 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 5 Nov 2024 16:24:47 +0800 Subject: [PATCH 358/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../dependency/hichain/hichain_connector.cpp | 6 ++-- .../hichain_connector_fuzzer.cpp | 32 +++++++++---------- .../UTTest_dm_publish_manager.cpp | 2 +- .../UTTest_device_manager_service.cpp | 20 ++++++------ test/unittest/mock/app_manager_mock.h | 4 +-- .../mock/device_manager_service_impl_mock.h | 4 +-- .../mock/deviceprofile_connector_mock.h | 4 +-- test/unittest/mock/kv_adapter_manager_mock.h | 4 +-- test/unittest/mock/permission_manager_mock.h | 4 +-- test/unittest/mock/softbus_listener_mock.h | 4 +-- 10 files changed, 40 insertions(+), 44 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 1f2093c4d..06801f1c1 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -159,8 +159,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou { jsonObj.dump(); } - catch(nlohmann::json::type_error& e) - { + catch(nlohmann::json_abi_v3_11_2::detail::type_error& e){ LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); return ERR_DM_FAILED; } @@ -815,8 +814,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const { jsonObj.dump(); } - catch(nlohmann::json::type_error& e) - { + catch(nlohmann::json_abi_v3_11_2::detail::type_error& e){ LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); return ERR_DM_FAILED; } diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index a2c36d54e..d44180b4b 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -66,17 +66,20 @@ void AddGroupInfo(std::vector &groupList) groupList.push_back(groupInfo2); } -void AddAclInfo(std::vector> &delACLInfoVec) +void AddAclInfo(std::vector> &delACLInfoVec, std::vector &userIdVec) { int32_t key = 12; std::string value = "acl_info1"; delACLInfoVec.push_back(std::make_pair(key, value)); - key = 23; + userIdVec.push_back(key); + int32_t key1 = 23; value = "acl_info2"; - delACLInfoVec.push_back(std::make_pair(key, value)); - key = 25; + delACLInfoVec.push_back(std::make_pair(key1, value)); + userIdVec.push_back(key); + int32_t key2 = 25; value = "acl_info3"; - delACLInfoVec.push_back(std::make_pair(key, value)); + delACLInfoVec.push_back(std::make_pair(key2, value)); + userIdVec.push_back(key); } void HiChainConnectorFuzzTest(const uint8_t* data, size_t size) @@ -165,9 +168,7 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) nlohmann::json jsonOutObj; std::shared_ptr callback; std::string jsonStr(reinterpret_cast(data), size); - nlohmann::json jsonDeviceList; int32_t groupType = *(reinterpret_cast(data)); - std::string udid(reinterpret_cast(data), size); int32_t switchUserId = *(reinterpret_cast(data)); std::string reqParams(reinterpret_cast(data), size); int operationCode = GroupOperationCode::MEMBER_JOIN; @@ -176,8 +177,8 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) hichainConnector->CreateGroup(requestId, groupName); hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); hichainConnector->getRegisterInfo(queryParams, jsonStr); - hichainConnector->addMultiMembers(groupType, userId, jsonDeviceList); - hichainConnector->deleteMultiMembers(groupType, userId, jsonDeviceList); + hichainConnector->addMultiMembers(groupType, userId, jsonOutObj); + hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); hichainConnector->GetGroupInfoCommon(usersId, queryParams, pkgName.c_str(), groupList); hichainConnector->hiChainResCallback_ = nullptr; hichainConnector->GetConnectPara(deviceId, reqDeviceId); @@ -188,13 +189,13 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) } hichainConnector->CreateGroup(requestId, groupName); hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); - hichainConnector->IsGroupCreated(groupName ,groupInfo); + hichainConnector->IsGroupCreated(groupName, groupInfo); hichainConnector->GetGroupInfoExt(usersId, queryParams, groupList); hichainConnector->GetGroupInfoCommon(usersId, queryParams, pkgName.c_str(), groupList); hichainConnector->RegisterHiChainGroupCallback(callback); - hichainConnector->GetJsonInt(jsonDeviceList, "key"); - hichainConnector->deleteMultiMembers(groupType, userId, jsonDeviceList); - hichainConnector->DeleteAllGroupByUdid(udid); + hichainConnector->GetJsonInt(jsonOutObj, "key"); + hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); + hichainConnector->DeleteAllGroupByUdid(reqParams); hichainConnector->DeleteP2PGroup(switchUserId); } @@ -219,13 +220,10 @@ void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) std::vector syncGroupList; std::vector> delACLInfoVec; std::vector userIdVec; - AddAclInfo(delACLInfoVec); hichainConnector->DeleteGroupByACL(delACLInfoVec, userIdVec); - userIdVec.push_back(key); - key = 32; - userIdVec.push_back(key); std::vector groupList; AddGroupInfo(groupList); + AddAclInfo(delACLInfoVec, userIdVec); hichainConnector->DeleteGroup(groupId); hichainConnector->DeleteGroupExt(groupId); hichainConnector->DeleteGroup(authType, groupId); diff --git a/test/commonunittest/UTTest_dm_publish_manager.cpp b/test/commonunittest/UTTest_dm_publish_manager.cpp index 7f50c30d2..5043ec557 100644 --- a/test/commonunittest/UTTest_dm_publish_manager.cpp +++ b/test/commonunittest/UTTest_dm_publish_manager.cpp @@ -121,7 +121,7 @@ HWTEST_F(DmPublishManagerTest, PublishDeviceDiscovery_002, testing::ext::TestSiz /** * @tc.name: OnPublishResult_001 - * + * * @tc.desc: The OnPublishFailed function takes the wrong case and emptying pkgName * @tc.type: FUNC * @tc.require: I5N1K3 diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 4c8c67b5f..af8180c88 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -692,7 +692,7 @@ HWTEST_F(DeviceManagerServiceTest, GetUdidByNetworkId_001, testing::ext::TestSiz std::string pkgName = "com.ohos.test"; std::string netWorkId = "123"; std::string udid = "123"; - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(SOFTBUS_IPC_ERR)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_IPC_ERR)); int ret = DeviceManagerService::GetInstance().GetUdidByNetworkId(pkgName, netWorkId, udid); EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } @@ -758,7 +758,7 @@ HWTEST_F(DeviceManagerServiceTest, GetUuidByNetworkId_001, testing::ext::TestSiz std::string pkgName = "com.ohos.test"; std::string netWorkId = "12"; std::string uuid = "12"; - EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_,_)).WillOnce(Return(SOFTBUS_IPC_ERR)); + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_IPC_ERR)); int ret = DeviceManagerService::GetInstance().GetUuidByNetworkId(pkgName, netWorkId, uuid); EXPECT_EQ(ret, SOFTBUS_IPC_ERR); } @@ -1593,7 +1593,7 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_003, testing::ext if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); } - EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_,_)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_EQ(ret, ERR_DM_FAILED); @@ -2170,7 +2170,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_005, testing::ext::Tes HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Level0) { std::string udid = ""; - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -2553,7 +2553,7 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_008, testing::ext::TestSize.Leve std::string callerId = "ShiftLNNGear_008"; bool isRefresh = true; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_,_)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_, _)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_EQ(ret, ERR_DM_FAILED); @@ -2588,7 +2588,7 @@ HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_003, testing::ext::TestSize.Le HWTEST_F(DeviceManagerServiceTest, IsSameAccount_004, testing::ext::TestSize.Level0) { std::string udid = "udidTest"; - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -2599,7 +2599,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_006, testing::ext::Tes std::string invalidNetworkId; int32_t securityLevel = 0; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetDeviceSecurityLevel(_,_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetDeviceSecurityLevel(_, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, invalidNetworkId, securityLevel); DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_EQ(ret, DM_OK); @@ -2610,7 +2610,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_005, testing::ext::TestSize.Lev std::string networkId = "networkIdTest5"; DmDeviceInfo info; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_,_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().softbusListener_ = nullptr; @@ -2624,7 +2624,7 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_004, testing::ext if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); } - EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_,_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_EQ(ret, DM_OK); @@ -2650,7 +2650,7 @@ HWTEST_F(DeviceManagerServiceTest, GetUdidHashByAnoyDeviceId_001, testing::ext:: int32_t ret = DeviceManagerService::GetInstance().GetUdidHashByAnoyDeviceId(anoyDeviceId, udidHash); EXPECT_EQ(ret, DM_OK); - EXPECT_CALL(*kVAdapterManagerMock_, Get(_,_)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(ERR_DM_FAILED)); ret = DeviceManagerService::GetInstance().GetUdidHashByAnoyDeviceId(anoyDeviceId, udidHash); EXPECT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/unittest/mock/app_manager_mock.h b/test/unittest/mock/app_manager_mock.h index 5bbb89f11..e79eea4e3 100644 --- a/test/unittest/mock/app_manager_mock.h +++ b/test/unittest/mock/app_manager_mock.h @@ -20,8 +20,8 @@ #include "app_manager.h" -namespace OHOS{ -namespace DistributedHardware{ +namespace OHOS { +namespace DistributedHardware { class DmAppManager { public: virtual ~DmAppManager() = default; diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h index 52cc2d584..33da0f28d 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.h +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -20,8 +20,8 @@ #include "device_manager_service_impl.h" -namespace OHOS{ -namespace DistributedHardware{ +namespace OHOS { +namespace DistributedHardware { class DmDeviceManagerServiceImpl { public: virtual ~DmDeviceManagerServiceImpl() = default; diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index e7826b9bd..d2356d6ff 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -20,8 +20,8 @@ #include "deviceprofile_connector.h" -namespace OHOS{ -namespace DistributedHardware{ +namespace OHOS { +namespace DistributedHardware { class DmDeviceProfileConnector { public: virtual ~DmDeviceProfileConnector() = default; diff --git a/test/unittest/mock/kv_adapter_manager_mock.h b/test/unittest/mock/kv_adapter_manager_mock.h index ba5fb564d..f88b89b1f 100644 --- a/test/unittest/mock/kv_adapter_manager_mock.h +++ b/test/unittest/mock/kv_adapter_manager_mock.h @@ -20,8 +20,8 @@ #include "kv_adapter_manager.h" -namespace OHOS{ -namespace DistributedHardware{ +namespace OHOS { +namespace DistributedHardware { class DmKVAdapterManager { public: virtual ~DmKVAdapterManager() = default; diff --git a/test/unittest/mock/permission_manager_mock.h b/test/unittest/mock/permission_manager_mock.h index 68c0cb2d4..14d4e96b2 100644 --- a/test/unittest/mock/permission_manager_mock.h +++ b/test/unittest/mock/permission_manager_mock.h @@ -20,8 +20,8 @@ #include "permission_manager.h" -namespace OHOS{ -namespace DistributedHardware{ +namespace OHOS { +namespace DistributedHardware { class DmPermissionManager { public: virtual ~DmPermissionManager() = default; diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h index 27a044b21..d99de2602 100644 --- a/test/unittest/mock/softbus_listener_mock.h +++ b/test/unittest/mock/softbus_listener_mock.h @@ -20,8 +20,8 @@ #include "softbus_listener.h" -namespace OHOS{ -namespace DistributedHardware{ +namespace OHOS { +namespace DistributedHardware { class DmSoftbusListener { public: virtual ~DmSoftbusListener() = default; -- Gitee From f6d6e151b11193a1e1c32c422a56e74d228dd5ce Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 5 Nov 2024 16:29:31 +0800 Subject: [PATCH 359/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 4aa296bc3..429ebfeaf 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -944,7 +944,7 @@ ohos_unittest("UTTest_device_manager_service_impl") { "UTTest_device_manager_service_impl.cpp", ] - deps = [ + deps = [ ":device_manager_test_common", "//third_party/googletest:gmock_main", ] -- Gitee From e0e49b702e861d5fe91bcf233e2d0f4be1a99fb5 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 5 Nov 2024 17:15:17 +0800 Subject: [PATCH 360/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../src/dependency/hichain/hichain_connector.cpp | 12 ++++-------- .../hichain_connector_fuzzer.cpp | 1 - test/softbusunittest/UTTest_softbus_connector.cpp | 2 -- test/unittest/BUILD.gn | 10 +++++----- test/unittest/UTTest_device_manager_service.cpp | 4 ++-- 5 files changed, 11 insertions(+), 18 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 06801f1c1..d950748f2 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -155,15 +155,13 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou return ERR_DM_FAILED; } - try - { + try{ jsonObj.dump(); } - catch(nlohmann::json_abi_v3_11_2::detail::type_error& e){ + catch(nlohmann::json_abi_v3_11_2::detail::exception& e) { LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); struct RadarInfo info = { .funcName = "CreateGroup", @@ -810,15 +808,13 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const return ERR_DM_FAILED; } - try - { + try{ jsonObj.dump(); } - catch(nlohmann::json_abi_v3_11_2::detail::type_error& e){ + catch(nlohmann::json_abi_v3_11_2::detail::exception& e) { LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index d44180b4b..1c7fa3d37 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -152,7 +152,6 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) } std::shared_ptr hichainConnector = std::make_shared(); hichainConnector->RegisterHiChainCallback(std::make_shared()); - int64_t requestId = *(reinterpret_cast(data)); std::string groupName(reinterpret_cast(data), size); GroupInfo groupInfo; diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index cc8c4fd78..397c277c4 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -100,8 +100,6 @@ void SoftbusConnectorTest::TearDownTestCase() { } - - namespace { std::shared_ptr listener = std::make_shared(); diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 429ebfeaf..64571d1ae 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -321,19 +321,19 @@ ohos_unittest("UTTest_device_manager_service") { module_out_path = module_out_path sources = [ + "UTTest_device_manager_service.cpp", + "UTTest_device_manager_service_two.cpp", "mock/app_manager_mock.cpp", "mock/device_manager_service_impl_mock.cpp", "mock/kv_adapter_manager_mock.cpp", "mock/permission_manager_mock.cpp", "mock/softbus_listener_mock.cpp", - "UTTest_device_manager_service.cpp", - "UTTest_device_manager_service_two.cpp", ] deps = [ ":device_manager_test_common", "//third_party/googletest:gmock_main", - ] + ] external_deps = [ "access_token:libaccesstoken_sdk", @@ -939,15 +939,15 @@ ohos_unittest("UTTest_device_manager_service_impl") { sources = [ "${devicemanager_path}/commondependency/src/multiple_user_connector.cpp", - "mock/deviceprofile_connector_mock.cpp", "${servicesimpl_path}/src/device_manager_service_impl.cpp", "UTTest_device_manager_service_impl.cpp", + "mock/deviceprofile_connector_mock.cpp", ] deps = [ ":device_manager_test_common", "//third_party/googletest:gmock_main", - ] + ] external_deps = [ "device_auth:deviceauth_sdk", diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index af8180c88..63adb8700 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -550,7 +550,7 @@ HWTEST_F(DeviceManagerServiceTest, ShiftLNNGear_007, testing::ext::TestSize.Leve std::string callerId = "ShiftLNNGear_007"; bool isRefresh = true; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_,_)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*softbusListenerMock_, ShiftLNNGear(_, _)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().ShiftLNNGear(pkgName, callerId, isRefresh, false); DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_EQ(ret, ERR_DM_FAILED); @@ -2178,7 +2178,7 @@ HWTEST_F(DeviceManagerServiceTest, IsSameAccount_001, testing::ext::TestSize.Lev HWTEST_F(DeviceManagerServiceTest, IsSameAccount_002, testing::ext::TestSize.Level0) { std::string udid = "udidTest"; - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_,_)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); EXPECT_NE(ret, DM_OK); } -- Gitee From f1e98bc6ebb82232ea3244f7973744a08fec98e4 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 5 Nov 2024 17:25:29 +0800 Subject: [PATCH 361/520] =?UTF-8?q?=E5=8F=8C=E7=AB=AF=E7=BE=A4=E7=BB=84?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../src/authentication/dm_auth_manager.cpp | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index dc3857698..3b6502be6 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2289,7 +2289,14 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) int32_t DmAuthManager::CheckTrustState() { - if (authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + bool isSameGroup = false; + if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT && + hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, + authRequestContext_->localDeviceId)) { + isSameGroup = true; + } + if (isSameGroup && authResponseContext_->isOnline && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + authResponseContext_->isFinish = true; SetReasonAndFinish(DM_OK, AuthState::AUTH_REQUEST_FINISH); return ALREADY_BIND; } @@ -2302,18 +2309,15 @@ int32_t DmAuthManager::CheckTrustState() return ALREADY_BIND; } } - if (authResponseContext_->reply == ERR_DM_AUTH_PEER_REJECT) { - if (hiChainConnector_->IsDevicesInP2PGroup(authResponseContext_->localDeviceId, - authRequestContext_->localDeviceId)) { - if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName, - authResponseContext_->localDeviceId)) { - CompatiblePutAcl(); - } - softbusConnector_->JoinLnn(authResponseContext_->deviceId); - authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; - authRequestState_->TransitionTo(std::make_shared()); - return ALREADY_BIND; + if (isSameGroup) { + if (!DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(authResponseContext_->hostPkgName, + authResponseContext_->localDeviceId)) { + CompatiblePutAcl(); } + softbusConnector_->JoinLnn(authResponseContext_->deviceId); + authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; + authRequestState_->TransitionTo(std::make_shared()); + return ALREADY_BIND; } if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && -- Gitee From 3a285fee361b69dd571d056e752c076525613fba Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 5 Nov 2024 17:51:30 +0800 Subject: [PATCH 362/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../src/dependency/hichain/hichain_connector.cpp | 10 +--------- .../hichain_connector_fuzzer.cpp | 4 ++-- test/unittest/UTTest_device_manager_service_impl.cpp | 1 + test/unittest/UTTest_device_manager_service_impl.h | 1 - 4 files changed, 4 insertions(+), 12 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index d950748f2..b6be09b7e 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -155,7 +155,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou return ERR_DM_FAILED; } - try{ + try { jsonObj.dump(); } catch(nlohmann::json_abi_v3_11_2::detail::exception& e) { @@ -807,14 +807,6 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - - try{ - jsonObj.dump(); - } - catch(nlohmann::json_abi_v3_11_2::detail::exception& e) { - LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); - return ERR_DM_FAILED; - } int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 1c7fa3d37..6b292b236 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -153,7 +153,7 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) std::shared_ptr hichainConnector = std::make_shared(); hichainConnector->RegisterHiChainCallback(std::make_shared()); int64_t requestId = *(reinterpret_cast(data)); - std::string groupName(reinterpret_cast(data), size); + std::string groupName = "groupName"; GroupInfo groupInfo; std::string userId(reinterpret_cast(data), size); int32_t usersId = *(reinterpret_cast(data)); @@ -187,7 +187,7 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) hichainConnector->deviceGroupManager_ = GetGmInstance(); } hichainConnector->CreateGroup(requestId, groupName); - hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); + hichainConnector->CreateGroup(requestId, groupName, userId, jsonOutObj); hichainConnector->IsGroupCreated(groupName, groupInfo); hichainConnector->GetGroupInfoExt(usersId, queryParams, groupList); hichainConnector->GetGroupInfoCommon(usersId, queryParams, pkgName.c_str(), groupList); diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 50709091f..86a1d7efe 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -44,6 +44,7 @@ void DeviceManagerServiceImplTest::SetUpTestCase() void DeviceManagerServiceImplTest::TearDownTestCase() { + deviceProfileConnectorMock_ = nullptr; } namespace { diff --git a/test/unittest/UTTest_device_manager_service_impl.h b/test/unittest/UTTest_device_manager_service_impl.h index a2e0f8e32..087ce7f61 100644 --- a/test/unittest/UTTest_device_manager_service_impl.h +++ b/test/unittest/UTTest_device_manager_service_impl.h @@ -38,7 +38,6 @@ public: std::shared_ptr deviceManagerServiceImpl_ = std::make_shared(); static inline std::shared_ptr deviceProfileConnectorMock_ = std::make_shared(); - }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 4ef1536a34ba54eb201aedb4d5233688943ecf7c Mon Sep 17 00:00:00 2001 From: q30043944 Date: Fri, 1 Nov 2024 15:55:20 +0800 Subject: [PATCH 363/520] =?UTF-8?q?=E7=BE=A4=E7=BB=84=E5=88=87=E6=8D=A2acl?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../include/authentication/dm_auth_manager.h | 1 + .../src/authentication/dm_auth_manager.cpp | 58 ++++++++++++++----- 2 files changed, 43 insertions(+), 16 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index bbea5de22..85982bc12 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -512,6 +512,7 @@ private: int32_t DeleteAcl(const std::string &pkgName, const std::string &localUdid, const std::string &remoteUdid, int32_t bindLevel); void ProcessAuthRequestExt(const int32_t &sessionId); + bool IsAuthFinish(); void ProcessAuthRequest(const int32_t &sessionId); int32_t ConfirmProcess(const int32_t &action); int32_t ConfirmProcessExt(const int32_t &action); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 3e4f8aa35..0848b84f0 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -932,24 +932,57 @@ void DmAuthManager::GetAuthRequestContext() void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) { LOGI("ProcessAuthRequestExt start."); + if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !authResponseContext_->importAuthCode.empty() && !importAuthCode_.empty()) { + if (authResponseContext_->importAuthCode != Crypto::Sha256(importAuthCode_)) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } + } + GetAuthRequestContext(); std::vector bindType = DeviceProfileConnector::GetInstance().SyncAclByBindType(authResponseContext_->hostPkgName, authResponseContext_->bindType, authResponseContext_->localDeviceId, authResponseContext_->deviceId); authResponseContext_->authed = !bindType.empty(); + if (authResponseContext_->isOnline && authResponseContext_->authed && + authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + (authResponseContext_->importAuthCode.empty() || importAuthCode_.empty())) { + SetReasonAndFinish(ERR_DM_AUTH_CODE_INCORRECT, AuthState::AUTH_REQUEST_FINISH); + return; + } authResponseContext_->bindType = bindType; + if (IsAuthFinish()) { + return; + } + + std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); + for (auto msg : messageList) { + softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + } + listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, + authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); + listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); + timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); +} + +bool DmAuthManager::IsAuthFinish() +{ if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) { listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); authRequestState_->TransitionTo(std::make_shared()); - return; + return true; } if (authResponseContext_->isOnline && authResponseContext_->authed) { authRequestContext_->reason = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); - return; + return true; } if ((authResponseContext_->isIdenticalAccount && !authResponseContext_->authed) || @@ -958,27 +991,16 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) authRequestContext_->reason = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestState_->TransitionTo(std::make_shared()); - return; + return true; } if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE || (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && authResponseContext_->isAuthCodeReady == false)) { authRequestState_->TransitionTo(std::make_shared()); - return; - } - - std::vector messageList = authMessageProcessor_->CreateAuthRequestMessage(); - for (auto msg : messageList) { - softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); + return true; } - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); - listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); - timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), - GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + return false; } int32_t DmAuthManager::ConfirmProcess(const int32_t &action) @@ -2106,6 +2128,10 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(authResponseContext_->hostPkgName, authResponseContext_->localDeviceId, authResponseContext_->deviceId); authResponseContext_->authed = !authResponseContext_->bindType.empty(); + if (authResponseContext_->authed && authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE && + !importAuthCode_.empty()) { + authResponseContext_->importAuthCode = Crypto::Sha256(importAuthCode_); + } authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); authResponseContext_->haveCredential = hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, authResponseContext_->localUserId); -- Gitee From d4460a5aaaf17b49fa9775646c41d963f0d41308 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 5 Nov 2024 19:35:42 +0800 Subject: [PATCH 364/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../src/dependency/hichain/hichain_connector.cpp | 8 -------- .../hichainconnector_fuzzer/hichain_connector_fuzzer.cpp | 9 ++++----- test/unittest/UTTest_device_manager_service.h | 1 - test/unittest/mock/device_manager_service_impl_mock.cpp | 2 +- test/unittest/mock/permission_manager_mock.cpp | 5 +++++ test/unittest/mock/permission_manager_mock.h | 2 ++ 6 files changed, 12 insertions(+), 15 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index b6be09b7e..567f6d344 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -154,14 +154,6 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - - try { - jsonObj.dump(); - } - catch(nlohmann::json_abi_v3_11_2::detail::exception& e) { - LOGE("HiChainConnector::CreateGroup json throw an error:%s, try to fix", e.what()); - return ERR_DM_FAILED; - } int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); struct RadarInfo info = { .funcName = "CreateGroup", diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 6b292b236..899dcd5b0 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -156,7 +156,6 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) std::string groupName = "groupName"; GroupInfo groupInfo; std::string userId(reinterpret_cast(data), size); - int32_t usersId = *(reinterpret_cast(data)); int32_t authType = *(reinterpret_cast(data)); std::vector groupList; std::string queryParams(reinterpret_cast(data), size); @@ -178,7 +177,7 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) hichainConnector->getRegisterInfo(queryParams, jsonStr); hichainConnector->addMultiMembers(groupType, userId, jsonOutObj); hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); - hichainConnector->GetGroupInfoCommon(usersId, queryParams, pkgName.c_str(), groupList); + hichainConnector->GetGroupInfoCommon(authType, queryParams, pkgName.c_str(), groupList); hichainConnector->hiChainResCallback_ = nullptr; hichainConnector->GetConnectPara(deviceId, reqDeviceId); hichainConnector->onRequest(requestId, operationCode, reqParams.c_str()); @@ -187,10 +186,10 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) hichainConnector->deviceGroupManager_ = GetGmInstance(); } hichainConnector->CreateGroup(requestId, groupName); - hichainConnector->CreateGroup(requestId, groupName, userId, jsonOutObj); + hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); hichainConnector->IsGroupCreated(groupName, groupInfo); - hichainConnector->GetGroupInfoExt(usersId, queryParams, groupList); - hichainConnector->GetGroupInfoCommon(usersId, queryParams, pkgName.c_str(), groupList); + hichainConnector->GetGroupInfoExt(authType, queryParams, groupList); + hichainConnector->GetGroupInfoCommon(authType, queryParams, pkgName.c_str(), groupList); hichainConnector->RegisterHiChainGroupCallback(callback); hichainConnector->GetJsonInt(jsonOutObj, "key"); hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index f85349221..a7c550863 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -45,7 +45,6 @@ public: std::make_shared(); static inline std::shared_ptr softbusListenerMock_ = std::make_shared(); - std::make_shared(); static inline std::shared_ptr appManagerMock_ = std::make_shared(); static inline std::shared_ptr kVAdapterManagerMock_ = diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp index 87b11676e..58f43f8a3 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.cpp +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "device_manager_service_impl.h" +#include "device_manager_service_impl_mock.h" #include "gtest/gtest.h" diff --git a/test/unittest/mock/permission_manager_mock.cpp b/test/unittest/mock/permission_manager_mock.cpp index 02c0a9608..384707cbb 100644 --- a/test/unittest/mock/permission_manager_mock.cpp +++ b/test/unittest/mock/permission_manager_mock.cpp @@ -24,5 +24,10 @@ bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &proc { return DmPermissionManager::dmPermissionManager->CheckProcessNameValidOnPinHolder(processName); } + +bool PermissionManager::CheckProcessNameValidOnAuthCode(const std::string &processName) +{ + return DmPermissionManager::dmPermissionManager->CheckProcessNameValidOnAuthCode(processName); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/permission_manager_mock.h b/test/unittest/mock/permission_manager_mock.h index 14d4e96b2..ec7fde7f8 100644 --- a/test/unittest/mock/permission_manager_mock.h +++ b/test/unittest/mock/permission_manager_mock.h @@ -27,6 +27,7 @@ public: virtual ~DmPermissionManager() = default; public: virtual bool CheckProcessNameValidOnPinHolder(const std::string &processName) = 0; + virtual bool CheckProcessNameValidOnAuthCode(const std::string &processName) = 0; public: static inline std::shared_ptr dmPermissionManager = nullptr; }; @@ -34,6 +35,7 @@ public: class PermissionManagerMock : public DmPermissionManager { public: MOCK_METHOD(bool, CheckProcessNameValidOnPinHolder, (const std::string &)); + MOCK_METHOD(bool, CheckProcessNameValidOnAuthCode, (const std::string &)); }; } } -- Gitee From 8056ea7a7f6eea9281a1f5f558ac4849acdb9f04 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 6 Nov 2024 10:37:40 +0800 Subject: [PATCH 365/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichain_connector_fuzzer.cpp | 32 +++++++++++++++---- .../UTTest_device_manager_service.cpp | 11 +++---- .../UTTest_device_manager_service_two.cpp | 10 ++++-- 3 files changed, 38 insertions(+), 15 deletions(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 899dcd5b0..103ce234d 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -172,8 +172,6 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) int operationCode = GroupOperationCode::MEMBER_JOIN; hichainConnector->deviceGroupManager_ = nullptr; hichainConnector->AddMember(deviceId, queryParams); - hichainConnector->CreateGroup(requestId, groupName); - hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); hichainConnector->getRegisterInfo(queryParams, jsonStr); hichainConnector->addMultiMembers(groupType, userId, jsonOutObj); hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); @@ -185,8 +183,6 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) if (hichainConnector->deviceGroupManager_ == nullptr) { hichainConnector->deviceGroupManager_ = GetGmInstance(); } - hichainConnector->CreateGroup(requestId, groupName); - hichainConnector->CreateGroup(requestId, authType, userId, jsonOutObj); hichainConnector->IsGroupCreated(groupName, groupInfo); hichainConnector->GetGroupInfoExt(authType, queryParams, groupList); hichainConnector->GetGroupInfoCommon(authType, queryParams, pkgName.c_str(), groupList); @@ -208,8 +204,8 @@ void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) int64_t requestId = *(reinterpret_cast(data)); std::string groupName(reinterpret_cast(data), size); - std::string groupId(reinterpret_cast(data), size); - std::string deviceId(reinterpret_cast(data), size); + std::string groupId = "groupId_forth"; + std::string deviceId = "deviceId_forth"; std::string returnData(reinterpret_cast(data), size); std::string userId(reinterpret_cast(data), size); int32_t authType = *(reinterpret_cast(data)); @@ -249,6 +245,29 @@ void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) hichainConnector->GetSyncGroupList(groupList, syncGroupList); hichainConnector->GetGroupId(userId, authType, userId); } + +void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + + int64_t requestId = *(reinterpret_cast(data)); + std::string groupName = "groupName_fifth"; + int32_t authType = *(reinterpret_cast(data)); + nlohmann::json jsonDeviceList; + hichainConnector->deviceGroupManager_ = nullptr; + hichainConnector->CreateGroup(requestId, groupName); + hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); + if (hichainConnector->deviceGroupManager_ == nullptr) { + hichainConnector->deviceGroupManager_ = GetGmInstance(); + } + hichainConnector->CreateGroup(requestId, groupName); + hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); +} } } @@ -260,5 +279,6 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) OHOS::DistributedHardware::HiChainConnectorSecondFuzzTest(data, size); OHOS::DistributedHardware::HiChainConnectorThirdFuzzTest(data, size); OHOS::DistributedHardware::HiChainConnectorForthFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorFifthFuzzTest(data, size); return 0; } \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 63adb8700..feb162aec 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2563,7 +2563,7 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_003, testing::ext::TestSize.Le { std::string pkgName = "pkgName"; std::string authCode; - EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -2572,17 +2572,16 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_004, testing::ext::TestSize.Le { std::string pkgName = "pkgName"; std::string authCode = "authCode"; - EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_003, testing::ext::TestSize.Level0) { std::string authCode = "authCode"; - EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, IsSameAccount_004, testing::ext::TestSize.Level0) @@ -2596,7 +2595,7 @@ HWTEST_F(DeviceManagerServiceTest, IsSameAccount_004, testing::ext::TestSize.Lev HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_006, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test"; - std::string invalidNetworkId; + std::string invalidNetworkId = "networkId"; int32_t securityLevel = 0; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); EXPECT_CALL(*softbusListenerMock_, GetDeviceSecurityLevel(_, _)).WillOnce(Return(DM_OK)); diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 55c9b29a4..c65161847 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -177,6 +177,7 @@ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize. HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext::TestSize.Level0) { std::string pkgName = "CollaborationFwk"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -191,6 +192,7 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = NUMBER_PIN_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -205,8 +207,10 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceSecurityLevel_201, testing::ext::Tes std::string networkId = "123"; int32_t securityLevel; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceSecurityLevel(_, _)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().GetDeviceSecurityLevel(pkgName, networkId, securityLevel); EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; } /** @@ -218,7 +222,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz DmAccessCaller caller; DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } /** @@ -243,7 +247,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz DmAccessCaller caller; DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } /** @@ -313,7 +317,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD || ret == SOFTBUS_IPC_ERR) { bRet = true; } - ASSERT_EQ(bRet, false); + ASSERT_EQ(bRet, true); } /** -- Gitee From 2cf407d2362e1020f64106413889d139d3002c81 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 6 Nov 2024 10:40:20 +0800 Subject: [PATCH 366/520] =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E7=BC=96=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- bundle.json | 1 - 1 file changed, 1 deletion(-) diff --git a/bundle.json b/bundle.json index b9b529e90..dd2be1b8d 100644 --- a/bundle.json +++ b/bundle.json @@ -29,7 +29,6 @@ "ability_base", "ability_runtime", "access_token", - "benchmark", "bounds_checking_function", "bluetooth", "bundle_framework", -- Gitee From f04d1417cefb62ad11c3dc0e2d5c16d3c89d040a Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 6 Nov 2024 10:45:27 +0800 Subject: [PATCH 367/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index feb162aec..7ced28282 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2574,14 +2574,15 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_004, testing::ext::TestSize.Le std::string authCode = "authCode"; EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_003, testing::ext::TestSize.Level0) { std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(DeviceManagerServiceTest, IsSameAccount_004, testing::ext::TestSize.Level0) -- Gitee From 8cf08f119ba96dbc4ef072059e8907a8c9bd52e1 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 6 Nov 2024 11:47:45 +0800 Subject: [PATCH 368/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service_two.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index c65161847..0df6a1552 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -25,6 +25,8 @@ #include "softbus_error_code.h" using namespace OHOS::Security::AccessToken; +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { namespace { -- Gitee From 5dab5af37e99a48b44e4c5957a748ca6f4e4a93b Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 6 Nov 2024 15:09:40 +0800 Subject: [PATCH 369/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichainconnector_fuzzer/hichain_connector_fuzzer.cpp | 2 +- test/unittest/UTTest_device_manager_service_two.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 103ce234d..d36efe6ea 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -207,7 +207,7 @@ void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) std::string groupId = "groupId_forth"; std::string deviceId = "deviceId_forth"; std::string returnData(reinterpret_cast(data), size); - std::string userId(reinterpret_cast(data), size); + std::string userId = "userId_forth"; int32_t authType = *(reinterpret_cast(data)); int operationCode = GroupOperationCode::MEMBER_JOIN; int errCode = 102; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 0df6a1552..d181708db 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -224,7 +224,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz DmAccessCaller caller; DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); - EXPECT_EQ(ret, false); + EXPECT_EQ(ret, true); } /** @@ -249,7 +249,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz DmAccessCaller caller; DmAccessCallee callee; bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); - EXPECT_EQ(ret, false); + EXPECT_EQ(ret, true); } /** -- Gitee From a656f2eba898977246a64a8c23094116ca81758f Mon Sep 17 00:00:00 2001 From: wzhhhh Date: Wed, 6 Nov 2024 10:45:15 +0000 Subject: [PATCH 370/520] update test/unittest/mock/mock_distributed_device_profile_client.cpp. Signed-off-by: wzhhhh --- test/unittest/mock/mock_distributed_device_profile_client.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index b640d78bb..f4840766b 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -676,13 +676,13 @@ int32_t DistributedDeviceProfileClient::GetCharacteristicProfile(const std::stri } int32_t DistributedDeviceProfileClient::DeleteServiceProfile(const std::string& deviceId, - const std::string& serviceName) + const std::string& serviceName, bool isMultiUser, int32_t userId) { return 0; } int32_t DistributedDeviceProfileClient::DeleteCharacteristicProfile(const std::string& deviceId, - const std::string& serviceName, const std::string& characteristicKey) + const std::string& serviceName, const std::string& characteristicKey, bool isMultiUser, int32_t userId) { return 0; } -- Gitee From a7bb7a8634aa72e1a42959d35e303fe8c609972c Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 7 Nov 2024 08:51:18 +0800 Subject: [PATCH 371/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichainconnector_fuzzer/hichain_connector_fuzzer.cpp | 5 +++++ test/commonunittest/UTTest_dm_discovery_manager.cpp | 4 ++-- test/softbusunittest/UTTest_mine_softbus_listener.cpp | 4 ++-- test/softbusunittest/UTTest_softbus_connector.cpp | 4 ++-- test/softbusunittest/UTTest_softbus_listener.cpp | 4 ++-- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++-- 6 files changed, 15 insertions(+), 10 deletions(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index d36efe6ea..7f8975519 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -258,6 +258,8 @@ void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) int64_t requestId = *(reinterpret_cast(data)); std::string groupName = "groupName_fifth"; int32_t authType = *(reinterpret_cast(data)); + std::string params = "params"; + int32_t osAccountUserId = *(reinterpret_cast(data)); nlohmann::json jsonDeviceList; hichainConnector->deviceGroupManager_ = nullptr; hichainConnector->CreateGroup(requestId, groupName); @@ -267,6 +269,9 @@ void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) } hichainConnector->CreateGroup(requestId, groupName); hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); + hichainConnector->ParseRemoteCredential(authType, groupName, jsonDeviceList, params, osAccountUserId); + hichainConnector->ParseRemoteCredential(authType, "", jsonDeviceList, params, osAccountUserId); + } } } diff --git a/test/commonunittest/UTTest_dm_discovery_manager.cpp b/test/commonunittest/UTTest_dm_discovery_manager.cpp index 73299f1a8..0026854a0 100644 --- a/test/commonunittest/UTTest_dm_discovery_manager.cpp +++ b/test/commonunittest/UTTest_dm_discovery_manager.cpp @@ -55,8 +55,8 @@ std::shared_ptr discoveryMgr_ = bool CheckSoftbusRes(int32_t ret) { - return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR - || ret == SOFTBUS_IPC_ERR; + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || + ret == SOFTBUS_IPC_ERR; } /** diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index ee2d19c81..9799617a8 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -48,8 +48,8 @@ namespace { bool CheckSoftbusRes(int32_t ret) { - return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR - || ret == SOFTBUS_IPC_ERR; + return ret == SOFTBUS_INVALID_PARAM || ret == SOFTBUS_NETWORK_NOT_INIT || ret == SOFTBUS_NETWORK_LOOPER_ERR || + ret == SOFTBUS_IPC_ERR; } HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_001, testing::ext::TestSize.Level0) diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 397c277c4..ebd24ea1a 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -105,8 +105,8 @@ std::shared_ptr listener = std::make_shared& accessControlProfiles) -- Gitee From 4ee2c1024c1ab9535e9541aefd27c85a4bde7ca3 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 7 Nov 2024 09:01:59 +0800 Subject: [PATCH 372/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=92=8Cut=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichainconnector_fuzzer/hichain_connector_fuzzer.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 7f8975519..4158807f0 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -271,7 +271,6 @@ void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); hichainConnector->ParseRemoteCredential(authType, groupName, jsonDeviceList, params, osAccountUserId); hichainConnector->ParseRemoteCredential(authType, "", jsonDeviceList, params, osAccountUserId); - } } } -- Gitee From 64084e8556ada94fb1c7bd3d672ec8ff31a63671 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Thu, 7 Nov 2024 14:13:00 +0800 Subject: [PATCH 373/520] =?UTF-8?q?=E8=AE=BE=E7=BD=AEdeviceName=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../src/devicenamemgr/account_boot_listener.cpp | 2 +- .../src/devicenamemgr/local_device_name_mgr.cpp | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 0d2b77a7e..0795dbf2a 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -101,8 +101,8 @@ void AccountBootListener::DoAccountBootProc() } localDeviceMgr_->RegisterDeviceNameChangeCb(); localDeviceMgr_->RegisterDisplayNameChangeCb(); - localDeviceMgr_->QueryLocalDeviceName(); localDeviceMgr_->QueryLocalDisplayName(); + localDeviceMgr_->QueryLocalDeviceName(); } void AccountBootListener::SetSaTriggerFlag(SaTriggerFlag triggerFlag) diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp index a3213d641..f09203c6a 100644 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -192,11 +192,25 @@ int32_t LocalDeviceNameMgr::QueryLocalDeviceName() localDeviceName_ = localDeviceName; dataShareHelper->Release(); LOGI("get user defined deviceName=%{public}s", localDeviceName.c_str()); + if (localDisplayName_.empty()) { + LOGI("displayName is null, set user define device name to softbus."); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); + } return DM_OK; } ret = GetDefaultDeviceName(dataShareHelper, localDeviceName); - LOGI("get default deviceName=%{public}s", localDeviceName.c_str()); + if (ret != DM_OK || localDeviceName.empty()) { + LOGE("get default deviceName failed"); + return ERR_DM_FAILED; + } + std::lock_guard lock(devNameMtx_); + localDeviceName_ = localDeviceName; dataShareHelper->Release(); + LOGI("get default deviceName=%{public}s", localDeviceName.c_str()); + if (localDisplayName_.empty()) { + LOGI("displayName is null, set default deviceName to softbus."); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); + } return DM_OK; } -- Gitee From 558f78c01aac90282be874e3e07e23d20b64d3cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 8 Nov 2024 20:15:50 +0800 Subject: [PATCH 374/520] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=BB=84=E8=93=9D?= =?UTF-8?q?=E5=8C=BA=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- device_manager.gni | 7 ++++++ services/service/BUILD.gn | 8 ++++++ .../service/include/device_manager_service.h | 2 +- .../devicenamemgr/account_boot_listener.h | 1 + .../devicenamemgr/local_device_name_mgr.h | 1 + .../include/softbus/softbus_listener.h | 2 +- .../service/src/device_manager_service.cpp | 8 ++---- .../devicenamemgr/account_boot_listener.cpp | 5 ++++ .../devicenamemgr/local_device_name_mgr.cpp | 17 ++++++------- .../src/ipc/standard/ipc_server_stub.cpp | 8 +++--- .../service/src/softbus/softbus_listener.cpp | 25 ++++++++++++++++--- 11 files changed, 60 insertions(+), 24 deletions(-) diff --git a/device_manager.gni b/device_manager.gni index d4c31fbb5..57eb3a487 100644 --- a/device_manager.gni +++ b/device_manager.gni @@ -77,4 +77,11 @@ declare_args() { } else { support_memmgr = false } + + if (defined(global_parts_info) && + defined(global_parts_info.distributedhardware_distributed_hardware_adapter)) { + device_manager_common = false + } else { + device_manager_common = true + } } diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index ee1da5e34..b3e68af5c 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -107,6 +107,10 @@ if (defined(ohos_lite)) { "-Wshadow", ] + if (dm_common) { + cflags += [ "-DDEVICE_MANAGER_COMMON_SWITCH" ] + } + cflags_cc = cflags } } @@ -256,6 +260,10 @@ if (defined(ohos_lite)) { external_deps += [ "memmgr:memmgrclient" ] } + if (device_manager_common) { + defines += [ "DDEVICE_MANAGER_COMMON_SWITCH" ] + } + public_external_deps = [ "json:nlohmann_json_static" ] subsystem_name = "distributedhardware" diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index b735cfd55..a8bd81208 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -202,7 +202,7 @@ public: void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); - int32_t SetLocalDeviceName(const std::string &localDeviceName); + int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/devicenamemgr/account_boot_listener.h b/services/service/include/devicenamemgr/account_boot_listener.h index a2df48e8e..c964054b3 100644 --- a/services/service/include/devicenamemgr/account_boot_listener.h +++ b/services/service/include/devicenamemgr/account_boot_listener.h @@ -36,6 +36,7 @@ public: void InitDataShareEvent(); void DataShareCallback(); std::string GetLocalDisplayName() const; + std::string GetLocalDeviceName() const; private: /** diff --git a/services/service/include/devicenamemgr/local_device_name_mgr.h b/services/service/include/devicenamemgr/local_device_name_mgr.h index 2c03f786f..56fc6b89d 100644 --- a/services/service/include/devicenamemgr/local_device_name_mgr.h +++ b/services/service/include/devicenamemgr/local_device_name_mgr.h @@ -33,6 +33,7 @@ public: int32_t QueryLocalDisplayName(); void RegisterDisplayNameChangeCb(); std::string GetLocalDisplayName() const; + std::string GetLocalDeviceName() const; private: std::shared_ptr GetDataShareHelper(); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 52ee84058..9220f2e13 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -102,7 +102,7 @@ public: void SendAclChangedBroadcast(const std::string &msg); int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); static int32_t GetNetworkIdByUdid(const std::string &udid, std::string &networkId); - int32_t SetLocalDeviceName(const std::string &localDeviceName); + int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 1a61335ef..46f015844 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2017,15 +2017,11 @@ void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceL } } -int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceName) +int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) { LOGI("DeviceManagerService Start SetLocalDeviceName!"); - if (localDeviceName.empty()) { - LOGE("Invalid parameter, parameter is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); - int32_t ret = softbusListener_->SetLocalDeviceName(localDeviceName); + int32_t ret = softbusListener_->SetLocalDeviceName(localDeviceName, localDisplayName); if (ret != DM_OK) { LOGE("SetLocalDeviceName error, failed ret: %{public}d", ret); return ret; diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 0795dbf2a..29e4eb932 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -163,5 +163,10 @@ std::string AccountBootListener::GetLocalDisplayName() const { return localDeviceMgr_->GetLocalDisplayName(); } + +std::string AccountBootListener::GetLocalDeviceName() const +{ + return localDeviceMgr_->GetLocalDeviceName(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp index f09203c6a..22227f15b 100644 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -192,10 +192,7 @@ int32_t LocalDeviceNameMgr::QueryLocalDeviceName() localDeviceName_ = localDeviceName; dataShareHelper->Release(); LOGI("get user defined deviceName=%{public}s", localDeviceName.c_str()); - if (localDisplayName_.empty()) { - LOGI("displayName is null, set user define device name to softbus."); - DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); - } + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName_, localDisplayName_); return DM_OK; } ret = GetDefaultDeviceName(dataShareHelper, localDeviceName); @@ -207,10 +204,7 @@ int32_t LocalDeviceNameMgr::QueryLocalDeviceName() localDeviceName_ = localDeviceName; dataShareHelper->Release(); LOGI("get default deviceName=%{public}s", localDeviceName.c_str()); - if (localDisplayName_.empty()) { - LOGI("displayName is null, set default deviceName to softbus."); - DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); - } + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName_, localDisplayName_); return DM_OK; } @@ -261,7 +255,7 @@ int32_t LocalDeviceNameMgr::QueryLocalDisplayName() localDisplayName_ = localDisplayName; dataShareHelper->Release(); LOGI("get display deviceName=%{public}s", localDisplayName.c_str()); - DeviceManagerService::GetInstance().SetLocalDeviceName(localDisplayName); + DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName_, localDisplayName_); return DM_OK; } @@ -294,5 +288,10 @@ std::string LocalDeviceNameMgr::GetLocalDisplayName() const { return localDisplayName_; } + +std::string LocalDeviceNameMgr::GetLocalDeviceName() const +{ + return localDeviceName_; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 037a3532f..359e3c76c 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -86,10 +86,12 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; + std::string localDeviceName = accountBootListener_->GetLocalDisplayName(); std::string localDisplayName = accountBootListener_->GetLocalDisplayName(); - if (!localDisplayName.empty()) { - LOGI("Already have display deviceName=%{public}s", localDisplayName.c_str()); - DeviceManagerService::GetInstance().SetLocalDeviceName(localDisplayName); + int ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + if (ret == DM_OK) { + LOGI("Already have deviceName=%{public}s or displayName=%{public}s", + localDeviceName.c_str(), localDisplayName.c_str()); return; } accountBootListener_->SetSaTriggerFlag(SaTriggerFlag::DM_SA_READY); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a945c24bf..903e18ad0 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -688,18 +688,35 @@ int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId); } -int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName) +int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) { LOGI("SoftbusListener Start SetLocalDeviceName!"); - if (localDeviceName.empty()) { - LOGE("Invalid parameter, callerId is empty."); +#ifdef DDEVICE_MANAGER_COMMON_SWITCH + LOGI("device_manager_common is true, Blue!"); + int32_t ret = 1; + if (!localDisplayName.empty()) { + ret = ::SetLocalDeviceName(DM_PKG_NAME, localDisplayName.c_str()); + } else if (!localDeviceName.empty()) { + ret = ::SetLocalDeviceName(DM_PKG_NAME, localDeviceName.c_str()); + } else { + LOGE("localDeviceName and localDisplayName is null!"); + } + if (ret != DM_OK) { + LOGE("[SOFTBUS]SetLocalDeviceName error, failed ret: %{public}d", ret); + return ret; + } +#else + LOGI("device_manager_common is false, Yellow!"); + if (localDisplayName.empty()) { + LOGE("Invalid parameter, localDisplayName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - int32_t ret = ::SetLocalDeviceName(DM_PKG_NAME, localDeviceName.c_str()); + int32_t ret = ::SetLocalDeviceName(DM_PKG_NAME, localDisplayName.c_str()); if (ret != DM_OK) { LOGE("[SOFTBUS]SetLocalDeviceName error, failed ret: %{public}d", ret); return ret; } +#endif return DM_OK; } -- Gitee From 9888181b799bf8b5adf68c12f7484844b6584830 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 8 Nov 2024 21:20:59 +0800 Subject: [PATCH 375/520] =?UTF-8?q?=E6=B5=81=E6=B0=B4=E7=BA=BF=E6=95=B4?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- device_manager.gni | 5 +++-- services/service/BUILD.gn | 6 +----- services/service/src/device_manager_service.cpp | 3 ++- services/service/src/softbus/softbus_listener.cpp | 3 ++- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/device_manager.gni b/device_manager.gni index 57eb3a487..49de91bae 100644 --- a/device_manager.gni +++ b/device_manager.gni @@ -79,9 +79,10 @@ declare_args() { } if (defined(global_parts_info) && - defined(global_parts_info.distributedhardware_distributed_hardware_adapter)) { + defined( + global_parts_info.distributedhardware_distributed_hardware_adapter)) { device_manager_common = false } else { device_manager_common = true } -} +} \ No newline at end of file diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index b3e68af5c..41ff450db 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -106,11 +106,7 @@ if (defined(ohos_lite)) { "-Wfloat-equal", "-Wshadow", ] - - if (dm_common) { - cflags += [ "-DDEVICE_MANAGER_COMMON_SWITCH" ] - } - + cflags_cc = cflags } } diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 46f015844..db144ccbe 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2017,7 +2017,8 @@ void DeviceManagerService::HandleCredentialAuthStatus(const std::string &deviceL } } -int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) +int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceName, + const std::string &localDisplayName) { LOGI("DeviceManagerService Start SetLocalDeviceName!"); CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 903e18ad0..d420034e5 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -688,7 +688,8 @@ int32_t SoftbusListener::GetNetworkIdByUdid(const std::string &udid, std::string return SoftbusCache::GetInstance().GetNetworkIdFromCache(udid, networkId); } -int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) +int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, + const std::string &localDisplayName) { LOGI("SoftbusListener Start SetLocalDeviceName!"); #ifdef DDEVICE_MANAGER_COMMON_SWITCH -- Gitee From 0eb55fc790969d733316e1df542644f07810ed23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sat, 9 Nov 2024 10:27:31 +0800 Subject: [PATCH 376/520] =?UTF-8?q?gn=E6=96=87=E4=BB=B6=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- device_manager.gni | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/device_manager.gni b/device_manager.gni index 49de91bae..d197e5b76 100644 --- a/device_manager.gni +++ b/device_manager.gni @@ -85,4 +85,4 @@ declare_args() { } else { device_manager_common = true } -} \ No newline at end of file +} -- Gitee From d33b77b71f123bb12d48786b987194ee5baf0fbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sat, 9 Nov 2024 10:43:22 +0800 Subject: [PATCH 377/520] =?UTF-8?q?gn=E6=96=87=E4=BB=B6=E6=A0=BC=E5=BC=8F?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index 41ff450db..3f3723dcd 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -106,7 +106,7 @@ if (defined(ohos_lite)) { "-Wfloat-equal", "-Wshadow", ] - + cflags_cc = cflags } } -- Gitee From f025e8869590c6c361ed3864ea079fc5d812d60c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sat, 9 Nov 2024 11:44:18 +0800 Subject: [PATCH 378/520] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=93=9D=E5=8C=BA?= =?UTF-8?q?=E6=80=BB=E7=BA=BF=E6=AD=BB=E4=BA=A1=EF=BC=8C=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/src/ipc/standard/ipc_server_stub.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 359e3c76c..c5dd20a76 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -86,8 +86,10 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; - std::string localDeviceName = accountBootListener_->GetLocalDisplayName(); + std::string localDeviceName = accountBootListener_->GetLocalDeviceName(); std::string localDisplayName = accountBootListener_->GetLocalDisplayName(); + LOGI("deviceName=%{public}s, displayName=%{public}s", + localDeviceName.c_str(), localDisplayName.c_str()); int ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); if (ret == DM_OK) { LOGI("Already have deviceName=%{public}s or displayName=%{public}s", -- Gitee From b9ddf67d3fb78ccf9a4f06ff9cb59c12197978c0 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Thu, 7 Nov 2024 14:34:27 +0800 Subject: [PATCH 379/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- interfaces/kits/js/src/native_devicemanager_js.cpp | 8 +++++++- interfaces/kits/js4.0/src/native_devicemanager_js.cpp | 8 +++++++- test/commonunittest/UTTest_dm_auth_manager_first.cpp | 4 ++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 037ef23a5..e0f90c5ce 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -3227,7 +3227,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) obj->bundleName_ = std::string(bundleName); std::lock_guard autoLock(g_deviceManagerMapMutex); g_deviceManagerMap[obj->bundleName_] = obj; - napi_wrap( + napi_status status = napi_wrap( env, thisVar, reinterpret_cast(obj), [](napi_env env, void *data, void *hint) { (void)env; @@ -3238,6 +3238,12 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) LOGI("delete deviceManager"); }, nullptr, nullptr); + if (status != napi_ok) { + delete obj; + obj = nullptr; + LOGE("failed to wrap JS object"); + return nullptr; + } return thisVar; } diff --git a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp index 72d024acc..88e602eb9 100644 --- a/interfaces/kits/js4.0/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js4.0/src/native_devicemanager_js.cpp @@ -1954,7 +1954,7 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) obj->bundleName_ = bundleName; std::lock_guard autoLock(g_deviceManagerMapMutex); g_deviceManagerMap[obj->bundleName_] = obj; - napi_wrap( + napi_status status = napi_wrap( env, thisVar, reinterpret_cast(obj), [](napi_env env, void *data, void *hint) { (void)env; @@ -1965,6 +1965,12 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) LOGI("delete deviceManager"); }, nullptr, nullptr); + if (status != napi_ok) { + delete obj; + obj = nullptr; + LOGE("failed to wrap JS object"); + return nullptr; + } return thisVar; } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 57f0ca81b..505afb15d 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -302,8 +302,8 @@ HWTEST_F(DmAuthManagerTest, GetPinCode_002, testing::ext::TestSize.Level0) authManager_->ShowAuthInfoDialog(); authManager_->ShowStartAuthDialog(); int32_t code = 0; - authManager_->GetPinCode(code); - ASSERT_EQ(code, ERR_DM_AUTH_NOT_START); + int32_t ret = authManager_->GetPinCode(code); + ASSERT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DmAuthManagerTest, SetPageId_001, testing::ext::TestSize.Level0) -- Gitee From d4e765d32301936a3932fa893eb7d5209fef9807 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sun, 10 Nov 2024 15:02:58 +0800 Subject: [PATCH 380/520] =?UTF-8?q?=E6=A3=80=E8=A7=86=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/BUILD.gn | 2 +- services/service/src/softbus/softbus_listener.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index 3f3723dcd..b1e2abbc9 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -257,7 +257,7 @@ if (defined(ohos_lite)) { } if (device_manager_common) { - defines += [ "DDEVICE_MANAGER_COMMON_SWITCH" ] + defines += [ "DEVICE_MANAGER_COMMON_FLAG" ] } public_external_deps = [ "json:nlohmann_json_static" ] diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index d420034e5..f04bb4a0f 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -692,8 +692,8 @@ int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) { LOGI("SoftbusListener Start SetLocalDeviceName!"); -#ifdef DDEVICE_MANAGER_COMMON_SWITCH - LOGI("device_manager_common is true, Blue!"); +#ifdef DEVICE_MANAGER_COMMON_FLAG + LOGI("device_manager_common is true!"); int32_t ret = 1; if (!localDisplayName.empty()) { ret = ::SetLocalDeviceName(DM_PKG_NAME, localDisplayName.c_str()); @@ -707,7 +707,7 @@ int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, return ret; } #else - LOGI("device_manager_common is false, Yellow!"); + LOGI("device_manager_common is false!"); if (localDisplayName.empty()) { LOGE("Invalid parameter, localDisplayName is empty."); return ERR_DM_INPUT_PARA_INVALID; -- Gitee From 7fadb75efaa328a953bca8befdaccd68de969f9f Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 11 Nov 2024 15:34:50 +0800 Subject: [PATCH 381/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichain_connector_fuzzer.cpp | 1 - .../UTTest_dm_deviceprofile_connector.cpp | 483 +++++++++++++++++- ...Test_dm_deviceprofile_connector_second.cpp | 115 +++++ ...UTTest_dm_deviceprofile_connector_second.h | 41 ++ test/unittest/BUILD.gn | 72 ++- .../UTTest_device_manager_service.cpp | 152 +++++- test/unittest/UTTest_device_manager_service.h | 4 +- .../UTTest_device_manager_service_impl.cpp | 13 + .../UTTest_device_manager_service_three.cpp | 380 ++++++++++++++ .../UTTest_device_manager_service_three.h | 58 +++ .../UTTest_device_manager_service_two.cpp | 2 + .../mock/device_manager_service_impl_mock.cpp | 12 + .../mock/device_manager_service_impl_mock.h | 5 + .../mock/device_manager_service_mock.cpp | 28 + .../mock/device_manager_service_mock.h | 40 ++ .../mock/deviceprofile_connector_mock.cpp | 21 + .../mock/deviceprofile_connector_mock.h | 10 + ...distributed_device_profile_client_mock.cpp | 43 ++ .../distributed_device_profile_client_mock.h | 46 ++ test/unittest/mock/dm_softbus_cache_mock.cpp | 28 + test/unittest/mock/dm_softbus_cache_mock.h | 40 ++ ...mock_distributed_device_profile_client.cpp | 209 ++++++++ test/unittest/mock/softbus_listener_mock.cpp | 16 + test/unittest/mock/softbus_listener_mock.h | 7 + 24 files changed, 1804 insertions(+), 22 deletions(-) create mode 100644 test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp create mode 100644 test/commonunittest/UTTest_dm_deviceprofile_connector_second.h create mode 100644 test/unittest/UTTest_device_manager_service_three.cpp create mode 100644 test/unittest/UTTest_device_manager_service_three.h create mode 100644 test/unittest/mock/device_manager_service_mock.cpp create mode 100644 test/unittest/mock/device_manager_service_mock.h create mode 100644 test/unittest/mock/distributed_device_profile_client_mock.cpp create mode 100644 test/unittest/mock/distributed_device_profile_client_mock.h create mode 100644 test/unittest/mock/dm_softbus_cache_mock.cpp create mode 100644 test/unittest/mock/dm_softbus_cache_mock.h diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 4158807f0..b62626826 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -190,7 +190,6 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) hichainConnector->GetJsonInt(jsonOutObj, "key"); hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); hichainConnector->DeleteAllGroupByUdid(reqParams); - hichainConnector->DeleteP2PGroup(switchUserId); } void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 3e2038dc2..c71f80db2 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -36,6 +36,274 @@ void DeviceProfileConnectorTest::TearDownTestCase() { } +void AddAccessControlProfileFirst(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileSecond(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileThird(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileForth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileFifth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void GetAccessControlProfiles(std::vector& accessControlProfiles) +{ + AddAccessControlProfileFirst(accessControlProfiles); + AddAccessControlProfileSecond(accessControlProfiles); + AddAccessControlProfileThird(accessControlProfiles); + AddAccessControlProfileForth(accessControlProfiles); + AddAccessControlProfileFifth(accessControlProfiles); +} HWTEST_F(DeviceProfileConnectorTest, GetAccessControlProfile_001, testing::ext::TestSize.Level0) { auto ret = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); @@ -47,7 +315,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_001, testing::ext::Te std::string pkgName; std::string deviceId = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); - EXPECT_EQ(ret.empty(), true); + EXPECT_EQ(ret.empty(), false); } HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::TestSize.Level0) @@ -55,7 +323,15 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::Te std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); - EXPECT_EQ(ret.empty(), true); + EXPECT_EQ(ret.empty(), false); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "deviceId_003"; + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + EXPECT_EQ(ret.empty(), false); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) @@ -195,6 +471,15 @@ HWTEST_F(DeviceProfileConnectorTest, GetBindTypeByPkgName_001, testing::ext::Tes EXPECT_EQ(ret.empty(), true); } +HWTEST_F(DeviceProfileConnectorTest, GetBindTypeByPkgName_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string requestDeviceId; + std::string trustUdid = "123456"; + auto ret = DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); + EXPECT_EQ(ret.empty(), false); +} + HWTEST_F(DeviceProfileConnectorTest, GetParamBindTypeVec_001, testing::ext::TestSize.Level0) { DistributedDeviceProfile::AccessControlProfile profiles; @@ -451,6 +736,45 @@ HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_001, testing::ext::TestSi EXPECT_EQ(ret.empty(), true); } +HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_002, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::vector bindTypeVec; + std::string localDeviceId; + std::string targetDeviceId = "123456"; + bindTypeVec.push_back(IDENTICAL_ACCOUNT_TYPE); + bindTypeVec.push_back(DEVICE_PEER_TO_PEER_TYPE); + auto ret = DeviceProfileConnector::GetInstance().SyncAclByBindType(pkgName, bindTypeVec, localDeviceId, + targetDeviceId); + EXPECT_EQ(ret.empty(), false); +} + +HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_003, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::vector bindTypeVec; + std::string localDeviceId = "deviceId"; + std::string targetDeviceId = "remoteDeviceId"; + bindTypeVec.push_back(DEVICE_ACROSS_ACCOUNT_TYPE); + bindTypeVec.push_back(APP_ACROSS_ACCOUNT_TYPE); + auto ret = DeviceProfileConnector::GetInstance().SyncAclByBindType(pkgName, bindTypeVec, localDeviceId, + targetDeviceId); + EXPECT_EQ(ret.empty(), false); +} + +HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::vector bindTypeVec; + std::string localDeviceId = "deviceId"; + std::string targetDeviceId = "remoteDeviceId"; + bindTypeVec.push_back(DEVICE_PEER_TO_PEER_TYPE); + bindTypeVec.push_back(IDENTICAL_ACCOUNT_TYPE); + auto ret = DeviceProfileConnector::GetInstance().SyncAclByBindType(pkgName, bindTypeVec, localDeviceId, + targetDeviceId); + EXPECT_EQ(ret.empty(), true); +} + HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_001, testing::ext::TestSize.Level0) { std::string localDeviceId = "localDeviceId"; @@ -488,7 +812,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_002, testing::ext::T std::string trustDeviceId = "123456"; std::string requestDeviceId = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); + EXPECT_EQ(ret.bindType, 5); } HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_003, testing::ext::TestSize.Level0) @@ -504,6 +828,8 @@ HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::Tes DmAclInfo aclInfo; DmAccesser dmAccesser; DmAccessee dmAccessee; + int32_t userId = 123456; + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(userId); int32_t ret = DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); EXPECT_EQ(ret, DM_OK); } @@ -833,5 +1159,156 @@ HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSi ret = DeviceProfileConnector::GetInstance().SingleUserProcess(profile, caller, callee); EXPECT_EQ(ret, false); } + +HWTEST_F(DeviceProfileConnectorTest, GetAccessControlProfileByUserId_001, testing::ext::TestSize.Level0) +{ + int32_t userId = DEVICE; + std::vector profiles; + profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); + EXPECT_GE(profiles.size(), 0); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAppBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::string pkgName = "bundleName1"; + std::vector profiles; + std::string localUdid = "remoteDeviceId"; + std::string remoteUdid="localDeviceId"; + GetAccessControlProfiles(profiles); + DeviceProfileConnector::GetInstance().DeleteAppBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, APP); + + pkgName = "bundleName2"; + localUdid = "localDeviceId"; + remoteUdid="remoteDeviceId"; + DeviceProfileConnector::GetInstance().DeleteAppBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, APP); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteDeviceBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::vector profiles; + std::string localUdid = "remoteDeviceId"; + std::string remoteUdid="localDeviceId"; + GetAccessControlProfiles(profiles); + DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, DEVICE); + + localUdid = "localDeviceId"; + remoteUdid="remoteDeviceId"; + DeviceProfileConnector::GetInstance().DeleteDeviceBindLevel(offlineParam, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, DEVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteServiceBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::string pkgName = "bundleName1"; + std::vector profiles; + std::string localUdid = "remoteDeviceId"; + std::string remoteUdid="localDeviceId"; + GetAccessControlProfiles(profiles); + DeviceProfileConnector::GetInstance().DeleteServiceBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, SERVICE); + + pkgName = "bundleName2"; + localUdid = "localDeviceId"; + remoteUdid="remoteDeviceId"; + DeviceProfileConnector::GetInstance().DeleteServiceBindLevel(offlineParam, pkgName, profiles, + localUdid, remoteUdid); + EXPECT_EQ(offlineParam.bindType, SERVICE); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "remoteDeviceId"; + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteTimeOutAcl_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "remoteDeviceId"; + uint32_t ret = DeviceProfileConnector::GetInstance().DeleteTimeOutAcl(deviceId); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(DeviceProfileConnectorTest, GetTrustNumber_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "remoteDeviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().GetTrustNumber(deviceId); + EXPECT_NE(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, IsSameAccount_003, testing::ext::TestSize.Level0) +{ + std::string udid = "123456"; + int32_t ret = DeviceProfileConnector::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + std::string srcUdid; + DmAccessCallee callee; + std::string sinkUdid; + int32_t ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, ERR_DM_FAILED); + + srcUdid = "123456"; + sinkUdid = "123456"; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + std::string srcUdid; + DmAccessCallee callee; + std::string sinkUdid; + int32_t ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, ERR_DM_FAILED); + + srcUdid = "123456"; + sinkUdid = "123456"; + ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_002, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + int32_t bindType = DM_INVALIED_BINDTYPE; + std::string remoteAccountHash = "remoteAccountHash"; + std::string remoteUdid = "123456"; + std::string localUdid = "localDeviceId"; + + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 0; + std::string remoteUdid; + std::string localUdid = "localDeviceId"; + int32_t bindType = DM_INVALIED_BINDTYPE; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAllAccessControlProfile_001, testing::ext::TestSize.Level0) +{ + int64_t accessControlId = 1; + DeviceProfileConnector::GetInstance().DeleteAccessControlById(accessControlId); + auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + EXPECT_TRUE(ret.empty()); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp new file mode 100644 index 000000000..692c4a701 --- /dev/null +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_deviceprofile_connector_second.h" + +#include "dm_constants.h" +#include "deviceprofile_connector.h" +#include + +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { +void DeviceProfileConnectorSecondTest::SetUp() +{ +} + +void DeviceProfileConnectorSecondTest::TearDown() +{ +} + +void DeviceProfileConnectorSecondTest::SetUpTestCase() +{ + DistributedDeviceProfile::DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient = + distributedDeviceProfileClientMock_; +} + +void DeviceProfileConnectorSecondTest::TearDownTestCase() +{ + distributedDeviceProfileClientMock_ = nullptr; +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfile_201, testing::ext::TestSize.Level0) +{ + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + EXPECT_TRUE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfileByUserId_201, testing::ext::TestSize.Level0) +{ + int32_t userId = DEVICE; + std::vector profiles; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfileByUserId(userId); + EXPECT_TRUE(profiles.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, CheckAuthForm_201, testing::ext::TestSize.Level0) +{ + DmAuthForm form = DmAuthForm::ACROSS_ACCOUNT; + DistributedDeviceProfile::AccessControlProfile profiles; + profiles.SetBindType(DM_ACROSS_ACCOUNT); + profiles.SetBindLevel(APP); + profiles.accessee_.SetAccesseeBundleName("pkgName"); + profiles.accessee_.SetAccesseeDeviceId("localDeviceId"); + DmDiscoveryInfo discoveryInfo; + discoveryInfo.pkgname = "pkgName"; + discoveryInfo.localDeviceId = "localDeviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); + + profiles.accesser_.SetAccesserBundleName("pkgName"); + profiles.accesser_.SetAccesserDeviceId("localDeviceId"); + ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); + + profiles.SetBindLevel(SERVICE); + ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::INVALID_TYPE); + + profiles.SetBindLevel(DEVICE); + ret = DeviceProfileConnector::GetInstance().CheckAuthForm(form, profiles, discoveryInfo); + EXPECT_EQ(ret, DmAuthForm::ACROSS_ACCOUNT); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, PutAccessControlList_201, testing::ext::TestSize.Level0) +{ + DmAclInfo aclInfo; + DmAccesser dmAccesser; + DmAccessee dmAccessee; + EXPECT_CALL(*distributedDeviceProfileClientMock_, PutAccessControlProfile(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, CheckIdenticalAccount_201, testing::ext::TestSize.Level0) +{ + int32_t userId = 0; + std::string accountId; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + bool ret = DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAllAccessControlProfile_201, testing::ext::TestSize.Level0) +{ + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + EXPECT_TRUE(ret.empty()); +} +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h new file mode 100644 index 000000000..7f638ce73 --- /dev/null +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_UTTEST_DM_DEVICEPROFILE_CONNECTOR_SECOND_H +#define OHOS_UTTEST_DM_DEVICEPROFILE_CONNECTOR_SECOND_H + +#include +#include + +#include "deviceprofile_connector.h" +#include "distributed_device_profile_client_mock.h" +#include "deviceprofile_connector_mock.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceProfileConnectorSecondTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + static inline std::shared_ptr + distributedDeviceProfileClientMock_ = + std::make_shared(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_UTTEST_DM_DEVICEPROFILE_CONNECTOR_SECOND_H diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 64571d1ae..f8161dc4d 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -27,6 +27,7 @@ group("unittest") { ":UTTest_device_manager_service", ":UTTest_device_manager_service_impl", ":UTTest_device_manager_service_listener", + ":UTTest_device_manager_service_three", ":UTTest_discovery_filter", ":UTTest_discovery_manager", ":UTTest_dm_account_common_event", @@ -40,6 +41,7 @@ group("unittest") { ":UTTest_dm_crypto", ":UTTest_dm_device_state_manager", ":UTTest_dm_deviceprofile_connector", + ":UTTest_dm_deviceprofile_connector_second", ":UTTest_dm_dfx", ":UTTest_dm_discovery_filter", ":UTTest_dm_discovery_manager", @@ -330,10 +332,7 @@ ohos_unittest("UTTest_device_manager_service") { "mock/softbus_listener_mock.cpp", ] - deps = [ - ":device_manager_test_common", - "//third_party/googletest:gmock_main", - ] + deps = [ ":device_manager_test_common" ] external_deps = [ "access_token:libaccesstoken_sdk", @@ -344,11 +343,42 @@ ohos_unittest("UTTest_device_manager_service") { "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", "googletest:gmock", + "googletest:gmock_main", ] } ## UnitTest UTTest_device_manager_service }}} +## UnitTest UTTest_device_manager_service_three {{{ +ohos_unittest("UTTest_device_manager_service_three") { + module_out_path = module_out_path + + sources = [ + "UTTest_device_manager_service_three.cpp", + "mock/device_manager_service_impl_mock.cpp", + "mock/device_manager_service_mock.cpp", + "mock/dm_softbus_cache_mock.cpp", + "mock/permission_manager_mock.cpp", + "mock/softbus_listener_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", + ] +} + +## UnitTest UTTest_device_manager_service_three }}} + ## UnitTest UTTest_hichain_auth_connector {{{ ohos_unittest("UTTest_hichain_auth_connector") { module_out_path = module_out_path @@ -944,10 +974,7 @@ ohos_unittest("UTTest_device_manager_service_impl") { "mock/deviceprofile_connector_mock.cpp", ] - deps = [ - ":device_manager_test_common", - "//third_party/googletest:gmock_main", - ] + deps = [ ":device_manager_test_common" ] external_deps = [ "device_auth:deviceauth_sdk", @@ -955,6 +982,7 @@ ohos_unittest("UTTest_device_manager_service_impl") { "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", "googletest:gmock", + "googletest:gmock_main", "os_account:libaccountkits", "os_account:os_account_innerkits", ] @@ -1234,6 +1262,34 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { ## UTTest_dm_deviceprofile_connector }}} +############################### +## UnitTest UTTest_dm_deviceprofile_connector_second {{{ +ohos_unittest("UTTest_dm_deviceprofile_connector_second") { + module_out_path = module_out_path + + include_dirs = [ + "${devicemanager_path}/commondependency/include", + "${devicemanager_path}/test/commonunittest", + ] + + sources = [ + "${devicemanager_path}/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp", + "${devicemanager_path}/test/unittest/mock/distributed_device_profile_client_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "ffrt:libffrt", + "googletest:gmock", + "googletest:gmock_main", + ] +} + +## UTTest_dm_deviceprofile_connector_second }}} + ############################# ## UnitTest UTTest_dm_discovery_manager {{{ diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 7ced28282..e20e63410 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -68,7 +68,6 @@ void DeviceManagerServiceTest::SetUpTestCase() DmPermissionManager::dmPermissionManager = permissionManagerMock_; DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; DmKVAdapterManager::dmKVAdapterManager = kVAdapterManagerMock_; - DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; DmAppManager::dmAppManager = appManagerMock_; } @@ -77,7 +76,6 @@ void DeviceManagerServiceTest::TearDownTestCase() permissionManagerMock_ = nullptr; softbusListenerMock_ = nullptr; kVAdapterManagerMock_ = nullptr; - deviceManagerServiceImplMock_ = nullptr; appManagerMock_ = nullptr; } @@ -178,7 +176,7 @@ HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSi uint16_t subscribeId = 1; DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL); + EXPECT_TRUE(ret == SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL || ret == SOFTBUS_ERR); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -323,7 +321,7 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_003, testing::ext::T int32_t publishId = 1; DeviceManagerService::GetInstance().InitDMServiceListener(); int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL); + EXPECT_TRUE(ret == SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL || ret == SOFTBUS_ERR); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -406,6 +404,7 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_003, testing::ext::TestS std::vector deviceList; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().UninitDMServiceListener(); @@ -600,6 +599,8 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_003, testing::ext::TestSiz std::string extra = "jdddd"; int32_t authType = 0; std::string deviceId = " 2345"; + EXPECT_CALL(*softbusListenerMock_, + GetTargetInfoFromCache(_, _, _)).WillOnce(Return(ERR_DM_BIND_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } @@ -676,6 +677,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_004, testing::ext::TestS { std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1970,7 +1972,7 @@ HWTEST_F(DeviceManagerServiceTest, StopAdvertising_004, testing::ext::TestSize.L std::map advertiseParam; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().StopAdvertising(pkgName, advertiseParam); - EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL); + EXPECT_TRUE(ret == SOFTBUS_DISCOVER_COAP_STOP_PUBLISH_FAIL || ret == SOFTBUS_ERR); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -2078,6 +2080,7 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_002, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); EXPECT_NE(ret, DM_OK); } @@ -2099,6 +2102,7 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_002, testing::ext::TestSize. PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); EXPECT_NE(ret, DM_OK); } @@ -2277,6 +2281,7 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize. PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -2468,6 +2473,8 @@ HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_002, testing::ext::Tes HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_003, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName_003"; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().IsDMServiceImplReady(); int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); EXPECT_EQ(ret, DM_OK); } @@ -2610,9 +2617,9 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_005, testing::ext::TestSize.Lev std::string networkId = "networkIdTest5"; DmDeviceInfo info; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } @@ -2630,6 +2637,50 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_004, testing::ext EXPECT_EQ(ret, DM_OK); } +/** + * @tc.name: UnAuthenticateDevice_005 + * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return + * value is SOFTBUS_IPC_ERR + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string networkId = "12345"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, BindDevice_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int32_t authType = 1; + std::string deviceId = "1234"; + std::string bindParam; + EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); + EXPECT_EQ(ret, DM_OK); +} + +/** + * @tc.name: AuthenticateDevice_005 + * @tc.desc: Set intFlag for GAuthenticateDevice to True and deviceId to null; Return ERR_DM_BIND_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + int32_t authType = 0; + std::string deviceId = " 2345"; + EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, DM_OK); +} + #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoyDeviceId_001, testing::ext::TestSize.Level0) { @@ -2655,6 +2706,93 @@ HWTEST_F(DeviceManagerServiceTest, GetUdidHashByAnoyDeviceId_001, testing::ext:: EXPECT_EQ(ret, ERR_DM_FAILED); } #endif + +/** + * @tc.name: GetTrustedDeviceList_004 + * @tc.desc:Set the intFlag of GetTrustedDeviceList_004 to true; Return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos_test"; + std::string extra = "jdddd"; + std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().UninitDMServiceListener(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: GetLocalDeviceInfo_003 + * @tc.desc: The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_003, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: GetLocalDeviceInfo_004 + * @tc.desc: The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_004, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeletePermission(); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, BindTarget_007, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + targetId.wifiIp = "wifi_Ip"; + std::map bindParam; + std::string key = PARAM_KEY_TARGET_ID; + std::string value = "186"; + bindParam.insert(std::make_pair(key, value)); + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_001, testing::ext::TestSize.Level0) +{ + std::string localDeviceName; + int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + localDeviceName = "localDeviceName_001"; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + + std::string deviceList; + uint16_t deviceTypeId = 0; + int32_t errcode = 1; + DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index a7c550863..00de35736 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -31,7 +31,7 @@ #include "softbus_listener_mock.h" #include "app_manager_mock.h" #include "kv_adapter_manager_mock.h" -#include "device_manager_service_impl_mock.h" + namespace OHOS { namespace DistributedHardware { class DeviceManagerServiceTest : public testing::Test { @@ -49,8 +49,6 @@ public: std::make_shared(); static inline std::shared_ptr kVAdapterManagerMock_ = std::make_shared(); - static inline std::shared_ptr deviceManagerServiceImplMock_ = - std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index bdf8cfd33..86723fb07 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -348,6 +348,11 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L int32_t remoteUserId = 1; std::string remoteAccountHash = "45552878"; std::string remoteUdid = "ajdakndkwj98877"; + EXPECT_CALL(*deviceProfileConnectorMock_, + HandleAccountLogoutEvent(_, _, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); + deviceManagerServiceImpl_->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid); + EXPECT_CALL(*deviceProfileConnectorMock_, + HandleAccountLogoutEvent(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); deviceManagerServiceImpl_->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid); int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); EXPECT_EQ(ret, DM_OK); @@ -1523,6 +1528,9 @@ HWTEST_F(DeviceManagerServiceImplTest, GetBindLevel_101, testing::ext::TestSize. int32_t tokenId2 = 123; int32_t remoteUserId = 100; int32_t ret = deviceManagerServiceImpl_->GetBindLevel(pkgName, localUdid, udid, tokenId); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return("")); + deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, localUdid, tokenId2); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(udid)); deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, localUdid, tokenId2); EXPECT_EQ(ret, INVALIED_TYPE); } @@ -1533,6 +1541,9 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndBindType_101, testing::ext: const std::string localUdid = "234"; int32_t userId = 100; std::map temp = deviceManagerServiceImpl_->GetDeviceIdAndBindType(userId, accountId); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); + deviceManagerServiceImpl_->HandleDevUnBindEvent(userId, localUdid); + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); deviceManagerServiceImpl_->HandleDevUnBindEvent(userId, localUdid); EXPECT_EQ(temp.empty(), true); } @@ -1599,6 +1610,8 @@ HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_103, testing::ext::Tes std::string appId; int32_t accessTokenId = 1001; std::vector profiles; + DmDeviceInfo devInfo; + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); AddAccessControlProfileFirst(profiles); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); if (deviceManagerServiceImpl_->hiChainConnector_ == nullptr) { diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp new file mode 100644 index 000000000..4004a2948 --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -0,0 +1,380 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_device_manager_service_three.h" + +#include "accesstoken_kit.h" +#include "dm_constants.h" +#include "dm_device_info.h" +#include "dm_log.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "softbus_common.h" +#include "softbus_error_code.h" + +using namespace OHOS::Security::AccessToken; +using namespace testing; +using namespace testing::ext; +namespace OHOS { +namespace DistributedHardware { + +void DeviceManagerServiceThreeTest::SetUp() +{ + const int32_t permsNum = 4; + const int32_t indexZero = 0; + const int32_t indexOne = 1; + const int32_t indexTwo = 2; + const int32_t indexThree = 3; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.DISTRIBUTED_SOFTBUS_CENTER"; + perms[indexOne] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[indexTwo] = "ohos.permission.ACCESS_SERVICE_DM"; + perms[indexThree] = "ohos.permission.MONITOR_DEVICE_NETWORK_STATE"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "dsoftbus_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + +void DeviceManagerServiceThreeTest::TearDown() +{ +} + +void DeviceManagerServiceThreeTest::SetUpTestCase() +{ + DmDeviceManagerService::dmDeviceManagerService = deviceManagerServiceMock_; + DmPermissionManager::dmPermissionManager = permissionManagerMock_; + DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; + DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; +} + +void DeviceManagerServiceThreeTest::TearDownTestCase() +{ + deviceManagerServiceMock_ = nullptr; + permissionManagerMock_ = nullptr; + softbusListenerMock_ = nullptr; + softbusCacheMock_ = nullptr; + deviceManagerServiceImplMock_ = nullptr; +} + +namespace { + +/** + * @tc.name: AuthenticateDevice_301 + * @tc.desc: Set unsupport authType = 0 and return ERR_DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, AuthenticateDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + int32_t authType = 1; + std::string deviceId = "deviceId"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: UnAuthenticateDevice_301 + * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return + * value is SOFTBUS_IPC_ERR + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, UnAuthenticateDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string networkId = "12345"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: SetUserOperation_301 + * @tc.desc: Make pkgName empty for SetUserOperation,The return value is + * DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, SetUserOperation_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + int32_t action = 0; + const std::string param = "extra"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int ret = DeviceManagerService::GetInstance().SetUserOperation(pkgName, action, param); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: RequestCredential_301 + * @tc.desc:The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, RequestCredential_301, testing::ext::TestSize.Level0) +{ + const std::string reqJsonStr = "test"; + std::string returnJsonStr = "returntest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().RequestCredential(reqJsonStr, returnJsonStr); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: ImportCredential_301 + * @tc.desc:The return value is ERR_DM_NOT_INIT + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, ImportCredential_301, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + const std::string credentialInfo = "credentialInfotest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().ImportCredential(pkgName, credentialInfo); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: DeleteCredential_301 + * @tc.desc:The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, DeleteCredential_301, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + const std::string deleteInfo = "deleteInfotest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().DeleteCredential(pkgName, deleteInfo); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +/** + * @tc.name: RegisterCredentialCallback_301 + * @tc.desc: The return value is DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceThreeTest, RegisterCredentialCallback_301, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().RegisterCredentialCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, BindDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int32_t authType = 1; + std::string deviceId = "1234"; + std::string bindParam; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, UnBindDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, MineRequestCredential_301, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + std::string pkgName; + std::string returnJsonStr; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().MineRequestCredential(pkgName, returnJsonStr); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, CheckCredential_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::string returnJsonStr; + std::string reqJsonStr; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().CheckCredential(pkgName, reqJsonStr, returnJsonStr); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, RegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().RegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, UnRegisterUiStateCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().UnRegisterUiStateCallback(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, NotifyEvent_301, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int32_t eventId = 0; + std::string event; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); + EXPECT_NE(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, BindTarget_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + std::map bindParam; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, DpAclAdd_301, testing::ext::TestSize.Level0) +{ + std::string udid = "udid"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().DpAclAdd(udid); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, IsSameAccount_301, testing::ext::TestSize.Level0) +{ + std::string udid = "udidTest"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().IsSameAccount(udid); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, CheckIsSameAccount_301, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceManagerServiceThreeTest, CheckAccessControl_301, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + DmAccessCallee callee; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StopAuthenticateDevice_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_003"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, ImportAuthCode_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSize.Level0) +{ + std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); +} + +HWTEST_F(DeviceManagerServiceThreeTest, UnBindDevice_302, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceThreeTest, UnBindDevice_303, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceThreeTest, StopAuthenticateDevice_302, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_004"; + std::string msg = R"( + { + "type" : 0, + "userId" : 123, + "accountId" : "28776", + "tokenId" : 16, + "peerUdid" : "104", + "accountName" : "account_xiao" + })"; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); + EXPECT_CALL(*deviceManagerServiceImplMock_, StopAuthenticateDevice(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_FAILED); +} +} // namespace +} // namespace DistributedHardware +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_three.h b/test/unittest/UTTest_device_manager_service_three.h new file mode 100644 index 000000000..243286b3b --- /dev/null +++ b/test/unittest/UTTest_device_manager_service_three.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICE_MANAGER_SERVICE_THREE_H +#define OHOS_DEVICE_MANAGER_SERVICE_THREE_H + +#include +#include +#include + +#include +#include + +#include "device_manager_service.h" +#include "device_manager_service_listener.h" +#include "device_manager_service_impl.h" +#include "dm_single_instance.h" +#include "common_event_support.h" +#include "permission_manager_mock.h" +#include "softbus_listener_mock.h" +#include "device_manager_service_mock.h" +#include "dm_softbus_cache_mock.h" +#include "device_manager_service_impl_mock.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerServiceThreeTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + static inline std::shared_ptr deviceManagerServiceMock_ = + std::make_shared(); + static inline std::shared_ptr permissionManagerMock_ = + std::make_shared(); + static inline std::shared_ptr softbusListenerMock_ = + std::make_shared(); + static inline std::shared_ptr softbusCacheMock_ = + std::make_shared(); + static inline std::shared_ptr deviceManagerServiceImplMock_ = + std::make_shared(); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index d181708db..74a978d83 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -223,6 +223,8 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz { DmAccessCaller caller; DmAccessCallee callee; + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_EQ(ret, true); } diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp index 58f43f8a3..50ca2b918 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.cpp +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -23,5 +23,17 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN { return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->StopAuthenticateDevice(pkgName); } + +int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetBindLevel(pkgName, localUdid, udid, tokenId); +} + +int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->UnBindDevice(pkgName, udid, bindLevel); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h index 33da0f28d..2079452f7 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.h +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -27,6 +27,9 @@ public: virtual ~DmDeviceManagerServiceImpl() = default; public: virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; + virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, + const std::string &udid, uint64_t &tokenId) = 0; + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; public: static inline std::shared_ptr dmDeviceManagerServiceImpl = nullptr; }; @@ -34,6 +37,8 @@ public: class DeviceManagerServiceImplMock : public DmDeviceManagerServiceImpl { public: MOCK_METHOD(int32_t, StopAuthenticateDevice, (const std::string &)); + MOCK_METHOD(int32_t, GetBindLevel, (const std::string &, const std::string &, const std::string &, uint64_t &)); + MOCK_METHOD(int32_t, UnBindDevice, (const std::string &, const std::string &, int32_t)); }; } } diff --git a/test/unittest/mock/device_manager_service_mock.cpp b/test/unittest/mock/device_manager_service_mock.cpp new file mode 100644 index 000000000..77b82c325 --- /dev/null +++ b/test/unittest/mock/device_manager_service_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_service_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); +bool DeviceManagerService::IsDMServiceImplReady() +{ + return DmDeviceManagerService::dmDeviceManagerService->IsDMServiceImplReady(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_mock.h b/test/unittest/mock/device_manager_service_mock.h new file mode 100644 index 000000000..29d3b9bcc --- /dev/null +++ b/test/unittest/mock/device_manager_service_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICE_MANAGER_SERVICE_MOCK_H +#define OHOS_DEVICE_MANAGER_SERVICE_MOCK_H + +#include +#include + +#include "device_manager_service.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDeviceManagerService { +public: + virtual ~DmDeviceManagerService() = default; +public: + virtual bool IsDMServiceImplReady() = 0; +public: + static inline std::shared_ptr dmDeviceManagerService = nullptr; +}; + +class DeviceManagerServiceMock : public DmDeviceManagerService { +public: + MOCK_METHOD(bool, IsDMServiceImplReady, ()); +}; +} +} +#endif diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index 7aa1a95da..dc8a99601 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -24,5 +24,26 @@ std::vector DeviceProfileConnect { return DmDeviceProfileConnector::dmDeviceProfileConnector->GetAllAccessControlProfile(); } + +int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleDevUnBindEvent(remoteUserId, remoteUdid, + localUdid); +} + +std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, + localUdid); +} + +int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid, const std::string &localUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, + remoteUdid, localUdid); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index d2356d6ff..17464a708 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -27,6 +27,12 @@ public: virtual ~DmDeviceProfileConnector() = default; public: virtual std::vector GetAllAccessControlProfile() = 0; + virtual int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + const std::string &localUdid) = 0; + virtual std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, + const std::string &localUdid) = 0; + virtual int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, + const std::string &remoteUdid, const std::string &localUdid) = 0; public: static inline std::shared_ptr dmDeviceProfileConnector = nullptr; }; @@ -34,6 +40,10 @@ public: class DeviceProfileConnectorMock : public DmDeviceProfileConnector { public: MOCK_METHOD(std::vector, GetAllAccessControlProfile, ()); + MOCK_METHOD(int32_t, HandleDevUnBindEvent, (int32_t, const std::string &, const std::string &)); + MOCK_METHOD(std::string, HandleAppUnBindEvent, (int32_t, const std::string &, int32_t, const std::string &)); + MOCK_METHOD(int32_t, HandleAccountLogoutEvent, (int32_t, const std::string &, const std::string &, + const std::string &)); }; } } diff --git a/test/unittest/mock/distributed_device_profile_client_mock.cpp b/test/unittest/mock/distributed_device_profile_client_mock.cpp new file mode 100644 index 000000000..f76c9d451 --- /dev/null +++ b/test/unittest/mock/distributed_device_profile_client_mock.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "distributed_device_profile_client_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedDeviceProfile { +IMPLEMENT_SINGLE_INSTANCE(DistributedDeviceProfileClient); +int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map params, + std::vector& accessControlProfiles) +{ + return DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient->GetAccessControlProfile(params, + accessControlProfiles); +} + +int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) +{ + return DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient->PutAccessControlProfile( + accessControlProfile); +} + +int32_t DistributedDeviceProfileClient::GetAllAccessControlProfile( + std::vector& accessControlProfiles) +{ + return DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient->GetAllAccessControlProfile( + accessControlProfiles); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/distributed_device_profile_client_mock.h b/test/unittest/mock/distributed_device_profile_client_mock.h new file mode 100644 index 000000000..740d8ef08 --- /dev/null +++ b/test/unittest/mock/distributed_device_profile_client_mock.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DISTRIBUTED_DEVICE_PROFILE_CLIENT_MOCK_H +#define OHOS_DISTRIBUTED_DEVICE_PROFILE_CLIENT_MOCK_H + +#include +#include + +#include "distributed_device_profile_client.h" + +namespace OHOS { +namespace DistributedDeviceProfile { +class DpDistributedDeviceProfileClient { +public: + virtual ~DpDistributedDeviceProfileClient() = default; +public: + virtual int32_t GetAccessControlProfile(std::map params, + std::vector& accessControlProfiles) = 0; + virtual int32_t PutAccessControlProfile(const AccessControlProfile& accessControlProfile) = 0; + virtual int32_t GetAllAccessControlProfile(std::vector& accessControlProfiles) = 0; +public: + static inline std::shared_ptr dpDistributedDeviceProfileClient = nullptr; +}; + +class DistributedDeviceProfileClientMock : public DpDistributedDeviceProfileClient { +public: + MOCK_METHOD(int32_t, GetAccessControlProfile, ((std::map), + std::vector&)); + MOCK_METHOD(int32_t, PutAccessControlProfile, (const AccessControlProfile&)); + MOCK_METHOD(int32_t, GetAllAccessControlProfile, (std::vector&)); +}; +} +} +#endif diff --git a/test/unittest/mock/dm_softbus_cache_mock.cpp b/test/unittest/mock/dm_softbus_cache_mock.cpp new file mode 100644 index 000000000..994212433 --- /dev/null +++ b/test/unittest/mock/dm_softbus_cache_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_softbus_cache_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusCache); +int32_t SoftbusCache::GetUdidByUdidHash(const std::string &udidHash, std::string &udid) +{ + return DmSoftbusCache::dmSoftbusCache->GetUdidByUdidHash(udidHash, udid); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_softbus_cache_mock.h b/test/unittest/mock/dm_softbus_cache_mock.h new file mode 100644 index 000000000..d492cacc0 --- /dev/null +++ b/test/unittest/mock/dm_softbus_cache_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DM_SOFTBUS_CACHE_MOCK_H +#define OHOS_DM_SOFTBUS_CACHE_MOCK_H + +#include +#include + +#include "dm_softbus_cache.h" + +namespace OHOS { +namespace DistributedHardware { +class DmSoftbusCache { +public: + virtual ~DmSoftbusCache() = default; +public: + virtual int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid) = 0; +public: + static inline std::shared_ptr dmSoftbusCache = nullptr; +}; + +class SoftbusCacheMock : public DmSoftbusCache { +public: + MOCK_METHOD(int32_t, GetUdidByUdidHash, (const std::string &, std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index f4840766b..447c31c9e 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -585,6 +585,211 @@ void AddAccessControlProfileEleventh(std::vector& accessCo accessControlProfiles.push_back(profileFifth); } +void AddAccessControlProfileTwelfth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlprofileThirteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileFourteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1282; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileFifteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -620,6 +825,10 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::mapGetUuidByNetworkId(networkId, uuid); } + +int32_t SoftbusListener::GetTargetInfoFromCache(const std::string &deviceId, PeerTargetId &targetId, + ConnectionAddrType &addrType) +{ + return DmSoftbusListener::dmSoftbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); +} + +int32_t SoftbusListener::GetTrustedDeviceList(std::vector &deviceInfoList) +{ + return DmSoftbusListener::dmSoftbusListener->GetTrustedDeviceList(deviceInfoList); +} + +int32_t SoftbusListener::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) +{ + return DmSoftbusListener::dmSoftbusListener->GetLocalDeviceInfo(deviceInfo); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h index d99de2602..e2199f60e 100644 --- a/test/unittest/mock/softbus_listener_mock.h +++ b/test/unittest/mock/softbus_listener_mock.h @@ -31,6 +31,10 @@ public: virtual int32_t GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) = 0; virtual int32_t GetDeviceInfo(const std::string &networkId, DmDeviceInfo &info) = 0; virtual int32_t GetUuidByNetworkId(const char *networkId, std::string &uuid) = 0; + virtual int32_t GetTargetInfoFromCache(const std::string &deviceId, PeerTargetId &targetId, + ConnectionAddrType &addrType) = 0; + virtual int32_t GetTrustedDeviceList(std::vector &deviceInfoList) = 0; + virtual int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) = 0; public: static inline std::shared_ptr dmSoftbusListener = nullptr; }; @@ -42,6 +46,9 @@ public: MOCK_METHOD(int32_t, GetDeviceSecurityLevel, (const char *, int32_t &)); MOCK_METHOD(int32_t, GetDeviceInfo, (const std::string &, DmDeviceInfo &)); MOCK_METHOD(int32_t, GetUuidByNetworkId, (const char *, std::string &)); + MOCK_METHOD(int32_t, GetTargetInfoFromCache, (const std::string &, PeerTargetId &, ConnectionAddrType &addrType)); + MOCK_METHOD(int32_t, GetTrustedDeviceList, (std::vector &)); + MOCK_METHOD(int32_t, GetLocalDeviceInfo, (DmDeviceInfo &)); }; } } -- Gitee From 686b1a2091317aa5d2367157d086bf2c02a2db2a Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 11 Nov 2024 15:54:33 +0800 Subject: [PATCH 382/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/BUILD.gn | 2 +- .../UTTest_device_manager_service.cpp | 68 ++++++++++++++++--- test/unittest/UTTest_device_manager_service.h | 6 ++ .../UTTest_device_manager_service_three.cpp | 50 +------------- .../UTTest_device_manager_service_three.h | 3 - 5 files changed, 68 insertions(+), 61 deletions(-) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index f8161dc4d..502a08926 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -327,6 +327,7 @@ ohos_unittest("UTTest_device_manager_service") { "UTTest_device_manager_service_two.cpp", "mock/app_manager_mock.cpp", "mock/device_manager_service_impl_mock.cpp", + "mock/dm_softbus_cache_mock.cpp", "mock/kv_adapter_manager_mock.cpp", "mock/permission_manager_mock.cpp", "mock/softbus_listener_mock.cpp", @@ -357,7 +358,6 @@ ohos_unittest("UTTest_device_manager_service_three") { "UTTest_device_manager_service_three.cpp", "mock/device_manager_service_impl_mock.cpp", "mock/device_manager_service_mock.cpp", - "mock/dm_softbus_cache_mock.cpp", "mock/permission_manager_mock.cpp", "mock/softbus_listener_mock.cpp", ] diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index e20e63410..05c00b3e8 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -69,6 +69,8 @@ void DeviceManagerServiceTest::SetUpTestCase() DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; DmKVAdapterManager::dmKVAdapterManager = kVAdapterManagerMock_; DmAppManager::dmAppManager = appManagerMock_; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; + DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; } void DeviceManagerServiceTest::TearDownTestCase() @@ -77,6 +79,8 @@ void DeviceManagerServiceTest::TearDownTestCase() softbusListenerMock_ = nullptr; kVAdapterManagerMock_ = nullptr; appManagerMock_ = nullptr; + deviceManagerServiceImplMock_ = nullptr; + softbusCacheMock_ = nullptr; } namespace { @@ -404,7 +408,6 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_003, testing::ext::TestS std::vector deviceList; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); DeviceManagerService::GetInstance().InitDMServiceListener(); - EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().UninitDMServiceListener(); @@ -1299,6 +1302,7 @@ HWTEST_F(DeviceManagerServiceTest, BindDevice_003, testing::ext::TestSize.Level0 int32_t authType = 1; std::string deviceId = "1234"; std::string bindParam; + EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(ERR_DM_BIND_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } @@ -2059,6 +2063,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_001, testing::ext:: HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_002, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); EXPECT_NE(ret, DM_OK); } @@ -2475,6 +2480,7 @@ HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_003, testing::ext::Tes std::string pkgName = "pkgName_003"; DeviceManagerService::GetInstance().isImplsoLoaded_ = false; DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_CALL(*deviceManagerServiceImplMock_, StopAuthenticateDevice(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); EXPECT_EQ(ret, DM_OK); } @@ -2617,9 +2623,9 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_005, testing::ext::TestSize.Lev std::string networkId = "networkIdTest5"; DmDeviceInfo info; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); - EXPECT_EQ(ret, ERR_DM_FAILED); + EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } @@ -2637,6 +2643,14 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_004, testing::ext EXPECT_EQ(ret, DM_OK); } +HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName_004"; + EXPECT_CALL(*deviceManagerServiceImplMock_, StopAuthenticateDevice(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + /** * @tc.name: UnAuthenticateDevice_005 * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return @@ -2661,7 +2675,7 @@ HWTEST_F(DeviceManagerServiceTest, BindDevice_005, testing::ext::TestSize.Level0 std::string bindParam; EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } /** @@ -2678,7 +2692,7 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_005, testing::ext::TestSiz std::string deviceId = " 2345"; EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -2737,7 +2751,7 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_003, testing::ext::TestSiz { DmDeviceInfo info; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); EXPECT_EQ(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().softbusListener_ = nullptr; @@ -2754,7 +2768,7 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_004, testing::ext::TestSiz DmDeviceInfo info; DeletePermission(); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().softbusListener_ = nullptr; @@ -2785,7 +2799,7 @@ HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_001, testing::ext::TestSiz EXPECT_EQ(ret, ERR_DM_POINT_NULL); std::string deviceList; - uint16_t deviceTypeId = 0; + uint16_t deviceTypeId = 0 ; int32_t errcode = 1; DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); @@ -2793,6 +2807,44 @@ HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_001, testing::ext::TestSiz EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } + +HWTEST_F(DeviceManagerServiceTest, UnBindDevice_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, UnBindDevice_006, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_002, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index 00de35736..8a2afa326 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -31,6 +31,8 @@ #include "softbus_listener_mock.h" #include "app_manager_mock.h" #include "kv_adapter_manager_mock.h" +#include "device_manager_service_impl_mock.h" +#include "dm_softbus_cache_mock.h" namespace OHOS { namespace DistributedHardware { @@ -49,6 +51,10 @@ public: std::make_shared(); static inline std::shared_ptr kVAdapterManagerMock_ = std::make_shared(); + static inline std::shared_ptr deviceManagerServiceImplMock_ = + std::make_shared(); + static inline std::shared_ptr softbusCacheMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 4004a2948..2042f824f 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -67,7 +67,6 @@ void DeviceManagerServiceThreeTest::SetUpTestCase() DmDeviceManagerService::dmDeviceManagerService = deviceManagerServiceMock_; DmPermissionManager::dmPermissionManager = permissionManagerMock_; DmSoftbusListener::dmSoftbusListener = softbusListenerMock_; - DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; } @@ -76,7 +75,6 @@ void DeviceManagerServiceThreeTest::TearDownTestCase() deviceManagerServiceMock_ = nullptr; permissionManagerMock_ = nullptr; softbusListenerMock_ = nullptr; - softbusCacheMock_ = nullptr; deviceManagerServiceImplMock_ = nullptr; } @@ -255,7 +253,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, NotifyEvent_301, testing::ext::TestSize. std::string event; EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().NotifyEvent(pkgName, eventId, event); - EXPECT_NE(ret, ERR_DM_NOT_INIT); + EXPECT_EQ(ret, ERR_DM_NOT_INIT); } HWTEST_F(DeviceManagerServiceThreeTest, BindTarget_301, testing::ext::TestSize.Level0) @@ -329,52 +327,6 @@ HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSi int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); EXPECT_EQ(ret, ERR_DM_NOT_INIT); } - -HWTEST_F(DeviceManagerServiceThreeTest, UnBindDevice_302, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string deviceId = "1234"; - EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); - int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); - EXPECT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DeviceManagerServiceThreeTest, UnBindDevice_303, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string deviceId = "1234"; - EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); - EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); - int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); - EXPECT_EQ(ret, ERR_DM_FAILED); - - EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); - EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); - ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceManagerServiceThreeTest, StopAuthenticateDevice_302, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName_004"; - std::string msg = R"( - { - "type" : 0, - "userId" : 123, - "accountId" : "28776", - "tokenId" : 16, - "peerUdid" : "104", - "accountName" : "account_xiao" - })"; - EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); - DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); - EXPECT_CALL(*deviceManagerServiceImplMock_, StopAuthenticateDevice(_)).WillOnce(Return(ERR_DM_FAILED)); - int32_t ret = DeviceManagerService::GetInstance().StopAuthenticateDevice(pkgName); - EXPECT_EQ(ret, ERR_DM_FAILED); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_three.h b/test/unittest/UTTest_device_manager_service_three.h index 243286b3b..4f7c7666b 100644 --- a/test/unittest/UTTest_device_manager_service_three.h +++ b/test/unittest/UTTest_device_manager_service_three.h @@ -30,7 +30,6 @@ #include "permission_manager_mock.h" #include "softbus_listener_mock.h" #include "device_manager_service_mock.h" -#include "dm_softbus_cache_mock.h" #include "device_manager_service_impl_mock.h" namespace OHOS { @@ -48,8 +47,6 @@ public: std::make_shared(); static inline std::shared_ptr softbusListenerMock_ = std::make_shared(); - static inline std::shared_ptr softbusCacheMock_ = - std::make_shared(); static inline std::shared_ptr deviceManagerServiceImplMock_ = std::make_shared(); }; -- Gitee From d1b336292e018429f56f31e940ef364ef828b5fe Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 11 Nov 2024 17:03:42 +0800 Subject: [PATCH 383/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 3 +- .../UTTest_device_manager_service.cpp | 128 +----------------- .../UTTest_device_manager_service_two.cpp | 118 ++++++++++++++++ 3 files changed, 122 insertions(+), 127 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index c71f80db2..b2ef97ba2 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1210,7 +1210,8 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteServiceBindLevel_001, testing::ext::T std::string localUdid = "remoteDeviceId"; std::string remoteUdid="localDeviceId"; GetAccessControlProfiles(profiles); - DeviceProfileConnector::GetInstance().DeleteServiceBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + DeviceProfileConnector::GetInstance().DeleteServiceBindLevel(offlineParam, pkgName, profiles, + localUdid, remoteUdid); EXPECT_EQ(offlineParam.bindType, SERVICE); pkgName = "bundleName2"; diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 05c00b3e8..0fb948104 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1302,7 +1302,8 @@ HWTEST_F(DeviceManagerServiceTest, BindDevice_003, testing::ext::TestSize.Level0 int32_t authType = 1; std::string deviceId = "1234"; std::string bindParam; - EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(ERR_DM_BIND_INPUT_PARA_INVALID)); + EXPECT_CALL(*softbusListenerMock_, + GetTargetInfoFromCache(_, _, _)).WillOnce(Return(ERR_DM_BIND_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } @@ -2720,131 +2721,6 @@ HWTEST_F(DeviceManagerServiceTest, GetUdidHashByAnoyDeviceId_001, testing::ext:: EXPECT_EQ(ret, ERR_DM_FAILED); } #endif - -/** - * @tc.name: GetTrustedDeviceList_004 - * @tc.desc:Set the intFlag of GetTrustedDeviceList_004 to true; Return DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_004, testing::ext::TestSize.Level0) -{ - std::string pkgName = "ohos_test"; - std::string extra = "jdddd"; - std::vector deviceList; - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - DeviceManagerService::GetInstance().InitDMServiceListener(); - EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); - int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); - EXPECT_EQ(ret, ERR_DM_FAILED); - DeviceManagerService::GetInstance().UninitDMServiceListener(); - DeviceManagerService::GetInstance().softbusListener_ = nullptr; -} - -/** - * @tc.name: GetLocalDeviceInfo_003 - * @tc.desc: The return value is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_003, testing::ext::TestSize.Level0) -{ - DmDeviceInfo info; - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(ERR_DM_FAILED)); - int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); - EXPECT_EQ(ret, ERR_DM_FAILED); - DeviceManagerService::GetInstance().softbusListener_ = nullptr; -} - -/** - * @tc.name: GetLocalDeviceInfo_004 - * @tc.desc: The return value is ERR_DM_FAILED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_004, testing::ext::TestSize.Level0) -{ - DmDeviceInfo info; - DeletePermission(); - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(DM_OK)); - int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); - EXPECT_EQ(ret, DM_OK); - DeviceManagerService::GetInstance().softbusListener_ = nullptr; -} - -HWTEST_F(DeviceManagerServiceTest, BindTarget_007, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - PeerTargetId targetId; - targetId.wifiIp = "wifi_Ip"; - std::map bindParam; - std::string key = PARAM_KEY_TARGET_ID; - std::string value = "186"; - bindParam.insert(std::make_pair(key, value)); - int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_001, testing::ext::TestSize.Level0) -{ - std::string localDeviceName; - int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); - - localDeviceName = "localDeviceName_001"; - DeviceManagerService::GetInstance().softbusListener_ = nullptr; - ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); - EXPECT_EQ(ret, ERR_DM_POINT_NULL); - - std::string deviceList; - uint16_t deviceTypeId = 0 ; - int32_t errcode = 1; - DeviceManagerService::GetInstance().HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName); - EXPECT_EQ(ret, DM_OK); - DeviceManagerService::GetInstance().softbusListener_ = nullptr; -} - -HWTEST_F(DeviceManagerServiceTest, UnBindDevice_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string deviceId = "1234"; - EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); - int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); - EXPECT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DeviceManagerServiceTest, UnBindDevice_006, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string deviceId = "1234"; - EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); - EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); - int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); - EXPECT_EQ(ret, ERR_DM_FAILED); - - EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); - EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); - ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); - EXPECT_EQ(ret, DM_OK); -} - -HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_002, testing::ext::TestSize.Level0) -{ - DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); - DeviceManagerService::GetInstance().LoadHardwareFwkService(); - EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); - DeviceManagerService::GetInstance().LoadHardwareFwkService(); - DeviceManagerService::GetInstance().softbusListener_ = nullptr; - EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 74a978d83..535708122 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -414,6 +414,124 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_202, testing::ext::Test int32_t ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } + +/** + * @tc.name: GetTrustedDeviceList_204 + * @tc.desc:Set the intFlag of GetTrustedDeviceList_004 to true; Return DM_OK + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_204, testing::ext::TestSize.Level0) +{ + std::string pkgName = "ohos_test"; + std::string extra = "jdddd"; + std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().UninitDMServiceListener(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: GetLocalDeviceInfo_203 + * @tc.desc: The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_203, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, ERR_DM_FAILED); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +/** + * @tc.name: GetLocalDeviceInfo_204 + * @tc.desc: The return value is ERR_DM_FAILED + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_204, testing::ext::TestSize.Level0) +{ + DmDeviceInfo info; + DeletePermission(); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + targetId.wifiIp = "wifi_Ip"; + std::map bindParam; + std::string key = PARAM_KEY_TARGET_ID; + std::string value = "186"; + bindParam.insert(std::make_pair(key, value)); + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_201, testing::ext::TestSize.Level0) +{ + std::string localDeviceName = "localDeviceName_201"; + std::string localDisplayName = "localDisplayName_201"; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} + +HWTEST_F(DeviceManagerServiceTest, UnBindDevice_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); + int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_201, testing::ext::TestSize.Level0) +{ + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From c098290b52b968072c0eb1b3f6848acb927b5ddb Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 11 Nov 2024 18:38:01 +0800 Subject: [PATCH 384/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 44 --------------- .../UTTest_device_manager_service_two.cpp | 55 ++++++++++++++++++- 2 files changed, 52 insertions(+), 47 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 0fb948104..dafa5e490 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2652,50 +2652,6 @@ HWTEST_F(DeviceManagerServiceTest, StopAuthenticateDevice_004, testing::ext::Tes EXPECT_EQ(ret, ERR_DM_FAILED); } -/** - * @tc.name: UnAuthenticateDevice_005 - * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return - * value is SOFTBUS_IPC_ERR - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string networkId = "12345"; - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); - EXPECT_EQ(ret, ERR_DM_FAILED); -} - -HWTEST_F(DeviceManagerServiceTest, BindDevice_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - int32_t authType = 1; - std::string deviceId = "1234"; - std::string bindParam; - EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); - int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: AuthenticateDevice_005 - * @tc.desc: Set intFlag for GAuthenticateDevice to True and deviceId to null; Return ERR_DM_BIND_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_005, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - std::string extra = "jdddd"; - int32_t authType = 0; - std::string deviceId = " 2345"; - EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); - int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoyDeviceId_001, testing::ext::TestSize.Level0) { diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 535708122..542fd8763 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -86,6 +86,7 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestS DeletePermission(); const std::string extra; std::vector deviceList; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; int32_t ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, ERR_DM_POINT_NULL); } @@ -486,7 +487,7 @@ HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_201, testing::ext::TestSiz std::string localDeviceName = "localDeviceName_201"; std::string localDisplayName = "localDisplayName_201"; DeviceManagerService::GetInstance().softbusListener_ = nullptr; - int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); EXPECT_EQ(ret, ERR_DM_POINT_NULL); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); @@ -498,7 +499,9 @@ HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_201, testing::ext::TestSiz HWTEST_F(DeviceManagerServiceTest, UnBindDevice_201, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test"; - std::string deviceId = "1234"; + std::string deviceId = "123456"; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().IsDMServiceImplReady(); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); @@ -508,7 +511,9 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_201, testing::ext::TestSize.Leve HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test"; - std::string deviceId = "1234"; + std::string deviceId = "123456"; + DeviceManagerService::GetInstance().isImplsoLoaded_ = false; + DeviceManagerService::GetInstance().IsDMServiceImplReady(); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); @@ -532,6 +537,50 @@ HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_201, testing::ext::Tes DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } + +/** + * @tc.name: UnAuthenticateDevice_201 + * @tc.desc: Set intFlag for UnAuthenticateDevice to true and pkgName to com.ohos.test; set deviceId null ,The return + * value is SOFTBUS_IPC_ERR + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string networkId = "12345"; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceTest, BindDevice_205, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + int32_t authType = 1; + std::string deviceId = "1234"; + std::string bindParam; + EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: AuthenticateDevice_205 + * @tc.desc: Set intFlag for GAuthenticateDevice to True and deviceId to null; Return ERR_DM_BIND_INPUT_PARA_INVALID + * @tc.type: FUNC + * @tc.require: AR000GHSJK + */ +HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test"; + std::string extra = "jdddd"; + int32_t authType = 0; + std::string deviceId = " 2345"; + EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From eaae717cdbe227eeb9d98a857f30794331b77d40 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 11 Nov 2024 18:46:35 +0800 Subject: [PATCH 385/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service_two.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 542fd8763..5108b2436 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -487,7 +487,7 @@ HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_201, testing::ext::TestSiz std::string localDeviceName = "localDeviceName_201"; std::string localDisplayName = "localDisplayName_201"; DeviceManagerService::GetInstance().softbusListener_ = nullptr; - int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + int32_t ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); EXPECT_EQ(ret, ERR_DM_POINT_NULL); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); -- Gitee From 0e258ce0b8ce17247fc226251a2074a1fb8fdcef Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 11 Nov 2024 20:37:57 +0800 Subject: [PATCH 386/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service_two.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 5108b2436..667ffa6a3 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -550,6 +550,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); } -- Gitee From 35ae75a689da971e008fccb81a8e3bb448549ccb Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 12 Nov 2024 09:49:12 +0800 Subject: [PATCH 387/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 2 ++ .../UTTest_device_manager_service_two.cpp | 16 ++++++++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index dafa5e490..086892184 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -408,6 +408,7 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_003, testing::ext::TestS std::vector deviceList; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(DM_OK)); int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, extra, deviceList); EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().UninitDMServiceListener(); @@ -2639,6 +2640,7 @@ HWTEST_F(DeviceManagerServiceTest, GetEncryptedUuidByNetworkId_004, testing::ext DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); } EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); int32_t ret = DeviceManagerService::GetInstance().GetEncryptedUuidByNetworkId(pkgName, networkId, uuid); DeviceManagerService::GetInstance().softbusListener_ = nullptr; EXPECT_EQ(ret, DM_OK); diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 667ffa6a3..2b7c15602 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -81,6 +81,7 @@ void SetSetDnPolicyPermission() HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); DeviceManagerService::GetInstance().listener_ = std::make_shared(); DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); DeletePermission(); @@ -224,8 +225,8 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz { DmAccessCaller caller; DmAccessCallee callee; - EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); - EXPECT_CALL(*softbusListenerMock_, GetUuidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_EQ(ret, true); } @@ -251,6 +252,8 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz { DmAccessCaller caller; DmAccessCallee callee; + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); EXPECT_EQ(ret, true); } @@ -500,8 +503,7 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_201, testing::ext::TestSize.Leve { std::string pkgName = "com.ohos.test"; std::string deviceId = "123456"; - DeviceManagerService::GetInstance().isImplsoLoaded_ = false; - DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); @@ -512,14 +514,14 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Leve { std::string pkgName = "com.ohos.test"; std::string deviceId = "123456"; - DeviceManagerService::GetInstance().isImplsoLoaded_ = false; - DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, ERR_DM_FAILED); + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); @@ -561,6 +563,7 @@ HWTEST_F(DeviceManagerServiceTest, BindDevice_205, testing::ext::TestSize.Level0 int32_t authType = 1; std::string deviceId = "1234"; std::string bindParam; + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -578,6 +581,7 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz std::string extra = "jdddd"; int32_t authType = 0; std::string deviceId = " 2345"; + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -- Gitee From 16676cdf64421145b73bca8a9d224b4c5d75f897 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 12 Nov 2024 10:36:38 +0800 Subject: [PATCH 388/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichainconnector_fuzzer/hichain_connector_fuzzer.cpp | 2 +- test/unittest/UTTest_device_manager_service.cpp | 1 + test/unittest/UTTest_device_manager_service_two.cpp | 6 ++---- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index b62626826..3feab9906 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -147,7 +147,7 @@ void HiChainConnectorSecondFuzzTest(const uint8_t* data, size_t size) void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(int32_t))) { + if ((data == nullptr) || (size < sizeof(int64_t))) { return; } std::shared_ptr hichainConnector = std::make_shared(); diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 086892184..738809e6a 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2659,6 +2659,7 @@ HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoyDeviceId_001, testing::e { std::string udidHash; std::string result; + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("")); int32_t ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); EXPECT_EQ(ret, ERR_DM_FAILED); diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 2b7c15602..9b5113f74 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -225,8 +225,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckAccessControl_201, testing::ext::TestSiz { DmAccessCaller caller; DmAccessCallee callee; - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); bool ret = DeviceManagerService::GetInstance().CheckAccessControl(caller, callee); EXPECT_EQ(ret, true); } @@ -252,8 +251,7 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_201, testing::ext::TestSiz { DmAccessCaller caller; DmAccessCallee callee; - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); bool ret = DeviceManagerService::GetInstance().CheckIsSameAccount(caller, callee); EXPECT_EQ(ret, true); } -- Gitee From 4530d739460f214d8183e2d801a02a236466a45f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Tue, 12 Nov 2024 17:02:06 +0800 Subject: [PATCH 389/520] =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E5=86=85=E5=AD=98?= =?UTF-8?q?=E5=A0=86=E7=A7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/src/ipc/standard/ipc_server_stub.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index c5dd20a76..1b04c48f0 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -42,6 +42,7 @@ DM_IMPLEMENT_SINGLE_INSTANCE(IpcServerStub); const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(&IpcServerStub::GetInstance()); constexpr int32_t DM_IPC_THREAD_NUM = 32; +constexpr int32_t MAX_CALLBACK_NUM = 5000; IpcServerStub::IpcServerStub() : SystemAbility(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, true) { @@ -240,6 +241,10 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< if (!listener->AsObject()->AddDeathRecipient(appRecipient)) { LOGE("AddDeathRecipient Failed"); } + if (dmListener_.size() > MAX_CALLBACK_NUM || appRecipient_.size() > MAX_CALLBACK_NUM) { + LOGE("dmListener_ or appRecipient_ size exceed the limit!"); + return ERR_DM_FAILED; + } dmListener_[pkgName] = listener; appRecipient_[pkgName] = appRecipient; LOGD("Register listener complete."); -- Gitee From 7eba1f72c397477e62ece6c1a0f6cacc13aee7e5 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 13 Nov 2024 14:24:58 +0800 Subject: [PATCH 390/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/BUILD.gn | 3 + .../UTTest_device_manager_service_impl.cpp | 236 +++++++++++++++++- .../UTTest_device_manager_service_impl.h | 9 + .../mock/deviceprofile_connector_mock.cpp | 16 ++ .../mock/deviceprofile_connector_mock.h | 6 + .../mock/dm_device_state_manager_mock.cpp | 33 +++ .../mock/dm_device_state_manager_mock.h | 42 ++++ .../mock/mine_hichain_connector_mock.cpp | 28 +++ .../mock/mine_hichain_connector_mock.h | 40 +++ test/unittest/mock/softbus_connector_mock.cpp | 29 +++ test/unittest/mock/softbus_connector_mock.h | 40 +++ 11 files changed, 480 insertions(+), 2 deletions(-) create mode 100644 test/unittest/mock/dm_device_state_manager_mock.cpp create mode 100644 test/unittest/mock/dm_device_state_manager_mock.h create mode 100644 test/unittest/mock/mine_hichain_connector_mock.cpp create mode 100644 test/unittest/mock/mine_hichain_connector_mock.h create mode 100644 test/unittest/mock/softbus_connector_mock.cpp create mode 100644 test/unittest/mock/softbus_connector_mock.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 502a08926..4ff2624b9 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -972,6 +972,9 @@ ohos_unittest("UTTest_device_manager_service_impl") { "${servicesimpl_path}/src/device_manager_service_impl.cpp", "UTTest_device_manager_service_impl.cpp", "mock/deviceprofile_connector_mock.cpp", + "mock/dm_device_state_manager_mock.cpp", + "mock/mine_hichain_connector_mock.cpp", + "mock/softbus_connector_mock.cpp", ] deps = [ ":device_manager_test_common" ] diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 86723fb07..3b96fb276 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -40,11 +40,17 @@ void DeviceManagerServiceImplTest::TearDown() void DeviceManagerServiceImplTest::SetUpTestCase() { DmDeviceProfileConnector::dmDeviceProfileConnector = deviceProfileConnectorMock_; + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock_; + DmDmDeviceStateManager::dmDeviceStateManager = dmDeviceStateManagerMock_; + DmMineHiChainConnector::dmMineHiChainConnector = mineHiChainConnectorMock_; } void DeviceManagerServiceImplTest::TearDownTestCase() { deviceProfileConnectorMock_ = nullptr; + softbusConnectorMock_ = nullptr; + dmDeviceStateManagerMock_ = nullptr; + mineHiChainConnectorMock_ = nullptr; } namespace { @@ -354,6 +360,7 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L EXPECT_CALL(*deviceProfileConnectorMock_, HandleAccountLogoutEvent(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); deviceManagerServiceImpl_->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid); + EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(DM_OK)); int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); EXPECT_EQ(ret, DM_OK); } @@ -486,6 +493,8 @@ HWTEST_F(DeviceManagerServiceImplTest, ImportCredential_006, testing::ext::TestS if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*mineHiChainConnectorMock_, + ImportCredential(_, _)).WillOnce(Return(ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED)); int32_t ret = deviceManagerServiceImpl_->ImportCredential(pkgName, reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_CREDENTIAL_IMPORT_FAILED); } @@ -917,6 +926,10 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceStatusChange_004, testing::ex if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + deviceManagerServiceImpl_->HandleDeviceStatusChange(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); deviceManagerServiceImpl_->HandleDeviceStatusChange(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } @@ -1128,6 +1141,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetUdidHashByNetWorkId_003, testing::ext: if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_IPC_ERR)); int32_t ret = deviceManagerServiceImpl_->GetUdidHashByNetWorkId(networkId, deviceId); EXPECT_TRUE(CheckSoftbusRes(ret)); } @@ -1256,6 +1270,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetGroupType_003, testing::ext::TestSize. if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(SOFTBUS_INVALID_PARAM)); int32_t ret = deviceManagerServiceImpl_->GetGroupType(deviceList); EXPECT_EQ(ret, SOFTBUS_INVALID_PARAM); } @@ -1610,8 +1625,6 @@ HWTEST_F(DeviceManagerServiceImplTest, ProcessAppUnintall_103, testing::ext::Tes std::string appId; int32_t accessTokenId = 1001; std::vector profiles; - DmDeviceInfo devInfo; - deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); AddAccessControlProfileFirst(profiles); EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); if (deviceManagerServiceImpl_->hiChainConnector_ == nullptr) { @@ -1637,6 +1650,225 @@ HWTEST_F(DeviceManagerServiceImplTest, StopAuthenticateDevice_102, testing::ext: int ret = deviceManagerServiceImpl_->StopAuthenticateDevice(pkgName); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DeviceManagerServiceImplTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + std::string srcUdid = ""; + DmAccessCallee callee; + std::string sinkUdid = ""; + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + int ret = deviceManagerServiceImpl_->CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceImplTest, CheckAccessControl_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + std::string srcUdid = ""; + DmAccessCallee callee; + std::string sinkUdid = ""; + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + int ret = deviceManagerServiceImpl_->CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, ERR_DM_FAILED); +} + +HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceScreenStatusChange_001, testing::ext::TestSize.Level0) +{ + DmDeviceInfo devInfo; + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(INVALIED_TYPE)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(IDENTICAL_ACCOUNT_TYPE)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + std::vector pkgNameVec; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + pkgNameVec.push_back("pkgName"); + pkgNameVec.push_back("bundleName"); + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetUdidHashByNetWorkId_004, testing::ext::TestSize.Level0) +{ + const char *networkId = "networkId"; + std::string deviceId = "deviceId"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = deviceManagerServiceImpl_->GetUdidHashByNetWorkId(networkId, deviceId); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_003, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(ERR_DM_FAILED)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + deviceManagerServiceImpl_->isCredentialType_.store(true); + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(INVALIED_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + deviceManagerServiceImpl_->isCredentialType_.store(false); + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(IDENTICAL_ACCOUNT_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(DEVICE_PEER_TO_PEER_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(DEVICE_ACROSS_ACCOUNT_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + std::vector pkgNameVec; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + pkgNameVec.push_back("pkgName"); + pkgNameVec.push_back("bundleName"); + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + std::vector pkgNameVec1; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec1)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_003, testing::ext::TestSize.Level0) +{ + DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; + DmDeviceInfo devInfo; + strcpy_s(devInfo.networkId, sizeof(devInfo.networkId) - 1, testID.c_str()); + devInfo.networkId[sizeof(devInfo.networkId) - 1] = '\0'; + if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("")); + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + + DmOfflineParam offlineParam; + offlineParam.leftAclNumber = 0; + offlineParam.bindType = INVALID_TYPE; + EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); + EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + + offlineParam.bindType = IDENTICAL_ACCOUNT_TYPE; + EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); + EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + + offlineParam.bindType = DEVICE_PEER_TO_PEER_TYPE; + EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); + EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + + offlineParam.bindType = APP_PEER_TO_PEER_TYPE; + EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); + EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); + deviceManagerServiceImpl_->HandleOffline(devState, devInfo); + EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); +} + +HWTEST_F(DeviceManagerServiceImplTest, ImportCredential_007, testing::ext::TestSize.Level0) +{ + const std::string pkgName = "pkgNametest"; + std::string reqJsonStr = "reqJsonStr"; + std::string returnJsonStr; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + EXPECT_CALL(*mineHiChainConnectorMock_, ImportCredential(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = deviceManagerServiceImpl_->ImportCredential(pkgName, reqJsonStr, returnJsonStr); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_006, testing::ext::TestSize.Level0) +{ + std::string pkgName = "com.ohos.test_006"; + int32_t eventId = DM_NOTIFY_EVENT_ONDEVICEREADY; + std::string event = R"({"extra": {"deviceId": "789"}})"; + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + } + deviceManagerServiceImpl_->Initialize(listener_); + EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); + int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DeviceManagerServiceImplTest, GetGroupType_004, testing::ext::TestSize.Level0) +{ + DmDeviceInfo deviceInfo = { + .deviceId = "123456789101112131415", + .deviceName = "deviceName", + .deviceTypeId = 1 + }; + + DmDeviceInfo deviceInfo1 = { + .deviceId = "123456789689898989", + .deviceName = "deviceName1", + .deviceTypeId = 2 + }; + std::vector deviceList; + deviceList.push_back(deviceInfo); + deviceList.push_back(deviceInfo1); + if (deviceManagerServiceImpl_ == nullptr) { + deviceManagerServiceImpl_ = std::make_shared(); + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + int32_t ret = deviceManagerServiceImpl_->GetGroupType(deviceList); + EXPECT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.h b/test/unittest/UTTest_device_manager_service_impl.h index 087ce7f61..e41900940 100644 --- a/test/unittest/UTTest_device_manager_service_impl.h +++ b/test/unittest/UTTest_device_manager_service_impl.h @@ -24,6 +24,9 @@ #include "device_manager_service_impl.h" #include "deviceprofile_connector_mock.h" +#include "softbus_connector_mock.h" +#include "dm_device_state_manager_mock.h" +#include "mine_hichain_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -38,6 +41,12 @@ public: std::shared_ptr deviceManagerServiceImpl_ = std::make_shared(); static inline std::shared_ptr deviceProfileConnectorMock_ = std::make_shared(); + static inline std::shared_ptr softbusConnectorMock_ = + std::make_shared(); + static inline std::shared_ptr dmDeviceStateManagerMock_ = + std::make_shared(); + static inline std::shared_ptr mineHiChainConnectorMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index dc8a99601..27c22126f 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -45,5 +45,21 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, c return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid, localUdid); } + +uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::string requestDeviceId) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->CheckBindType(trustDeviceId, requestDeviceId); +} + +std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string &localDeviceId, + std::string &targetDeviceId) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->GetPkgNameFromAcl(localDeviceId, targetDeviceId); +} + +DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index 17464a708..51c57de43 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -33,6 +33,9 @@ public: const std::string &localUdid) = 0; virtual int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) = 0; + virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; + virtual std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId) = 0; + virtual DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) = 0; public: static inline std::shared_ptr dmDeviceProfileConnector = nullptr; }; @@ -44,6 +47,9 @@ public: MOCK_METHOD(std::string, HandleAppUnBindEvent, (int32_t, const std::string &, int32_t, const std::string &)); MOCK_METHOD(int32_t, HandleAccountLogoutEvent, (int32_t, const std::string &, const std::string &, const std::string &)); + MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); + MOCK_METHOD(std::vector, GetPkgNameFromAcl, (std::string &, std::string &)); + MOCK_METHOD(DmOfflineParam, GetOfflineParamFromAcl, (std::string, std::string)); }; } } diff --git a/test/unittest/mock/dm_device_state_manager_mock.cpp b/test/unittest/mock/dm_device_state_manager_mock.cpp new file mode 100644 index 000000000..d1625eea9 --- /dev/null +++ b/test/unittest/mock/dm_device_state_manager_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_device_state_manager_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { + +std::string DmDeviceStateManager::GetUdidByNetWorkId(std::string networkId) +{ + return DmDmDeviceStateManager::dmDeviceStateManager->GetUdidByNetWorkId(networkId); +} + +int32_t DmDeviceStateManager::ProcNotifyEvent(const int32_t eventId, const std::string &deviceId) +{ + return DmDmDeviceStateManager::dmDeviceStateManager->ProcNotifyEvent(eventId, deviceId); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_device_state_manager_mock.h b/test/unittest/mock/dm_device_state_manager_mock.h new file mode 100644 index 000000000..cc90c2647 --- /dev/null +++ b/test/unittest/mock/dm_device_state_manager_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DM_DEVICE_STATE_MANAGER_MOCK_H +#define OHOS_DM_DEVICE_STATE_MANAGER_MOCK_H + +#include +#include + +#include "dm_device_state_manager.h" + +namespace OHOS { +namespace DistributedHardware { +class DmDmDeviceStateManager { +public: + virtual ~DmDmDeviceStateManager() = default; +public: + virtual std::string GetUdidByNetWorkId(std::string networkId) = 0; + virtual int32_t ProcNotifyEvent(const int32_t eventId, const std::string &deviceId) = 0; +public: + static inline std::shared_ptr dmDeviceStateManager = nullptr; +}; + +class DmDeviceStateManagerMock : public DmDmDeviceStateManager { +public: + MOCK_METHOD(std::string, GetUdidByNetWorkId, (std::string)); + MOCK_METHOD(int32_t, ProcNotifyEvent, (const int32_t, const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/mine_hichain_connector_mock.cpp b/test/unittest/mock/mine_hichain_connector_mock.cpp new file mode 100644 index 000000000..ae4d527f6 --- /dev/null +++ b/test/unittest/mock/mine_hichain_connector_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mine_hichain_connector_mock.h" +#include "dm_softbus_cache_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int MineHiChainConnector::ImportCredential(std::string reqJsonStr, std::string &returnJsonStr) +{ + return DmMineHiChainConnector::dmMineHiChainConnector->ImportCredential(reqJsonStr, returnJsonStr); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/mine_hichain_connector_mock.h b/test/unittest/mock/mine_hichain_connector_mock.h new file mode 100644 index 000000000..01aabe9ef --- /dev/null +++ b/test/unittest/mock/mine_hichain_connector_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_MINE_HICHAIN_CONNECTOR_MOCK_H +#define OHOS_MINE_HICHAIN_CONNECTOR_MOCK_H + +#include +#include + +#include "mine_hichain_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmMineHiChainConnector { +public: + virtual ~DmMineHiChainConnector() = default; +public: + virtual int ImportCredential(std::string reqJsonStr, std::string &returnJsonStr) = 0; +public: + static inline std::shared_ptr dmMineHiChainConnector = nullptr; +}; + +class MineHiChainConnectorMock : public DmMineHiChainConnector { +public: + MOCK_METHOD(int, ImportCredential, (std::string, std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp new file mode 100644 index 000000000..69103fb6b --- /dev/null +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string &udid) +{ + return DmSoftbusConnector::dmSoftbusConnector->GetUdidByNetworkId(networkId, udid); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h new file mode 100644 index 000000000..51fe29690 --- /dev/null +++ b/test/unittest/mock/softbus_connector_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_SOFTBUS_CONNECTOR_MOCK_H +#define OHOS_SOFTBUS_CONNECTOR_MOCK_H + +#include +#include + +#include "softbus_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmSoftbusConnector { +public: + virtual ~DmSoftbusConnector() = default; +public: + virtual int32_t GetUdidByNetworkId(const char *networkId, std::string &udid) = 0; +public: + static inline std::shared_ptr dmSoftbusConnector = nullptr; +}; + +class SoftbusConnectorMock : public DmSoftbusConnector { +public: + MOCK_METHOD(int32_t, GetUdidByNetworkId, (const char *, std::string &)); +}; +} +} +#endif -- Gitee From 884f8914ec2a67e034d924baf634b23d66a1e7f5 Mon Sep 17 00:00:00 2001 From: liuth <@lzq> Date: Wed, 30 Oct 2024 17:23:31 +0800 Subject: [PATCH 391/520] =?UTF-8?q?[cj]:=20=E4=BB=93=E9=A2=89FFI=E5=B1=82?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E5=8F=8A=E5=85=B6=E5=AE=9E=E7=8E=B0.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Change-Id: If393b7b70f1c609d004d823d63e301588ece0bd4 Signed-off-by: liuth <948939870@qq.com> --- BUILD.gn | 1 + README.md | 1 + README_zh.md | 1 + interfaces/cj/BUILD.gn | 75 ++ interfaces/cj/include/device_manager_ffi.h | 70 ++ interfaces/cj/include/device_manager_impl.h | 102 +++ interfaces/cj/include/device_manager_utils.h | 133 +++ interfaces/cj/src/device_manager_ffi.cpp | 136 +++ interfaces/cj/src/device_manager_impl.cpp | 881 +++++++++++++++++++ interfaces/cj/src/device_manager_utils.cpp | 224 +++++ 10 files changed, 1624 insertions(+) create mode 100644 interfaces/cj/BUILD.gn create mode 100644 interfaces/cj/include/device_manager_ffi.h create mode 100644 interfaces/cj/include/device_manager_impl.h create mode 100644 interfaces/cj/include/device_manager_utils.h create mode 100644 interfaces/cj/src/device_manager_ffi.cpp create mode 100644 interfaces/cj/src/device_manager_impl.cpp create mode 100644 interfaces/cj/src/device_manager_utils.cpp diff --git a/BUILD.gn b/BUILD.gn index 71aed6844..f35ac3830 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -59,6 +59,7 @@ if (defined(ohos_lite)) { } group("device_manager_fwk") { deps = [ + "interfaces/cj:cj_distributed_device_manager_ffi", "interfaces/inner_kits/native_cpp:devicemanagersdk", "interfaces/kits:devicemanager_native_js", ] diff --git a/README.md b/README.md index e5359e382..db56f0a48 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ foundation/distributedhardware/device_manager │ └── resources # Resource configuration files for PIN display ServiceExtensionAbility ├── figures ├── interfaces +| ├── cj # Cangjie FFI interfaces and their implementation │ ├── inner_kits # Internal interfaces and their implementation │ │ └── native_cpp # Internal native interfaces and their implementation │ │ ├── include diff --git a/README_zh.md b/README_zh.md index a69927fa1..33fd30bc9 100644 --- a/README_zh.md +++ b/README_zh.md @@ -38,6 +38,7 @@ foundation/distributedhardware/distributedhardware_device_manager │ └── resources # DM PIN码显示ServiceExtensionAbility相关资源配置文件目录 ├── figures ├── interfaces +| ├── cj # 仓颉接口ffi层实现存放目录 │ ├── inner_kits # 内部接口及实现存放目录 │ │ └── native_cpp # 内部native接口及实现存放目录 │ │ ├── include diff --git a/interfaces/cj/BUILD.gn b/interfaces/cj/BUILD.gn new file mode 100644 index 000000000..9a245a111 --- /dev/null +++ b/interfaces/cj/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2024 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +ohos_shared_library("cj_distributed_device_manager_ffi") { + branch_protector_ret = "pac_ret" + + sanitize = { + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + integer_overflow = true + ubsan = true + } + + cflags = [ + "-fdata-sections", + "-ffunction-sections", + "-fvisibility=hidden", + ] + + include_dirs = [ + "include", + "${common_path}/include", + "${common_path}/include/ipc", + "${innerkits_path}/native_cpp/include", + "${innerkits_path}/native_cpp/include/ipc", + "${innerkits_path}/native_cpp/include/ipc/standard", + ] + + sources = [ + "${common_path}/src/dm_anonymous.cpp", + "${common_path}/src/dm_error_message.cpp", + "src/device_manager_ffi.cpp", + "src/device_manager_impl.cpp", + "src/device_manager_utils.cpp", + ] + + deps = [ "${innerkits_path}/native_cpp:devicemanagersdk" ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"cj_distrubuted_devicemanager\"", + "LOG_DOMAIN=0xD004111", + ] + + external_deps = [ + "access_token:libtokenid_sdk", + "bounds_checking_function:libsec_shared", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "json:nlohmann_json_static", + "napi:cj_bind_ffi", + "napi:cj_bind_native", + ] + + innerapi_tags = [ "platformsdk" ] + subsystem_name = "distributedhardware" + part_name = "device_manager" +} diff --git a/interfaces/cj/include/device_manager_ffi.h b/interfaces/cj/include/device_manager_ffi.h new file mode 100644 index 000000000..f29e16120 --- /dev/null +++ b/interfaces/cj/include/device_manager_ffi.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICE_MANAGER_FFI_H +#define OHOS_DEVICE_MANAGER_FFI_H + +#include "cj_common_ffi.h" +#include "ffi_remote_data.h" + +extern "C" { +typedef struct { + char *deviceId; + char *deviceName; + uint16_t deviceType; + char *networkId; +} FfiDeviceBasicInfo; + +typedef struct { + FfiDeviceBasicInfo *head; + int64_t size; +} FfiDeviceBasicInfoArray; + +FFI_EXPORT int64_t FfiOHOSDistributedDeviceManagerCreateDeviceManager(const char *name, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerReleaseDeviceManager(int64_t id, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerGetAvailableDeviceList( + int64_t id, FfiDeviceBasicInfoArray *deviceInfoList, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerFreeDeviceInfoList(FfiDeviceBasicInfoArray deviceInfoList); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceNetworkId(int64_t id, int32_t *errCode); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceName(int64_t id, int32_t *errCode); + +FFI_EXPORT int32_t FfiOHOSDistributedDeviceManagerGetLocalDeviceType(int64_t id, int32_t *errCode); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceId(int64_t id, int32_t *errCode); + +FFI_EXPORT const char *FfiOHOSDistributedDeviceManagerGetDeviceName( + int64_t id, const char *networkId, int32_t *errCode); + +FFI_EXPORT int32_t FfiOHOSDistributedDeviceManagerGetDeviceType(int64_t id, const char *networkId, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerStartDiscovering(int64_t id, const char *extra, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerStopDiscovering(int64_t id, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerBindTarget(int64_t id, const char *deviceId, const char *bindParam, + bool isMetaType, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerUnbindTarget(int64_t id, const char *deviceId, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerOn(int64_t id, const char *type, void *callback, int32_t *errCode); + +FFI_EXPORT void FfiOHOSDistributedDeviceManagerOff(int64_t id, const char *type, int32_t *errCode); +} + +#endif // OHOS_DEVICE_MANAGER_FFI_H diff --git a/interfaces/cj/include/device_manager_impl.h b/interfaces/cj/include/device_manager_impl.h new file mode 100644 index 000000000..30d8cd6c2 --- /dev/null +++ b/interfaces/cj/include/device_manager_impl.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICE_MANAGER_IMPL_H +#define OHOS_DEVICE_MANAGER_IMPL_H + +#include +#include +#include +#include + +#include "ffi_remote_data.h" + +#include "device_manager_ffi.h" +#include "device_manager_utils.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerFfiImpl : public OHOS::FFI::FFIData { +public: + explicit DeviceManagerFfiImpl(const std::string &bundleName, int32_t *errCode); + ~DeviceManagerFfiImpl() override = default; + + static DeviceManagerFfiImpl *GetDeviceManagerFfi(std::string &bundleName); + + int32_t ReleaseDeviceManager(); + int32_t GetAvailableDeviceList(FfiDeviceBasicInfoArray &deviceInfoList); + static void DeviceListFree(FfiDeviceBasicInfoArray &deviceInfoList, int64_t size = -1); + int32_t GetLocalDeviceNetworkId(const char *&networkId); + int32_t GetLocalDeviceName(const char *&deviceName); + int32_t GetLocalDeviceType(int32_t &deviceType); + int32_t GetLocalDeviceId(const char *&deviceId); + int32_t GetDeviceName(const std::string &networkId, const char *&deviceName); + int32_t GetDeviceType(const std::string &networkId, int32_t &deviceType); + int32_t StartDiscovering(const std::string &extra); + int32_t StopDiscovering(); + int32_t BindTarget(const std::string &deviceId, const std::string &bindParam, bool isMetaType); + int32_t UnbindTarget(const std::string &deviceId); + int32_t EventOn(const std::string &type, void *callback); + int32_t EventOff(const std::string &type); + + void OnDeviceStatusChange(int32_t action, const DmDeviceBasicInfo &deviceBasicInfo); + void OnDeviceNameChange(const std::string &deviceName); + void OnDeviceFound(uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo); + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason); + void OnPublishResult(int32_t publishId, int32_t publishResult); + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason); + void OnDmUiCall(const std::string ¶mJson); + +private: + void ClearBundleCallbacks(); + static int32_t Transform2FfiDeviceBasicInfo(const DmDeviceBasicInfo &in, FfiDeviceBasicInfo &out); + int32_t BindTargetWarpper(const std::string &deviceId, + const std::string &bindParam, std::shared_ptr callback); + int32_t WaitForCallbackCv(); + + int32_t RegisterDevStatusCallback(); + int32_t RegisterDiscoveryCallback(); + int32_t RegisterPublishCallback(); + int32_t RegisterReplyCallback(); + + int32_t ReleaseDevStatusCallback(); + int32_t ReleaseDiscoveryCallback(); + int32_t ReleasePublishCallback(); + int32_t ReleaseReplyCallback(); + + void RegisterCallbackByType(const std::string &type, void *callback); + void Off(const std::string &type); + + inline static void FreeDeviceInfo(const FfiDeviceBasicInfo &info) + { + free(info.deviceId); + free(info.deviceName); + free(info.networkId); + }; + + std::string bundleName_; + std::function deviceStateChangedCallback; + std::function discoverSuccessCallback; + std::function deviceNameChangedCallback; + std::function deviceDiscoverFailedCallback; + std::mutex callbackLock; + + std::condition_variable callbackFinishedCv; + std::mutex callbackFinishedMutex; + bool callbackFinished = false; + std::atomic errCode_ = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DEVICE_MANAGER_IMPL_H diff --git a/interfaces/cj/include/device_manager_utils.h b/interfaces/cj/include/device_manager_utils.h new file mode 100644 index 000000000..871634e8a --- /dev/null +++ b/interfaces/cj/include/device_manager_utils.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DEVICE_MANAGER_UTILS_H +#define OHOS_DEVICE_MANAGER_UTILS_H + +#include + +#include "nlohmann/json.hpp" + +#include "device_manager_callback.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { + +enum DmFfiDevStatusChange { UNKNOWN = 0, AVAILABLE = 1, UNAVAILABLE = 2, CHANGE = 3}; + +class DmFfiInitCallback : public DmInitCallback { +public: + explicit DmFfiInitCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiInitCallback() override = default; + void OnRemoteDied() override; + +private: + std::string bundleName_; +}; + +class DmFfiDeviceStatusCallback : public DeviceStatusCallback { +public: + explicit DmFfiDeviceStatusCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiDeviceStatusCallback() override = default; + void OnDeviceOnline(const DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceOffline(const DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDeviceChanged(const DmDeviceBasicInfo &deviceBasicInfo) override; +private: + std::string bundleName_; +}; + +class DmFfiDiscoveryCallback : public DiscoveryCallback { +public: + explicit DmFfiDiscoveryCallback(const std::string &bundleName): refCount_(0), bundleName_(bundleName) + { + } + ~DmFfiDiscoveryCallback() override = default; + void OnDeviceFound(uint16_t subscribeId, + const OHOS::DistributedHardware::DmDeviceBasicInfo &deviceBasicInfo) override; + void OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) override; + void OnDiscoverySuccess(uint16_t subscribeId) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); + +private: + std::atomic refCount_; + std::string bundleName_; +}; + +class DmFfiPublishCallback : public PublishCallback { +public: + explicit DmFfiPublishCallback(const std::string &bundleName): refCount_(0), bundleName_(bundleName) + { + } + ~DmFfiPublishCallback() override = default; + void OnPublishResult(int32_t publishId, int32_t publishResult) override; + void IncreaseRefCount(); + void DecreaseRefCount(); + int32_t GetRefCount(); + +private: + std::atomic refCount_; + std::string bundleName_; +}; + +class DmFfiDeviceManagerUiCallback : public DeviceManagerUiCallback { +public: + explicit DmFfiDeviceManagerUiCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiDeviceManagerUiCallback() override = default; + void OnCall(const std::string ¶mJson) override; + +private: + std::string bundleName_; +}; + +class DmFfiAuthenticateCallback : public AuthenticateCallback { +public: + explicit DmFfiAuthenticateCallback(const std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiAuthenticateCallback() override = default; + void OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override; + +private: + std::string bundleName_; +}; + +class DmFfiBindTargetCallback : public BindTargetCallback { +public: + explicit DmFfiBindTargetCallback(std::string &bundleName) : bundleName_(bundleName) + { + } + ~DmFfiBindTargetCallback() override = default; + void OnBindResult(const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; + +private: + std::string bundleName_; +}; + +const std::string &GetDeviceTypeById(DmDeviceType type); +char *MallocCStr(const char *in); +void InsertMapParames(nlohmann::json &bindParamObj, std::map &bindParamMap); +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_DEVICE_MANAGER_IMPL_H diff --git a/interfaces/cj/src/device_manager_ffi.cpp b/interfaces/cj/src/device_manager_ffi.cpp new file mode 100644 index 000000000..a6a0b9ca7 --- /dev/null +++ b/interfaces/cj/src/device_manager_ffi.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "device_manager_ffi.h" + +#include + +#include "device_manager.h" +#include "device_manager_impl.h" +#include "dm_log.h" + +int64_t FfiOHOSDistributedDeviceManagerCreateDeviceManager(const char *name, int32_t *errCode) +{ + auto deviceManager = OHOS::FFI::FFIData::Create( + std::string(name), errCode); + if (*errCode != 0) { + LOGE("deviceManager create fail, the errcode is %{public}d", *errCode); + delete static_cast(deviceManager); + return 0; + } + return deviceManager->GetID(); +} + +void FfiOHOSDistributedDeviceManagerReleaseDeviceManager(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->ReleaseDeviceManager(); +} + +void FfiOHOSDistributedDeviceManagerGetAvailableDeviceList( + int64_t id, FfiDeviceBasicInfoArray *deviceInfoList, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->GetAvailableDeviceList(*deviceInfoList); +} + +void FfiOHOSDistributedDeviceManagerFreeDeviceInfoList(FfiDeviceBasicInfoArray deviceInfoList) +{ + OHOS::DistributedHardware::DeviceManagerFfiImpl::DeviceListFree(deviceInfoList); +} + +const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceNetworkId(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *networkIdPtr = nullptr; + *errCode = instance->GetLocalDeviceNetworkId(networkIdPtr); + return networkIdPtr; +} + +const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceName(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *deviceName = nullptr; + *errCode = instance->GetLocalDeviceName(deviceName); + return deviceName; +} + +int32_t FfiOHOSDistributedDeviceManagerGetLocalDeviceType(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + int32_t deviceType = 0; + *errCode = instance->GetLocalDeviceType(deviceType); + return deviceType; +} + +const char *FfiOHOSDistributedDeviceManagerGetLocalDeviceId(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *deviceId = nullptr; + *errCode = instance->GetLocalDeviceId(deviceId); + return deviceId; +} + +const char *FfiOHOSDistributedDeviceManagerGetDeviceName(int64_t id, const char *networkId, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + const char *deviceName = nullptr; + *errCode = instance->GetDeviceName(networkId, deviceName); + return deviceName; +} + +int32_t FfiOHOSDistributedDeviceManagerGetDeviceType(int64_t id, const char *networkId, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + int32_t deviceType = 0; + *errCode = instance->GetDeviceType(networkId, deviceType); + return deviceType; +} + +void FfiOHOSDistributedDeviceManagerStartDiscovering(int64_t id, const char *extra, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->StartDiscovering(extra); +} + +void FfiOHOSDistributedDeviceManagerStopDiscovering(int64_t id, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->StopDiscovering(); +} + +void FfiOHOSDistributedDeviceManagerBindTarget( + int64_t id, const char *deviceId, const char *bindParam, bool isMetaType, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->BindTarget(deviceId, bindParam, isMetaType); +} + +void FfiOHOSDistributedDeviceManagerUnbindTarget(int64_t id, const char *deviceId, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->UnbindTarget(deviceId); +} + +void FfiOHOSDistributedDeviceManagerOn(int64_t id, const char *type, void *callback, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->EventOn(type, callback); +} + +void FfiOHOSDistributedDeviceManagerOff(int64_t id, const char *type, int32_t *errCode) +{ + auto instance = OHOS::FFI::FFIData::GetData(id); + *errCode = instance->EventOff(type); +} diff --git a/interfaces/cj/src/device_manager_impl.cpp b/interfaces/cj/src/device_manager_impl.cpp new file mode 100644 index 000000000..aee35808b --- /dev/null +++ b/interfaces/cj/src/device_manager_impl.cpp @@ -0,0 +1,881 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "device_manager_impl.h" + +#include +#include + +#include "cj_lambda.h" +#include "ipc_skeleton.h" + +#include "device_manager.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_error_message.h" +#include "dm_log.h" + +namespace OHOS::DistributedHardware { + +namespace { +std::map g_deviceManagerMap; +std::map> g_initCallbackMap; +std::map> g_deviceStatusCallbackMap; +std::map> g_DiscoveryCallbackMap; +std::map> g_publishCallbackMap; +std::map> g_authCallbackMap; +std::map> g_bindCallbackMap; +std::map> g_dmUiCallbackMap; + +std::mutex g_deviceManagerMapMutex; +std::mutex g_initCallbackMapMutex; +std::mutex g_deviceStatusCallbackMapMutex; +std::mutex g_discoveryCallbackMapMutex; +std::mutex g_publishCallbackMapMutex; +std::mutex g_authCallbackMapMutex; +std::mutex g_bindCallbackMapMutex; +std::mutex g_dmUiCallbackMapMutex; + +const int32_t DM_AUTH_REQUEST_SUCCESS_STATUS = 7; +const int32_t DM_FFI_BUF_LENGTH = 256; + +const std::string DM_FFI_EVENT_DEVICE_STATE_CHANGE = "deviceStateChange"; +const std::string DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS = "discoverSuccess"; +const std::string DM_FFI_EVENT_DEVICE_DISCOVER_FAIL = "discoverFailure"; +const std::string DM_FFI_EVENT_DEVICE_PUBLISH_SUCCESS = "publishSuccess"; +const std::string DM_FFI_EVENT_DEVICE_PUBLISH_FAIL = "publishFailure"; +const std::string DEVICE_MANAGER_FFI_CLASS_NAME = "DeviceManager"; +const std::string DM_FFI_EVENT_REPLY_RESULT = "replyResult"; +const std::string DM_FFI_EVENT_DEVICE_NAME_CHANGE = "deviceNameChange"; + +enum ErrorCode { + // OK + ERR_OK = 0, + // Permission verify failed. + ERR_NO_PERMISSION = 201, + // The caller is not a system application. + ERR_NOT_SYSTEM_APP = 202, + // Input parameter error. + ERR_INVALID_PARAMS = 401, + // Failed to execute the function. + DM_ERR_FAILED = 11600101, + // Failed to obtain the service. + DM_ERR_OBTAIN_SERVICE = 11600102, + // Authentication invalid. + DM_ERR_AUTHENTICALTION_INVALID = 11600103, + // Discovery invalid. + DM_ERR_DISCOVERY_INVALID = 11600104, + // Publish invalid. + DM_ERR_PUBLISH_INVALID = 11600105, +}; + +inline int32_t stringCheck(const std::string &str) +{ + if (str.size() == 0 || str.size() >= DM_FFI_BUF_LENGTH) { + return ERR_INVALID_PARAMS; + } + return ERR_OK; +} + +int32_t transformErrCode(const int32_t errCode) +{ + switch (errCode) { + case ERR_DM_NO_PERMISSION: + return ERR_NO_PERMISSION; + case ERR_DM_DISCOVERY_REPEATED: + return DM_ERR_DISCOVERY_INVALID; + case ERR_DM_PUBLISH_REPEATED: + return DM_ERR_PUBLISH_INVALID; + case ERR_DM_AUTH_BUSINESS_BUSY: + return DM_ERR_AUTHENTICALTION_INVALID; + case ERR_DM_INPUT_PARA_INVALID: + case ERR_DM_UNSUPPORTED_AUTH_TYPE: + return ERR_INVALID_PARAMS; + case ERR_DM_INIT_FAILED: + return DM_ERR_OBTAIN_SERVICE; + case ERR_NOT_SYSTEM_APP: + return ERR_NOT_SYSTEM_APP; + default: + return DM_ERR_FAILED; + } + return 0; +} + +inline void InsertIntItem(nlohmann::json &jsonObj, std::map &jsonMap, + const std::string &searchKey, const std::string &insertKey) +{ + if (IsInt32(jsonObj, searchKey)) { + int32_t value = jsonObj[searchKey].get(); + jsonMap.insert(std::pair(insertKey, std::to_string(value))); + } +} + +inline void InsertStringItem(nlohmann::json &jsonObj, std::map &jsonMap, + const std::string &searchKey, const std::string &insertKey) +{ + if (IsString(jsonObj, searchKey)) { + std::string value = jsonObj[searchKey].get(); + jsonMap.insert(std::pair(insertKey, value)); + } +} + +void InsertJsonParamesToMap(nlohmann::json &bindParamObj, std::map &bindParamMap) +{ + LOGI("Insert map parames start"); + InsertIntItem(bindParamObj, bindParamMap, AUTH_TYPE, PARAM_KEY_AUTH_TYPE); + InsertStringItem(bindParamObj, bindParamMap, APP_OPERATION, PARAM_KEY_APP_OPER); + InsertStringItem(bindParamObj, bindParamMap, CUSTOM_DESCRIPTION, PARAM_KEY_APP_DESC); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_TARGET_PKG_NAME, PARAM_KEY_TARGET_PKG_NAME); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_META_TYPE, PARAM_KEY_META_TYPE); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_PIN_CODE, PARAM_KEY_PIN_CODE); + InsertStringItem(bindParamObj, bindParamMap, PARAM_KEY_AUTH_TOKEN, PARAM_KEY_AUTH_TOKEN); + InsertIntItem(bindParamObj, bindParamMap, BIND_LEVEL, BIND_LEVEL); +} +} // namespace + +DeviceManagerFfiImpl::DeviceManagerFfiImpl(const std::string &bundleName, int32_t *errCode) : bundleName_(bundleName) +{ + *errCode = stringCheck(bundleName); + if (*errCode != 0) { + LOGE("CreateDeviceManager for bundleName %{public}s failed, ret %{public}d.", bundleName_.c_str(), *errCode); + return; + } + std::shared_ptr initCallback = std::make_shared(bundleName_); + *errCode = DeviceManager::GetInstance().InitDeviceManager(bundleName_, initCallback); + if (*errCode != 0) { + *errCode = transformErrCode(*errCode); + LOGE("CreateDeviceManager for bundleName %{public}s failed, ret %{public}d.", bundleName_.c_str(), *errCode); + return; + } + { + std::lock_guard autoLock(g_initCallbackMapMutex); + g_initCallbackMap[bundleName_] = initCallback; + } + + std::lock_guard autoLock(g_deviceManagerMapMutex); + g_deviceManagerMap[bundleName_] = this; +} + +int32_t DeviceManagerFfiImpl::ReleaseDeviceManager() +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + int ret = DeviceManager::GetInstance().UnInitDeviceManager(bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("ReleaseDeviceManager for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + ClearBundleCallbacks(); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetAvailableDeviceList(FfiDeviceBasicInfoArray &deviceInfoList) +{ + int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + if (ret != 0) { + return transformErrCode(ret); + } + std::vector result; + ret = DeviceManager::GetInstance().GetAvailableDeviceList(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetTrustedDeviceList for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + + if (result.size() == 0) { + return ERR_OK; + } + + deviceInfoList.head = static_cast(malloc(sizeof(FfiDeviceBasicInfo) * result.size())); + if (deviceInfoList.head == nullptr) { + LOGE("Malloc failed"); + return DM_ERR_FAILED; + } + deviceInfoList.size = result.size(); + for (decltype(result.size()) i = 0; i < result.size(); ++i) { + ret = Transform2FfiDeviceBasicInfo(result[i], deviceInfoList.head[i]); + if (ret != 0) { + DeviceListFree(deviceInfoList, i); + return ret; + } + } + return ERR_OK; +} + +void DeviceManagerFfiImpl::DeviceListFree(FfiDeviceBasicInfoArray &deviceInfoList, int64_t size) +{ + if (size == -1) { + size = deviceInfoList.size; + } + for (int32_t i = 0; i < size; ++i) { + FreeDeviceInfo(deviceInfoList.head[i]); + } + free(deviceInfoList.head); + deviceInfoList.head = nullptr; + deviceInfoList.size = 0; +} + +int32_t DeviceManagerFfiImpl::Transform2FfiDeviceBasicInfo(const DmDeviceBasicInfo &in, FfiDeviceBasicInfo &out) +{ + out.deviceId = MallocCStr(in.deviceId); + out.deviceName = MallocCStr(in.deviceName); + out.deviceType = in.deviceTypeId; + out.networkId = MallocCStr(in.networkId); + if (out.deviceId == nullptr || out.deviceName == nullptr || out.networkId == nullptr) { + FreeDeviceInfo(out); + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceNetworkId(const char *&networkId) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + std::string result; + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceNetWorkId(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceNetworkId for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceNetworkId networkId:%{public}s", GetAnonyString(result).c_str()); + + networkId = MallocCStr(result.c_str()); + if (networkId == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceName(const char *&deviceName) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + std::string result; + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceName(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceName for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceName deviceName:%{public}s", GetAnonyString(result).c_str()); + + deviceName = MallocCStr(result.c_str()); + if (deviceName == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceType(int32_t &deviceType) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceType(bundleName_, deviceType); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceType for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceType deviceType:%{public}d", deviceType); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetLocalDeviceId(const char *&deviceId) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + + std::string result; + int32_t ret = DeviceManager::GetInstance().GetLocalDeviceId(bundleName_, result); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetLocalDeviceId for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetLocalDeviceId deviceId:%{public}s", GetAnonyString(result).c_str()); + + deviceId = MallocCStr(result.c_str()); + if (deviceId == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetDeviceName(const std::string &networkId, const char *&deviceName) +{ + int32_t ret = stringCheck(networkId); + if (ret != 0) { + return ret; + } + std::string result; + ret = DeviceManager::GetInstance().GetDeviceName(bundleName_, networkId, result); + LOGI("DeviceManager::GetDeviceName getinstance return."); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetDeviceName for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetDeviceName deviceName:%{public}s", GetAnonyString(result).c_str()); + + deviceName = MallocCStr(result.c_str()); + if (deviceName == nullptr) { + return DM_ERR_FAILED; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::GetDeviceType(const std::string &networkId, int32_t &deviceType) +{ + int32_t ret = stringCheck(networkId); + if (ret != 0) { + return ret; + } + ret = DeviceManager::GetInstance().GetDeviceType(bundleName_, networkId, deviceType); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("GetDeviceType for failed, ret %{public}d", ret); + return ret; + } + LOGI("DeviceManager::GetDeviceType deviceType:%{public}d", deviceType); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::StartDiscovering(const std::string &extra) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + std::shared_ptr discoveryCallback = nullptr; + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + auto iter = g_DiscoveryCallbackMap.find(bundleName_); + if (iter == g_DiscoveryCallbackMap.end()) { + discoveryCallback = std::make_shared(bundleName_); + g_DiscoveryCallbackMap[bundleName_] = discoveryCallback; + } else { + discoveryCallback = iter->second; + } + } + uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID(); + int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(bundleName_, tokenId, extra, discoveryCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("Discovery failed, bundleName %{public}s, ret %{public}d", bundleName_.c_str(), ret); + discoveryCallback->OnDiscoveryFailed(static_cast(0), ret); + return ret; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::StopDiscovering() +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + uint64_t tokenId = OHOS::IPCSkeleton::GetSelfTokenID(); + int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(tokenId, bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("StopDeviceDiscovery for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::BindTarget(const std::string &deviceId, + const std::string &bindParam, const bool isMetaType) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + int32_t ret = stringCheck(deviceId); + if (ret != 0) { + return ret; + } + + callbackFinished = false; + if (isMetaType) { + std::shared_ptr bindTargetCallback = nullptr; + { + std::lock_guard autoLock(g_bindCallbackMapMutex); + auto iter = g_bindCallbackMap.find(bundleName_); + if (iter == g_bindCallbackMap.end()) { + bindTargetCallback = std::make_shared(bundleName_); + g_bindCallbackMap[bundleName_] = bindTargetCallback; + } else { + bindTargetCallback = iter->second; + } + } + int32_t ret = BindTargetWarpper(deviceId, bindParam, bindTargetCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("BindTarget for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return WaitForCallbackCv(); + } + + std::shared_ptr bindDeviceCallback = nullptr; + { + std::lock_guard autoLock(g_authCallbackMapMutex); + auto iter = g_authCallbackMap.find(bundleName_); + if (iter == g_authCallbackMap.end()) { + bindDeviceCallback = std::make_shared(bundleName_); + g_authCallbackMap[bundleName_] = bindDeviceCallback; + } else { + bindDeviceCallback = iter->second; + } + } + constexpr int32_t bindType = 1; + ret = DeviceManager::GetInstance().BindDevice(bundleName_, bindType, deviceId, bindParam, bindDeviceCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("BindDevice for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return WaitForCallbackCv(); +} + +int32_t DeviceManagerFfiImpl::WaitForCallbackCv() +{ + std::unique_lock autoLock(callbackFinishedMutex); + callbackFinishedCv.wait(autoLock, [this] { return this->callbackFinished; }); + LOGI("WaitForCallbackCv got notified, errCode is %{public}d", errCode_.load()); + return errCode_.load(); +} + +int32_t DeviceManagerFfiImpl::UnbindTarget(const std::string &deviceId) +{ + if (DeviceManager::GetInstance().CheckNewAPIAccessPermission() != 0) { + return ERR_NO_PERMISSION; + } + int32_t ret = stringCheck(deviceId); + if (ret != 0) { + return ret; + } + LOGI("UnBindDevice deviceId = %{public}s", GetAnonyString(deviceId).c_str()); + ret = DeviceManager::GetInstance().UnBindDevice(bundleName_, deviceId); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("UnBindDevice for bundleName %{public}s failed, ret %{public}d", bundleName_.c_str(), ret); + return ret; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::EventOn(const std::string &type, void *callback) +{ + int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + if (ret != 0) { + return transformErrCode(ret); + } + + LOGI("EventOn for bundleName %{public}s, eventType %{public}s ", bundleName_.c_str(), type.c_str()); + RegisterCallbackByType(type, callback); + + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE || type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + return RegisterDevStatusCallback(); + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS || type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + return RegisterDiscoveryCallback(); + } + + return ERR_INVALID_PARAMS; +} + +int32_t DeviceManagerFfiImpl::EventOff(const std::string &type) +{ + int32_t ret = DeviceManager::GetInstance().CheckNewAPIAccessPermission(); + if (ret != 0) { + return ret; + } + + LOGI("EventOff for bundleName %{public}s, eventType %{public}s ", bundleName_.c_str(), type.c_str()); + Off(type); + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE || type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + if (!deviceStateChangedCallback && !deviceNameChangedCallback) { + return ReleaseDevStatusCallback(); + } + return ERR_OK; + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS || type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + return ReleaseDiscoveryCallback(); + } + return ERR_INVALID_PARAMS; +} + + +void DeviceManagerFfiImpl::OnDeviceStatusChange(int32_t action, const DmDeviceBasicInfo &deviceBasicInfo) +{ + std::lock_guard autoLock(callbackLock); + if (deviceStateChangedCallback) { + auto ptr = static_cast(malloc(sizeof(FfiDeviceBasicInfo))); + if (ptr == nullptr) { + LOGE("OnDeviceStatusChange malloc FfiDeviceBasicInfo failed."); + return; + } + int32_t ret = Transform2FfiDeviceBasicInfo(deviceBasicInfo, *ptr); + if (ret != 0) { + LOGE("OnDeviceStatusChange failed to transform DmDeviceBasicInfo."); + return; + } + deviceStateChangedCallback(action, ptr); + FreeDeviceInfo(*ptr); + free(ptr); + } +} + +void DeviceManagerFfiImpl::OnDeviceNameChange(const std::string &deviceName) +{ + std::lock_guard autoLock(callbackLock); + if (deviceNameChangedCallback) { + char *cDeviceName = MallocCStr(deviceName.c_str()); + if (cDeviceName == nullptr) { + LOGE("OnDeviceNameChange malloc deviname failed."); + return; + } + deviceNameChangedCallback(cDeviceName); + free(cDeviceName); + } +} + +void DeviceManagerFfiImpl::OnDeviceFound(uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo) +{ + std::lock_guard autoLock(callbackLock); + if (discoverSuccessCallback) { + auto ptr = static_cast(malloc(sizeof(FfiDeviceBasicInfo))); + if (ptr == nullptr) { + LOGE("OnDeviceStatusChange malloc FfiDeviceBasicInfo failed."); + return; + } + int32_t ret = Transform2FfiDeviceBasicInfo(deviceBasicInfo, *ptr); + if (ret != 0) { + LOGE("OnDeviceStatusChange failed to transform DmDeviceBasicInfo."); + return; + } + discoverSuccessCallback(ptr); + FreeDeviceInfo(*ptr); + free(ptr); + } +} + +void DeviceManagerFfiImpl::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) +{ + std::lock_guard autoLock(callbackLock); + LOGI("OnDiscoveryFailed for subscribeId %{public}d", (int32_t)subscribeId); + if (deviceDiscoverFailedCallback) { + deviceDiscoverFailedCallback(failedReason); + } +} + +void DeviceManagerFfiImpl::OnPublishResult(int32_t publishId, int32_t publishResult) +{ + LOGI("OnPublishResult for publishId %{public}d, publishResult %{public}d", publishId, publishResult); +} + +void DeviceManagerFfiImpl::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) +{ + LOGI("OnAuthResult for status: %{public}d, reason: %{public}d", status, reason); + if (reason == DM_OK && (status <= STATUS_DM_CLOSE_PIN_INPUT_UI && status >= STATUS_DM_SHOW_AUTHORIZE_UI)) { + LOGI("update ui change, status: %{public}d, reason: %{public}d", status, reason); + return; + } + + if (status == DM_AUTH_REQUEST_SUCCESS_STATUS && reason == 0) { + LOGI("OnAuthResult success"); + errCode_ = ERR_OK; + } else { + LOGI("OnAuthResult failed"); + errCode_ = reason; + } + + std::lock_guard autoLock(g_authCallbackMapMutex); + g_authCallbackMap.erase(bundleName_); + callbackFinished = true; + callbackFinishedCv.notify_one(); +} + +void DeviceManagerFfiImpl::OnDmUiCall(const std::string ¶mJson) +{ + LOGI("OnCall for paramJson"); +} + +DeviceManagerFfiImpl *DeviceManagerFfiImpl::GetDeviceManagerFfi(std::string &bundleName) +{ + std::lock_guard autoLock(g_deviceManagerMapMutex); + auto iter = g_deviceManagerMap.find(bundleName); + if (iter == g_deviceManagerMap.end()) { + return nullptr; + } + return iter->second; +} + +void DeviceManagerFfiImpl::ClearBundleCallbacks() +{ + LOGI("ClearBundleCallbacks start for bundleName %{public}s", bundleName_.c_str()); + { + std::lock_guard autoLock(g_deviceManagerMapMutex); + g_deviceManagerMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_initCallbackMapMutex); + g_initCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + g_deviceStatusCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + g_DiscoveryCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_publishCallbackMapMutex); + g_publishCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_authCallbackMapMutex); + g_authCallbackMap.erase(bundleName_); + } + { + std::lock_guard autoLock(g_bindCallbackMapMutex); + g_bindCallbackMap.erase(bundleName_); + } + return; +} + +int32_t DeviceManagerFfiImpl::BindTargetWarpper(const std::string &deviceId, + const std::string &bindParam, std::shared_ptr callback) +{ + if (bindParam.empty()) { + return ERR_INVALID_PARAMS; + } + nlohmann::json bindParamObj = nlohmann::json::parse(bindParam, nullptr, false); + if (bindParamObj.is_discarded()) { + return ERR_INVALID_PARAMS; + } + PeerTargetId targetId; + targetId.deviceId = deviceId; + if (IsString(bindParamObj, PARAM_KEY_BR_MAC)) { + targetId.brMac = bindParamObj[PARAM_KEY_BR_MAC].get(); + } + if (IsString(bindParamObj, PARAM_KEY_BLE_MAC)) { + targetId.bleMac = bindParamObj[PARAM_KEY_BLE_MAC].get(); + } + if (IsString(bindParamObj, PARAM_KEY_WIFI_IP)) { + targetId.wifiIp = bindParamObj[PARAM_KEY_WIFI_IP].get(); + } + if (IsInt32(bindParamObj, PARAM_KEY_WIFI_PORT)) { + targetId.wifiPort = (uint16_t)(bindParamObj[PARAM_KEY_WIFI_PORT].get()); + } + + std::map bindParamMap; + InsertJsonParamesToMap(bindParamObj, bindParamMap); + return DeviceManager::GetInstance().BindTarget(bundleName_, targetId, bindParamMap, callback); +} + + +int32_t DeviceManagerFfiImpl::RegisterDevStatusCallback() +{ + LOGI("RegisterDevStatusCallback start for bundleName %{public}s", bundleName_.c_str()); + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + if (g_deviceStatusCallbackMap.find(bundleName_) != g_deviceStatusCallbackMap.end()) { + LOGI("bundleName already register."); + return ERR_OK; + } + } + auto callback = std::make_shared(bundleName_); + int32_t ret = DeviceManager::GetInstance().RegisterDevStatusCallback(bundleName_, "", callback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("RegisterDevStatusCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + g_deviceStatusCallbackMap[bundleName_] = callback; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::RegisterDiscoveryCallback() +{ + auto discoveryCallback = std::make_shared(bundleName_); + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + g_DiscoveryCallbackMap[bundleName_] = discoveryCallback; + } + discoveryCallback->IncreaseRefCount(); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::RegisterPublishCallback() +{ + auto publishCallback = std::make_shared(bundleName_); + { + std::lock_guard autoLock(g_publishCallbackMapMutex); + g_publishCallbackMap[bundleName_] = publishCallback; + } + publishCallback->IncreaseRefCount(); + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::RegisterReplyCallback() +{ + auto dmUiCallback = std::make_shared(bundleName_); + int32_t ret = DeviceManager::GetInstance().RegisterDeviceManagerFaCallback(bundleName_, dmUiCallback); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("RegisterDeviceManagerFaCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_dmUiCallbackMapMutex); + g_dmUiCallbackMap[bundleName_] = dmUiCallback; + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleaseDevStatusCallback() +{ + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + auto iter = g_deviceStatusCallbackMap.find(bundleName_); + if (iter == g_deviceStatusCallbackMap.end()) { + LOGE("ReleaseDmCallback: cannot find statusCallback for bundleName %{public}s", bundleName_.c_str()); + return ERR_INVALID_PARAMS; + } + } + int32_t ret = DeviceManager::GetInstance().UnRegisterDevStatusCallback(bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("UnRegisterDevStatusCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_deviceStatusCallbackMapMutex); + g_deviceStatusCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleaseDiscoveryCallback() +{ + LOGI("ReleaseDiscoveryCallback for bundleName %{public}s", bundleName_.c_str()); + std::shared_ptr DiscoveryCallback = nullptr; + { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + auto iter = g_DiscoveryCallbackMap.find(bundleName_); + if (iter == g_DiscoveryCallbackMap.end()) { + return ERR_OK; + } + DiscoveryCallback = iter->second; + } + DiscoveryCallback->DecreaseRefCount(); + if (DiscoveryCallback->GetRefCount() == 0) { + std::lock_guard autoLock(g_discoveryCallbackMapMutex); + g_DiscoveryCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleasePublishCallback() +{ + LOGI("ReleasePublishCallback for bundleName %{public}s", bundleName_.c_str()); + std::shared_ptr publishCallback = nullptr; + { + std::lock_guard autoLock(g_publishCallbackMapMutex); + auto iter = g_publishCallbackMap.find(bundleName_); + if (iter == g_publishCallbackMap.end()) { + return ERR_OK; + } + publishCallback = iter->second; + } + publishCallback->DecreaseRefCount(); + if (publishCallback->GetRefCount() == 0) { + std::lock_guard autoLock(g_publishCallbackMapMutex); + g_publishCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + +int32_t DeviceManagerFfiImpl::ReleaseReplyCallback() +{ + { + std::lock_guard autoLock(g_dmUiCallbackMapMutex); + auto iter = g_dmUiCallbackMap.find(bundleName_); + if (iter == g_dmUiCallbackMap.end()) { + LOGE("cannot find dmFaCallback for bundleName %{public}s", bundleName_.c_str()); + return ERR_INVALID_PARAMS; + } + } + int32_t ret = DeviceManager::GetInstance().UnRegisterDeviceManagerFaCallback(bundleName_); + if (ret != 0) { + ret = transformErrCode(ret); + LOGE("UnRegisterDeviceManagerFaCallback failed for bundleName %{public}s", bundleName_.c_str()); + return ret; + } + { + std::lock_guard autoLock(g_dmUiCallbackMapMutex); + g_dmUiCallbackMap.erase(bundleName_); + } + return ERR_OK; +} + + +void DeviceManagerFfiImpl::RegisterCallbackByType(const std::string &type, void *callback) +{ + std::lock_guard autoLock(callbackLock); + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE) { + deviceStateChangedCallback = CJLambda::Create( + reinterpret_cast(callback)); + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS) { + discoverSuccessCallback = CJLambda::Create(reinterpret_cast(callback)); + } else if (type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + deviceNameChangedCallback = CJLambda::Create(reinterpret_cast(callback)); + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + deviceDiscoverFailedCallback = CJLambda::Create(reinterpret_cast(callback)); + } else { + LOGE("RegisterCallbackByType call with wrong type."); + } +} + +void DeviceManagerFfiImpl::Off(const std::string &type) +{ + std::lock_guard autoLock(callbackLock); + if (type == DM_FFI_EVENT_DEVICE_STATE_CHANGE) { + deviceStateChangedCallback = nullptr; + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_SUCCESS) { + discoverSuccessCallback = nullptr; + } else if (type == DM_FFI_EVENT_DEVICE_NAME_CHANGE) { + deviceNameChangedCallback = nullptr; + } else if (type == DM_FFI_EVENT_DEVICE_DISCOVER_FAIL) { + deviceDiscoverFailedCallback = nullptr; + } else { + LOGE("Off call with wrong type."); + } +} +} // namespace OHOS::DistributedHardware diff --git a/interfaces/cj/src/device_manager_utils.cpp b/interfaces/cj/src/device_manager_utils.cpp new file mode 100644 index 000000000..86010e954 --- /dev/null +++ b/interfaces/cj/src/device_manager_utils.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "device_manager_utils.h" + +#include +#include +#include + +#include "device_manager_impl.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS::DistributedHardware { + +namespace { + constexpr std::size_t MAX_MALLOC_SIZE = 0x10000; +} + +void DmFfiInitCallback::OnRemoteDied() +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnRemoteDied, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } + LOGI("OnRemoteDied, deviceManagerFfi bundleName %{public}s", bundleName_.c_str()); +} + +void DmFfiDeviceStatusCallback::OnDeviceOnline(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceOnline, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceStatusChange(DmFfiDevStatusChange::UNKNOWN, deviceBasicInfo); + } +} + +void DmFfiDeviceStatusCallback::OnDeviceReady(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceReady, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceStatusChange(DmFfiDevStatusChange::AVAILABLE, deviceBasicInfo); + } +} + +void DmFfiDeviceStatusCallback::OnDeviceOffline(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceOffline, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceStatusChange(DmFfiDevStatusChange::UNAVAILABLE, deviceBasicInfo); + } +} + +void DmFfiDeviceStatusCallback::OnDeviceChanged(const DmDeviceBasicInfo &deviceBasicInfo) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceChanged, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceNameChange(deviceBasicInfo.deviceName); + } +} + +void DmFfiDiscoveryCallback::OnDeviceFound(uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("OnDeviceFound for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDeviceFound, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDeviceFound(subscribeId, deviceBasicInfo); + } +} + +void DmFfiDiscoveryCallback::OnDiscoveryFailed(uint16_t subscribeId, int32_t failedReason) +{ + LOGI("OnDiscoveryFailed for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDiscoveryFailed, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDiscoveryFailed(subscribeId, failedReason); + } +} + +void DmFfiDiscoveryCallback::OnDiscoverySuccess(uint16_t subscribeId) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnDiscoverySuccess, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + return; + } + LOGI("DiscoverySuccess for %{public}s, subscribeId %{public}d", bundleName_.c_str(), (int32_t)subscribeId); +} + +void DmFfiDiscoveryCallback::IncreaseRefCount() +{ + refCount_++; +} + +void DmFfiDiscoveryCallback::DecreaseRefCount() +{ + refCount_--; +} + +int32_t DmFfiDiscoveryCallback::GetRefCount() +{ + return refCount_; +} + +void DmFfiPublishCallback::OnPublishResult(int32_t publishId, int32_t publishResult) +{ + LOGI("OnPublishResult for %{public}s, publishId %{public}d, publishResult %{public}d", bundleName_.c_str(), + publishId, publishResult); + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnPublishResult, deviceManagerFfi failed for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnPublishResult(publishId, publishResult); + } +} + +void DmFfiPublishCallback::IncreaseRefCount() +{ + refCount_++; +} + +void DmFfiPublishCallback::DecreaseRefCount() +{ + refCount_--; +} + +int32_t DmFfiPublishCallback::GetRefCount() +{ + return refCount_; +} + +void DmFfiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const std::string &token, int32_t status, + int32_t reason) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnAuthResult, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnAuthResult(deviceId, token, status, reason); + } +} + +void DmFfiDeviceManagerUiCallback::OnCall(const std::string ¶mJson) +{ + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnCall, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnDmUiCall(paramJson); + } +} + +void DmFfiBindTargetCallback::OnBindResult(const PeerTargetId &targetId, int32_t result, int32_t status, + std::string content) +{ + (void)targetId; + DeviceManagerFfiImpl *deviceManagerFfi = DeviceManagerFfiImpl::GetDeviceManagerFfi(bundleName_); + if (deviceManagerFfi == nullptr) { + LOGE("OnBindResult, deviceManagerFfi not find for bundleName %{public}s", bundleName_.c_str()); + } else { + deviceManagerFfi->OnAuthResult(content, "", status, result); + } +} + +const std::string &GetDeviceTypeById(DmDeviceType type) +{ + const static std::pair mapArray[] = { + {DEVICE_TYPE_UNKNOWN, DEVICE_TYPE_UNKNOWN_STRING}, + {DEVICE_TYPE_PHONE, DEVICE_TYPE_PHONE_STRING}, + {DEVICE_TYPE_PAD, DEVICE_TYPE_PAD_STRING}, + {DEVICE_TYPE_TV, DEVICE_TYPE_TV_STRING}, + {DEVICE_TYPE_CAR, DEVICE_TYPE_CAR_STRING}, + {DEVICE_TYPE_WATCH, DEVICE_TYPE_WATCH_STRING}, + {DEVICE_TYPE_WIFI_CAMERA, DEVICE_TYPE_WIFICAMERA_STRING}, + {DEVICE_TYPE_PC, DEVICE_TYPE_PC_STRING}, + {DEVICE_TYPE_SMART_DISPLAY, DEVICE_TYPE_SMART_DISPLAY_STRING}, + {DEVICE_TYPE_2IN1, DEVICE_TYPE_2IN1_STRING}, + }; + for (const auto& item : mapArray) { + if (item.first == type) { + return item.second; + } + } + return DEVICE_TYPE_UNKNOWN_STRING; +} + +char *MallocCStr(const char *in) +{ + std::size_t len = strlen(in); + if (len >= MAX_MALLOC_SIZE) { + return nullptr; + } + char *result = static_cast(malloc(len + 1)); + if (result == nullptr) { + LOGE("Malloc failed."); + return nullptr; + } + std::char_traits::copy(result, in, len+1); + return result; +} +} // OHOS::DistributedHardware -- Gitee From 73311141b2ba03f685b68c9d3c5f46fc9909a29c Mon Sep 17 00:00:00 2001 From: q30043944 Date: Wed, 13 Nov 2024 15:51:40 +0800 Subject: [PATCH 392/520] delete userid Signed-off-by: q30043944 --- .../inner_kits/native_cpp/src/notify/device_manager_notify.cpp | 1 + services/service/src/device_manager_service.cpp | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 046090539..2ca8f4f70 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 @@ -348,6 +348,7 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); + LOGI("Completed, Offline with DmDeviceInfo, pkgName:%{public}s", pkgName.c_str()); #else std::thread deviceOffline([=]() { DeviceInfoOffline(deviceInfo, tempCbk); }); if (pthread_setname_np(deviceOffline.native_handle(), DEVICE_OFFLINE) != DM_OK) { diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index db144ccbe..2494ed739 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1640,8 +1640,7 @@ void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std: MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - HandleAccountLogout(MultipleUserConnector::GetCurrentAccountUserID(), - MultipleUserConnector::GetSwitchOldAccountId()); + HandleAccountLogout(userId, MultipleUserConnector::GetSwitchOldAccountId()); } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { HandleUserRemoved(userId); } else { -- Gitee From 550002b0291bc7912a18f037e094ef1147c92a4e Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 13 Nov 2024 17:37:25 +0800 Subject: [PATCH 393/520] =?UTF-8?q?=E8=A7=84=E9=81=BF=E4=B8=9A=E5=8A=A1?= =?UTF-8?q?=E5=B9=B6=E5=8F=91=E5=9C=BA=E6=99=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../service/include/pinholder/pin_holder.h | 1 + services/service/src/pinholder/pin_holder.cpp | 45 ++++++++++++++++++- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index 75d999cd9..b12aa0e8a 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -61,6 +61,7 @@ public: private: int32_t CreateGeneratePinHolderMsg(); int32_t ParseMsgType(const std::string &message); + void ProcessCloseSessionMsg(const std::string &message); void ProcessCreateMsg(const std::string &message); void ProcessCreateRespMsg(const std::string &message); void ProcessDestroyMsg(const std::string &message); diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 8b86a63d2..ef30a517a 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -34,6 +34,7 @@ constexpr int32_t MSG_TYPE_DESTROY_PIN_HOLDER = 650; constexpr int32_t MSG_TYPE_DESTROY_PIN_HOLDER_RESP = 651; constexpr int32_t MSG_TYPE_PIN_HOLDER_CHANGE = 700; constexpr int32_t MSG_TYPE_PIN_HOLDER_CHANGE_RESP = 701; +constexpr int32_t MSG_TYPE_PIN_CLOSE_SESSION = 800; constexpr const char* PINHOLDER_CREATE_TIMEOUT_TASK = "deviceManagerTimer:pinholdercreate"; constexpr int32_t PIN_HOLDER_SESSION_CREATE_TIMEOUT = 60; @@ -46,6 +47,7 @@ constexpr const char* TAG_REMOTE_DEVICE_ID = "REMOTE_DEVICE_ID"; constexpr int32_t DM_OK = 0; constexpr int32_t ERR_DM_FAILED = 96929744; constexpr int32_t ERR_DM_TIME_OUT = 96929745; +constexpr int32_t ERR_DM_CREATE_PIN_HOLDER_BUSY = 96929821; constexpr const char* TAG_MSG_TYPE = "MSG_TYPE"; constexpr const char* TAG_DM_VERSION = "DM_VERSION"; constexpr const char* DM_CONNECTION_DISCONNECTED = "DM_CONNECTION_DISCONNECTED"; @@ -231,6 +233,20 @@ int32_t PinHolder::ParseMsgType(const std::string &message) return msgType; } +void PinHolder::ProcessCloseSessionMsg(const std::string &message) +{ + if (listener_ == nullptr || session_ == nullptr) { + LOGE("ProcessCloseSessionMsg listener or session is nullptr."); + return; + } + LOGI("CloseSessionMsg, message type is: %{public}d.", MSG_TYPE_PIN_CLOSE_SESSION); + session_->CloseSessionServer(sessionId_); + sessionId_ = SESSION_ID_INVALID; + sourceState_ = SOURCE_INIT; + sinkState_ = SINK_INIT; + listener_->OnCreateResult(registerPkgName_, ERR_DM_CREATE_PIN_HOLDER_BUSY); +} + void PinHolder::ProcessCreateMsg(const std::string &message) { if (listener_ == nullptr || session_ == nullptr) { @@ -307,6 +323,8 @@ void PinHolder::ProcessCreateRespMsg(const std::string &message) session_->CloseSessionServer(sessionId_); sessionId_ = SESSION_ID_INVALID; destroyState_ = STATE_REMOTE_WRONG; + sourceState_ = SOURCE_INIT; + sinkState_ = SINK_INIT; } } @@ -412,6 +430,8 @@ void PinHolder::ProcessDestroyResMsg(const std::string &message) LOGE("ProcessDestroyResMsg remote state is wrong."); listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + sinkState_ = SINK_INIT; + sourceState_ = SOURCE_INIT; } session_->CloseSessionServer(sessionId_); sessionId_ = SESSION_ID_INVALID; @@ -422,8 +442,23 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) { int32_t msgType = ParseMsgType(message); LOGI("OnDataReceived, msgType: %{public}d.", msgType); - + int32_t sessionSide = GetSessionSide(sessionId); + if (sessionSide == SESSION_SIDE_SERVER && sessionId != sessionId_) { + LOGE("another session opened, close this sessionId: %{public}d.", sessionId); + nlohmann::json jsonObj; + jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; + std::string msg = jsonObj.dump(); + int32_t ret = session_->SendData(sessionId, msg); + if (ret != DM_OK) { + LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); + listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); + } + return; + } switch (msgType) { + case MSG_TYPE_PIN_CLOSE_SESSION: + ProcessCloseSessionMsg(message); + break; case MSG_TYPE_CREATE_PIN_HOLDER: ProcessCreateMsg(message); break; @@ -479,12 +514,15 @@ void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t LOGI("OnSessionOpened, peerDeviceId: %{public}s.", GetAnonyString(peerDeviceId).c_str()); DmRadarHelper::GetInstance().ReportSendOrReceiveHolderMsg(static_cast(PinHolderStage::SESSION_OPENED), std::string("OnSessionOpened"), std::string(peerDeviceId)); - sessionId_ = sessionId; if (sessionSide == SESSION_SIDE_SERVER) { LOGI("[SOFTBUS]onSesssionOpened success, side is sink. sessionId: %{public}d.", sessionId); GetPeerDeviceId(sessionId, remoteDeviceId_); + if (sessionId_ == SESSION_ID_INVALID) { + sessionId_ = sessionId; + } return; } + sessionId_ = sessionId; if (result == DM_OK) { CreateGeneratePinHolderMsg(); return; @@ -500,6 +538,9 @@ void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t void PinHolder::OnSessionClosed(int32_t sessionId) { + if (sessionId != sessionId_) { + return; + } LOGI("[SOFTBUS]OnSessionClosed sessionId: %{public}d.", sessionId); sessionId_ = SESSION_ID_INVALID; sinkState_ = SINK_INIT; -- Gitee From ea1d67fae80d532a221944bc126804ec4b849b16 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 16 Nov 2024 19:08:56 +0800 Subject: [PATCH 394/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../src/authentication/dm_auth_manager.cpp | 32 +- .../hichain_connector_fuzzer.cpp | 78 ++++- .../UTTest_dm_auth_manager_first.cpp | 190 ++++++++++- .../UTTest_dm_auth_manager_first.h | 8 + .../UTTest_dm_auth_manager_second.cpp | 89 ++++- .../UTTest_dm_auth_manager_second.h | 12 + .../UTTest_permission_manager.cpp | 21 ++ .../UTTest_softbus_listener.cpp | 320 ++++++++++++++++++ test/unittest/BUILD.gn | 16 +- test/unittest/mock/app_manager_mock.cpp | 5 + test/unittest/mock/app_manager_mock.h | 2 + .../mock/hichain_auth_connector_mock.cpp | 27 ++ .../mock/hichain_auth_connector_mock.h | 40 +++ test/unittest/mock/hichain_connector_mock.cpp | 50 +++ test/unittest/mock/hichain_connector_mock.h | 43 +++ .../mock/mine_hichain_connector_mock.cpp | 1 - .../mock/multiple_user_connector_mock.cpp | 27 ++ .../mock/multiple_user_connector_mock.h | 40 +++ test/unittest/mock/softbus_connector_mock.cpp | 4 + test/unittest/mock/softbus_connector_mock.h | 2 + test/unittest/mock/softbus_session_mock.cpp | 29 ++ test/unittest/mock/softbus_session_mock.h | 40 +++ 22 files changed, 1051 insertions(+), 25 deletions(-) create mode 100644 test/unittest/mock/hichain_auth_connector_mock.cpp create mode 100644 test/unittest/mock/hichain_auth_connector_mock.h create mode 100644 test/unittest/mock/hichain_connector_mock.cpp create mode 100644 test/unittest/mock/hichain_connector_mock.h create mode 100644 test/unittest/mock/multiple_user_connector_mock.cpp create mode 100644 test/unittest/mock/multiple_user_connector_mock.h create mode 100644 test/unittest/mock/softbus_session_mock.cpp create mode 100644 test/unittest/mock/softbus_session_mock.h diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index aa1973ff7..c6a7e68ea 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -15,6 +15,7 @@ #include "dm_auth_manager.h" +#include #include #include #include @@ -166,18 +167,19 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra) { nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); - if (!jsonObject.is_discarded()) { - if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { - int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); - if (bindLevel > APP || bindLevel < INVALID_TYPE) { - LOGE("bindlevel error %{public}d.", bindLevel); - return ERR_DM_INPUT_PARA_INVALID; - } - if (bindLevel == DEVICE && !IsAllowDeviceBind()) { - LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); - return ERR_DM_INPUT_PARA_INVALID; - } - } + if (jsonObject.is_discarded() || jsonObject.find(TAG_BIND_LEVEL) == jsonObject.end() || + !IsInt32(jsonObject, TAG_BIND_LEVEL)) { + return DM_OK; + } + int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < INVALID_TYPE) { + LOGE("bindlevel error %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (static_cast(bindLevel) == DEVICE && !IsAllowDeviceBind()) { + LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; } return DM_OK; } @@ -2516,12 +2518,14 @@ bool DmAuthManager::IsAllowDeviceBind() int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) { if (IsAllowDeviceBind()) { - if (bindLevel == INVALIED_TYPE || bindLevel > APP || bindLevel < DEVICE) { + if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || + static_cast(bindLevel) < DEVICE) { return DEVICE; } return bindLevel; } - if (bindLevel == INVALIED_TYPE || (bindLevel != APP && bindLevel != SERVICE)) { + if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && + static_cast(bindLevel) != SERVICE)) { return APP; } return bindLevel; diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 3feab9906..f0299d5c8 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -169,14 +169,16 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) int32_t groupType = *(reinterpret_cast(data)); int32_t switchUserId = *(reinterpret_cast(data)); std::string reqParams(reinterpret_cast(data), size); + std::string credentialInfo(reinterpret_cast(data), size); int operationCode = GroupOperationCode::MEMBER_JOIN; hichainConnector->deviceGroupManager_ = nullptr; hichainConnector->AddMember(deviceId, queryParams); hichainConnector->getRegisterInfo(queryParams, jsonStr); hichainConnector->addMultiMembers(groupType, userId, jsonOutObj); + hichainConnector->addMultiMembersExt(credentialInfo); hichainConnector->deleteMultiMembers(groupType, userId, jsonOutObj); hichainConnector->GetGroupInfoCommon(authType, queryParams, pkgName.c_str(), groupList); - hichainConnector->hiChainResCallback_ = nullptr; + hichainConnector->hiChainConnectorCallback_ = nullptr; hichainConnector->GetConnectPara(deviceId, reqDeviceId); hichainConnector->onRequest(requestId, operationCode, reqParams.c_str()); hichainConnector->RegisterHiChainCallback(std::make_shared()); @@ -194,7 +196,7 @@ void HiChainConnectorThirdFuzzTest(const uint8_t* data, size_t size) void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(int32_t))) { + if ((data == nullptr) || (size < sizeof(int64_t))) { return; } @@ -247,19 +249,36 @@ void HiChainConnectorForthFuzzTest(const uint8_t* data, size_t size) void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) { - if ((data == nullptr) || (size < sizeof(int32_t))) { + if ((data == nullptr) || (size < sizeof(int64_t))) { return; } std::shared_ptr hichainConnector = std::make_shared(); hichainConnector->RegisterHiChainCallback(std::make_shared()); - int64_t requestId = *(reinterpret_cast(data)); std::string groupName = "groupName_fifth"; int32_t authType = *(reinterpret_cast(data)); std::string params = "params"; int32_t osAccountUserId = *(reinterpret_cast(data)); nlohmann::json jsonDeviceList; + std::vector> delACLInfoVec; + std::vector userIdVec; + std::vector> delAclInfoVec1; + std::string jsonStr = R"({"content": {"deviceid": "123"}}, authId: "123456"))"; + std::vector udidList; + int32_t key = 12; + std::string value = "acl_info1"; + std::string credentialInfo = R"({"content": {"deviceid": "123"}}, authId: "123456"))"; + std::string params(reinterpret_cast(data), size); + std::string groupOwner(reinterpret_cast(data), size); + delAclInfoVec1.push_back(std::make_pair(key1, value)); + nlohmann::json jsonObj; + jsonObj[AUTH_TYPE] = 1; + jsonObj[FIELD_USER_ID] = "123456"; + jsonObj[FIELD_CREDENTIAL_TYPE] = 2; + jsonObj[FIELD_OPERATION_CODE] = 876; + jsonObj[FIELD_TYPE] = "filed_type"; + jsonObj[FIELD_DEVICE_LIST] = "device_list"; hichainConnector->deviceGroupManager_ = nullptr; hichainConnector->CreateGroup(requestId, groupName); hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); @@ -270,6 +289,56 @@ void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) hichainConnector->CreateGroup(requestId, authType, groupName, jsonDeviceList); hichainConnector->ParseRemoteCredential(authType, groupName, jsonDeviceList, params, osAccountUserId); hichainConnector->ParseRemoteCredential(authType, "", jsonDeviceList, params, osAccountUserId); + hichainConnector->IsNeedDelete(groupName, authType, delACLInfoVec); + hichainConnector->DeleteGroupByACL(delAclInfoVec1, userIdVec); + hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); + jsonStr = R"({"content": {"deviceid": "123"}}, authId: "123456")"; + hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); + jsonStr = R"({"content": {"deviceid": "123"}}, localId: "123456")"; + hichainConnector->GetTrustedDevicesUdid(jsonStr.data(), udidList); +} + +void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr hichainConnector = std::make_shared(); + hichainConnector->RegisterHiChainCallback(std::make_shared()); + nlohmann::json jsonObj; + std::string deviceId = "deviceId"; + std::string key = "localDeviceId"; + jsonObj["deviceId"] = 32; + hichainConnector->GetJsonInt(jsonObj, key); + hichainConnector->GetJsonInt(jsonObj, key); + jsonObj[key] = 87; + jsonObj["deviceName"] = "devieName1"; + hichainConnector->GetJsonInt(jsonObj, "devieName"); + hichainConnector->AddMember(deviceId, jsonObj.dump()); + jsonObj[TAG_DEVICE_ID] = "deviceId_001"; + jsonObj[PIN_CODE_KEY] = 125; + jsonObj[TAG_GROUP_ID] = "groupId"; + jsonObj[TAG_REQUEST_ID] = 256; + jsonObj[TAG_GROUP_NAME] = "groupName"; + hichainConnector->AddMember(deviceId, jsonObj.dump()); + + nlohmann::json jsonObjCre; + jsonObjCre[AUTH_TYPE] = 1; + jsonObjCre["userId"] = "user_001"; + jsonObjCre[FIELD_CREDENTIAL_TYPE] = 25; + jsonObjCre[FIELD_OPERATION_CODE] = 33; + jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; + jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; + std::string credentialInfo = jsonObjCre.dump(); + hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); + int32_t groupType = *(reinterpret_cast(data)); + nlohmann::json jsonDeviceList; + std::string params; + int32_t osAccountUserId = 0; + std::string userId = "user_002"; + jsonDeviceList[FIELD_DEVICE_LIST] = "deviceList"; + hichainConnector->ParseRemoteCredential(groupType, userId, jsonDeviceList, params, osAccountUserId); } } } @@ -283,5 +352,6 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) OHOS::DistributedHardware::HiChainConnectorThirdFuzzTest(data, size); OHOS::DistributedHardware::HiChainConnectorForthFuzzTest(data, size); OHOS::DistributedHardware::HiChainConnectorFifthFuzzTest(data, size); + OHOS::DistributedHardware::HiChainConnectorSixthFuzzTest(data, size); return 0; } \ No newline at end of file diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 505afb15d..e341d23c8 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -28,6 +28,10 @@ static bool g_reportAuthOpenSessionReturnBoolValue = false; static bool g_reportAuthConfirmBoxReturnBoolValue = false; +constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; +constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; +constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; + namespace OHOS { namespace DistributedHardware { const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; @@ -66,8 +70,19 @@ void DmAuthManagerTest::SetUp() authManager_->timer_ = std::make_shared(); } void DmAuthManagerTest::TearDown() {} -void DmAuthManagerTest::SetUpTestCase() {} -void DmAuthManagerTest::TearDownTestCase() {} +void DmAuthManagerTest::SetUpTestCase() +{ + DmSoftbusSession::dmSoftbusSession = softbusSessionMock_; + DmAppManager::dmAppManager = appManagerMock_; + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; + +} +void DmAuthManagerTest::TearDownTestCase() +{ + softbusSessionMock_ = nullptr; + appManagerMock_ = nullptr; + multipleUserConnectorMock_ = nullptr; +} namespace { const int32_t MIN_PIN_CODE = 100000; @@ -1123,6 +1138,11 @@ HWTEST_F(DmAuthManagerTest, PutAccessControlList001, testing::ext::TestSize.Leve authManager_->authResponseContext_->isIdenticalAccount = true; authManager_->PutAccessControlList(); ASSERT_EQ(authManager_->isAuthDevice_, false); + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->localAccountId = "ohosAnonymousUid"; + authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + authManager_->PutAccessControlList(); + ASSERT_EQ(authManager_->isIdenticalAccount, false); } HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_001, testing::ext::TestSize.Level0) @@ -1303,6 +1323,172 @@ HWTEST_F(DmAuthManagerTest, GetTaskTimeout_001, testing::ext::TestSize.Level0) authManager_->SetAuthType(AUTH_TYPE_IMPORT_AUTH_CODE); EXPECT_EQ(authManager_->GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, taskTimeOut), CLONE_AUTHENTICATE_TIMEOUT); } + +HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize.Level0) +{ + std::string extra = R"({"extra": {"bindLevel": 1}})"; + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); + int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); + ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + extra = R"({"extra": {"bindLevel": 789}})"; + ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + extra = R"({"extra": {"bindLevel": 789})"; + ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, AuthenticateDevice_004, testing::ext::TestSize.Level0) +{ + int32_t authType = 0; + std::string extra = R"({"extra": {"bindLevel": 789}})"; + std::string pkgName = "ohos_test_004"; + std::string deviceId = "512156"; + authManager_->importPkgName_ = "ohos_test_004"; + authManager_->importAuthCode_ = "156161"; + authManager_->authRequestState_ = nullptr; + authManager_->authResponseState_ = nullptr; + std::shared_ptr listener = std::make_shared(); + authManager_->authUiStateMgr_ = std::make_shared(listener); + authManager_->authenticationMap_.insert(std::pair>(authType, nullptr)); + int32_t ret = authManager_->AuthenticateDevice(pkgName, authType, deviceId, extra); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); +} + +HWTEST_F(DmAuthManagerTest, StopAuthenticateDevice_001, testing::ext::TestSize.Level0) +{ + std::string pkgName; + int32_t ret = authManager_->StopAuthenticateDevice(pkgName); + ASSERT_EQ(ret, ERR_DM_FAILED); + + pkgName = "pkgName_001"; + int64_t requestId = 12; + int32_t status = 0; + int32_t sessionId = 1; + std::string peerUdidHash; + if (authManager_->timer_ == nullptr) { + authManager_->timer_ = std::make_shared(); + } + authManager_->authRequestState_ = std::make_shared(); + authManager_->authResponseContext_ = std::make_shared(); + authManager_->authRequestContext_ = std::make_shared(); + authManager_->authRequestContext_->hostPkgName = pkgName; + authManager_->authResponseContext_->hostPkgName = pkgName; + authManager_->isAuthenticateDevice_ = true; + + authManager_->authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->MemberJoinAuthRequest(requestId, status); + authManager_->authResponseContext_->authType == AUTH_TYPE_NFC; + authManager_->authResponseContext_->requestId = requestId; + status = 1; + authManager_->authTimes_ = MAX_AUTH_TIMES; + authManager_->MemberJoinAuthRequest(requestId, status); + status = 0; + authManager_->authTimes_ = 2; + authManager_->MemberJoinAuthRequest(requestId, status); + status = 0; + authManager_->HandleMemberJoinImportAuthCode(requestId, status); + authManager_->NegotiateRespMsg(DM_VERSION_5_0_1); + authManager_->NegotiateRespMsg(DM_VERSION_4_1_5_1); + authManager_->NegotiateRespMsg(DM_VERSION_5_0_2); + EXPECT_CALL(*softbusSessionMock_, GetPeerDeviceId(_, _)).WillOnce(Return(DM_OK)); + authManager_->GetPeerUdidHash(sessionId, peerUdidHash); + ret = authManager_->StopAuthenticateDevice(pkgName, authType, deviceId, extra); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(DmAuthManagerTest, GetBindLevel_001, testing::ext::TestSize.Level0) +{ + int32_t bindLevel = INVALIED_TYPE; + std::string udid; + authManager_->HandleDeviceNotTrust(udid); + udid = "988989"; + int32_t sessionId = 32166; + authManager_->ProcIncompatible(sessionId); + + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); + int32_t ret = authManager_->GetBindLevel(bindLevel); + ASSERT_EQ(ret, DEVICE); + + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); + ret = authManager_->GetBindLevel(bindLevel); + ASSERT_EQ(ret, APP); + + int32_t sessionId = 123; + authManager_->authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->importAuthCode_ = "importAuthCode"; + authManager_->ProcessAuthRequest(sessionId); + + authManager_->authResponseContext_->authType == AUTH_TYPE_NFC; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->reply = 0; + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->isAuthCodeReady = true; + authManager_->ProcessAuthRequest(sessionId); + + authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->isAuthCodeReady == false; + authManager_->ProcessAuthRequest(sessionId); + + bindLevel = SERVICE; + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); + ret = authManager_->GetBindLevel(bindLevel); + ASSERT_EQ(ret, SERVICE); +} + +HWTEST_F(DmAuthManagerTest, IsAuthFinish_001, testing::ext::TestSize.Level0) +{ + authManager_->authResponseContext_->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + bool ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->reply = ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authed = true; + ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->authed = false; + ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->isIdenticalAccount = false; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->isAuthCodeReady == false; + ret = authManager_->IsAuthFinish(); + EXPECT_TRUE(ret); + + authManager_->authResponseContext_->isAuthCodeReady == true; + ret = authManager_->IsAuthFinish(); + EXPECT_FALSE(ret); + + int32_t sessionId = 1; + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->importAuthCode_= "importAuthCode"; + authManager_->ProcessAuthRequestExt(sessionId); + + authManager_->authResponseContext_->isOnline = true; + authManager_->authResponseContext_->authed = true; + authManager_->authResponseContext_->importAuthCode = ""; + authManager_->ProcessAuthRequestExt(sessionId); + authManager_->authResponseContext_->reply = ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->isOnline = false; + authManager_->authResponseContext_->importAuthCode = "importAuthCode"; + authManager_->authResponseContext_->isIdenticalAccount = false; + authResponseContext_->isAuthCodeReady = true; + authManager_->ProcessAuthRequestExt(sessionId); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.h b/test/commonunittest/UTTest_dm_auth_manager_first.h index 7963c5dd7..8bcb5d787 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.h +++ b/test/commonunittest/UTTest_dm_auth_manager_first.h @@ -33,6 +33,9 @@ #include "auth_message_processor.h" #include "dm_timer.h" #include "dm_auth_manager.h" +#include "softbus_session_mock.h" +#include "app_manager_mock.h" +#include "multiple_user_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -50,6 +53,11 @@ public: std::shared_ptr authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); + static inline std::shared_ptr softbusSessionMock_ + = std::make_shared(); + static inline std::shared_ptr appManagerMock_ = std::make_shared(); + static inline std::shared_ptr multipleUserConnectorMock_ = + std::make_shared(); }; class AuthRequestFinishStateMock : public AuthRequestFinishState { diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 3342521d6..98b64101a 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -50,8 +50,20 @@ void DmAuthManagerTest::TearDown() { authManager_ = nullptr; } -void DmAuthManagerTest::SetUpTestCase() {} -void DmAuthManagerTest::TearDownTestCase() {} +void DmAuthManagerTest::SetUpTestCase() +{ + DmHiChainConnector::dmHiChainConnector = hiChainConnectorMock_; + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock_; + DmHiChainAuthConnector::dmHiChainAuthConnector = hiChainAuthConnectorMock_; +} +void DmAuthManagerTest::TearDownTestCase() +{ + hiChainConnectorMock_ = nullptr; + multipleUserConnectorMock_ = nullptr; + softbusConnectorMock_ = nullptr; + hiChainAuthConnectorMock_ = nullptr; +} namespace { HWTEST_F(DmAuthManagerTest, OnDataReceived_001, testing::ext::TestSize.Level0) @@ -1441,6 +1453,79 @@ HWTEST_F(DmAuthManagerTest, CheckTrustState_002, testing::ext::TestSize.Level0) int32_t ret = authManager_->CheckTrustState(); ASSERT_NE(ret, DM_OK); } + +HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level0) +{ + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(-1)); + bool ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); + + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(false)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); + + authManager_->authRequestContext_ = nullptr; + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); + + authManager_->authRequestContext_ = std::make_shared(); + authManager_->authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT; + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_TRUE(ret); + + EXPECT_CALL(*hiChainConnectorMock_, IsDevicesInP2PGroup(_, _)).WillOnce(Return(true)); + authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; + authManager_->importAuthCode_= "importAuthCode"; + authManager_->importPkgName_ = "importPkgName"; + authResponseContext_->hostPkgName = "importPkgName"; + authManager_->AbilityNegotiate(); + + EXPECT_CALL(*hiChainConnectorMock_, IsDevicesInP2PGroup(_, _)).WillOnce(Return(true)); + authManager_->importAuthCode_= ""; + authManager_->authResponseContext_->authType = AUTH_TYPE_NFC; + authManager_->AbilityNegotiate(); + + authManager_->authResponseContext_->isOnline = true; + EXPECT_CALL(*softbusConnectorMock_, CheckIsOnline(_)).WillOnce(Return(true)); + EXPECT_CALL(*hiChainAuthConnectorMock_, QueryCredential(_, _)).WillOnce(Return(true)); + authManager_->GetAuthRequestContext(); + + nlohmann::json jsonPeerGroupIdObj; + jsonPeerGroupIdObj["groupId"] = "123456"; + authResponseContext_->accountGroupIdHash = jsonPeerGroupIdObj.dump(); + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + ret = authManager_->IsIdenticalAccount(); + ASSERT_FALSE(ret); +} + +HWTEST_F(DmAuthManagerTest, GetAccountGroupIdHash_201, testing::ext::TestSize.Level0) +{ + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(-1)); + auto ret = authManager_->GetAccountGroupIdHash(); + ASSERT_TRUE(ret.empty()); + + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + auto ret = authManager_->GetAccountGroupIdHash(); + ASSERT_FALSE(ret.empty()); +} + +HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) +{ + authResponseContext_->reply == ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->isIdenticalAccount = true; + authManager_->authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT; + EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); + int32_t ret = authManager_->CheckTrustState(); + ASSERT_EQ(ret, 1); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.h b/test/commonunittest/UTTest_dm_auth_manager_second.h index 5b1dde490..f8fac51fa 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.h +++ b/test/commonunittest/UTTest_dm_auth_manager_second.h @@ -33,6 +33,10 @@ #include "hichain_connector.h" #include "softbus_connector.h" #include "softbus_session.h" +#include "hichain_connector_mock.h" +#include "multiple_user_connector_mock.h" +#include "softbus_connector_mock.h" +#include "hichain_auth_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -44,6 +48,14 @@ public: void TearDown(); std::shared_ptr authManager_; + static inline std::shared_ptr hiChainConnectorMock_ = + std::make_shared(); + static inline std::shared_ptr multipleUserConnectorMock_ = + std::make_shared(); + static inline std::shared_ptr softbusConnectorMock_ = + std::make_shared(); + static inline std::shared_ptr hiChainAuthConnectorMock_ = + std::make_shared(); }; class AuthResponseInitStateMock : public AuthResponseInitState { diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 8c8ef0f39..bd8f4fc9d 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -249,6 +249,27 @@ HWTEST_F(PermissionManagerTest, CheckSystemSA_102, testing::ext::TestSize.Level0 bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); ASSERT_TRUE(ret); } + +HWTEST_F(PermissionManagerTest, CheckMonitorPermission_001, testing::ext::TestSize.Level0) +{ + bool ret = PermissionManager::GetInstance().CheckMonitorPermission(pkgName); + ASSERT_TRUE(ret); +} + +HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnSetDnPolicy_001, testing::ext::TestSize.Level0) +{ + std::string processName = ""; + bool ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); + ASSERT_FALSE(ret); + + processName = "processName"; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); + ASSERT_FALSE(ret); + + processName = "collaboration_service"; + ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); + ASSERT_TRUE(ret); +} } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 03689fbb5..fe4f50b9b 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -415,6 +415,56 @@ HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_004, testing::ext::Tes EXPECT_EQ(softbusListener->isRadarSoLoad_, true); } +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_005, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + +HWTEST_F(SoftbusListenerTest, ConvertDeviceInfoToDmDevice_006, testing::ext::TestSize.Level0) +{ + DmDeviceInfo dmDevice; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BLE, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + softbusListener->ConvertDeviceInfoToDmDevice(deviceInfo, dmDevice); + EXPECT_EQ(softbusListener->isRadarSoLoad_, true); +} + HWTEST_F(SoftbusListenerTest, GetNetworkTypeByNetworkId_001, testing::ext::TestSize.Level0) { char *networkId; @@ -464,6 +514,199 @@ HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); } +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_002, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_002"; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + PeerTargetId targetId; + ConnectionAddrType addrType; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_003, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_003"; + DeviceInfo deviceInfo = { + .devId = "deviceId_003", + .devType = (DeviceType)1, + .devName = "11112", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr = &deviceInfo; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_004, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_004"; + DeviceInfo deviceInfo = { + .devId = "deviceId_004", + .devType = (DeviceType)1, + .devName = "11113", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_ETH, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + PeerTargetId targetId; + ConnectionAddrType addrType = ConnectionAddrType::CONNECTION_ADDR_ETH; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr = &deviceInfo; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, + )); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + softbusListener->CacheDeviceInfo(deviceId, infoPtr); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_005, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_005"; + DeviceInfo deviceInfo = { + .devId = "deviceId_005", + .devType = (DeviceType)1, + .devName = "11115", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BR, + .info { + .ip { + .ip = "172.0.0.1", + .port = 1, + } + } + } + }; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr = &deviceInfo; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_006, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_006"; + DeviceInfo deviceInfo = { + .devId = "deviceId_006", + .devType = (DeviceType)1, + .devName = "11116", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BLE, + .info { + .ip { + .ip = "172.0.0.1", + .port = 2, + } + } + } + }; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr = &deviceInfo; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_007, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId_007"; + DeviceInfo deviceInfo = { + .devId = "deviceId_006", + .devType = (DeviceType)1, + .devName = "11116", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_BLE, + .info { + .ip { + .ip = "172.0.0.1", + .port = 2, + } + } + } + }; + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr = &deviceInfo; + std::vector>> deviceVec; + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetTargetInfoFromCache(deviceId, targetId, addrType); + EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); +} + HWTEST_F(SoftbusListenerTest, ClearDiscoveredDevice_001, testing::ext::TestSize.Level0) { if (softbusListener == nullptr) { @@ -724,6 +967,40 @@ HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_003, testing::ext::TestSize EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } +HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_004, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId"; + std::string ip = "172.0.0.1"; + ConnectionAddrType addrType = ConnectionAddrType::CONNECTION_ADDR_ETH; + DeviceInfo deviceInfo = { + .devId = "deviceId", + .devType = (DeviceType)1, + .devName = "11111", + .addrNum = 1, + .addr[0] = { + .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, + .info { + .ip { + .ip = "172.0.0.1", + .port = 0, + } + } + } + }; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr = &deviceInfo; + std::vector>> deviceVec; + deviceVec.push_back(std::pair>(addrType, infoPtr)); + discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetIPAddrTypeFromCache(deviceId, ip, addrType); + softbusListener->CacheDeviceInfo(deviceId, infoPtr); + EXPECT_EQ(ret, DM_OK); +} + HWTEST_F(SoftbusListenerTest, InitSoftbusListener_001, testing::ext::TestSize.Level0) { SoftbusListener::GetSoftbusRefreshCb(); @@ -798,6 +1075,49 @@ HWTEST_F(SoftbusListenerTest, StopRefreshSoftbusLNN_001, testing::ext::TestSize. softbusListener->CredentialAuthStatusProcess(deviceList2, deviceTypeId, errcode); EXPECT_EQ(true, checkSoftbusRes(ret)); } + +HWTEST_F(SoftbusListenerTest, GetNetworkIdByUdid_001, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkId"; + std::string udid; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetNetworkIdByUdid(udid, networkId); + EXPECT_EQ(true, checkSoftbusRes(ret)); +} + +HWTEST_F(SoftbusListenerTest, SetLocalDeviceName_001, testing::ext::TestSize.Level0) +{ + std::string localDeviceName; + std::string localDisplayName; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + localDeviceName = "localDeviceName"; + ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_NE(ret, DM_OK); + + localDisplayName = "localDisplayName"; + ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_NE(ret, DM_OK); + softbusListener = nullptr; +} + +HWTEST_F(SoftbusListenerTest, GetDeviceScreenStatus_001, testing::ext::TestSize.Level0) +{ + std::string networkId = "networkId"; + int32_t screenStatus = 1; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->GetDeviceScreenStatus(networkId.c_str(), screenStatus); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + softbusListener = nullptr; +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 4ff2624b9..ccbb39ef6 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1090,7 +1090,11 @@ ohos_unittest("UTTest_dm_auth_manager_first") { include_dirs = [ "${devicemanager_path}/test/commonunittest" ] - sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_first.cpp" ] + sources = [ + "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_first.cpp", + "mock/app_manager_mock.cpp", + "mock/softbus_session_mock.cpp", + ] deps = [ ":device_manager_test_common" ] @@ -1100,6 +1104,7 @@ ohos_unittest("UTTest_dm_auth_manager_first") { "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", "googletest:gmock", + "googletest:gmock_main", ] cflags = [ @@ -1120,7 +1125,13 @@ ohos_unittest("UTTest_dm_auth_manager_second") { include_dirs = [ "${devicemanager_path}/test/commonunittest" ] - sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_second.cpp" ] + sources = [ + "${devicemanager_path}/test/commonunittest/UTTest_dm_auth_manager_second.cpp", + "mock/hichain_auth_connector_mock.cpp", + "mock/hichain_connector_mock.cpp", + "mock/multiple_user_connector_mock.cpp", + "mock/softbus_connector_mock.cpp", + ] deps = [ ":device_manager_test_common" ] @@ -1131,6 +1142,7 @@ ohos_unittest("UTTest_dm_auth_manager_second") { "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", "googletest:gmock", + "googletest::gmock_main", ] } diff --git a/test/unittest/mock/app_manager_mock.cpp b/test/unittest/mock/app_manager_mock.cpp index 0fc612b21..02d2abd44 100644 --- a/test/unittest/mock/app_manager_mock.cpp +++ b/test/unittest/mock/app_manager_mock.cpp @@ -24,5 +24,10 @@ const std::string AppManager::GetAppId() { return DmAppManager::dmAppManager->GetAppId(); } + +bool AppManager::IsSystemSA() +{ + return DmAppManager::dmAppManager->IsSystemSA(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/app_manager_mock.h b/test/unittest/mock/app_manager_mock.h index e79eea4e3..7439494b4 100644 --- a/test/unittest/mock/app_manager_mock.h +++ b/test/unittest/mock/app_manager_mock.h @@ -27,6 +27,7 @@ public: virtual ~DmAppManager() = default; public: virtual std::string GetAppId() = 0; + virtual bool IsSystemSA() = 0; public: static inline std::shared_ptr dmAppManager = nullptr; }; @@ -34,6 +35,7 @@ public: class AppManagerMock : public DmAppManager { public: MOCK_METHOD(std::string, GetAppId, ()); + MOCK_METHOD(bool, IsSystemSA, ()); }; } } diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp new file mode 100644 index 000000000..ead3818e0 --- /dev/null +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hichain_auth_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->QueryCredential(localUdid, osAccountId); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h new file mode 100644 index 000000000..18df9b831 --- /dev/null +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_HICHAIN_AUTH_CONNECTOR_MOCK_H +#define OHOS_HICHAIN_AUTH_CONNECTOR_MOCK_H + +#include +#include + +#include "hichain_auth_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmHiChainAuthConnector { +public: + virtual ~DmHiChainAuthConnector() = default; +public: + virtual bool QueryCredential(std::string &localUdid, int32_t osAccountId) = 0; +public: + static inline std::shared_ptr dmHiChainAuthConnector = nullptr; +}; + +class HiChainAuthConnectorMock : public DmHiChainAuthConnector { +public: + MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t)); +}; +} +} +#endif diff --git a/test/unittest/mock/hichain_connector_mock.cpp b/test/unittest/mock/hichain_connector_mock.cpp new file mode 100644 index 000000000..91f1d8b09 --- /dev/null +++ b/test/unittest/mock/hichain_connector_mock.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "hichain_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +bool HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &queryParams, + std::vector &groupList) +{ + GroupInfo groupInfo = { + .groupId = "123456", + .groupName = "group1" + }; + + GroupInfo groupInfo2 = { + .groupId = "123789", + .groupName = "group2" + }; + + GroupInfo groupInfo3 = { + .groupId = "45789", + .groupName = "group3" + }; + groupList.push_back(groupInfo); + groupList.push_back(groupInfo2); + groupList.push_back(groupInfo3); + return DmHiChainConnector::dmHiChainConnector->GroupInfo(userId, queryParams, groupList); +} + +bool HiChainConnector::IsDevicesInP2PGroup(const std::string &hostDevice, const std::string &peerDevice) +{ + return DmHiChainConnector::dmHiChainConnector->IsDevicesInP2PGroup(hostDevice, peerDevice); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/hichain_connector_mock.h b/test/unittest/mock/hichain_connector_mock.h new file mode 100644 index 000000000..88b3d1c59 --- /dev/null +++ b/test/unittest/mock/hichain_connector_mock.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_HICHAIN_CONNECTOR_MOCK_H +#define OHOS_HICHAIN_CONNECTOR_MOCK_H + +#include +#include + +#include "hichain_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmHiChainConnector { +public: + virtual ~DmHiChainConnector() = default; +public: + virtual bool GetGroupInfo(const int32_t userId, const std::string &queryParams, + std::vector &groupList) = 0; + virtual bool IsDevicesInP2PGroup(const std::string &hostDevice, const std::string &peerDevice) = 0; +public: + static inline std::shared_ptr dmHiChainConnector = nullptr; +}; + +class HiChainConnectorMock : public DmHiChainConnector { +public: + MOCK_METHOD(bool, GetGroupInfo, (const int32_t, const std::string &, std::vector &)); + MOCK_METHOD(bool, IsDevicesInP2PGroup, (const std::string &, const std::string &)); +}; +} +} +#endif diff --git a/test/unittest/mock/mine_hichain_connector_mock.cpp b/test/unittest/mock/mine_hichain_connector_mock.cpp index ae4d527f6..f3b6e9f17 100644 --- a/test/unittest/mock/mine_hichain_connector_mock.cpp +++ b/test/unittest/mock/mine_hichain_connector_mock.cpp @@ -14,7 +14,6 @@ */ #include "mine_hichain_connector_mock.h" -#include "dm_softbus_cache_mock.h" #include "gtest/gtest.h" diff --git a/test/unittest/mock/multiple_user_connector_mock.cpp b/test/unittest/mock/multiple_user_connector_mock.cpp new file mode 100644 index 000000000..b2ae307a9 --- /dev/null +++ b/test/unittest/mock/multiple_user_connector_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "multiple_user_connector_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +int32_t MultipleUserConnector::GetCurrentAccountUserID(void) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetCurrentAccountUserID(); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/multiple_user_connector_mock.h b/test/unittest/mock/multiple_user_connector_mock.h new file mode 100644 index 000000000..8a428ef7d --- /dev/null +++ b/test/unittest/mock/multiple_user_connector_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_MULTIPLE_USER_CONNECTOR_MOCK_H +#define OHOS_MULTIPLE_USER_CONNECTOR_MOCK_H + +#include +#include + +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { +class DmMultipleUserConnector { +public: + virtual ~DmMultipleUserConnector() = default; +public: + virtual int32_t GetCurrentAccountUserID(void) = 0; +public: + static inline std::shared_ptr dmMultipleUserConnector = nullptr; +}; + +class MultipleUserConnectorMock : public DmMultipleUserConnector { +public: + MOCK_METHOD(int32_t, GetCurrentAccountUserID, ()); +}; +} +} +#endif diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp index 69103fb6b..70351519e 100644 --- a/test/unittest/mock/softbus_connector_mock.cpp +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -24,6 +24,10 @@ int32_t SoftbusConnector::GetUdidByNetworkId(const char *networkId, std::string { return DmSoftbusConnector::dmSoftbusConnector->GetUdidByNetworkId(networkId, udid); } +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +{ + return DmSoftbusConnector::dmSoftbusConnector->CheckIsOnline(targetDeviceId); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h index 51fe29690..10145e8c5 100644 --- a/test/unittest/mock/softbus_connector_mock.h +++ b/test/unittest/mock/softbus_connector_mock.h @@ -27,6 +27,7 @@ public: virtual ~DmSoftbusConnector() = default; public: virtual int32_t GetUdidByNetworkId(const char *networkId, std::string &udid) = 0; + virtual bool CheckIsOnline(const std::string &targetDeviceId) = 0; public: static inline std::shared_ptr dmSoftbusConnector = nullptr; }; @@ -34,6 +35,7 @@ public: class SoftbusConnectorMock : public DmSoftbusConnector { public: MOCK_METHOD(int32_t, GetUdidByNetworkId, (const char *, std::string &)); + MOCK_METHOD(bool, CheckIsOnline, (const std::string &)); }; } } diff --git a/test/unittest/mock/softbus_session_mock.cpp b/test/unittest/mock/softbus_session_mock.cpp new file mode 100644 index 000000000..1c657174e --- /dev/null +++ b/test/unittest/mock/softbus_session_mock.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "softbus_session_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) +{ + return DmSoftbusSession::dmSoftbusSession->GetPeerDeviceId(sessionId, peerDevId); +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_session_mock.h b/test/unittest/mock/softbus_session_mock.h new file mode 100644 index 000000000..732174ef4 --- /dev/null +++ b/test/unittest/mock/softbus_session_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_SOFTBUS_SESSION_MOCK_H +#define OHOS_SOFTBUS_SESSION_MOCK_H + +#include +#include + +#include "softbus_session.h" + +namespace OHOS { +namespace DistributedHardware { +class DmSoftbusSession { +public: + virtual ~DmSoftbusSession() = default; +public: + virtual int32_t GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) = 0; +public: + static inline std::shared_ptr dmSoftbusSession = nullptr; +}; + +class SoftbusSessionMock : public DmSoftbusSession { +public: + MOCK_METHOD(int32_t, GetPeerDeviceId, (int32_t, std::string &)); +}; +} +} +#endif -- Gitee From 71e788980eb481e48e94e71c3c073fedaac34118 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Sat, 16 Nov 2024 10:49:13 +0800 Subject: [PATCH 395/520] =?UTF-8?q?=E8=AE=BE=E7=BD=AEaccountInfo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../include/multiple_user_connector.h | 11 +++ .../src/multiple_user_connector.cpp | 31 +++++++ .../include/authentication/dm_auth_manager.h | 1 + .../dependency/hichain/hichain_connector.h | 4 +- .../include/device_manager_service_impl.h | 1 - .../device_manager_service_impl_lite.h | 1 - .../src/authentication/dm_auth_manager.cpp | 36 ++++++-- .../dependency/hichain/hichain_connector.cpp | 84 +++++++++++++++---- .../src/device_manager_service_impl.cpp | 10 +-- .../src/device_manager_service_impl_lite.cpp | 6 -- .../service/include/device_manager_service.h | 3 +- .../include/idevice_manager_service_impl.h | 1 - .../service/src/device_manager_service.cpp | 37 ++++---- .../src/ipc/standard/ipc_server_stub.cpp | 7 +- .../dm_account_common_event.cpp | 12 +-- .../UTTest_device_manager_service.cpp | 2 +- 16 files changed, 174 insertions(+), 73 deletions(-) diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 6cdbc214b..e534ec1ee 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -17,10 +17,15 @@ #define OHOS_DM_MULTIPLE_USER_CONNECTOR_H #include +#include #include #include namespace OHOS { namespace DistributedHardware { +typedef struct DMAccountInfo { + std::string accountId; + std::string accountName; +} DMAccountInfo; class MultipleUserConnector { public: /** @@ -85,11 +90,17 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountName(void); + + static void SetAccountInfo(int32_t userId, DMAccountInfo dmAccountInfo); + static DMAccountInfo GetAccountInfoByUserId(int32_t userId); + static void DeleteAccountInfoByUserId(int32_t userId); private: static int32_t oldUserId_; static std::string accountId_; static std::string accountName_; static std::mutex lock_; + static std::map dmAccountInfoMap_; + static std::mutex dmAccountInfoMaplock_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index c284da7b8..a09f23363 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -32,6 +32,8 @@ int32_t MultipleUserConnector::oldUserId_ = -1; std::string MultipleUserConnector::accountId_ = ""; std::string MultipleUserConnector::accountName_ = ""; std::mutex MultipleUserConnector::lock_; +std::map MultipleUserConnector::dmAccountInfoMap_ = {}; +std::mutex MultipleUserConnector::dmAccountInfoMaplock_; #ifndef OS_ACCOUNT_PART_EXISTS const int32_t DEFAULT_OS_ACCOUNT_ID = 0; // 0 is the default id when there is no os_account part #endif // OS_ACCOUNT_PART_EXISTS @@ -125,5 +127,34 @@ std::string MultipleUserConnector::GetSwitchOldAccountName(void) std::lock_guard lock(lock_); return accountName_; } + +void MultipleUserConnector::SetAccountInfo(int32_t userId, DMAccountInfo dmAccountInfo) +{ + std::lock_guard lock(dmAccountInfoMaplock_); + dmAccountInfoMap_[userId] = dmAccountInfo; +} + +DMAccountInfo MultipleUserConnector::GetAccountInfoByUserId(int32_t userId) +{ + DMAccountInfo dmAccountInfo; + { + std::lock_guard lock(dmAccountInfoMaplock_); + if (dmAccountInfoMap_.find(userId) != dmAccountInfoMap_.end()) { + dmAccountInfo = dmAccountInfoMap_[userId]; + return dmAccountInfo; + } + } + LOGE("userId is not exist."); + return dmAccountInfo; +} + +void MultipleUserConnector::DeleteAccountInfoByUserId(int32_t userId) +{ + std::lock_guard lock(dmAccountInfoMaplock_); + LOGI("userId: %{public}d", userId); + if (dmAccountInfoMap_.find(userId) != dmAccountInfoMap_.end()) { + dmAccountInfoMap_.erase(userId); + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 85982bc12..308c7b535 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -504,6 +504,7 @@ public: void OnScreenLocked(); void HandleDeviceNotTrust(const std::string &udid); int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId); int32_t StopAuthenticateDevice(const std::string &pkgName); private: int32_t ImportCredential(std::string &deviceId, std::string &publicKey); diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index 37c1dbecd..ec99c924e 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -232,13 +232,15 @@ public: int32_t addMultiMembersExt(const std::string &credentialInfo); void DeleteAllGroup(int32_t userId); - + int32_t GetRelatedGroups(int32_t userId, const std::string &deviceId, std::vector &groupList); int32_t GetRelatedGroupsExt(const std::string &deviceId, std::vector &groupList); int32_t DeleteGroupExt(std::string &groupId); int32_t GetRelatedGroupsCommon(const std::string &deviceId, const char* pkgName, std::vector &groupList); + int32_t GetRelatedGroupsCommon(int32_t userId, const std::string &deviceId, const char* pkgName, + std::vector &groupList); void DeleteAllGroupByUdid(const std::string &udid); void DeleteP2PGroup(int32_t switchUserId); int32_t DeleteGroupByACL(std::vector> &delACLInfoVec, diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 551f91518..d2a227d46 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -147,7 +147,6 @@ private: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleUserRemoved(int32_t preUserId); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - void HandleUserSwitched(int32_t switchUserId); private: std::shared_ptr authMgr_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 67c30b863..9a511c04d 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -135,7 +135,6 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleUserSwitched(int32_t switchUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index aa1973ff7..6b5eb79f9 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -198,10 +198,9 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->deviceId = deviceId; authRequestContext_->addr = deviceId; authRequestContext_->dmVersion = DM_VERSION_5_0_2; - authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); - MultipleUserConnector::SetSwitchOldAccountId(authRequestContext_->localAccountId); authRequestContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); - MultipleUserConnector::SetSwitchOldUserId(authRequestContext_->localUserId); + authRequestContext_->localAccountId = MultipleUserConnector::GetAccountInfoByUserId( + authRequestContext_->localUserId).accountId; authRequestContext_->isOnline = false; authRequestContext_->authed = !authRequestContext_->bindType.empty(); authRequestContext_->bindLevel = INVALIED_TYPE; @@ -2102,7 +2101,7 @@ void DmAuthManager::CompatiblePutAcl() accesser.requestBundleName = authResponseContext_->hostPkgName; if (authRequestState_ != nullptr && authResponseState_ == nullptr) { accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId(); + accesser.requestAccountId = MultipleUserConnector::GetAccountInfoByUserId(accesser.requestUserId).accountId; accesser.requestDeviceId = localUdid; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { accesser.requestDeviceId = authResponseContext_->localDeviceId; @@ -2115,7 +2114,7 @@ void DmAuthManager::CompatiblePutAcl() accessee.trustDeviceId = remoteDeviceId_; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { accessee.trustUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accessee.trustAccountId = MultipleUserConnector::GetOhosAccountId(); + accessee.trustAccountId = MultipleUserConnector::GetAccountInfoByUserId(accessee.trustUserId).accountId; accessee.trustDeviceId = localUdid; } DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, accesser, accessee); @@ -2125,10 +2124,8 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) { LOGI("DmAuthManager::ProcRespNegotiateExt start."); remoteDeviceId_ = authResponseContext_->localDeviceId; - std::string accountId = MultipleUserConnector::GetOhosAccountId(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - MultipleUserConnector::SetSwitchOldAccountId(accountId); - MultipleUserConnector::SetSwitchOldUserId(userId); + std::string accountId = MultipleUserConnector::GetAccountInfoByUserId(userId).accountId; authResponseContext_->isIdenticalAccount = false; if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") { authResponseContext_->isIdenticalAccount = true; @@ -2259,6 +2256,29 @@ int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string return DM_OK; } +int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId) +{ + LOGI("DmAuthManager::DeleteGroup"); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_FAILED; + } + std::vector groupList; + hiChainConnector_->GetRelatedGroups(userId, deviceId, groupList); + if (groupList.size() > 0) { + std::string groupId = ""; + groupId = groupList.front().groupId; + hiChainConnector_->DeleteGroup(userId, groupId); + } else { + LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0"); + return ERR_DM_FAILED; + } + if (softbusConnector_ != nullptr) { + softbusConnector_->EraseUdidFromMap(deviceId); + } + return DM_OK; +} + void DmAuthManager::PutAccessControlList() { char localDeviceId[DEVICE_UUID_LENGTH] = {0}; diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 567f6d344..7e2ae818c 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -519,6 +519,12 @@ int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vec return GetRelatedGroupsCommon(deviceId, DM_PKG_NAME, groupList); } +int32_t HiChainConnector::GetRelatedGroups(int32_t userId, const std::string &deviceId, + std::vector &groupList) +{ + return GetRelatedGroupsCommon(userId, deviceId, DM_PKG_NAME, groupList); +} + int32_t HiChainConnector::GetRelatedGroupsExt(const std::string &deviceId, std::vector &groupList) { return GetRelatedGroupsCommon(deviceId, DM_PKG_NAME_EXT, groupList); @@ -650,20 +656,6 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) return DM_OK; } -int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId) -{ - int64_t requestId = GenRequestId(); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); - int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); - if (ret != 0) { - LOGE("[HICHAIN]fail to delete group failed, ret: %{public}d.", ret); - return ERR_DM_FAILED; - } - return DM_OK; -} - int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &userId, const int32_t authType) { networkStyle_ = CREDENTIAL_NETWORK; @@ -1156,6 +1148,70 @@ int32_t HiChainConnector::GetRelatedGroupsCommon(const std::string &deviceId, co return DM_OK; } +int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId) +{ + if (userId < 0) { + LOGE("user id failed"); + return ERR_DM_FAILED; + } + int64_t requestId = GenRequestId(); + nlohmann::json jsonObj; + jsonObj[FIELD_GROUP_ID] = groupId; + std::string disbandParams = jsonObj.dump(); + int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); + if (ret != 0) { + LOGE("[HICHAIN]fail to delete group with ret:%{public}d.", ret); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t HiChainConnector::GetRelatedGroupsCommon(int32_t userId, const std::string &deviceId, const char* pkgName, + std::vector &groupList) +{ + LOGI("Start to get related groups."); + if (userId < 0) { + LOGE("user id failed"); + return ERR_DM_FAILED; + } + uint32_t groupNum = 0; + char *returnGroups = nullptr; + int32_t ret = + deviceGroupManager_->getRelatedGroups(userId, pkgName, deviceId.c_str(), &returnGroups, &groupNum); + if (ret != 0) { + LOGE("[HICHAIN] fail to get related groups with ret:%{public}d.", ret); + returnGroups = nullptr; + return ERR_DM_FAILED; + } + if (returnGroups == nullptr) { + LOGE("[HICHAIN] return related goups point is nullptr"); + return ERR_DM_FAILED; + } + if (groupNum == 0) { + LOGE("[HICHAIN]return related goups number is zero."); + returnGroups = nullptr; + return ERR_DM_FAILED; + } + std::string relatedGroups = std::string(returnGroups); + returnGroups = nullptr; + nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("returnGroups parse error"); + return ERR_DM_FAILED; + } + if (!jsonObject.is_array()) { + LOGE("jsonObject is not an array."); + return ERR_DM_FAILED; + } + std::vector groupInfos = jsonObject.get>(); + if (groupInfos.empty()) { + LOGE("HiChainConnector::GetRelatedGroups group failed, groupInfos is empty."); + return ERR_DM_FAILED; + } + groupList = groupInfos; + return DM_OK; +} + void HiChainConnector::DeleteAllGroupByUdid(const std::string &udid) { LOGI("HiChainConnector::DeleteAllGroupByUdid %{public}s.", GetAnonyString(udid).c_str()); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index f24af10f6..4b5e9da9e 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -681,7 +681,7 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &udid, std::string localUdid = std::string(localUdidTemp); DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, userId, udid); CHECK_NULL_VOID(hiChainConnector_); - authMgr_->DeleteGroup(DM_PKG_NAME, udid); + authMgr_->DeleteGroup(DM_PKG_NAME, userId, udid); } void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) @@ -692,14 +692,6 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) hiChainConnector_->DeleteAllGroup(preUserId); } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) -{ - LOGI("switchUserId: %{public}d.", switchUserId); - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteP2PGroup(switchUserId); -} - void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) { if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index d8b73f856..117f3a743 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -512,12 +512,6 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) -{ - (void)switchUserId; - return; -} - int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) { (void)pkgName; diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index a8bd81208..d603e7e74 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -225,9 +225,8 @@ private: void ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInfo); int32_t ConvertUdidHashToAnoyDeviceId(const std::string &udidHash, std::string &anoyDeviceId); int32_t GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash); - void HandleAccountLogout(int32_t userId, const std::string &accountId); + void HandleAccountLogout(int32_t userId, const std::string &accountId, const std::string &accountName); void HandleUserRemoved(int32_t preUserId); - void HandleUserSwitched(int32_t switchUserId); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index f447e2ebc..9816d1359 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -271,7 +271,6 @@ public: virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; - virtual void HandleUserSwitched(int32_t switchUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 2494ed739..5923fb4eb 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1626,32 +1626,36 @@ void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std: { LOGI("CommonEventType: %{public}s, userId: %{public}d", commonEventType.c_str(), userId); if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - if (MultipleUserConnector::GetSwitchOldUserId() > 0 && - (userId != MultipleUserConnector::GetSwitchOldUserId())) { - HandleUserSwitched(MultipleUserConnector::GetSwitchOldUserId()); - } - MultipleUserConnector::SetSwitchOldUserId(userId); - MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); - MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + MultipleUserConnector::SetAccountInfo(userId, dmAccountInfo); if (IsDMServiceAdapterLoad()) { dmServiceImplExt_->AccountUserSwitched(userId, MultipleUserConnector::GetOhosAccountId()); } } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { - MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); - MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + MultipleUserConnector::SetAccountInfo(userId, dmAccountInfo); } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - HandleAccountLogout(userId, MultipleUserConnector::GetSwitchOldAccountId()); + DMAccountInfo dmAccountInfo = MultipleUserConnector::GetAccountInfoByUserId(userId); + HandleAccountLogout(userId, dmAccountInfo.accountId, dmAccountInfo.accountName); + MultipleUserConnector::DeleteAccountInfoByUserId(userId); } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { HandleUserRemoved(userId); + MultipleUserConnector::DeleteAccountInfoByUserId(userId); } else { LOGE("Invalied account common event."); } return; } -void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string &accountId) +void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string &accountId, + const std::string &accountName) { - LOGI("UserId %{public}d, accountId %{public}s.", userId, GetAnonyString(accountId).c_str()); + LOGI("UserId: %{public}d, accountId: %{public}s, accountName: %{public}s", userId, GetAnonyString(accountId).c_str(), + GetAnonyString(accountName).c_str()); if (IsDMServiceAdapterLoad()) { dmServiceImplExt_->AccountIdLogout(userId, accountId); } @@ -1674,19 +1678,10 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string LOGE("GetAccountHash failed."); return; } - std::string accountName = MultipleUserConnector::GetSwitchOldAccountName(); SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); } } -void DeviceManagerService::HandleUserSwitched(int32_t switchUserId) -{ - LOGI("switchUserId: %{public}d.", switchUserId); - if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleUserSwitched(switchUserId); - } -} - void DeviceManagerService::HandleUserRemoved(int32_t preUserId) { LOGI("PreUserId %{public}d.", preUserId); diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 1b04c48f0..a831a2f7b 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -110,9 +110,10 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin #endif // SUPPORT_MEMMGR if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) { - MultipleUserConnector::SetSwitchOldUserId(MultipleUserConnector::GetCurrentAccountUserID()); - MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); - MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + MultipleUserConnector::SetAccountInfo(MultipleUserConnector::GetCurrentAccountUserID(), dmAccountInfo); DeviceManagerService::GetInstance().InitAccountInfo(); return; } diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 50ca53d73..b867bb1f1 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -181,13 +181,15 @@ void DmAccountCommonEventManager::SystemAbilityStatusChangeListener::OnAddSystem if (!CommonEventManager::SubscribeCommonEvent(changeSubscriber_)) { LOGE("failed to subscribe account commom event: %{public}zu", eventNameVec.size()); } + DMAccountInfo dmAccountInfo; int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - LOGI("after subscribe account event accountId: %{public}s, userId: %{public}s", - GetAnonyString(accountId).c_str(), GetAnonyInt32(userId).c_str()); + dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); + dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); + LOGI("after subscribe account event accountId: %{public}s, userId: %{public}s, accountName: %{public}s", + GetAnonyString(dmAccountInfo.accountId).c_str(), GetAnonyInt32(userId).c_str(), + GetAnonyString(dmAccountInfo.accountName).c_str()); if (userId > 0) { - MultipleUserConnector::SetSwitchOldUserId(userId); - MultipleUserConnector::SetSwitchOldAccountId(accountId); + MultipleUserConnector::SetAccountInfo(userId, dmAccountInfo); } } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 738809e6a..197e065a7 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -354,7 +354,7 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::T DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); - DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); DeviceManagerService::GetInstance().SendAccountLogoutBroadCast(peerUdids, accountId, accountName, userId); -- Gitee From 9ee845a1987fb2c361c8df82fbebaa0a26bb89e1 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Sun, 17 Nov 2024 10:20:11 +0800 Subject: [PATCH 396/520] =?UTF-8?q?=E9=80=82=E9=85=8D=E5=A4=9A=E7=94=A8?= =?UTF-8?q?=E6=88=B7=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../device_manager_ipc_interface_code.h | 3 - common/include/dm_anonymous.h | 64 +- common/include/dm_constants.h | 1 + common/include/ipc/model/ipc_req.h | 13 +- .../ipc/model/ipc_start_discover_req.h | 73 -- .../ipc/model/ipc_start_discovery_req.h | 74 -- .../ipc/model/ipc_stop_discovery_req.h | 54 -- common/src/dm_anonymous.cpp | 80 +++ common/src/dm_error_message.cpp | 2 +- .../include/deviceprofile_connector.h | 41 +- .../include/multiple_user_connector.h | 22 +- .../src/deviceprofile_connector.cpp | 659 ++++++++++++++---- .../src/multiple_user_connector.cpp | 146 +++- .../native_cpp/include/device_manager_impl.h | 7 +- .../native_cpp/include/dm_device_info.h | 39 ++ .../include/notify/device_manager_notify.h | 1 + .../native_cpp/src/device_manager_impl.cpp | 308 ++++---- .../src/ipc/lite/ipc_cmd_parser.cpp | 40 -- .../src/ipc/standard/ipc_cmd_parser.cpp | 83 --- .../src/notify/device_manager_notify.cpp | 108 +-- .../authentication/auth_message_processor.h | 1 + .../authentication/auth_ui_state_manager.h | 2 +- .../include/authentication/dm_auth_manager.h | 14 +- .../credential/dm_credential_manager.h | 5 +- .../dependency/softbus/softbus_connector.h | 14 +- .../include/device_manager_service_impl.h | 15 +- .../device_manager_service_impl_lite.h | 13 +- .../devicestate/dm_device_state_manager.h | 1 - .../authentication/auth_message_processor.cpp | 9 +- .../authentication/auth_ui_state_manager.cpp | 26 +- .../src/authentication/dm_auth_manager.cpp | 200 ++++-- .../src/credential/dm_credential_manager.cpp | 31 +- .../dependency/softbus/softbus_connector.cpp | 32 +- .../src/device_manager_service_impl.cpp | 258 +++++-- .../src/device_manager_service_impl_lite.cpp | 51 +- .../devicestate/dm_device_state_manager.cpp | 62 +- .../src/discovery/dm_discovery_manager.cpp | 8 - services/service/BUILD.gn | 5 +- .../service/include/device_manager_service.h | 55 +- .../include/device_manager_service_listener.h | 67 +- .../include/discovery/discovery_manager.h | 13 +- .../include/idevice_manager_service_impl.h | 13 +- .../idevice_manager_service_listener.h | 42 +- .../include/ipc/lite/ipc_server_listener.h | 16 +- .../ipc/standard/ipc_server_listener.h | 17 +- .../include/ipc/standard/ipc_server_stub.h | 29 +- .../permission/lite/permission_manager.h | 3 +- .../permission/standard/permission_manager.h | 3 +- .../service/include/pinholder/pin_holder.h | 2 +- .../dm_account_common_event.h | 14 +- .../relationshipsyncmgr/dm_comm_tool.h | 69 ++ .../relationshipsyncmgr/dm_transport.h | 67 ++ .../relationshipsyncmgr/dm_transport_msg.h | 77 ++ .../relationship_sync_mgr.h | 31 +- .../include/softbus/softbus_listener.h | 2 + .../service/src/device_manager_service.cpp | 425 ++++++++--- .../src/device_manager_service_listener.cpp | 532 +++++++++----- .../src/discovery/discovery_manager.cpp | 134 +++- .../service/src/ipc/lite/ipc_cmd_parser.cpp | 21 - .../src/ipc/lite/ipc_server_listener.cpp | 37 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 59 +- .../src/ipc/standard/ipc_server_listener.cpp | 27 +- .../src/ipc/standard/ipc_server_stub.cpp | 114 +-- .../permission/lite/permission_manager.cpp | 10 +- .../standard/permission_manager.cpp | 18 +- services/service/src/pinholder/pin_holder.cpp | 88 +-- .../dm_account_common_event.cpp | 32 +- .../src/relationshipsyncmgr/dm_comm_tool.cpp | 259 +++++++ .../src/relationshipsyncmgr/dm_transport.cpp | 454 ++++++++++++ .../relationshipsyncmgr/dm_transport_msg.cpp | 208 ++++++ .../relationship_sync_mgr.cpp | 276 +++++++- .../service/src/softbus/softbus_listener.cpp | 44 +- .../authenticate_device_fuzzer.cpp | 2 +- .../authenticatedeviceservice_fuzzer/BUILD.gn | 1 + .../BUILD.gn | 1 + .../UTTest_discovery_manager.cpp | 12 +- test/commonunittest/UTTest_dm_anonymous.cpp | 4 +- .../UTTest_dm_auth_manager_first.cpp | 19 +- .../UTTest_dm_credential_manager.h | 2 +- .../UTTest_dm_device_state_manager.cpp | 9 - .../UTTest_dm_deviceprofile_connector.cpp | 75 +- .../UTTest_permission_manager.cpp | 28 +- .../devicemanagerservice_fuzzer/BUILD.gn | 1 + .../device_manager_service_fuzzer.cpp | 3 - .../device_profile_connector_fuzzer.cpp | 4 +- .../BUILD.gn | 1 + .../ipc_cmd_register_fuzzer.cpp | 2 - .../ipc_server_listener_fuzzer.cpp | 1 - .../ipc_server_stub_fuzzer.cpp | 10 +- .../shiftlnngeardeviceservice_fuzzer/BUILD.gn | 1 + .../softbus_connector_common_fuzzer.cpp | 1 - .../UTTest_softbus_connector.cpp | 38 +- test/unittest/BUILD.gn | 9 + test/unittest/UTTest_device_manager_impl.cpp | 14 +- .../UTTest_device_manager_impl_three.cpp | 11 +- .../UTTest_device_manager_impl_two.cpp | 16 +- .../UTTest_device_manager_notify_two.cpp | 6 +- .../UTTest_device_manager_service.cpp | 161 +---- .../UTTest_device_manager_service_impl.cpp | 61 +- ...UTTest_device_manager_service_listener.cpp | 124 ++-- .../UTTest_device_manager_service_two.cpp | 29 +- test/unittest/UTTest_dm_pin_holder.cpp | 32 +- test/unittest/UTTest_dm_pin_holder.h | 83 ++- .../UTTest_ipc_client_server_proxy.cpp | 2 - .../unittest/UTTest_ipc_cmd_parser_client.cpp | 8 - .../UTTest_ipc_cmd_parser_service.cpp | 58 -- test/unittest/UTTest_ipc_cmd_register.cpp | 68 -- .../UTTest_ipc_server_client_proxy.cpp | 20 +- test/unittest/UTTest_ipc_server_listener.cpp | 110 +-- test/unittest/UTTest_ipc_server_stub.cpp | 156 ++--- .../mock/deviceprofile_connector_mock.cpp | 18 - .../mock/deviceprofile_connector_mock.h | 8 +- test/unittest/mock/ipc_server_listener.cpp | 8 - test/unittest/mock/ipc_server_listener.h | 16 +- utils/include/appInfo/lite/app_manager.h | 3 + utils/include/appInfo/standard/app_manager.h | 3 + utils/src/appInfo/lite/app_manager.cpp | 22 + utils/src/appInfo/standard/app_manager.cpp | 54 ++ 118 files changed, 4625 insertions(+), 2513 deletions(-) delete mode 100644 common/include/ipc/model/ipc_start_discover_req.h delete mode 100644 common/include/ipc/model/ipc_start_discovery_req.h delete mode 100644 common/include/ipc/model/ipc_stop_discovery_req.h create mode 100644 services/service/include/relationshipsyncmgr/dm_comm_tool.h create mode 100644 services/service/include/relationshipsyncmgr/dm_transport.h create mode 100644 services/service/include/relationshipsyncmgr/dm_transport_msg.h create mode 100644 services/service/src/relationshipsyncmgr/dm_comm_tool.cpp create mode 100644 services/service/src/relationshipsyncmgr/dm_transport.cpp create mode 100644 services/service/src/relationshipsyncmgr/dm_transport_msg.cpp diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index cd6dee5cd..b0b7f485b 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -29,9 +29,6 @@ enum DMIpcCmdInterfaceCode { GET_UDID_BY_NETWORK, GET_UUID_BY_NETWORK, GET_NETWORKTYPE_BY_NETWORK, - START_DEVICE_DISCOVER, - START_DEVICE_DISCOVERY, - STOP_DEVICE_DISCOVER, PUBLISH_DEVICE_DISCOVER, UNPUBLISH_DEVICE_DISCOVER, AUTHENTICATE_DEVICE, diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 292a3049c..12e5d9776 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -18,15 +18,20 @@ #include #include - -#include "dm_device_info.h" - #include "nlohmann/json.hpp" +#include +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { +namespace { + const std::string PRINT_LIST_SPLIT = ", "; + const int32_t LIST_SPLIT_LEN = 2; +} std::string GetAnonyString(const std::string &value); +std::string GetAnonyStringList(const std::vector &values); std::string GetAnonyInt32(const int32_t value); +std::string GetAnonyInt32List(const std::vector &values); bool IsNumberString(const std::string &inputString); bool IsString(const nlohmann::json &jsonObj, const std::string &key); bool IsInt32(const nlohmann::json &jsonObj, const std::string &key); @@ -43,6 +48,59 @@ int64_t StringToInt64(const std::string &str, int32_t base); void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec); bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); +std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId); +std::string GetCallerPkgName(const std::string &pkgName); +uint16_t GetSubscribeId(const std::string &pkgName); +template +std::string GetAnonyInteger(const T value) +{ + std::string tempString = std::to_string(value); + size_t length = tempString.length(); + if (length == 0x01) { + tempString[0] = '*'; + return tempString; + } + for (size_t i = 1; i < length - 1; i++) { + tempString[i] = '*'; + } + return tempString; +} + +template +std::string GetAnonyIntegerList(const std::vector &values) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &v : values) { + temp += GetAnonyInteger(v) + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + +template +std::string GetIntegerList(const std::vector &values) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &v : values) { + temp += std::to_string(v) + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + +bool IsIdLengthValid(const std::string &inputID); +bool IsMessageLengthValid(const std::string &inputMessage); +bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 932dc0562..856920cd6 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -133,6 +133,7 @@ constexpr const char* DM_ITF_VER = "1.1"; constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; constexpr const char* DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; constexpr const char* DM_PIN_HOLDER_SESSION_NAME = "ohos.distributedhardware.devicemanager.pinholder"; +constexpr const char* DM_SYNC_USERID_SESSION_NAME = "ohos.distributedhardware.devicemanager.syncuserid"; constexpr const char* DM_CAPABILITY_OSD = "osdCapability"; constexpr const char* DM_CAPABILITY_APPROACH = "approach"; constexpr const char* DM_CAPABILITY_TOUCH = "touch"; diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index fd0d0c785..f16984c71 100644 --- a/common/include/ipc/model/ipc_req.h +++ b/common/include/ipc/model/ipc_req.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include #include "ipc_def.h" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -36,8 +37,18 @@ public: pkgName_ = pkgName; } + const ProcessInfo GetProcessInfo() const + { + return processInfo_; + } + + void SetProcessInfo(const ProcessInfo &processInfo) + { + processInfo_ = processInfo; + } private: std::string pkgName_; + ProcessInfo processInfo_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/common/include/ipc/model/ipc_start_discover_req.h b/common/include/ipc/model/ipc_start_discover_req.h deleted file mode 100644 index 863951cea..000000000 --- a/common/include/ipc/model/ipc_start_discover_req.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DM_IPC_START_DISCOVER_REQ_H -#define OHOS_DM_IPC_START_DISCOVER_REQ_H - -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcStartDevDiscoveryByIdReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStartDevDiscoveryByIdReq); - -public: - /** - * @tc.name: IpcStartDiscoveryReq::GetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Get SubscribeInfo - * @tc.type: FUNC - */ - const uint16_t &GetSubscribeId() const - { - return subscribeId_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Set SubscribeInfo - * @tc.type: FUNC - */ - void SetSubscribeId(const uint16_t &subscribeId) - { - subscribeId_ = subscribeId; - } - - /** - * @tc.name: IpcStartDiscoveryReq::GetExtra - * @tc.desc: Ipc Start Discovery Request Get Extra - * @tc.type: FUNC - */ - const std::string &GetFilterOption() const - { - return filterOptions_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetExtra - * @tc.desc: Ipc Start Discovery Request Set Extra - * @tc.type: FUNC - */ - void SetFilterOption(const std::string &filterOptions) - { - filterOptions_ = filterOptions; - } - -private: - std::string filterOptions_; - uint16_t subscribeId_ { 0 }; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_START_DISCOVER_REQ_H diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h deleted file mode 100644 index 421402c85..000000000 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DM_IPC_START_DISCOVERY_REQ_H -#define OHOS_DM_IPC_START_DISCOVERY_REQ_H - -#include "dm_subscribe_info.h" -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcStartDiscoveryReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStartDiscoveryReq); - -public: - /** - * @tc.name: IpcStartDiscoveryReq::GetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Get SubscribeInfo - * @tc.type: FUNC - */ - const DmSubscribeInfo &GetSubscribeInfo() const - { - return subscribeInfo_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Set SubscribeInfo - * @tc.type: FUNC - */ - void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) - { - subscribeInfo_ = subscribeInfo; - } - - /** - * @tc.name: IpcStartDiscoveryReq::GetExtra - * @tc.desc: Ipc Start Discovery Request Get Extra - * @tc.type: FUNC - */ - const std::string &GetExtra() const - { - return extra_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetExtra - * @tc.desc: Ipc Start Discovery Request Set Extra - * @tc.type: FUNC - */ - void SetExtra(const std::string &extra) - { - extra_ = extra; - } - -private: - std::string extra_; - DmSubscribeInfo subscribeInfo_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_START_DISCOVERY_REQ_H diff --git a/common/include/ipc/model/ipc_stop_discovery_req.h b/common/include/ipc/model/ipc_stop_discovery_req.h deleted file mode 100644 index d5d2ae5ec..000000000 --- a/common/include/ipc/model/ipc_stop_discovery_req.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DM_IPC_STOP_DISCOVERY_REQ_H -#define OHOS_DM_IPC_STOP_DISCOVERY_REQ_H - -#include - -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcStopDiscoveryReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStopDiscoveryReq); - -public: - /** - * @tc.name: IpcStopDiscoveryReq::GetSubscribeId - * @tc.desc: Ipc stop discovery request get subscription id - * @tc.type: FUNC - */ - uint16_t GetSubscribeId() const - { - return subscribeId_; - } - - /** - * @tc.name: IpcStopDiscoveryReq::SetSubscribeId - * @tc.desc: Ipc stop discovery request set subscription id - * @tc.type: FUNC - */ - void SetSubscribeId(uint16_t subscribeId) - { - subscribeId_ = subscribeId; - } - -private: - uint16_t subscribeId_ { 0 }; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_STOP_DISCOVERY_REQ_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 6bfd22004..140338771 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -22,6 +22,7 @@ namespace { constexpr uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; constexpr uint32_t MAX_MAP_LEN = 1000; constexpr uint32_t MAX_INT_LEN = 20; +constexpr uint32_t MAX_ID_LEN = 256; } std::string GetAnonyString(const std::string &value) @@ -50,6 +51,15 @@ std::string GetAnonyString(const std::string &value) return res; } +std::string GetAnonyStringList(const std::vector &values) +{ + std::string temp = ""; + for (auto const &v : values) { + temp += GetAnonyString(v) + ", "; + } + return temp; +} + std::string GetAnonyInt32(const int32_t value) { std::string tempString = std::to_string(value); @@ -64,6 +74,15 @@ std::string GetAnonyInt32(const int32_t value) return tempString; } +std::string GetAnonyInt32List(const std::vector &values) +{ + std::string temp = ""; + for (auto const &v : values) { + temp += GetAnonyInt32(v) + ", "; + } + return temp; +} + bool IsNumberString(const std::string &inputString) { LOGI("IsNumberString for DeviceManagerNapi"); @@ -265,5 +284,66 @@ bool CompareVersion(const std::string &remoteVersion, const std::string &oldVers VersionSplitToInt(oldVersion, '.', oldVersionVec); return CompareVecNum(remoteVersionVec, oldVersionVec); } + +std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId) +{ + std::string strTemp = pkgName + "#" + std::to_string(subscribeId); + return strTemp; +} + +std::string GetCallerPkgName(const std::string &pkgName) +{ + std::istringstream stream(pkgName); + std::string item = ""; + getline(stream, item, '#'); + return item; +} + +uint16_t GetSubscribeId(const std::string &pkgName) +{ + std::vector strVec; + size_t subIdIndex = 1; + size_t start = 0; + size_t end = pkgName.find("#"); + + while (end != std::string::npos) { + strVec.push_back(pkgName.substr(start, end - start)); + start = end + 1; + end = pkgName.find("#", start); + } + strVec.push_back(pkgName.substr(start)); + if (strVec.size() >= subIdIndex + 1) { + return std::atoi(strVec.at(subIdIndex).c_str()); + } + return 0; +} + +bool IsIdLengthValid(const std::string &inputID) +{ + if (inputID.empty() || inputID.length() > MAX_ID_LEN) { + LOGE("On parameter length error, maybe empty or beyond MAX_ID_LEN!"); + return false; + } + return true; +} + +bool IsMessageLengthValid(const std::string &inputMessage) +{ + if (inputMessage.empty() || inputMessage.length() > MAX_MESSAGE_LEN) { + LOGE("On parameter error, maybe empty or beyond MAX_MESSAGE_LEN!"); + return false; + } + return true; +} + +bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId) +{ + for (const auto &item : unorderedmap) { + if (item.first == udid && item.second == userId) { + return true; + } + } + return false; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/common/src/dm_error_message.cpp b/common/src/dm_error_message.cpp index 8cf81bdfa..18d2cbe11 100644 --- a/common/src/dm_error_message.cpp +++ b/common/src/dm_error_message.cpp @@ -25,7 +25,7 @@ typedef struct ERROR_INFO { } ERROR_INFO; ERROR_INFO g_errorMessages[] = { - {ERR_DM_FAILED, "dm process execution failed."}, + {ERR_DM_FAILED, "dm process execution failed..."}, {ERR_DM_TIME_OUT, "dm process execution timeout."}, {ERR_DM_NOT_INIT, "dm service is not initialized, please try again later."}, {ERR_DM_INIT_FAILED, "dm service initialize failed."}, diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index fb95f058b..0c4f7fc45 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -45,6 +45,7 @@ constexpr uint32_t ACTIVE = 1; typedef struct DmDiscoveryInfo { std::string pkgname; std::string localDeviceId; + int32_t userId; std::string remoteDeviceIdHash; } DmDiscoveryInfo; @@ -78,7 +79,7 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; - std::vector pkgNameVec; + std::vector processVec; int32_t leftAclNumber; } DmOfflineParam; @@ -95,22 +96,25 @@ class DeviceProfileConnector : public IDeviceProfileConnector { public: std::vector GetAccessControlProfile(); std::vector GetAccessControlProfileByUserId(int32_t userId); - uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId); + std::vector GetAclProfileByDeviceIdAndUserId( + const std::string &deviceId, int32_t userId); + uint32_t CheckBindType(std::string peerUdid, std::string localUdid); int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee); int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId); std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, const std::string &deviceId); - DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId); std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid); std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId); int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); - void DeleteAclForAccountLogOut(const std::string &localUdid, int32_t userId, const std::string &remoteUdid); - void DeleteAclForUserRemoved(int32_t userId); + int32_t DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId); + void DeleteAclForUserRemoved(std::string localUdid, int32_t userId); DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel); - std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId); + std::vector GetProcessInfoFromAclByUserId(const std::string &localDeviceId, + const std::string &targetDeviceId, int32_t userId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); @@ -127,15 +131,30 @@ public: void DeleteAccessControlList(const std::string &udid); int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); - std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId, + std::map GetDeviceIdAndBindLevel(std::vector userIds, const std::string &localUdid); + std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId, const std::string &localUdid); int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid); int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); - std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, - const std::string &localUdid); + OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid); std::vector GetAllAccessControlProfile(); void DeleteAccessControlById(int64_t accessControlId); + int32_t HandleUserSwitched(const std::string &localUdid, int32_t currentUserId, int32_t beforeUserId); + void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid, + const std::vector &localUserIds, std::string &localUdid); + std::vector GetOfflineProcessInfo(std::string &localUdid, const std::vector &localUserIds, + const std::string &remoteUdid, const std::vector &remoteUserIds); + std::map GetUserIdAndBindLevel(const std::string &localUdid, const std::string &peerUdid); + void UpdatePeerUserId(std::string &localUdid, const std::vector &localUserIds, + const std::string &remoteUdid, const std::vector &remoteFrontUserIds, + const std::vector &remoteBackUserIds); + std::multimap GetDevIdAndUserIdByActHash(const std::string &localUdid, + const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash); + std::multimap GetDeviceIdAndUserId(const std::string &localUdid, int32_t localUserId); + void HandleSyncBackgroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid, + const std::vector &localUserIds, std::string &localUdid); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); @@ -158,7 +177,9 @@ private: void DeleteServiceBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid); - void UpdateBindType(const std::string &udid, int32_t bindType, std::map &deviceMap); + void UpdateBindType(const std::string &udid, int32_t compareParam, std::map &deviceMap); + std::vector GetAclProfileByUserId(const std::string &localUdid, + int32_t userId, const std::string &remoteUdid); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index e534ec1ee..2df32cf7c 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,6 +20,7 @@ #include #include #include +#include namespace OHOS { namespace DistributedHardware { typedef struct DMAccountInfo { @@ -51,11 +52,19 @@ public: /** * @tc.name: MultipleUserConnector::GetOhosAccountId - * @tc.desc: Get Current AccountId of the Multiple User Connector + * @tc.desc: Get Current AccountId of current user * @tc.type: FUNC */ static std::string GetOhosAccountId(void); - + + /** + * @brief Get the Ohos Account Id By Userid + * + * @param userId the user id in which account login + * @return std::string the account id + */ + static std::string GetOhosAccountIdByUserId(int32_t userId); + /** * @tc.name: MultipleUserConnector::SetSwitchOldAccountId * @tc.desc: Set Switch Old UserId of the Multiple User Connector @@ -94,6 +103,13 @@ public: static void SetAccountInfo(int32_t userId, DMAccountInfo dmAccountInfo); static DMAccountInfo GetAccountInfoByUserId(int32_t userId); static void DeleteAccountInfoByUserId(int32_t userId); + static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); + static void GetCallerUserId(int32_t &userId); + static int32_t GetForegroundUserIds(std::vector &userVec); + static int32_t GetFirstForegroundUserId(void); + static int32_t GetBackgroundUserIds(std::vector &userIdVec); + static int32_t GetAllUserIds(std::vector &userIdVec); + private: static int32_t oldUserId_; static std::string accountId_; diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index c581a8224..36f7dcb03 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -49,12 +49,42 @@ std::vector DeviceProfileConnector::GetAccessControlProfil return profiles; } +std::vector DeviceProfileConnector::GetAclProfileByDeviceIdAndUserId(const std::string &deviceId, + int32_t userId) +{ + std::vector profiles; + std::vector aclProfileVec; + std::map queryParams; + queryParams[USERID] = std::to_string(userId); + if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { + LOGE("DP GetAccessControlProfile failed."); + } + for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserDeviceId() == deviceId && + item.GetAccesser().GetAccesserUserId() == userId) || + (item.GetAccessee().GetAccesseeDeviceId() == deviceId && + item.GetAccessee().GetAccesseeUserId() == userId)) { + aclProfileVec.push_back(item); + } + } + return aclProfileVec; +} + std::unordered_map DeviceProfileConnector::GetAppTrustDeviceList(const std::string &pkgName, const std::string &deviceId) { - std::vector profiles = GetAccessControlProfile(); - std::unordered_map deviceIdMap; + int32_t userId = MultipleUserConnector::GetFirstForegroundUserId(); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(deviceId, userId); + std::vector profilesFilter = {}; for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserUserId() == userId && item.GetAccesser().GetAccesserDeviceId() == deviceId) + || (item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == deviceId)) { + profilesFilter.push_back(item); + } + } + std::unordered_map deviceIdMap; + for (auto &item : profilesFilter) { std::string trustDeviceId = item.GetTrustDeviceId(); if (trustDeviceId == deviceId || item.GetStatus() != ACTIVE) { continue; @@ -87,18 +117,19 @@ std::unordered_map DeviceProfileConnector::GetAppTrustD int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm) { - std::vector profiles = GetAccessControlProfile(); - if (profiles.size() == 0) { - return DM_OK; - } + std::vector profiles = GetAccessControlProfileByUserId(discoveryInfo.userId); std::vector bindTypes; for (auto &item : profiles) { char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(item.GetTrustDeviceId(), reinterpret_cast(deviceIdHash)) != DM_OK) { LOGE("get deviceIdHash by deviceId: %{public}s failed.", GetAnonyString(deviceIdHash).c_str()); - return ERR_DM_FAILED; + continue; } - if (static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || item.GetStatus() != ACTIVE) { + if (static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || + (discoveryInfo.localDeviceId == item.GetAccesser().GetAccesserDeviceId() && + discoveryInfo.userId != item.GetAccesser().GetAccesserUserId()) || + (discoveryInfo.localDeviceId == item.GetAccessee().GetAccesseeDeviceId() && + discoveryInfo.userId != item.GetAccessee().GetAccesseeUserId())) { continue; } int32_t bindType = HandleDmAuthForm(item, discoveryInfo); @@ -162,17 +193,17 @@ int32_t DeviceProfileConnector::HandleDmAuthForm(AccessControlProfile profiles, return DmAuthForm::INVALID_TYPE; } -uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::string requestDeviceId) +uint32_t DeviceProfileConnector::CheckBindType(std::string peerUdid, std::string localUdid) { - LOGI("Start."); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + std::vector filterProfiles = GetAclProfileByUserId(localUdid, + MultipleUserConnector::GetFirstForegroundUserId(), peerUdid); + LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); uint32_t highestPriority = INVALIED_TYPE; - for (auto &item : profiles) { - if (trustDeviceId != item.GetTrustDeviceId() || item.GetStatus() != ACTIVE) { + for (auto &item : filterProfiles) { + if (peerUdid != item.GetTrustDeviceId()) { continue; } - uint32_t priority = static_cast(GetAuthForm(item, trustDeviceId, requestDeviceId)); + uint32_t priority = static_cast(GetAuthForm(item, peerUdid, localUdid)); if (priority > highestPriority) { highestPriority = priority; } @@ -194,22 +225,18 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont case DM_POINT_TO_POINT: if (profiles.GetBindLevel() == DEVICE) { priority = DEVICE_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccesser().GetAccesserDeviceId() == reqDev && - profiles.GetAccessee().GetAccesseeDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccessee().GetAccesseeDeviceId() == reqDev && - profiles.GetAccesser().GetAccesserDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; } break; case DM_ACROSS_ACCOUNT: if (profiles.GetBindLevel() == DEVICE) { priority = DEVICE_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccesser().GetAccesserDeviceId() == reqDev && - profiles.GetAccessee().GetAccesseeDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccessee().GetAccesseeDeviceId() == reqDev && - profiles.GetAccesser().GetAccesserDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; } break; @@ -224,7 +251,8 @@ std::vector DeviceProfileConnector::GetBindTypeByPkgName(std::string pk std::string trustUdid) { LOGI("Start."); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetFirstForegroundUserId()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector bindTypeVec; for (auto &item : profiles) { @@ -339,7 +367,8 @@ void DeviceProfileConnector::ProcessBindType(AccessControlProfile profiles, DmDi std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId) { - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetFirstForegroundUserId()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector sinkBindType; std::vector bindType; @@ -361,61 +390,23 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa return bindType; } -std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string &localDeviceId, - std::string &targetDeviceId) +std::vector DeviceProfileConnector::GetProcessInfoFromAclByUserId( + const std::string &localDeviceId, const std::string &targetDeviceId, int32_t userId) { - LOGI("Start."); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - std::vector pkgNameVec; - for (auto &item : profiles) { + std::vector filterProfiles = GetAclProfileByUserId(localDeviceId, + userId, targetDeviceId); + LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); + std::vector processInfoVec; + for (auto &item : filterProfiles) { if (item.GetTrustDeviceId() != targetDeviceId || item.GetStatus() != ACTIVE) { continue; } - if ((item.GetAccesser().GetAccesserDeviceId() == localDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == targetDeviceId) || - (item.GetAccesser().GetAccesserDeviceId() == targetDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == localDeviceId)) { - pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } - } - return pkgNameVec; -} - -DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) -{ - LOGI("TrustDeviceId = %{public}s and requestDeviceId = %{public}s", - GetAnonyString(trustDeviceId).c_str(), GetAnonyString(requestDeviceId).c_str()); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - DmOfflineParam offlineParam; - offlineParam.leftAclNumber = 0; - offlineParam.bindType = INVALIED_TYPE; - for (auto &item : profiles) { - if (item.GetTrustDeviceId() != trustDeviceId || item.GetStatus() != ACTIVE) { - continue; - } - offlineParam.leftAclNumber++; - uint32_t priority = INVALIED_TYPE; - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - priority = IDENTICAL_ACCOUNT_TYPE; - } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ALWAYS) { - priority = DEVICE_PEER_TO_PEER_TYPE; - } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { - priority = DEVICE_PEER_TO_PEER_TYPE; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } else if ((item.GetAccesser().GetAccesserDeviceId() == requestDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == trustDeviceId) || - (item.GetAccesser().GetAccesserDeviceId() == trustDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == requestDeviceId)) { - priority = APP_PEER_TO_PEER_TYPE; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } - if (priority > offlineParam.bindType) { - offlineParam.bindType = priority; - } + OHOS::DistributedHardware::ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfoVec.push_back(processInfo); } - return offlineParam; + return processInfoVec; } int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee) @@ -450,25 +441,48 @@ int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccess return ret; } -void DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t userId, - const std::string &remoteUdid) +int32_t DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) { - LOGI("localUdid %{public}s, userId %{public}d, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), userId, - GetAnonyString(remoteUdid).c_str()); - std::vector profiles = GetAccessControlProfileByUserId(userId); + LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", + GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); + std::vector profiles = GetAllAccessControlProfile(); + bool notifyOffline = false; for (const auto &item : profiles) { - if (item.GetTrustDeviceId() == remoteUdid) { + if (item.GetTrustDeviceId() != peerUdid) { + continue; + } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesserUserId == localUserId && + accesseeUdid == peerUdid && accesseeUserId == peerUserId) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + notifyOffline = (item.GetStatus() == ACTIVE); + continue; + } + if (accesserUdid == peerUdid && accesserUserId == peerUserId && + accesseeUdid == localUdid && accesseeUserId == localUserId) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + notifyOffline = (item.GetStatus() == ACTIVE); + continue; } } + return notifyOffline; } -void DeviceProfileConnector::DeleteAclForUserRemoved(int32_t userId) +void DeviceProfileConnector::DeleteAclForUserRemoved(std::string localUdid, int32_t userId) { - LOGI("DeleteAclForUserRemoved userId %{public}d.", userId); + LOGI("localUdid %{public}s, userId %{public}d.", GetAnonyString(localUdid).c_str(), userId); std::vector profiles = GetAccessControlProfileByUserId(userId); for (const auto &item : profiles) { - if (item.GetAccesser().GetAccesserUserId() == userId || item.GetAccessee().GetAccesseeUserId() == userId) { + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if ((accesserUdid == localUdid && accesserUserId == userId) || + (accesseeUdid == localUdid && accesseeUserId == userId)) { DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); } } @@ -539,6 +553,10 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -550,6 +568,10 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -653,24 +675,6 @@ int32_t DeviceProfileConnector::UpdateAccessControlList(int32_t userId, std::str return DM_OK; } -bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::string &accountId) -{ - LOGI("Start"); - std::vector profiles; - std::map queryParams; - queryParams[USERID] = std::to_string(userId); - queryParams[ACCOUNTID] = accountId; - if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { - LOGE("DP GetAccessControlProfile failed."); - } - for (auto &item : profiles) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT && item.GetStatus() == ACTIVE) { - return true; - } - } - return false; -} - bool DeviceProfileConnector::CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId) { LOGI("Start"); @@ -756,13 +760,48 @@ int32_t DeviceProfileConnector::IsSameAccount(const std::string &udid) return ERR_DM_FAILED; } +std::vector GetACLByDeviceIdAndUserId(std::vector profiles, + const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) +{ + std::vector profilesFilter; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserUserId() == caller.userId + && item.GetAccesser().GetAccesserDeviceId() == srcUdid + && item.GetAccessee().GetAccesseeDeviceId() == sinkUdid) { + profilesFilter.push_back(item); + continue; + } + if (item.GetAccesser().GetAccesserUserId() == callee.userId + && item.GetAccesser().GetAccesserDeviceId() == sinkUdid + && item.GetAccessee().GetAccesseeDeviceId() == srcUdid) { + profilesFilter.push_back(item); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == caller.userId + && item.GetAccessee().GetAccesseeDeviceId() == srcUdid + && item.GetAccesser().GetAccesserDeviceId() == sinkUdid) { + profilesFilter.push_back(item); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == callee.userId + && item.GetAccessee().GetAccesseeDeviceId() == sinkUdid + && item.GetAccesser().GetAccesserDeviceId() == srcUdid) { + profilesFilter.push_back(item); + continue; + } + } + return profilesFilter; +} + int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) { LOGI("PkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - for (auto &item : profiles) { + std::vector profiles = GetAllAccessControlProfile(); + std::vector profilesFilter + = GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, callee, sinkUdid); + for (auto &item : profilesFilter) { if (item.GetStatus() != ACTIVE || (item.GetTrustDeviceId() != sinkUdid && item.GetTrustDeviceId() != srcUdid)) { continue; @@ -774,6 +813,24 @@ int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, return ERR_DM_FAILED; } +bool DeviceProfileConnector::CheckIdenticalAccount(int32_t userId, const std::string &accountId) +{ + LOGI("Start"); + std::vector profiles; + std::map queryParams; + queryParams[USERID] = std::to_string(userId); + queryParams[ACCOUNTID] = accountId; + if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { + LOGE("DP GetAccessControlProfile failed."); + } + for (auto &item : profiles) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT && item.GetStatus() == ACTIVE) { + return true; + } + } + return false; +} + bool DeviceProfileConnector::SingleUserProcess(const DistributedDeviceProfile::AccessControlProfile &profile, const DmAccessCaller &caller, const DmAccessCallee &callee) { @@ -813,8 +870,10 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, { LOGI("DeviceProfileConnector::CheckIsSameAccount pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - for (auto &item : profiles) { + std::vector profiles = GetAllAccessControlProfile(); + std::vector profilesFilter + = GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, callee, sinkUdid); + for (auto &item : profilesFilter) { if (item.GetStatus() != ACTIVE || (item.GetTrustDeviceId() != sinkUdid && item.GetTrustDeviceId() != srcUdid)) { continue; @@ -858,56 +917,94 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s return bindLevel; } -std::map DeviceProfileConnector::GetDeviceIdAndBindType(int32_t userId, - const std::string &accountId, const std::string &localUdid) +std::map DeviceProfileConnector::GetDeviceIdAndBindLevel(std::vector userIds, + const std::string &localUdid) { - LOGI("userId %{public}d, accountId %{public}s.", userId, GetAnonyString(accountId).c_str()); - std::vector profiles = GetAccessControlProfileByUserId(userId); + std::vector profiles = GetAllAccessControlProfile(); std::map deviceIdMap; for (const auto &item : profiles) { - if (item.GetAccesser().GetAccesserUserId() == userId && - item.GetAccesser().GetAccesserAccountId() == accountId && + if (find(userIds.begin(), userIds.end(), item.GetAccesser().GetAccesserUserId()) != userIds.end() && item.GetAccesser().GetAccesserDeviceId() == localUdid) { - LOGI("Account logout localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); - UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + LOGI("Get Device Bind type localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindLevel(), deviceIdMap); continue; } - if (item.GetAccessee().GetAccesseeUserId() == userId && - item.GetAccessee().GetAccesseeAccountId() == accountId && + if (find(userIds.begin(), userIds.end(), item.GetAccessee().GetAccesseeUserId()) != userIds.end() && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { - LOGI("Account logout localUdid %{public}s is sink.", GetAnonyString(localUdid).c_str()); - UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + LOGI("Get Device Bind type localUdid %{public}s is sink.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindLevel(), deviceIdMap); continue; } } return deviceIdMap; } -void DeviceProfileConnector::UpdateBindType(const std::string &udid, int32_t bindType, +std::multimap DeviceProfileConnector::GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId, const std::string &localUdid) +{ + LOGI("localUdid %{public}s, userId %{public}d, accountId %{public}s.", GetAnonyString(localUdid).c_str(), + userId, GetAnonyString(accountId).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::multimap deviceIdMap; + for (const auto &item : profiles) { + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesserUserId == userId && item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + LOGI("Account logout trust udid %{public}s userid %{public}d is src.", + GetAnonyString(accesseeUdid).c_str(), accesseeUserId); + deviceIdMap.insert(std::pair(accesseeUdid, accesseeUserId)); + continue; + } + if (accesseeUdid == localUdid && accesseeUserId == userId && item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + LOGI("Account logout trust udid %{public}s userid %{public}d is sink.", + GetAnonyString(accesserUdid).c_str(), accesserUserId); + deviceIdMap.insert(std::pair(accesserUdid, accesserUserId)); + continue; + } + } + return deviceIdMap; +} + +void DeviceProfileConnector::UpdateBindType(const std::string &udid, int32_t compareParam, std::map &deviceMap) { - LOGI("BindType %{public}d.", bindType); + LOGI("BindType %{public}d.", compareParam); if (deviceMap.find(udid) == deviceMap.end()) { - deviceMap[udid] = bindType; + deviceMap[udid] = compareParam; } else { - deviceMap[udid] = std::min(deviceMap[udid], bindType); + deviceMap[udid] = std::min(deviceMap[udid], compareParam); } } -int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, - const std::string &remoteUdid, const std::string &localUdid) +int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, + const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteAccountHash %{public}s, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteAccountHash).c_str(), GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAccessControlProfileByUserId(remoteUserId); + std::map uaerIdAndBindType; int32_t bindType = DM_INVALIED_BINDTYPE; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid) { continue; } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - bindType = DM_IDENTICAL_ACCOUNT; + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == remoteUdid && accesseeUserId == remoteUserId) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = DM_IDENTICAL_ACCOUNT; + continue; + } + if (accesseeUdid == localUdid && accesserUdid == remoteUdid && accesserUserId == remoteUserId) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + bindType = DM_IDENTICAL_ACCOUNT; + continue; + } } return bindType; } @@ -945,13 +1042,13 @@ int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const return bindType; } -std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int32_t tokenId, const std::string &localUdid) +OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); std::vector profiles = GetAccessControlProfile(); - std::string pkgName = ""; + ProcessInfo processInfo; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { @@ -963,7 +1060,8 @@ std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, c item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && @@ -972,11 +1070,12 @@ std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, c item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); continue; } } - return pkgName; + return processInfo; } std::vector DeviceProfileConnector::GetAllAccessControlProfile() @@ -993,6 +1092,300 @@ void DeviceProfileConnector::DeleteAccessControlById(int64_t accessControlId) DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(accessControlId); } +int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, int32_t currentUserId, + int32_t beforeUserId) +{ + LOGI("Start."); + std::vector profiles = GetAccessControlProfileByUserId(beforeUserId); + LOGI("to inactive ACL size is %{public}zu", profiles.size()); + for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == beforeUserId) || + (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == beforeUserId)) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + continue; + } + if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == currentUserId) || ( + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == currentUserId)) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + continue; + } + } + return DM_OK; +} + +std::vector DeviceProfileConnector::GetAclProfileByUserId(const std::string &localUdid, + int32_t userId, const std::string &remoteUdid) +{ + LOGI("localUdid %{public}s, localUserId %{public}d, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + userId, GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::vector profilesTemp; + for (const auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } + } + return profilesTemp; +} + +void DeviceProfileConnector::HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != remoteUserIds.end()) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != remoteUserIds.end()) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + } +} + +std::vector DeviceProfileConnector::GetOfflineProcessInfo(std::string &localUdid, + const std::vector &localUserIds, const std::string &remoteUdid, const std::vector &remoteUserIds) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::vector processInfos; + int32_t bindLevel = 100; + for (const auto &item : profiles) { + ProcessInfo processInfo; + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != remoteUserIds.end() && + item.GetStatus() == ACTIVE) { + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != remoteUserIds.end() && + item.GetStatus() == ACTIVE) { + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); + } + processInfos.push_back(processInfo); + } + if (bindLevel == INVALIED_TYPE || bindLevel == DEVICE) { + processInfos.clear(); + for (const auto &item : localUserIds) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = item; + processInfos.push_back(processInfo); + } + } + return processInfos; +} + +std::map DeviceProfileConnector::GetUserIdAndBindLevel(const std::string &localUdid, + const std::string &peerUdid) +{ + LOGI("localUdid %{public}s, peerUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(peerUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::map userIdAndBindLevel; + for (const auto &item : profiles) { + if (item.GetStatus() == INACTIVE) { + continue; + } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == peerUdid) { + if (userIdAndBindLevel.find(accesserUserid) == userIdAndBindLevel.end()) { + userIdAndBindLevel[accesserUserid] = item.GetBindLevel(); + } else { + userIdAndBindLevel[accesserUserid] = + std::min(static_cast(item.GetBindLevel()), userIdAndBindLevel[accesserUserid]); + } + } else if (accesseeUdid == localUdid && accesserUdid == peerUdid) { + if (userIdAndBindLevel.find(accesseeUserid) == userIdAndBindLevel.end()) { + userIdAndBindLevel[accesseeUserid] = item.GetBindLevel(); + } else { + userIdAndBindLevel[accesseeUserid] = + std::min(static_cast(item.GetBindLevel()), userIdAndBindLevel[accesseeUserid]); + } + } + } + return userIdAndBindLevel; +} + +void DeviceProfileConnector::UpdatePeerUserId(std::string &localUdid, const std::vector &localUserIds, + const std::string &remoteUdid, const std::vector &remoteFrontUserIds, + const std::vector &remoteBackUserIds) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (auto item : profiles) { + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = item.GetAccessee().GetAccesseeUserId(); + int32_t bindType = item.GetBindType(); + // deleta signal trust acl. + if (accesserUdid == remoteUdid && accesserUserid != 0 && accesserUserid != -1 && + find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesserUserid) == remoteFrontUserIds.end() && + find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesserUserid) == remoteBackUserIds.end()) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + continue; + } + if (accesseeUdid == remoteUdid && accesseeUserid != 0 && accesseeUserid != -1 && + find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesseeUserid) == remoteFrontUserIds.end() && + find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesseeUserid) == remoteBackUserIds.end()) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + continue; + } + // update identical account userId. + if (accesserUdid == localUdid && accesseeUdid == remoteUdid && bindType == DM_IDENTICAL_ACCOUNT && + find(localUserIds.begin(), localUserIds.end(), accesserUserid) != localUserIds.end() && + (accesseeUserid == 0 || accesseeUserid == -1)) { + Accessee accessee = item.GetAccessee(); + accessee.SetAccesseeUserId(remoteFrontUserIds[0]); + item.SetAccessee(accessee); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + continue; + } + if (accesserUdid == remoteUdid && accesseeUdid == localUdid && bindType == DM_IDENTICAL_ACCOUNT && + find(localUserIds.begin(), localUserIds.end(), accesseeUserid) != localUserIds.end() && + (accesserUserid == 0 || accesserUserid == -1)) { + Accesser accesser = item.GetAccesser(); + accesser.SetAccesserUserId(remoteFrontUserIds[0]); + item.SetAccesser(accesser); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + continue; + } + } +} + +std::multimap DeviceProfileConnector::GetDevIdAndUserIdByActHash(const std::string &localUdid, + const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash) +{ + LOGI("localUdid %{public}s, peerUdid %{public}s, peerUserId %{public}d, peerAccountHash %{public}s.", + GetAnonyString(localUdid).c_str(), GetAnonyString(peerUdid).c_str(), peerUserId, peerAccountHash.c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::multimap deviceIdMap; + for (const auto &item : profiles) { + std::string accesserAccountId = item.GetAccesser().GetAccesserAccountId(); + std::string accesseeAccountId = item.GetAccessee().GetAccesseeAccountId(); + char accesserAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesserAccountId, reinterpret_cast(accesserAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + char accesseeAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesseeAccountId, reinterpret_cast(accesseeAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + LOGI("accesserAccountIdHash %{public}s, accesseeAccountIdHash %{public}s", accesserAccountIdHash, + accesseeAccountIdHash); + if (std::string(accesserAccountIdHash) != peerAccountHash || + std::string(accesseeAccountIdHash) != peerAccountHash) { + continue; + } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == peerUdid && accesseeUserid == peerUserId) { + deviceIdMap.insert(std::pair(accesserUdid, accesserUserid)); + continue; + } + if (accesseeUdid == localUdid && accesserUdid == peerUdid && accesserUserid == peerUserId) { + deviceIdMap.insert(std::pair(accesseeUdid, accesseeUserid)); + continue; + } + } + return deviceIdMap; +} + +std::multimap DeviceProfileConnector::GetDeviceIdAndUserId(const std::string &localUdid, + int32_t localUserId) +{ + LOGI("localUdid %{public}s, userId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId); + std::vector profiles = GetAllAccessControlProfile(); + std::multimap deviceIdMap; + for (const auto &item : profiles) { + std::string accesserDeviceId = item.GetAccesser().GetAccesserDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + std::string accesseeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserDeviceId == localUdid && accesserUserId == localUserId) { + if (!IsValueExist(deviceIdMap, accesseeDeviceId, accesseeUserId)) { + deviceIdMap.insert(std::pair(accesseeDeviceId, accesseeUserId)); + } + continue; + } + if (accesseeDeviceId == localUdid && accesseeUserId == localUserId) { + if (!IsValueExist(deviceIdMap, accesserDeviceId, accesserUserId)) { + deviceIdMap.insert(std::pair(accesserDeviceId, accesserUserId)); + } + continue; + } + } + return deviceIdMap; +} + +void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != remoteUserIds.end()) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } else if ((item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) == remoteUserIds.end()) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + } +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index a09f23363..7c5386de9 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -15,10 +15,11 @@ #include "multiple_user_connector.h" +#include "dm_constants.h" #include "dm_log.h" - #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "account_info.h" +#include "ipc_skeleton.h" #include "ohos_account_kits.h" #ifdef OS_ACCOUNT_PART_EXISTS #include "os_account_manager.h" @@ -72,6 +73,25 @@ std::string MultipleUserConnector::GetOhosAccountId(void) #endif } +std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + (void)userId; + return ""; +#elif OS_ACCOUNT_PART_EXISTS + OhosAccountInfo accountInfo; + ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfoByUserId(userId, accountInfo); + if (ret != 0 || accountInfo.uid_ == "") { + LOGE("error ret: %{public}d", ret); + return ""; + } + return accountInfo.uid_; +#else + (void)userId; + return ""; +#endif +} + std::string MultipleUserConnector::GetOhosAccountName(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -92,6 +112,34 @@ std::string MultipleUserConnector::GetOhosAccountName(void) #endif } +void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif + userId = GetFirstForegroundUserId(); +} + +void MultipleUserConnector::GetCallerUserId(int32_t &userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + (void)userId; + return; +#elif OS_ACCOUNT_PART_EXISTS + int32_t uid = OHOS::IPCSkeleton::GetCallingUid(); + ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + if (ret != 0) { + LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); + } + return; +#else // OS_ACCOUNT_PART_EXISTS + (void)userId; + return; +#endif +} + void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) { std::lock_guard lock(lock_); @@ -156,5 +204,101 @@ void MultipleUserConnector::DeleteAccountInfoByUserId(int32_t userId) dmAccountInfoMap_.erase(userId); } } + +int32_t MultipleUserConnector::GetForegroundUserIds(std::vector &userVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userVec.push_back(DEFAULT_OS_ACCOUNT_ID); + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + userVec.clear(); + std::vector accounts; + ErrCode ret = OsAccountManager::GetForegroundOsAccounts(accounts); + if (ret != 0 || accounts.empty()) { + LOGE("error ret: %{public}d", ret); + return ret; + } + for (auto &account : accounts) { + userVec.push_back(account.localId); + } + return DM_OK; +#else // OS_ACCOUNT_PART_EXISTS + userVec.push_back(DEFAULT_OS_ACCOUNT_ID); + return DM_OK; +#endif +} + +int32_t MultipleUserConnector::GetFirstForegroundUserId(void) +{ + std::vector userVec; + int32_t ret = GetForegroundUserIds(userVec); + if (ret != DM_OK || userVec.size() == 0) { + LOGE("get userid error ret: %{public}d.", ret); + return -1; + } + return userVec[0]; +} + +int32_t MultipleUserConnector::GetBackgroundUserIds(std::vector &userIdVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + userIdVec.clear(); + std::vector allOsAccounts; + ErrCode ret = OsAccountManager::QueryAllCreatedOsAccounts(allOsAccounts); + if (ret != 0) { + LOGE("Get all created accounts error, ret: %{public}d", ret); + return ret; + } + + std::vector foregroundAccounts; + ret = OsAccountManager::GetForegroundOsAccounts(foregroundAccounts); + if (ret != 0) { + LOGE("Get foreground accounts error ret: %{public}d", ret); + return ret; + } + + std::vector allUserIds; + std::vector foregroundUserIds; + for (const auto &u : allOsAccounts) { + allUserIds.push_back(u.GetLocalId()); + } + for (const auto &u : foregroundAccounts) { + foregroundUserIds.push_back(u.localId); + } + + for (const auto &userId : allUserIds) { + if (std::find(foregroundUserIds.begin(), foregroundUserIds.end(), userId) == foregroundUserIds.end()) { + userIdVec.push_back(userId); + } + } + return DM_OK; +#else + return DM_OK; +#endif +} + +int32_t MultipleUserConnector::GetAllUserIds(std::vector &userIdVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + userIdVec.clear(); + std::vector allOsAccounts; + ErrCode ret = OsAccountManager::QueryAllCreatedOsAccounts(allOsAccounts); + if (ret != 0) { + LOGE("Get all created accounts error, ret: %{public}d", ret); + return ret; + } + + for (const auto &u : allOsAccounts) { + userIdVec.push_back(u.GetLocalId()); + } + return DM_OK; +#else + return DM_OK; +#endif +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index f701b5540..f887ff9d6 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -412,21 +412,20 @@ private: DeviceManagerImpl(DeviceManagerImpl &&) = delete; DeviceManagerImpl &operator=(DeviceManagerImpl &&) = delete; - uint16_t AddDiscoveryCallback(const std::string &pkgName, std::shared_ptr callback); + uint16_t AddDiscoveryCallback(const std::string &pkgName, std::map &discoverParam, + std::shared_ptr callback); uint16_t RemoveDiscoveryCallback(const std::string &pkgName); int32_t AddPublishCallback(const std::string &pkgName); int32_t RemovePublishCallback(const std::string &pkgName); int32_t CheckApiPermission(int32_t permissionLevel); void ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); + uint16_t GetSubscribeIdFromMap(const std::string &pkgName); private: #if !defined(__LITEOS_M__) std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); #endif - std::mutex subscribIdLock; - std::map subscribIdMap_; - std::mutex subMapLock; std::map pkgName2SubIdMap_; diff --git a/interfaces/inner_kits/native_cpp/include/dm_device_info.h b/interfaces/inner_kits/native_cpp/include/dm_device_info.h index 4354ee3ea..2a6600d05 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -361,6 +361,45 @@ typedef struct DmAccessCallee { int32_t userId; std::string extra; } DmAccessCallee; + +typedef struct ProcessInfo { + int32_t userId; + std::string pkgName; + + bool operator==(const ProcessInfo &other) const + { + return (userId == other.userId) && (pkgName == other.pkgName); + } + + bool operator<(const ProcessInfo &other) const + { + return (userId < other.userId) || + (userId == other.userId && pkgName < other.pkgName); + } +} ProcessInfo; + +typedef struct DmNotifyKey { + int32_t processUserId; + std::string processPkgName; + int32_t notifyUserId; + std::string udid; + + bool operator==(const DmNotifyKey &other) const + { + return (processUserId == other.processUserId) && (processPkgName == other.processPkgName) && + (notifyUserId == other.notifyUserId) && (udid == other.udid); + } + + bool operator<(const DmNotifyKey &other) const + { + return (processUserId < other.processUserId) || + (processUserId == other.processUserId && processPkgName < other.processPkgName) || + (processUserId == other.processUserId && processPkgName == other.processPkgName && + notifyUserId < other.notifyUserId) || + (processUserId == other.processUserId && processPkgName == other.processPkgName && + notifyUserId == other.notifyUserId && udid < other.udid); + } +} DmNotifyKey; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_DEVICE_INFO_H \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 10ffd05cd..3f68a9ee0 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 @@ -125,6 +125,7 @@ public: uint16_t deviceTypeId, int32_t errcode); void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content); + std::shared_ptr GetDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId); private: #if !defined(__LITEOS_M__) 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 42e3e6086..4afabf438 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -55,9 +55,6 @@ #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_unbind_device_req.h" #include "ipc_unpublish_req.h" @@ -455,35 +452,14 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons LOGE("DeviceManagerImpl::StartDeviceDiscovery error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeInfo.subscribeId, callback); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetExtra(extra); - req->SetSubscribeInfo(subscribeInfo); - int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Failed with ret %{public}d", ret); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_FAILED), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_FAILED_MSG)); - return ret; - } - - DmTraceEnd(); - LOGI("Completed"); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, + std::to_string(subscribeInfo.subscribeId))); + discParam.insert(std::pair(PARAM_KEY_DISC_MEDIUM, std::to_string(subscribeInfo.medium))); + std::map filterOps; + filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, extra)); + return StartDiscovering(pkgName, discParam, filterOps, callback); } int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint64_t tokenId, @@ -493,106 +469,112 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint LOGE("DeviceManagerImpl::StartDeviceDiscovery error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(tokenId))); + std::map filterOps; + filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, filterOptions)); + return StartDiscovering(pkgName, discParam, filterOps, callback); +} - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = 0; - { - std::lock_guard autoLock(subscribIdLock); - if (subscribIdMap_.find(tokenId) != subscribIdMap_.end()) { - return ERR_DM_DISCOVERY_REPEATED; - } - subscribeId = GenRandUint(0, DM_MAX_RANDOM); - subscribIdMap_[tokenId] = subscribeId; - } - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFilterOption(filterOptions); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVERY, req, rsp); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Failed with ret %{public}d", ret); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_FAILED), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_FAILED_MSG)); - return ret; +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + if (pkgName.empty()) { + LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; } - - DmTraceEnd(); - LOGI("Completed"); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId))); + return StopDiscovering(pkgName, discParam); } -int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::string &pkgName) { if (pkgName.empty()) { LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(tokenId))); + return StopDiscovering(pkgName, discParam); +} + +int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, + std::map &discoverParam, const std::map &filterOptions, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("DeviceManagerImpl::StartDiscovering failed: input callback is null or pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - std::shared_ptr req = std::make_shared(); + DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); + + uint16_t subscribeId = AddDiscoveryCallback(pkgName, discoverParam, callback); + discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); + std::string discParaStr = ConvertMapToJsonString(discoverParam); + std::string filterOpStr = ConvertMapToJsonString(filterOptions); + + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); + req->SetFirstParam(discParaStr); + req->SetSecondParam(filterOpStr); + int32_t ret = ipcClientProxy_->SendRequest(START_DISCOVERING, req, rsp); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Send Request failed ret: %{public}d", ret); + LOGE("StartDiscovering error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } - ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Failed with ret %{public}d", ret); + LOGE("StartDiscovering error: Failed with ret %{public}d", ret); return ret; } - DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + DmTraceEnd(); LOGI("Completed"); + SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, + std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); return DM_OK; } -int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::string &pkgName) +int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, + std::map &discoverParam) { if (pkgName.empty()) { - LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); + LOGE("DeviceManagerImpl::StopDiscovering failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = 0; - { - std::lock_guard autoLock(subscribIdLock); - if (subscribIdMap_.find(tokenId) == subscribIdMap_.end()) { - return ERR_DM_STOP_DISCOVERY; - } - subscribeId = subscribIdMap_[tokenId]; - subscribIdMap_.erase(tokenId); + uint16_t subscribeId = DM_INVALID_FLAG_ID; + if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { + subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); + } + if (subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GetSubscribeIdFromMap(pkgName); } - std::shared_ptr req = std::make_shared(); + if (subscribeId == DM_INVALID_FLAG_ID) { + LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string discoveryFlag = ComposeStr(pkgName, subscribeId); + discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); + std::string discParaStr = ConvertMapToJsonString(discoverParam); + + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + req->SetPkgName(discoveryFlag); + req->SetFirstParam(discParaStr); + int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Send Request failed ret: %{public}d", ret); + LOGE("StopDiscovering error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } - ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Failed with ret %{public}d", ret); + LOGE("StopDiscovering error: Failed with ret %{public}d", ret); return ret; } - - DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + RemoveDiscoveryCallback(discoveryFlag); LOGI("Completed"); return DM_OK; } @@ -1648,86 +1630,6 @@ int32_t DeviceManagerImpl::ExportAuthCode(std::string &authCode) return DM_OK; } -int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, - std::map &discoverParam, const std::map &filterOptions, - std::shared_ptr callback) -{ - if (pkgName.empty() || callback == nullptr) { - LOGE("DeviceManagerImpl::StartDiscovering failed: input callback is null or pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - - uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); - discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); - std::string discParaStr = ConvertMapToJsonString(discoverParam); - std::string filterOpStr = ConvertMapToJsonString(filterOptions); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFirstParam(discParaStr); - req->SetSecondParam(filterOpStr); - int32_t ret = ipcClientProxy_->SendRequest(START_DISCOVERING, req, rsp); - if (ret != DM_OK) { - LOGE("StartDiscovering error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDiscovering error: Failed with ret %{public}d", ret); - return ret; - } - - DmTraceEnd(); - LOGI("Completed"); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; -} - -int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, - std::map &discoverParam) -{ - if (pkgName.empty()) { - LOGE("DeviceManagerImpl::StopDiscovering failed: input pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = DM_INVALID_FLAG_ID; - { - std::lock_guard autoLock(subMapLock); - if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { - subscribeId = pkgName2SubIdMap_[pkgName]; - } - } - if (subscribeId == DM_INVALID_FLAG_ID) { - LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); - return ERR_DM_INPUT_PARA_INVALID; - } - discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); - std::string discParaStr = ConvertMapToJsonString(discoverParam); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFirstParam(discParaStr); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); - if (ret != DM_OK) { - LOGE("StopDiscovering error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StopDiscovering error: Failed with ret %{public}d", ret); - return ret; - } - RemoveDiscoveryCallback(pkgName); - LOGI("Completed"); - return DM_OK; -} - int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, std::map &discoverParam, const std::map &filterOptions, std::shared_ptr callback) @@ -1737,15 +1639,14 @@ int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); + uint16_t subscribeId = AddDiscoveryCallback(pkgName, discoverParam, callback); discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); std::string discParaStr = ConvertMapToJsonString(discoverParam); std::string filterOpStr = ConvertMapToJsonString(filterOptions); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); req->SetFirstParam(discParaStr); req->SetSecondParam(filterOpStr); int32_t ret = ipcClientProxy_->SendRequest(REGISTER_DISCOVERY_CALLBACK, req, rsp); @@ -1771,8 +1672,8 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); + std::string discoveryFlag = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + uint16_t subscribeId = RemoveDiscoveryCallback(discoveryFlag); if (subscribeId == DM_INVALID_FLAG_ID) { DmRadarHelper::GetInstance().ReportDmBehavior( pkgName, "UnRegisterDiscoveryCallback", ERR_DM_INPUT_PARA_INVALID); @@ -1785,21 +1686,21 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); + req->SetPkgName(discoveryFlag); req->SetFirstParam(extraParaStr); int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_DISCOVERY_CALLBACK, req, rsp); if (ret != DM_OK) { - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", ret); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", ret); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", DM_OK); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -1982,20 +1883,32 @@ int32_t DeviceManagerImpl::CheckAccessToTarget(uint64_t tokenId, const std::stri } uint16_t DeviceManagerImpl::AddDiscoveryCallback(const std::string &pkgName, - std::shared_ptr callback) + std::map &discoverParam, std::shared_ptr callback) { + if (discoverParam.empty() || callback == nullptr) { + LOGE("input param invalid."); + return DM_INVALID_FLAG_ID; + } uint16_t subscribeId = DM_INVALID_FLAG_ID; + if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { + subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); + } + if (subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GetSubscribeIdFromMap(pkgName); + } + if (subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); + } + std::string discoveryFlag = ComposeStr(pkgName, subscribeId); { std::lock_guard autoLock(subMapLock); - if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { - subscribeId = pkgName2SubIdMap_[pkgName]; - } else { - subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); - pkgName2SubIdMap_[pkgName] = subscribeId; + auto iter = pkgName2SubIdMap_.find(discoveryFlag); + if (iter == pkgName2SubIdMap_.end()) { + pkgName2SubIdMap_[discoveryFlag] = subscribeId; } } - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "AddDiscoveryCallback", DM_OK); + DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(discoveryFlag, subscribeId, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "AddDiscoveryCallback", DM_OK); return subscribeId; } @@ -2488,5 +2401,18 @@ int32_t DeviceManagerImpl::UnRegisterSinkBindCallback(const std::string &pkgName LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } + +uint16_t DeviceManagerImpl::GetSubscribeIdFromMap(const std::string &pkgName) +{ + { + std::lock_guard autoLock(subMapLock); + for (auto &item : pkgName2SubIdMap_) { + if (item.first.find(pkgName) == 0) { + return GetSubscribeId(item.first); + } + } + } + return DM_INVALID_FLAG_ID; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 248628c0d..18b494a3d 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp @@ -30,8 +30,6 @@ #include "ipc_register_listener_req.h" #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" #include "securec.h" namespace OHOS { @@ -163,44 +161,6 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, - size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string extra = pReq->GetFilterOption(); - uint16_t subscribeId = pReq->GetSubscribeId(); - - IpcIoInit(&request, buffer, buffLen, 0); - WriteString(&request, pkgName.c_str()); - WriteString(&request, extra.c_str()); - WriteUint16(&request, subscribeId); - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVERY, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - return SetRspErrCode(reply, pBaseRsp); -} - -ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, - size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - - IpcIoInit(&request, buffer, buffLen, 0); - WriteString(&request, pkgName.c_str()); - WriteUint16(&request, subscribeId); - return DM_OK; -} - -ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - return SetRspErrCode(reply, pBaseRsp); -} - ON_IPC_SET_REQUEST(REQUEST_CREDENTIAL, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, size_t buffLen) { 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 a18aa8327..a69f4a513 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 @@ -48,9 +48,6 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_permission_req.h" #include "ipc_publish_req.h" #include "ipc_unbind_device_req.h" @@ -314,86 +311,6 @@ ON_IPC_READ_RESPONSE(GET_UUID_BY_NETWORK, MessageParcel &reply, std::shared_ptr< return DM_OK; } -ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string extra = pReq->GetExtra(); - const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteString(extra)) { - LOGE("write extra failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo))) { - LOGE("write subscribe info failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - -ON_IPC_SET_REQUEST(START_DEVICE_DISCOVERY, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string filterOption = pReq->GetFilterOption(); - const uint16_t subscribeId = pReq->GetSubscribeId(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteString(filterOption)) { - LOGE("write filterOption failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteUint16(subscribeId)) { - LOGE("write subscribe id failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVERY, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - -ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteInt16((int16_t)subscribeId)) { - LOGE("write subscribeId failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - if (pBaseRsp == nullptr) { - LOGE("pBaseRsp is null"); - return ERR_DM_FAILED; - } - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - ON_IPC_SET_REQUEST(PUBLISH_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); 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 2ca8f4f70..e25133b4e 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 @@ -31,7 +31,7 @@ constexpr const char* DEVICEINFO_CHANGE = "deviceInfoChange"; constexpr const char* DEVICE_READY = "deviceReady"; constexpr const char* DEVICE_TRUST_CHANGE = "deviceTrustChange"; #endif - +const uint16_t DM_INVALID_FLAG_ID = 0; void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback) { @@ -521,68 +521,34 @@ void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDevi void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { + LOGD("pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } - - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDeviceFound error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDeviceFound error, no register deviceDiscoveryCallback for subscribeId %{public}d.", - (int32_t)subscribeId); - return; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGD("Complete with devInfo, pkgName:%{public}s, subscribeId:%{public}d.", - GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceInfo); } void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo) { + LOGD("pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } - - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDeviceFound error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDeviceFound error, no register deviceDiscoveryCallback for subscribeId %{public}d.", - (int32_t)subscribeId); - return; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGD("Complete with DmDeviceBasicInfo, pkgName:%{public}s, subscribeId:%{public}d.", - GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceBasicInfo); } @@ -594,23 +560,7 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t } LOGI("DeviceManagerNotify::OnDiscoveryFailed in, pkgName:%{public}s, subscribeId %{public}d, failed" "reason %{public}d", pkgName.c_str(), (int32_t)subscribeId, failedReason); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDiscoveryFailed error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDiscoveryFailed error, device discovery callback not register for subscribeId %{public}d.", - subscribeId); - return; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoveryFailed error, registered device discovery callback is nullptr."); return; @@ -625,23 +575,7 @@ void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_ return; } LOGI("PkgName:%{public}s, subscribeId:%{public}d.", GetAnonyString(pkgName).c_str(), subscribeId); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("OnDiscoverySuccess error, device discovery callback not register for pkgName %{public}s.", - pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDiscoverySuccess error, device discovery callback not register for subscribeId %{public}d.", - (int32_t)subscribeId); - return; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoverySuccess error, registered device discovery callback is nullptr."); return; @@ -1238,5 +1172,29 @@ void DeviceManagerNotify::OnSinkBindResult(const std::string &pkgName, const Pee } tempCbk->OnBindResult(targetId, result, status, content); } + +std::shared_ptr DeviceManagerNotify::GetDiscoveryCallback(const std::string &pkgName, + uint16_t subscribeId) +{ + std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); + std::lock_guard autoLock(lock_); + auto iter = deviceDiscoveryCallbacks_.find(discWithSubscribeId); + if (iter != deviceDiscoveryCallbacks_.end()) { + auto subIter = iter->second.find(subscribeId); + if (subIter != iter->second.end()) { + return subIter->second; + } + return nullptr; + } + std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + iter = deviceDiscoveryCallbacks_.find(discNoSubscribeId); + if (iter != deviceDiscoveryCallbacks_.end()) { + auto subIter = iter->second.find(DM_INVALID_FLAG_ID); + if (subIter != iter->second.end()) { + return subIter->second; + } + } + return nullptr; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index 959d3a87a..e5eb58829 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -72,6 +72,7 @@ constexpr const char* TAG_DATA_LEN = "dataLen"; constexpr const char* TAG_IMPORT_AUTH_CODE = "IMPORT_AUTH_CODE"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; constexpr const char* TAG_EDITION = "edition"; +constexpr const char* TAG_BUNDLE_NAME = "bundleName"; class DmAuthManager; struct DmAuthRequestContext; diff --git a/services/implementation/include/authentication/auth_ui_state_manager.h b/services/implementation/include/authentication/auth_ui_state_manager.h index badf235d6..2a7bdbc6d 100644 --- a/services/implementation/include/authentication/auth_ui_state_manager.h +++ b/services/implementation/include/authentication/auth_ui_state_manager.h @@ -42,7 +42,7 @@ public: void UnRegisterUiStateCallback(const std::string pkgName); void UpdateUiState(const DmUiStateMsg msg); private: - std::set pkgSet_; + std::set pkgSet_; std::mutex pkgSetMutex_; std::shared_ptr listener_; }; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 308c7b535..38ebf8607 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -103,6 +103,7 @@ typedef struct DmAuthRequestContext { std::string cryptoVer; std::string hostPkgName; std::string targetPkgName; + std::string bundleName; std::string appOperation; std::string appDesc; std::string appName; @@ -145,6 +146,7 @@ typedef struct DmAuthResponseContext { std::string groupName; std::string hostPkgName; std::string targetPkgName; + std::string bundleName; std::string appOperation; std::string appDesc; std::string customDesc; @@ -166,6 +168,7 @@ typedef struct DmAuthResponseContext { std::string localAccountId; int32_t localUserId; int64_t tokenId; + int64_t remoteTokenId; bool authed; std::string dmVersion; std::vector bindType; @@ -368,13 +371,6 @@ public: */ void HandleAuthenticateTimeout(std::string name); - /** - * @tc.name: DmAuthManager::CancelDisplay - * @tc.desc: Cancel Display of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void CancelDisplay(); - /** * @tc.name: DmAuthManager::GeneratePincode * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager @@ -533,6 +529,9 @@ private: void DeleteOffLineTimer(int32_t sessionId); bool IsAllowDeviceBind(); int32_t GetBindLevel(int32_t bindLevel); + std::string GetBundleName(nlohmann::json &jsonObject); + int32_t GetBinderInfo(); + void SetProcessInfo(); private: std::shared_ptr softbusConnector_; @@ -568,6 +567,7 @@ private: std::string remoteVersion_ = ""; std::atomic authType_ = AUTH_TYPE_UNKNOW; std::string remoteUdidHash_ = ""; + ProcessInfo processInfo_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/credential/dm_credential_manager.h b/services/implementation/include/credential/dm_credential_manager.h index b20c09bfb..3b933fec6 100644 --- a/services/implementation/include/credential/dm_credential_manager.h +++ b/services/implementation/include/credential/dm_credential_manager.h @@ -95,7 +95,7 @@ public: int32_t DeleteCredential(const std::string &pkgName, const std::string &deleteInfo); /** - * @tc.name: HiChainConnector::OnCredentialResult + * @tc.name: HiChainConnector::OnGroupResult * @tc.desc: Credential Result of the DmCredential Manager * @tc.type: FUNC */ @@ -103,6 +103,7 @@ public: int32_t ImportRemoteCredentialExt(const std::string &credentialInfo); void OnGroupResultExt(int32_t action, const std::string &resultInfo); + void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); private: std::shared_ptr hiChainConnector_; @@ -110,7 +111,7 @@ private: std::vector credentialVec_; int64_t requestId_ = 0; std::mutex locks_; - std::string pkgName_; + ProcessInfo processInfo_; private: int32_t GetCredentialData(const std::string &credentialInfo, const CredentialData &inputCreData, nlohmann::json &jsonOutObj); diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 674002a71..49b417ce1 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -143,11 +143,11 @@ public: std::string GetNetworkIdByDeviceId(const std::string &deviceId); void HandleDeviceOnline(std::string deviceId, int32_t authForm); void HandleDeviceOffline(std::string deviceId); - void SetPkgName(std::string pkgName); + void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); - void SetPkgNameVec(std::vector pkgNameVec); - std::vector GetPkgName(); - void ClearPkgName(); + void SetProcessInfoVec(std::vector processInfoVec); + std::vector GetProcessInfo(); + void ClearProcessInfo(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); void DeleteOffLineTimer(std::string &udidHash); @@ -177,11 +177,11 @@ private: std::shared_ptr deviceStateManagerCallback_; static std::queue discoveryDeviceIdQueue_; static std::unordered_map deviceUdidMap_; - static std::vector pkgNameVec_; + static std::vector processInfoVec_; static std::mutex discoveryCallbackMutex_; static std::mutex discoveryDeviceInfoMutex_; static std::mutex deviceUdidLocks_; - static std::mutex pkgNameVecMutex_; + static std::mutex processInfoVecMutex_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index d2a227d46..d52bec824 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -128,26 +128,33 @@ public: void HandleDeviceNotTrust(const std::string &udid); int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); - void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); + void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, + int32_t peerUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); - + void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backroundUserIds, const std::string &remoteUdid); + void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId); + std::multimap GetDeviceIdAndUserId(int32_t localUserId); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); void HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo); void HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo); void PutIdenticalAccountToAcl(std::string requestDeviceId, std::string trustDeviceId); - std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId); + std::map GetDeviceIdAndBindLevel(int32_t userId); + std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId); void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid); void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleUserRemoved(int32_t preUserId); + void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - + private: std::shared_ptr authMgr_; std::shared_ptr deviceStateMgr_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 9a511c04d..13cf86a11 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -127,18 +127,25 @@ public: void HandleDeviceNotTrust(const std::string &udid); int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); - std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId); + std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId); void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid); void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); - void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); + void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, + int32_t peerUserId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); + void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); - + void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backroundUserIds, const std::string &remoteUdid); + void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); + std::map GetDeviceIdAndBindLevel(int32_t userId); + std::multimap GetDeviceIdAndUserId(int32_t localUserId); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index e1343283e..8e6806ef4 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,7 +96,6 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index de6028f18..26ab14c88 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -42,7 +42,7 @@ AuthMessageProcessor::~AuthMessageProcessor() void AuthMessageProcessor::GetJsonObj(nlohmann::json &jsonObj) { - if (authResponseContext_->bindType.size() > MAX_BINDTYPE_SIZE) { + if (authResponseContext_ == nullptr || authResponseContext_->bindType.size() > MAX_BINDTYPE_SIZE) { LOGE("GetJsonObj invalid bindType size."); return; } @@ -176,6 +176,7 @@ void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) json[TAG_AUTHED] = authResponseContext_->authed; json[TAG_DMVERSION] = authResponseContext_->dmVersion; json[TAG_HOST] = authResponseContext_->hostPkgName; + json[TAG_BUNDLE_NAME] = authResponseContext_->bundleName; json[TAG_TOKENID] = authResponseContext_->tokenId; json[TAG_IDENTICAL_ACCOUNT] = authResponseContext_->isIdenticalAccount; json[TAG_HAVE_CREDENTIAL] = authResponseContext_->haveCredential; @@ -201,6 +202,7 @@ void AuthMessageProcessor::CreateRespNegotiateMessage(nlohmann::json &json) json[TAG_LOCAL_ACCOUNTID] = authResponseContext_->localAccountId; json[TAG_LOCAL_USERID] = authResponseContext_->localUserId; + json[TAG_TOKENID] = authResponseContext_->tokenId; json[TAG_ISONLINE] = authResponseContext_->isOnline; json[TAG_AUTHED] = authResponseContext_->authed; json[TAG_DMVERSION] = authResponseContext_->dmVersion; @@ -462,7 +464,7 @@ void AuthMessageProcessor::ParsePkgNegotiateMessage(const nlohmann::json &json) authResponseContext_->authed = json[TAG_AUTHED].get(); } if (IsInt64(json, TAG_TOKENID)) { - authResponseContext_->tokenId = json[TAG_TOKENID].get(); + authResponseContext_->remoteTokenId = json[TAG_TOKENID].get(); } if (IsString(json, TAG_DMVERSION)) { authResponseContext_->dmVersion = json[TAG_DMVERSION].get(); @@ -525,6 +527,9 @@ void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) if (IsString(json, TAG_EDITION)) { authResponseContext_->edition = json[TAG_EDITION].get(); } + if (IsString(json, TAG_BUNDLE_NAME)) { + authResponseContext_->bundleName = json[TAG_BUNDLE_NAME].get(); + } ParsePkgNegotiateMessage(json); } diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index ab4d5e415..d338980d7 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -16,7 +16,9 @@ #include "auth_ui_state_manager.h" #include "dm_log.h" #include "nlohmann/json.hpp" - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { constexpr const char* UI_STATE_MSG = "uiStateMsg"; @@ -27,18 +29,28 @@ AuthUiStateManager::AuthUiStateManager(std::shared_ptr lock(pkgSetMutex_); - pkgSet_.emplace(pkgName); + pkgSet_.emplace(processInfo); } void AuthUiStateManager::UnRegisterUiStateCallback(const std::string pkgName) { + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = pkgName; std::lock_guard lock(pkgSetMutex_); - if (pkgSet_.find(pkgName) == pkgSet_.end()) { - LOGE("AuthUiStateManager UnRegisterUiStateCallback pkgName is not exist."); + if (pkgSet_.find(processInfo) == pkgSet_.end()) { + LOGE("AuthUiStateManager UnRegisterUiStateCallback processInfo is not exist."); return; } - pkgSet_.erase(pkgName); + pkgSet_.erase(processInfo); } void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) @@ -51,8 +63,8 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) jsonObj[UI_STATE_MSG] = msg; std::string paramJson = jsonObj.dump(); std::lock_guard lock(pkgSetMutex_); - for (auto pkgName : pkgSet_) { - listener_->OnUiCall(pkgName, paramJson); + for (auto item : pkgSet_) { + listener_->OnUiCall(item, paramJson); } LOGI("AuthUiStateManager::UpdateUiState complete."); } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 6b5eb79f9..731948961 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -42,6 +42,9 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "show_confirm.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -90,6 +93,7 @@ constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; +constexpr const char* BUNDLE_NAME_KEY = "bundleName"; constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; @@ -136,9 +140,9 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a if (!IsAuthTypeSupported(authType)) { LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_UNSUPPORTED_AUTH_TYPE); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_UNSUPPORTED_AUTH_TYPE; } @@ -149,15 +153,17 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a if (!softbusConnector_->HaveDeviceInMap(deviceId)) { LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_INPUT_PARA_INVALID); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_INPUT_PARA_INVALID; } if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(pkgName))) { LOGE("Auth code not exist."); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_INPUT_PARA_INVALID); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_INPUT_PARA_INVALID; } return DM_OK; @@ -198,9 +204,11 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->deviceId = deviceId; authRequestContext_->addr = deviceId; authRequestContext_->dmVersion = DM_VERSION_5_0_2; - authRequestContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); - authRequestContext_->localAccountId = MultipleUserConnector::GetAccountInfoByUserId( - authRequestContext_->localUserId).accountId; + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId); + authRequestContext_->tokenId = static_cast(tokenId); + authRequestContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); authRequestContext_->isOnline = false; authRequestContext_->authed = !authRequestContext_->bindType.empty(); authRequestContext_->bindLevel = INVALIED_TYPE; @@ -218,14 +226,12 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, if (IsString(jsonObject, APP_THUMBNAIL)) { authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); } - if (IsString(jsonObject, TAG_TOKENID)) { - authRequestContext_->tokenId = StringToInt64(jsonObject[TAG_TOKENID].get(), STRTOLL_BASE_10); - } if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { authRequestContext_->bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); } + authRequestContext_->bundleName = GetBundleName(jsonObject); authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); } @@ -260,6 +266,10 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au { LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType); SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + processInfo_.pkgName = pkgName; + processInfo_.userId = userId; int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); if (ret != DM_OK) { LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild."); @@ -274,8 +284,8 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au if (authType == AUTH_TYPE_CRE) { LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly."); softbusConnector_->JoinLnn(deviceId); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); - listener_->OnBindResult(pkgName, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); return DM_OK; } InitAuthState(pkgName, authType, deviceId, extra); @@ -335,17 +345,22 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & LOGE("Acl not contain the pkgname bind data."); return ERR_DM_FAILED; } - if (bindLevel == APP && offlineParam.leftAclNumber != 0) { - LOGI("The pkgName unbind app-level type leftAclNumber not zero."); - softbusConnector_->SetPkgName(pkgName); - softbusConnector_->HandleDeviceOffline(remoteUdid); - return DM_OK; - } - if (bindLevel == APP && offlineParam.leftAclNumber == 0) { - LOGI("The pkgName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetPkgName(pkgName); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); - return DM_OK; + if (bindLevel == APP) { + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (offlineParam.leftAclNumber != 0) { + LOGI("The pkgName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return DM_OK; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The pkgName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } } if (bindLevel == DEVICE && offlineParam.leftAclNumber != 0) { LOGI("Unbind deivce-level, retain identical account bind type."); @@ -741,6 +756,7 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authResponseContext_->deviceId = authRequestContext_->deviceId; authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash(); authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; + authResponseContext_->bundleName = authRequestContext_->bundleName; authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel; authResponseContext_->tokenId = authRequestContext_->tokenId; authResponseContext_->bindLevel = authRequestContext_->bindLevel; @@ -898,9 +914,9 @@ void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); } - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); - listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); @@ -962,9 +978,9 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) for (auto msg : messageList) { softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); } - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); - listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); @@ -974,7 +990,7 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) bool DmAuthManager::IsAuthFinish() { if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) { - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); authRequestState_->TransitionTo(std::make_shared()); return true; @@ -1107,10 +1123,9 @@ void DmAuthManager::StartRespAuthProcess() GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleSessionHeartbeat(name); }); - listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK); - listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, DM_OK, - STATUS_DM_SHOW_PIN_INPUT_UI, ""); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_PIN_INPUT_UI, ""); authRequestState_->TransitionTo(std::make_shared()); } else { LOGE("do not accept"); @@ -1210,7 +1225,8 @@ int32_t DmAuthManager::JoinNetwork() void DmAuthManager::SinkAuthenticateFinish() { LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); - listener_->OnSinkBindResult(authResponseContext_->hostPkgName, peerTargetId_, authResponseContext_->reply, + processInfo_.pkgName = authResponseContext_->hostPkgName; + listener_->OnSinkBindResult(processInfo_, peerTargetId_, authResponseContext_->reply, authResponseContext_->state, GenerateBindResultContent()); if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && authPtr_ != nullptr) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); @@ -1239,9 +1255,9 @@ void DmAuthManager::SrcAuthenticateFinish() authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); } usleep(USLEEP_TIME_US_500000); // 500ms - listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); - listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, authRequestContext_->reason, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + authResponseContext_->state, authRequestContext_->reason); + listener_->OnBindResult(processInfo_, peerTargetId_, authRequestContext_->reason, authResponseContext_->state, GenerateBindResultContent()); softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); authRequestContext_ = nullptr; @@ -1284,16 +1300,6 @@ void DmAuthManager::AuthenticateFinish() LOGI("DmAuthManager::AuthenticateFinish complete"); } -void DmAuthManager::CancelDisplay() -{ - LOGI("DmAuthManager::CancelDisplay start"); - nlohmann::json jsonObj; - jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PIN_CODE_DISPLAY; - std::string paramJson = jsonObj.dump(); - std::string pkgName = "com.ohos.devicemanagerui"; - listener_->OnUiCall(pkgName, paramJson); -} - int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName) { LOGI("DmAuthManager::RegisterUiStateCallback start"); @@ -1956,9 +1962,8 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH || (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && authResponseContext_->haveCredential)) { - if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && - !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); @@ -1971,9 +1976,8 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && !authResponseContext_->haveCredential) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && - !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -2003,7 +2007,7 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + SetProcessInfo(); softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -2124,16 +2128,14 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) { LOGI("DmAuthManager::ProcRespNegotiateExt start."); remoteDeviceId_ = authResponseContext_->localDeviceId; - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - std::string accountId = MultipleUserConnector::GetAccountInfoByUserId(userId).accountId; + authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; + authResponseContext_->remoteUserId = authResponseContext_->localUserId; + GetBinderInfo(); authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") { + if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && + authResponseContext_->localAccountId != "ohosAnonymousUid") { authResponseContext_->isIdenticalAccount = true; } - authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; - authResponseContext_->localAccountId = accountId; - authResponseContext_->remoteUserId = authResponseContext_->localUserId; - authResponseContext_->localUserId = userId; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); authResponseContext_->deviceId = authResponseContext_->localDeviceId; @@ -2305,25 +2307,24 @@ void DmAuthManager::PutAccessControlList() } aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestTokenId = static_cast(authResponseContext_->tokenId); accesser.requestBundleName = authResponseContext_->hostPkgName; + DmAccessee accessee; + accessee.trustBundleName = authResponseContext_->hostPkgName; if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + accesser.requestTokenId = static_cast(authResponseContext_->tokenId); accesser.requestUserId = authRequestContext_->localUserId; accesser.requestAccountId = authRequestContext_->localAccountId; accesser.requestDeviceId = authRequestContext_->localDeviceId; - } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { - accesser.requestUserId = authResponseContext_->remoteUserId; - accesser.requestAccountId = authResponseContext_->remoteAccountId; - accesser.requestDeviceId = authResponseContext_->localDeviceId; - } - DmAccessee accessee; - accessee.trustTokenId = static_cast(authResponseContext_->tokenId); - accessee.trustBundleName = authResponseContext_->hostPkgName; - if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + accessee.trustTokenId = static_cast(authResponseContext_->remoteTokenId); accessee.trustUserId = authRequestContext_->remoteUserId; accessee.trustAccountId = authRequestContext_->remoteAccountId; accessee.trustDeviceId = authResponseContext_->deviceId; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); + accesser.requestUserId = authResponseContext_->remoteUserId; + accesser.requestAccountId = authResponseContext_->remoteAccountId; + accesser.requestDeviceId = authResponseContext_->localDeviceId; + accessee.trustTokenId = static_cast(authResponseContext_->tokenId); accessee.trustUserId = authResponseContext_->localUserId; accessee.trustAccountId = authResponseContext_->localAccountId; accessee.trustDeviceId = localUdid; @@ -2546,5 +2547,58 @@ int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) } return bindLevel; } + +std::string DmAuthManager::GetBundleName(nlohmann::json &jsonObject) +{ + if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { + return jsonObject[BUNDLE_NAME_KEY].get(); + } + bool isSystemSA = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +int32_t DmAuthManager::GetBinderInfo() +{ + CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); + if (authResponseContext_->bundleName.empty()) { + LOGI("bundleName is empty"); + authResponseContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); + authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); + authResponseContext_->tokenId = authResponseContext_->remoteTokenId; + return DM_OK; + } + authResponseContext_->localUserId = MultipleUserConnector::GetFirstForegroundUserId(); + authResponseContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); + int32_t ret = AppManager::GetInstance(). + GetNativeTokenIdByName(authResponseContext_->bundleName, authResponseContext_->tokenId); + if (ret == DM_OK) { + LOGI("bundleName is sa"); + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, + authResponseContext_->bundleName, 0, authResponseContext_->tokenId); + if (ret != DM_OK) { + LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str()); + authResponseContext_->tokenId = authResponseContext_->remoteTokenId; + } + return ret; +} + +void DmAuthManager::SetProcessInfo() +{ + CHECK_NULL_VOID(authResponseContext_); + ProcessInfo processInfo; + if (authResponseContext_->bindLevel == APP) { + processInfo.pkgName = authResponseContext_->hostPkgName; + processInfo.userId = authResponseContext_->localUserId; + } else if (authResponseContext_->bindLevel == DEVICE || authResponseContext_->bindLevel == INVALIED_TYPE) { + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = authResponseContext_->localUserId; + } + softbusConnector_->SetProcessInfo(processInfo); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 043d2dd32..e09699988 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -20,7 +20,9 @@ #include "dm_log.h" #include "dm_random.h" #include "parameter.h" - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { const int32_t LOCAL_CREDENTIAL_DEAL_TYPE = 1; @@ -123,7 +125,6 @@ int32_t DmCredentialManager::ImportCredential(const std::string &pkgName, const LOGE("credentialInfo not found by pkgName %{public}s", GetAnonyString(pkgName).c_str()); return ERR_DM_FAILED; } - pkgName_ = pkgName; nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); if (jsonObject.is_discarded()) { LOGE("credentialInfo string not a json type."); @@ -213,7 +214,12 @@ int32_t DmCredentialManager::DeleteCredential(const std::string &pkgName, const LOGE("credentialInfo not found by pkgName %{public}s", GetAnonyString(pkgName).c_str()); return ERR_DM_FAILED; } - pkgName_ = pkgName; + int32_t callerUserId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(callerUserId); +#endif + processInfo_.pkgName = pkgName; + processInfo_.userId = callerUserId; nlohmann::json jsonObject = nlohmann::json::parse(deleteInfo, nullptr, false); if (jsonObject.is_discarded()) { LOGE("deleteInfo string not a json type."); @@ -247,7 +253,8 @@ int32_t DmCredentialManager::DeleteCredential(const std::string &pkgName, const void DmCredentialManager::OnGroupResultExt(int32_t action, const std::string &resultInfo) { LOGI("DmCredentialManager::OnGroupResultExt action %{public}d, resultInfo %{public}s.", action, resultInfo.c_str()); - listener_->OnCredentialResult(pkgName_, action, resultInfo); + CHECK_NULL_VOID(listener_); + listener_->OnCredentialResult(processInfo_, action, resultInfo); } void DmCredentialManager::OnGroupResult(int64_t requestId, int32_t action, @@ -257,7 +264,8 @@ void DmCredentialManager::OnGroupResult(int64_t requestId, int32_t action, if (requestId_ != requestId) { return; } - listener_->OnCredentialResult(pkgName_, action, resultInfo); + CHECK_NULL_VOID(listener_); + listener_->OnCredentialResult(processInfo_, action, resultInfo); } int32_t DmCredentialManager::RegisterCredentialCallback(const std::string &pkgName) @@ -266,9 +274,15 @@ int32_t DmCredentialManager::RegisterCredentialCallback(const std::string &pkgNa LOGE("DmCredentialManager::RegisterCredentialCallback input param is empty"); return ERR_DM_FAILED; } + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif LOGI("DmCredentialManager::RegisterCredentialCallback pkgName = %{public}s", GetAnonyString(pkgName).c_str()); { std::lock_guard autoLock(locks_); + processInfo_.pkgName = pkgName; + processInfo_.userId = userId; credentialVec_.push_back(pkgName); } return hiChainConnector_->RegisterHiChainGroupCallback(std::shared_ptr(shared_from_this())); @@ -519,5 +533,12 @@ int32_t DmCredentialManager::DeleteRemoteCredential(const std::string &deleteInf } return DM_OK; } + +void DmCredentialManager::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, + int32_t errcode) +{ + CHECK_NULL_VOID(listener_); + listener_->OnCredentialAuthStatus(processInfo_, deviceList, deviceTypeId, errcode); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index e524c67d0..2f1124e40 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -49,11 +49,11 @@ std::map> SoftbusConnect std::map> SoftbusConnector::publishCallbackMap_ = {}; std::queue SoftbusConnector::discoveryDeviceIdQueue_ = {}; std::unordered_map SoftbusConnector::deviceUdidMap_ = {}; -std::vector SoftbusConnector::pkgNameVec_ = {}; +std::vector SoftbusConnector::processInfoVec_ = {}; std::mutex SoftbusConnector::discoveryCallbackMutex_; std::mutex SoftbusConnector::discoveryDeviceInfoMutex_; std::mutex SoftbusConnector::deviceUdidLocks_; -std::mutex SoftbusConnector::pkgNameVecMutex_; +std::mutex SoftbusConnector::processInfoVecMutex_; IPublishCb SoftbusConnector::softbusPublishCallback_ = { .OnPublishResult = SoftbusConnector::OnSoftbusPublishResult, @@ -675,32 +675,32 @@ std::string SoftbusConnector::GetNetworkIdByDeviceId(const std::string &deviceId return ""; } -void SoftbusConnector::SetPkgName(std::string pkgName) +void SoftbusConnector::SetProcessInfo(ProcessInfo processInfo) { - LOGI("SoftbusConnector::SetPkgName"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_.push_back(pkgName); + LOGI("SoftbusConnector::SetProcessInfo"); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_.push_back(processInfo); } -void SoftbusConnector::SetPkgNameVec(std::vector pkgNameVec) +void SoftbusConnector::SetProcessInfoVec(std::vector processInfoVec) { - LOGI("SoftbusConnector::SetPkgNameVec"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_ = pkgNameVec; + LOGI("SoftbusConnector::SetProcessInfoVec"); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_ = processInfoVec; } -std::vector SoftbusConnector::GetPkgName() +std::vector SoftbusConnector::GetProcessInfo() { LOGI("In"); - std::lock_guard lock(pkgNameVecMutex_); - return pkgNameVec_; + std::lock_guard lock(processInfoVecMutex_); + return processInfoVec_; } -void SoftbusConnector::ClearPkgName() +void SoftbusConnector::ClearProcessInfo() { LOGI("In"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_.clear(); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_.clear(); } void SoftbusConnector::HandleDeviceOnline(std::string deviceId, int32_t authForm) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 4b5e9da9e..a0df243b8 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -212,26 +212,31 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); std::string requestDeviceId = std::string(localUdid); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - LOGI("The offline device bind type is %{public}d.", offlineParam.bindType); - if (offlineParam.leftAclNumber == 0 && offlineParam.bindType == INVALIED_TYPE) { - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == IDENTICAL_ACCOUNT_TYPE) { - LOGI("The offline device is identical account bind type."); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE) { - LOGI("The offline device is device-level bind type."); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE) { - LOGI("The offline device is app-level bind type."); - softbusConnector_->SetPkgNameVec(offlineParam.pkgNameVec); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } - if (offlineParam.leftAclNumber == 0) { - LOGI("Delete credential in HandleDeviceOffline."); - hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetCurrentAccountUserID()); + std::map userIdAndBindLevel = + DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(requestDeviceId, trustDeviceId); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + for (const auto &item : userIdAndBindLevel) { + if (item.second == INVALIED_TYPE) { + LOGI("The offline device is identical account bind type."); + devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + processInfo.userId = item.first; + softbusConnector_->SetProcessInfo(processInfo); + } else if (item.second == DEVICE) { + LOGI("The offline device is device bind type."); + devInfo.authForm = DmAuthForm::PEER_TO_PEER; + processInfo.userId = item.first; + softbusConnector_->SetProcessInfo(processInfo); + } else if (item.second == SERVICE || item.second == APP) { + LOGI("The offline device is APP_PEER_TO_PEER_TYPE bind type."); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + item.first); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } } + deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -239,7 +244,7 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo LOGI("DeviceManagerServiceImpl::HandleOnline"); std::string trustDeviceId = ""; if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { - LOGE("HandleDeviceOffline get udid failed."); + LOGE("HandleOnline get udid failed."); return; } std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); @@ -252,32 +257,34 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo std::string requestDeviceId = std::string(localUdid); uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); LOGI("The online device bind type is %{public}d.", bindType); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); if (bindType == INVALIED_TYPE && isCredentialType_.load()) { PutIdenticalAccountToAcl(requestDeviceId, trustDeviceId); devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + isCredentialType_.store(false); + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == IDENTICAL_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == DEVICE_PEER_TO_PEER_TYPE) { devInfo.authForm = DmAuthForm::PEER_TO_PEER; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == APP_PEER_TO_PEER_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::PEER_TO_PEER; } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } LOGI("DeviceManagerServiceImpl::HandleOnline success devInfo auform %{public}d.", devInfo.authForm); @@ -300,6 +307,10 @@ void DeviceManagerServiceImpl::HandleDeviceStatusChange(DmDeviceState devState, LOGE("get deviceId: %{public}s failed", GetAnonyString(udiddHash).c_str()); return; } + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } } @@ -488,7 +499,7 @@ int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkg int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { - LOGE("RegisterUiStateCallback failed, pkgName is empty"); + LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } if (authMgr_ == nullptr) { @@ -624,8 +635,8 @@ void DeviceManagerServiceImpl::PutIdenticalAccountToAcl(std::string requestDevic aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId(); + accesser.requestUserId = MultipleUserConnector::GetFirstForegroundUserId(); + accesser.requestAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldAccountId(accesser.requestAccountId); accesser.requestDeviceId = requestDeviceId; @@ -641,6 +652,10 @@ int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); if (deviceStateMgr_->CheckIsOnline(udid)) { LOGI("DeviceManagerServiceImpl DpAclAdd identical account and online"); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); deviceStateMgr_->OnDeviceOnline(udid, DmAuthForm::IDENTICAL_ACCOUNT); } LOGI("DeviceManagerServiceImpl::DpAclAdd completed"); @@ -671,27 +686,68 @@ void DeviceManagerServiceImpl::LoadHardwareFwkService() DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); } -void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &udid, int32_t userId, - const std::string &accountId) +void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) { - LOGI("Udid %{public}s, userId %{public}d, accountId %{public}s.", GetAnonyString(udid).c_str(), - userId, GetAnonyString(accountId).c_str()); - char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; - GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); - std::string localUdid = std::string(localUdidTemp); - DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, userId, udid); - CHECK_NULL_VOID(hiChainConnector_); - authMgr_->DeleteGroup(DM_PKG_NAME, userId, udid); + LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", + GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); + if (notifyOffline) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = localUserId; + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(deviceStateMgr_); + deviceStateMgr_->OnDeviceOffline(peerUdid); + } } void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) { LOGI("PreUserId %{public}d.", preUserId); - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(preUserId); + char localDeviceId[DEVICE_UUID_LENGTH]; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = reinterpret_cast(localDeviceId); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localUdid, preUserId); CHECK_NULL_VOID(hiChainConnector_); hiChainConnector_->DeleteAllGroup(preUserId); } +void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) +{ + LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId); + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(remoteUdid, userId); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroup(userId); +} + +void DeviceManagerServiceImpl::HandleUserSwitched(const std::map &deviceMap, + int32_t currentUserId, int32_t beforeUserId) +{ + LOGI("currentUserId: %{public}s, beforeUserId: %{public}s", GetAnonyInt32(currentUserId).c_str(), + GetAnonyInt32(beforeUserId).c_str()); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = beforeUserId; + for (const auto &item : deviceMap) { + if (item.second == INVALIED_TYPE || item.second == DEVICE) { + softbusConnector_->SetProcessInfo(processInfo); + } else { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localUdid, + item.first, beforeUserId); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } + softbusConnector_->HandleDeviceOffline(item.first); + } + DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); +} + void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) { if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { @@ -731,13 +787,23 @@ int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const return DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); } -std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId, +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::vector userIds; + userIds.push_back(userId); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, const std::string &accountId) { char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindType(userId, accountId, localUdid); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); } void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, @@ -746,18 +812,26 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - int32_t bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, - remoteUdid, localUdid); - if (bindType == DM_INVALIED_BINDTYPE) { - LOGE("Invalied bindtype."); - return; - } - CHECK_NULL_VOID(authMgr_); - authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); + std::multimap devIdAndUserMap = + DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, + remoteUserId, remoteAccountHash); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); - listener_->OnDeviceTrustChange(remoteUdid, uuid, ConvertBindTypeToAuthForm(bindType)); + listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT); + for (const auto &item : devIdAndUserMap) { + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(item.first, item.second, + remoteUdid, remoteUserId); + if (notifyOffline) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = item.second; + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfo(processInfo); + CHECK_NULL_VOID(deviceStateMgr_); + deviceStateMgr_->OnDeviceOffline(remoteUdid); + } + } } DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) @@ -796,17 +870,47 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - std::string pkgName = + ProcessInfo processInfo = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Pkgname is empty."); return; } CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetPkgName(pkgName); + softbusConnector_->SetProcessInfo(processInfo); softbusConnector_->HandleDeviceOffline(remoteUdid); } +void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backroundUserIds, const std::string &remoteUdid) +{ + LOGI("remote udid: %{public}s", GetAnonyString(remoteUdid).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::vector rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end()); + std::vector rmtBackUserIdsTemp(backroundUserIds.begin(), backroundUserIds.end()); + std::vector localUserIds; + int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds); + if (ret != DM_OK || localUserIds.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + } + DeviceProfileConnector::GetInstance().UpdatePeerUserId(localUdid, localUserIds, remoteUdid, + rmtFrontUserIdsTemp, rmtBackUserIdsTemp); + std::vector offlineProcInfo = + DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUdid, localUserIds, + remoteUdid, rmtBackUserIdsTemp); + if (!offlineProcInfo.empty()) { + CHECK_NULL_VOID(softbusConnector_); + softbusConnector_->SetProcessInfoVec(offlineProcInfo); + softbusConnector_->HandleDeviceOffline(remoteUdid); + } + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, + localUserIds, localUdid); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, + localUserIds, localUdid); +} + void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) { LOGI("In"); @@ -831,16 +935,15 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { - softbusConnector_->ClearPkgName(); - LOGI("networkId: %{public}s", GetAnonyString(devInfo.networkId).c_str()); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetFirstForegroundUserId()); + softbusConnector_->SetProcessInfoVec(processInfoVec); } deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } @@ -848,8 +951,8 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) { - CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); + CHECK_NULL_VOID(credentialMgr_); + credentialMgr_->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) @@ -889,6 +992,15 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i return DM_OK; } +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId) +{ + LOGI("localUserId %{public}d.", localUserId); + char localdeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localdeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localdeviceId); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 117f3a743..0f4943293 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -458,12 +458,12 @@ int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const return DEVICE_BIUND_LEVEL; } -std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId, +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, const std::string &accountId) { (void)userId; (void)accountId; - return std::map {}; + return std::multimap {}; } void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, @@ -491,12 +491,13 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const return; } -void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &udid, int32_t userId, - const std::string &accountId) +void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) { - (void)udid; - (void)userId; - (void)accountId; + (void)localUdid; + (void)localUserId; + (void)peerUdid; + (void)peerUserId; return; } @@ -512,6 +513,15 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } +void DeviceManagerServiceImpl::HandleUserSwitched(const std::map &deviceMap, + int32_t currentUserId, int32_t beforeUserId) +{ + (void)deviceMap; + (void)currentUserId; + (void)beforeUserId; + return; +} + int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) { (void)pkgName; @@ -527,13 +537,38 @@ void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &dev return; } -int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) +int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) { (void)appId; (void)accessTokenId; return 0; } +void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backroundUserIds, const std::string &remoteUdid) +{ + (void)foregroundUserIds; + (void)backroundUserIds; + (void)remoteUdid; +} + +void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid) +{ + (void)preUserId; + (void)remoteUdid; +} + +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId) +{ + (void)userId; +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t localUserId) +{ + (void)localUserId; + return {}; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 1848fc3b1..9c3d367a6 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -21,6 +21,7 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" +#include "dm_device_info.h" #include "dm_distributed_hardware_load.h" #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -110,7 +111,7 @@ void DmDeviceStateManager::OnDeviceOnline(std::string deviceId, int32_t authForm } } ProcessDeviceStateChange(DEVICE_STATE_ONLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) @@ -126,7 +127,7 @@ void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) devInfo = stateDeviceInfos_[deviceId]; } ProcessDeviceStateChange(DEVICE_STATE_OFFLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -139,7 +140,7 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe SaveOnlineDeviceInfo(devInfo); DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_STATE_OFFLINE: StartOffLineTimer(devInfo); @@ -150,12 +151,12 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe softbusConnector_->EraseUdidFromMap(udid); } ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_INFO_CHANGED: ChangeDeviceInfo(devInfo); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; default: LOGE("HandleDeviceStatusChange error, unknown device state = %{public}d", devState); @@ -165,17 +166,11 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe void DmDeviceStateManager::ProcessDeviceStateChange(const DmDeviceState devState, const DmDeviceInfo &devInfo) { - if (softbusConnector_ == nullptr || listener_ == nullptr) { - LOGE("ProcessDeviceStateChange failed, callback_ptr is null."); - return; - } - std::vector pkgName = softbusConnector_->GetPkgName(); - if (pkgName.size() == 0) { - listener_->OnDeviceStateChange(std::string(DM_PKG_NAME), devState, devInfo); - } else { - for (auto item : pkgName) { - listener_->OnDeviceStateChange(item, devState, devInfo); - } + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); + std::vector processInfoVec = softbusConnector_->GetProcessInfo(); + for (const auto &item : processInfoVec) { + listener_->OnDeviceStateChange(item, devState, devInfo); } } @@ -201,7 +196,10 @@ void DmDeviceStateManager::OnDbReady(const std::string &pkgName, const std::stri } if (listener_ != nullptr) { DmDeviceState state = DEVICE_INFO_READY; - listener_->OnDeviceStateChange(pkgName, state, saveInfo); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + listener_->OnDeviceStateChange(processInfo, state, saveInfo); } } @@ -511,30 +509,14 @@ bool DmDeviceStateManager::CheckIsOnline(const std::string &udid) void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) { - if (softbusConnector_ == nullptr || listener_ == nullptr) { - LOGE("failed, ptr is null."); - return; - } - std::vector pkgName = softbusConnector_->GetPkgName(); - LOGI("pkgName size: %{public}zu", pkgName.size()); - if (pkgName.size() == 0) { - listener_->OnDeviceScreenStateChange(std::string(DM_PKG_NAME), devInfo); - } else { - for (auto item : pkgName) { - listener_->OnDeviceScreenStateChange(item, devInfo); - } - } - softbusConnector_->ClearPkgName(); -} - -void DmDeviceStateManager::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, - int32_t errcode) -{ - if (listener_ == nullptr) { - LOGE("Failed, listener_ is null."); - return; + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); + std::vector processInfos = softbusConnector_->GetProcessInfo(); + softbusConnector_->ClearProcessInfo(); + LOGI("pkgName size: %{public}zu", processInfos.size()); + for (const auto &item : processInfos) { + listener_->OnDeviceScreenStateChange(item, devInfo); } - listener_->OnCredentialAuthStatus(std::string(DM_PKG_NAME), deviceList, deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/discovery/dm_discovery_manager.cpp b/services/implementation/src/discovery/dm_discovery_manager.cpp index 594b949f1..a9ccaee3a 100644 --- a/services/implementation/src/discovery/dm_discovery_manager.cpp +++ b/services/implementation/src/discovery/dm_discovery_manager.cpp @@ -160,9 +160,6 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, DmDeviceInfo info.authForm = DmAuthForm::INVALID_TYPE; GetAuthForm(localDeviceId, info.deviceId, filterPara.isTrusted, info.authForm); filterPara.authForm = info.authForm; - if (filter.IsValidDevice(discoveryContext.filterOp, discoveryContext.filters, filterPara)) { - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); - } return; } @@ -223,9 +220,6 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, DmAuthForm authForm = DmAuthForm::INVALID_TYPE; GetAuthForm(localDeviceId, info.deviceId, filterPara.isTrusted, authForm); filterPara.authForm = authForm; - if (filter.IsValidDevice(discoveryContext.filterOp, discoveryContext.filters, filterPara)) { - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); - } return; } @@ -248,7 +242,6 @@ void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t s } } softbusConnector_->StopDiscovery(subscribeId); - listener_->OnDiscoveryFailed(pkgName, (uint32_t)subscribeId, failedReason); } void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) @@ -258,7 +251,6 @@ void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t std::lock_guard autoLock(locks_); discoveryContextMap_[pkgName].subscribeId = (uint32_t)subscribeId; } - listener_->OnDiscoverySuccess(pkgName, subscribeId); } void DmDiscoveryManager::HandleDiscoveryTimeout(std::string name) diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index b1e2abbc9..52412fe3d 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -30,7 +30,6 @@ if (defined(ohos_lite)) { "include/ipc/lite", "include/permission/lite", "include/pinholder", - "include/relationshipsyncmgr", "${common_path}/include", "${common_path}/include/ipc", "${common_path}/include/ipc/lite", @@ -72,7 +71,6 @@ if (defined(ohos_lite)) { "src/permission/lite/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", - "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", ] @@ -180,6 +178,9 @@ if (defined(ohos_lite)) { "src/publishcommonevent/dm_data_share_common_event.cpp", "src/publishcommonevent/dm_package_common_event.cpp", "src/publishcommonevent/dm_screen_common_event.cpp", + "src/relationshipsyncmgr/dm_comm_tool.cpp", + "src/relationshipsyncmgr/dm_transport.cpp", + "src/relationshipsyncmgr/dm_transport_msg.cpp", "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index d603e7e74..8d7f972da 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -35,6 +35,7 @@ #include "dm_account_common_event.h" #include "dm_package_common_event.h" #include "dm_screen_common_event.h" +#include "relationship_sync_mgr.h" #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) #include "dm_publish_common_event.h" #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI @@ -76,14 +77,6 @@ public: int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid); - int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, - const std::string &extra); - - int32_t StartDeviceDiscovery(const std::string &pkgName, const uint16_t subscribeInfo, - const std::string &filterOptions); - - int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId); - int32_t PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo); int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId); @@ -192,17 +185,22 @@ public: bool CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee); bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); void HandleDeviceNotTrust(const std::string &msg); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void HandleDeviceTrustedChange(const std::string &msg); - + void HandleUserIdCheckSumChange(const std::string &msg); +#endif int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); - void ClearDiscoveryCache(const std::string &pkgName); + void ClearDiscoveryCache(const ProcessInfo &processInfo); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, int32_t &screenStatus); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); + void ProcessSyncUserIds(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid); int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); + void RemoveNotifyRecord(const ProcessInfo &processInfo); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); @@ -216,17 +214,50 @@ private: void SendServiceUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId); void SendAccountLogoutBroadCast(const std::vector &peerUdids, const std::string &accountId, const std::string &accountName, int32_t userId); + /** + * @brief send local foreground or background userids by broadcast + * + * @param peerUdids the broadcast target device udid list + * @param foregroundUserIds local foreground userids + * @param backgroundUserIds local background userids + */ + void SendUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, + bool isNeedResponse); + void SendUserRemovedBroadCast(const std::vector &peerUdids, int32_t userId); + /** + * @brief parse dsoftbus checksum msg + * + * @param msg checksum msg + * @param networkId remote device networkid + * @param discoveryType remote device link type, wifi or ble/br + * @return int32_t 0 for success + */ + int32_t ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType); + void ProcessCheckSumByWifi(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds); + void ProcessCheckSumByBT(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void SubscribeAccountCommonEvent(); - void AccountCommonEventCallback(int32_t userId, const std::string commonEventType); + void AccountCommonEventCallback(const std::string commonEventType, int32_t currentUserId, int32_t beforeUserId); void SubscribeScreenLockEvent(); void ScreenCommonEventCallback(std::string commonEventType); void ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInfo); int32_t ConvertUdidHashToAnoyDeviceId(const std::string &udidHash, std::string &anoyDeviceId); int32_t GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash); void HandleAccountLogout(int32_t userId, const std::string &accountId, const std::string &accountName); - void HandleUserRemoved(int32_t preUserId); + void HandleUserRemoved(int32_t removedUserId); + /** + * @brief process the user switch + * + * @param currentUserId the user id which switched to foreground. + * @param beforeUserId the user id which switched to backend. + */ + void HandleUserSwitched(int32_t curUserId, int32_t preUserId); + void HandleUserIdsBroadCast(const std::vector &remoteUserIdInfos, + const std::string &remoteUdid, bool isNeedResponse); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index a175c8525..74df27405 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -39,57 +39,56 @@ public: DeviceManagerServiceListener() {}; virtual ~DeviceManagerServiceListener() {}; - void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) override; + void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info) override; - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) override; + void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) override; - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) override; + void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) override; - void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) override; - - void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) override; + void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) override; void OnPublishResult(const std::string &pkgName, int32_t publishId, int32_t publishResult) override; - void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, - int32_t reason) override; + void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) override; - void OnUiCall(std::string &pkgName, std::string ¶mJson) override; + void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) override; - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override; + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override; - void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; - void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) override; - void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) override; - void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) override; - void OnCreateResult(const std::string &pkgName, int32_t result) override; - void OnDestroyResult(const std::string &pkgName, int32_t result) override; - void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) override; + void OnCreateResult(const ProcessInfo &processInfo, int32_t result) override; + void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) override; + void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; - void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; - void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, + void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override; + void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) override; void OnAppUnintall(const std::string &pkgName) override; - void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; + void OnProcessRemove(const ProcessInfo &processInfo) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); - void SetDeviceInfo(std::shared_ptr pReq, const std::string &pkgName, + void SetDeviceInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, + void ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, + void ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - std::string ComposeOnlineKey(const std::string &pkgName, const std::string &devId); - void SetDeviceScreenInfo(std::shared_ptr pReq, const std::string &pkgName, + void SetDeviceScreenInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceInfo &deviceInfo); void RemoveOnlinePkgName(const DmDeviceInfo &info); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -97,11 +96,25 @@ private: int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, std::string &anoyDeviceId); #endif + std::vector GetWhiteListSAProcessInfo(); + std::vector GetNotifyProcessInfoByUserId(int32_t userId); + ProcessInfo DealBindProcessInfo(const ProcessInfo &processInfo); + void ProcessDeviceOnline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessDeviceOffline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessDeviceInfoChange(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessAppOnline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessAppOffline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void RemoveNotExistProcess(const std::vector &procInfoVec); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; - static std::mutex alreadyOnlinePkgNameLock_; - static std::unordered_map alreadyOnlinePkgName_; + static std::mutex alreadyNotifyPkgNameLock_; + static std::map alreadyOnlinePkgName_; #endif }; } // namespace DistributedHardware diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index 04c5deef3..ddb542ab2 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -36,6 +36,11 @@ typedef struct DiscoveryContext { std::vector filters; } DiscoveryContext; +typedef struct MultiUserDiscovery { + std::string pkgName; + int32_t userId; +} MultiUserDiscovery; + typedef enum { PROXY_TRANSMISION = 0, PROXY_HEARTBEAT = 1, @@ -84,12 +89,16 @@ private: const std::string &searchJson); int32_t HandleDiscoveryQueue(const std::string &pkgName, uint16_t subscribeId, const std::map &filterOps); - int32_t GetDeviceAclParam(const std::string &pkgName, std::string deviceId, bool &isOnline, int32_t &authForm); + int32_t GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, + int32_t &authForm); void ConfigDiscParam(const std::map &discoverParam, DmSubscribeInfo *dmSubInfo); bool CompareCapability(uint32_t capabilityType, const std::string &capabilityStr); void OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara); void UpdateInfoFreq(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); + std::string AddMultiUserIdentify(const std::string &pkgName); + std::string RemoveMultiUserIdentify(const std::string &pkgName); + void GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, int32_t &userId); private: std::mutex locks_; @@ -104,6 +113,8 @@ private: std::set pkgNameSet_; std::map capabilityMap_; std::mutex capabilityMapLocks_; + std::mutex multiUserDiscLocks_; + std::map multiUserDiscMap_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) static bool isSoLoaded_; diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 9816d1359..5d3cda0bb 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -261,20 +261,29 @@ public: virtual int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual void HandleDeviceNotTrust(const std::string &udid) = 0; - virtual std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId) = 0; virtual void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid) = 0; virtual void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid) = 0; virtual void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId) = 0; virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) = 0; - virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; + virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; + virtual void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; + virtual void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, + const std::vector &backroundUserIds, const std::string &remoteUdid) = 0; + virtual void HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) = 0; + virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 9e39d2440..bb1a95adc 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -32,7 +32,7 @@ public: * @tc.desc: Device State Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, + virtual void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info) = 0; /** @@ -40,28 +40,21 @@ public: * @tc.desc: Device Found of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) = 0; - - /** - * @tc.name: IDeviceManagerServiceListener::OnDeviceFound - * @tc.desc: Device Found of the DeviceManager Service Listener - * @tc.type: FUNC - */ - virtual void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) = 0; + virtual void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDiscoveryFailed * @tc.desc: Discovery Failed of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) = 0; + virtual void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDiscoverySuccess * @tc.desc: Discovery Success of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) = 0; + virtual void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnPublishResult @@ -75,7 +68,7 @@ public: * @tc.desc: Auth Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, + virtual void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) = 0; /** @@ -83,21 +76,21 @@ public: * @tc.desc: Fa Call of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnUiCall(std::string &pkgName, std::string ¶mJson) = 0; + virtual void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCredentialResult * @tc.desc: Credential Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) = 0; + virtual void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnBindResult * @tc.desc: Bind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) = 0; /** @@ -105,7 +98,7 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) = 0; /** @@ -113,7 +106,7 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + virtual void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) = 0; /** @@ -121,28 +114,28 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) = 0; + virtual void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCreateResult * @tc.desc: Create Pin Holder Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCreateResult(const std::string &pkgName, int32_t result) = 0; + virtual void OnCreateResult(const ProcessInfo &processInfo, int32_t result) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDestroyResult * @tc.desc: Destroy Pin Holder Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDestroyResult(const std::string &pkgName, int32_t result) = 0; + virtual void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnPinHolderEvent * @tc.desc: Pin Holder Event of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + virtual void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) = 0; /** @@ -157,18 +150,19 @@ public: * @tc.desc: Device Screen State Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) = 0; + virtual void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCredentialAuthStatus * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, + virtual void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; virtual void OnAppUnintall(const std::string &pkgName) = 0; - virtual void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) = 0; + virtual void OnProcessRemove(const ProcessInfo &processInfo) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/ipc/lite/ipc_server_listener.h b/services/service/include/ipc/lite/ipc_server_listener.h index f6dfcb6af..294cbe226 100644 --- a/services/service/include/ipc/lite/ipc_server_listener.h +++ b/services/service/include/ipc/lite/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,9 @@ #define OHOS_DM_IPC_SERVER_LISTENER_H #include +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" #include "ipc_server_listenermgr.h" @@ -38,18 +40,12 @@ public: int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Send All of the Ipc Server Listener - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); + std::set GetSystemSA(); private: void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity); diff --git a/services/service/include/ipc/standard/ipc_server_listener.h b/services/service/include/ipc/standard/ipc_server_listener.h index 4a19b1e57..af9761610 100644 --- a/services/service/include/ipc/standard/ipc_server_listener.h +++ b/services/service/include/ipc/standard/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -17,7 +17,8 @@ #define OHOS_DM_IPC_SERVER_LISTENER_H #include - +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -37,18 +38,12 @@ public: int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Send All of the Ipc Server Listener - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); + std::set GetSystemSA(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/ipc/standard/ipc_server_stub.h b/services/service/include/ipc/standard/ipc_server_stub.h index 6c3f819f2..ff6055c45 100644 --- a/services/service/include/ipc/standard/ipc_server_stub.h +++ b/services/service/include/ipc/standard/ipc_server_stub.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +31,7 @@ #include "system_ability.h" #include "account_boot_listener.h" +#include "dm_device_info.h" #include "dm_single_instance.h" namespace OHOS { @@ -86,14 +88,14 @@ public: * @tc.desc: Register DeviceManager Listener of the IpcServerStub * @tc.type: FUNC */ - int32_t RegisterDeviceManagerListener(std::string &pkgName, sptr listener); + int32_t RegisterDeviceManagerListener(const ProcessInfo &processInfo, sptr listener); /** * @tc.name: IpcServerStub::UnRegisterDeviceManagerListener * @tc.desc: UnRegister DeviceManager Listener of the IpcServerStub * @tc.type: FUNC */ - int32_t UnRegisterDeviceManagerListener(std::string &pkgName); + int32_t UnRegisterDeviceManagerListener(const ProcessInfo &processInfo); /** * @tc.name: IpcServerStub::QueryServiceState @@ -103,32 +105,25 @@ public: ServiceRunningState QueryServiceState() const; /** - * @tc.name: IpcServerStub::SendALL - * @tc.desc: SendALL of the IpcServerStub - * @tc.type: FUNC - */ - int32_t SendALL(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerStub::GetAllPkgName + * @tc.name: IpcServerStub::GetAllProcessInfo * @tc.desc: Get All PkgName from dmListener_ * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); /** * @tc.name: IpcServerStub::GetDmListener * @tc.desc: Get DmListener of the IpcServerStub * @tc.type: FUNC */ - const sptr GetDmListener(std::string pkgName) const; + const sptr GetDmListener(ProcessInfo processInfo) const; /** * @tc.name: IpcServerStub::GetDmListenerPkgName * @tc.desc: Get DmListener PkgName of the IpcServerStub * @tc.type: FUNC */ - const std::string GetDmListenerPkgName(const wptr &remote) const; + const ProcessInfo GetDmListenerPkgName(const wptr &remote) const; /** * @tc.name: IpcServerStub::Dump @@ -150,19 +145,23 @@ public: * @tc.type: FUNC */ void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + std::set GetSystemSA(); private: IpcServerStub(); ~IpcServerStub() override = default; bool Init(); + void AddSystemSA(const std::string &pkgName); + void RemoveSystemSA(const std::string &pkgName); private: bool registerToService_; ServiceRunningState state_; mutable std::mutex listenerLock_; - std::map> appRecipient_; - std::map> dmListener_; + std::map> appRecipient_; + std::map> dmListener_; std::shared_ptr accountBootListener_; + std::set systemSA_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/permission/lite/permission_manager.h b/services/service/include/permission/lite/permission_manager.h index 4d41f71db..85b6bd48e 100644 --- a/services/service/include/permission/lite/permission_manager.h +++ b/services/service/include/permission/lite/permission_manager.h @@ -32,8 +32,9 @@ public: int32_t GetCallerProcessName(std::string &processName); bool CheckProcessNameValidOnAuthCode(const std::string &processName); bool CheckProcessNameValidOnPinHolder(const std::string &processName); + bool CheckWhiteListSystemSA(const std::string &pkgName); + std::unordered_set GetWhiteListSystemSA(); bool CheckSystemSA(const std::string &pkgName); - std::unordered_set GetSystemSA(); bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index 6b3716507..ddf790bf0 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -33,8 +33,9 @@ public: int32_t GetCallerProcessName(std::string &processName); bool CheckProcessNameValidOnAuthCode(const std::string &processName); bool CheckProcessNameValidOnPinHolder(const std::string &processName); + bool CheckWhiteListSystemSA(const std::string &pkgName); + std::unordered_set GetWhiteListSystemSA(); bool CheckSystemSA(const std::string &pkgName); - std::unordered_set GetSystemSA(); bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index b12aa0e8a..f5d8a3fae 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -76,7 +76,6 @@ private: std::shared_ptr session_ = nullptr; std::shared_ptr timer_ = nullptr; - std::string registerPkgName_ = ""; std::string remoteDeviceId_ = ""; std::string payload_ = ""; DmPinType pinType_ = NUMBER_PIN_CODE; @@ -86,6 +85,7 @@ private: bool isRemoteSupported_ = false; std::atomic isDestroy_ {false}; DestroyState destroyState_ = STATE_UNKNOW; + ProcessInfo processInfo_; }; } } diff --git a/services/service/include/publishcommonevent/dm_account_common_event.h b/services/service/include/publishcommonevent/dm_account_common_event.h index b0a9e6878..640bf206f 100644 --- a/services/service/include/publishcommonevent/dm_account_common_event.h +++ b/services/service/include/publishcommonevent/dm_account_common_event.h @@ -33,7 +33,19 @@ namespace DistributedHardware { using OHOS::EventFwk::CommonEventData; using OHOS::EventFwk::CommonEventSubscriber; using OHOS::EventFwk::CommonEventSubscribeInfo; -using AccountEventCallback = std::function; +/** + * @brief account event callback define, fun(event_type, current userid, before userid) + * first param, accont event + * second param, the current userid + * third param, the userid before. + * first param | second param | third param + * ------------------------------------------ + * COMMON_EVENT_USER_SWITCHED | switch target user id | the user id before switch + * COMMON_EVENT_USER_REMOVED | -1 | the user id removed + * COMMON_EVENT_HWID_LOGOUT | logout in witch user id | logout in witch user id + * COMMON_EVENT_HWID_LOGIN | login in witch user id | login in witch user id + */ +using AccountEventCallback = std::function; class DmAccountEventSubscriber : public CommonEventSubscriber { public: diff --git a/services/service/include/relationshipsyncmgr/dm_comm_tool.h b/services/service/include/relationshipsyncmgr/dm_comm_tool.h new file mode 100644 index 000000000..8eba6a77a --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_comm_tool.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_COMM_TOOL_H +#define OHOS_DM_COMM_TOOL_H + +#include +#include +#include +#include + +#include "dm_transport.h" +#include "dm_transport_msg.h" +#include "event_handler.h" + +namespace OHOS { +namespace DistributedHardware { +// send local foreground userids msg +constexpr int32_t DM_COMM_SEND_LOCAL_USERIDS = 1; +// if receive remote device send foreground userids, response local foreground uerids +// This msg no need response +constexpr int32_t DM_COMM_RSP_LOCAL_USERIDS = 2; + +class DMCommTool : public std::enable_shared_from_this { +public: + DMCommTool(); + virtual ~DMCommTool() = default; + static std::shared_ptr GetInstance(); + void Init(); + void UnInit(); + + void SendUserIds(const std::string rmtNetworkId, const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds); + void RspLocalFrontOrBackUserIds(const std::string rmtNetworkId, const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds); + + class DMCommToolEventHandler : public AppExecFwk::EventHandler { + public: + DMCommToolEventHandler(const std::shared_ptr runner, + std::shared_ptr dmCommToolPtr); + ~DMCommToolEventHandler() override = default; + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; + private: + std::weak_ptr dmCommToolWPtr_; + }; + std::shared_ptr GetEventHandler(); + const std::shared_ptr GetDMTransportPtr(); + + void ProcessReceiveUserIdsEvent(const std::shared_ptr commMsg); + void ProcessResponseUserIdsEvent(const std::shared_ptr commMsg); +private: + std::shared_ptr dmTransportPtr_; + std::shared_ptr eventHandler_; +}; +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/dm_transport.h b/services/service/include/relationshipsyncmgr/dm_transport.h new file mode 100644 index 000000000..cf8eb0890 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_transport.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_TRANSPORT_H +#define OHOS_DM_TRANSPORT_H + +#include +#include +#include +#include +#include +#include + +#include "event_handler.h" +#include "socket.h" +#include "softbus_bus_center.h" + +namespace OHOS { +namespace DistributedHardware { +class DMCommTool; +class DMTransport { +public: + explicit DMTransport(std::shared_ptr dmCommToolPtr); + int32_t Init(); + int32_t UnInit(); + virtual ~DMTransport() = default; + // open softbus channel with remote device by networkid. + int32_t StartSocket(const std::string &rmtNetworkId); + // stop softbus channel with remote device by networkid. + int32_t StopSocket(const std::string &rmtNetworkId); + int32_t Send(const std::string &rmtNetworkId, const std::string &payload); + int32_t OnSocketOpened(int32_t socketId, const PeerSocketInfo &info); + void OnSocketClosed(int32_t socketId, ShutdownReason reason); + void OnBytesReceived(int32_t socketId, const void *data, uint32_t dataLen); + +private: + int32_t CreateServerSocket(); + int32_t CreateClientSocket(const std::string &remoteDevId); + bool IsDeviceSessionOpened(const std::string &remoteDevId, int32_t &socketId); + std::string GetRemoteNetworkIdBySocketId(int32_t socketId); + void ClearDeviceSocketOpened(const std::string &remoteDevId); + void HandleReceiveMessage(const int32_t socketId, const std::string &payload); + +private: + std::mutex rmtSocketIdMtx_; + // record the socket id for the connection with remote devices, + std::map remoteDevSocketIds_; + std::atomic localServerSocket_; + std::string localSocketName_; + std::atomic isSocketSvrCreateFlag_; + std::weak_ptr dmCommToolWPtr_; +}; +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/dm_transport_msg.h b/services/service/include/relationshipsyncmgr/dm_transport_msg.h new file mode 100644 index 000000000..bdca9e791 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_transport_msg.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_TRANSPORT_MSG_H +#define OHOS_DM_TRANSPORT_MSG_H + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +const char* const FOREGROUND_USERIDS_MSG_USERIDS_KEY = "foregroundUserIds"; +const char* const BACKGROUND_USERIDS_MSG_USERIDS_KEY = "backgroundUserIds"; +const char* const COMM_MSG_CODE_KEY = "code"; +const char* const COMM_MSG_MSG_KEY = "msg"; + +const char* const DSOFTBUS_NOTIFY_USERIDS_UDIDKEY = "remoteUdid"; +const char* const DSOFTBUS_NOTIFY_USERIDS_USERIDKEY = "foregroundUserIds"; + +struct UserIdsMsg { + std::vector foregroundUserIds; + std::vector backgroundUserIds; + UserIdsMsg() : foregroundUserIds({}), backgroundUserIds({}) {} + UserIdsMsg(std::vector foregroundUserIds, std::vector backgroundUserIds) + : foregroundUserIds(foregroundUserIds), backgroundUserIds(backgroundUserIds) {} +}; + +void ToJson(cJSON *jsonObject, const UserIdsMsg &userIdsMsg); +void FromJson(const cJSON *jsonObject, UserIdsMsg &userIdsMsg); + +struct CommMsg { + int32_t code; + std::string msg; + CommMsg() : code(-1), msg("") {} + CommMsg(int32_t code, std::string msg) : code(code), msg(msg) {} +}; + +void ToJson(cJSON *jsonObject, const CommMsg &commMsg); +void FromJson(const cJSON *jsonObject, CommMsg &commMsg); + +std::string GetCommMsgString(const CommMsg &commMsg); + +struct InnerCommMsg { + std::string remoteNetworkId; + std::shared_ptr commMsg; + InnerCommMsg(std::string remoteNetworkId, std::shared_ptr commMsg) + : remoteNetworkId(remoteNetworkId), commMsg(commMsg) {} +}; + +struct NotifyUserIds { + std::string remoteUdid; + std::vector userIds; + NotifyUserIds() : remoteUdid(""), userIds({}) {} + NotifyUserIds(std::string remoteUdid, std::vector userIds) + : remoteUdid(remoteUdid), userIds(userIds) {} + + std::string ToString(); +}; + +void ToJson(cJSON *jsonObject, const NotifyUserIds &userIds); +void FromJson(const cJSON *jsonObject, NotifyUserIds &userIds); +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index 10156b19d..f64c1af30 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -22,6 +22,7 @@ #include "dm_single_instance.h" namespace OHOS { namespace DistributedHardware { +const uint32_t MAX_USER_ID_NUM = 5; enum class RelationShipChangeType : uint32_t { ACCOUNT_LOGOUT = 0, DEVICE_UNBIND = 1, @@ -29,7 +30,18 @@ enum class RelationShipChangeType : uint32_t { SERVICE_UNBIND = 3, DEL_USER = 4, APP_UNINSTALL = 5, - TYPE_MAX = 6 + SYNC_USERID = 6, + TYPE_MAX = 7 +}; + +struct UserIdInfo { + /** + * @brief true for foreground userid, false for background + */ + bool isForeground; + std::uint16_t userId; + UserIdInfo(bool isForeground, std::uint16_t userId) : isForeground(isForeground), userId(userId) {} + const std::string ToString() const; }; struct RelationShipChangeMsg { @@ -37,9 +49,15 @@ struct RelationShipChangeMsg { uint32_t userId; std::string accountId; uint64_t tokenId; + // The broadcast need send to these devices with the udids std::vector peerUdids; + // The broadcast from which device with the udid. std::string peerUdid; std::string accountName; + // true: request, false: response + bool syncUserIdFlag; + // The foreground and background user id infos + std::vector userIdInfos; explicit RelationShipChangeMsg(); bool ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) const; @@ -50,14 +68,20 @@ struct RelationShipChangeMsg { void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; - cJSON *ToArrayJson() const; + bool ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const; + cJSON *ToPayLoadJson() const; bool FromAccountLogoutPayLoad(const cJSON *payloadJson); bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); bool FromAppUnbindPayLoad(const cJSON *payloadJson); + bool FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson); + bool FromDelUserPayLoad(const cJSON *payloadJson); std::string ToJson() const; bool FromJson(const std::string &msgJson); + + const std::string ToString() const; }; class ReleationShipSyncMgr { @@ -67,6 +91,9 @@ public: RelationShipChangeMsg ParseTrustRelationShipChange(const std::string &msgJson); }; +const std::string GetUserIdInfoList(const std::vector &list); +void GetFrontAndBackUserIdInfos(const std::vector &remoteUserIdInfos, + std::vector &foregroundUserIdInfos, std::vector &backgroundUserIdInfos); } // DistributedHardware } // OHOS #endif // OHOS_RELATIONSHIP_SYNC_MGR_H \ No newline at end of file diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 9220f2e13..1ccbaa02e 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -56,6 +56,7 @@ public: static void OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen); static void DeviceNotTrust(const std::string &msg); static void DeviceTrustedChange(const std::string &msg); + static void DeviceUserIdCheckSumChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); static void OnCredentialAuthStatus(const char *deviceList, uint32_t deviceListLen, uint16_t deviceTypeId, @@ -103,6 +104,7 @@ public: int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); static int32_t GetNetworkIdByUdid(const std::string &udid, std::string &networkId); int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); + int32_t SetForegroundUserIdsToDSoftBus(const std::string &remoteUserId, const std::vector &userIds); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 5923fb4eb..9e8c5e88a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -19,6 +19,7 @@ #include #include "app_manager.h" +#include "nlohmann/json.hpp" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" @@ -27,13 +28,15 @@ #include "dm_softbus_cache.h" #include "parameter.h" #include "permission_manager.h" -#include "relationship_sync_mgr.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "common_event_support.h" #include "datetime_ex.h" +#include "dm_comm_tool.h" +#include "dm_transport_msg.h" #include "iservice_registry.h" #include "kv_adapter_manager.h" #include "multiple_user_connector.h" +#include "relationship_sync_mgr.h" #if defined(SUPPORT_POWER_MANAGER) #include "power_mgr_client.h" #endif // SUPPORT_POWER_MANAGER @@ -60,13 +63,18 @@ constexpr const char* LIB_DM_ADAPTER_NAME = "libdevicemanageradapter.z.so"; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); -const int32_t NORMAL = 0; -const int32_t SYSTEM_BASIC = 1; -const int32_t SYSTEM_CORE = 2; -constexpr const char* ALL_PKGNAME = ""; -constexpr const char* NETWORKID = "NETWORK_ID"; -constexpr uint32_t INVALIED_BIND_LEVEL = 0; -constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; +namespace { + const int32_t NORMAL = 0; + const int32_t SYSTEM_BASIC = 1; + const int32_t SYSTEM_CORE = 2; + constexpr const char *ALL_PKGNAME = ""; + constexpr const char *NETWORKID = "NETWORK_ID"; + constexpr uint32_t INVALIED_BIND_LEVEL = 0; + constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; + const std::string USERID_CHECKSUM_NETWORKID_KEY = "networkId"; + const std::string USERID_CHECKSUM_DISCOVER_TYPE_KEY = "discoverType"; + constexpr uint32_t USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK = 0b0010; +} DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); @@ -203,6 +211,9 @@ int32_t DeviceManagerService::InitDMServiceListener() if (pinHolder_ == nullptr) { pinHolder_ = std::make_shared(listener_); } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + DMCommTool::GetInstance()->Init(); +#endif LOGI("Init success."); return DM_OK; } @@ -258,9 +269,9 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c } return DM_OK; } - if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { + if (!onlineDeviceList.empty() && IsDMServiceImplReady()) { std::unordered_map udidMap; - if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) { + if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) { udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME)); } else { udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName); @@ -404,72 +415,6 @@ int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, con return SoftbusListener::GetUuidByNetworkId(netWorkId.c_str(), uuid); } -int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, - const std::string &extra) -{ - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("Begin for pkgName = %{public}s, extra = %{public}s", - pkgName.c_str(), extra.c_str()); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - - SoftbusListener::SetHostPkgName(pkgName); - std::map discParam; - discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, - std::to_string(subscribeInfo.subscribeId))); - discParam.insert(std::pair(PARAM_KEY_DISC_MEDIUM, std::to_string(subscribeInfo.medium))); - - std::map filterOps; - filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, extra)); - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StartDiscovering(pkgName, discParam, filterOps); -} - -int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const uint16_t subscribeId, - const std::string &filterOptions) -{ - if (!PermissionManager::GetInstance().CheckNewPermission()) { - LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("Begin for pkgName = %{public}s, filterOptions = %{public}s, subscribeId = %{public}d", - pkgName.c_str(), filterOptions.c_str(), subscribeId); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - - SoftbusListener::SetHostPkgName(pkgName); - std::map discParam; - discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId))); - - std::map filterOps; - filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, filterOptions)); - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StartDiscovering(pkgName, discParam, filterOps); -} - -int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) -{ - if (!PermissionManager::GetInstance().CheckPermission() && - !PermissionManager::GetInstance().CheckNewPermission()) { - LOGE("The caller: %{public}s does not have permission to call StopDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StopDiscovering(pkgName, subscribeId); -} - int32_t DeviceManagerService::PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo) { if (!PermissionManager::GetInstance().CheckPermission()) { @@ -1593,8 +1538,8 @@ void DeviceManagerService::SubscribeAccountCommonEvent() if (accountCommonEventManager_ == nullptr) { accountCommonEventManager_ = std::make_shared(); } - AccountEventCallback callback = [=](const auto &arg1, const auto &arg2) { - this->AccountCommonEventCallback(arg1, arg2); + AccountEventCallback callback = [=](const auto &eventType, const auto ¤tUserId, const auto &beforeUserId) { + this->AccountCommonEventCallback(eventType, currentUserId, beforeUserId); }; std::vector AccountCommonEventVec; AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); @@ -1622,29 +1567,39 @@ void DeviceManagerService::SubscribeScreenLockEvent() return; } -void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std::string commonEventType) +void DeviceManagerService::AccountCommonEventCallback(const std::string commonEventType, int32_t currentUserId, + int32_t beforeUserId) { - LOGI("CommonEventType: %{public}s, userId: %{public}d", commonEventType.c_str(), userId); + LOGI("CommonEventType: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", commonEventType.c_str(), + currentUserId, beforeUserId); if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { DMAccountInfo dmAccountInfo; dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); - MultipleUserConnector::SetAccountInfo(userId, dmAccountInfo); + MultipleUserConnector::SetAccountInfo(currentUserId, dmAccountInfo); + if (beforeUserId == -1 || currentUserId == -1) { + return; + } else if (beforeUserId != -1 && currentUserId != -1) { + HandleUserSwitched(currentUserId, beforeUserId); + } if (IsDMServiceAdapterLoad()) { - dmServiceImplExt_->AccountUserSwitched(userId, MultipleUserConnector::GetOhosAccountId()); + dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { DMAccountInfo dmAccountInfo; dmAccountInfo.accountId = MultipleUserConnector::GetOhosAccountId(); dmAccountInfo.accountName = MultipleUserConnector::GetOhosAccountName(); - MultipleUserConnector::SetAccountInfo(userId, dmAccountInfo); + MultipleUserConnector::SetAccountInfo(currentUserId, dmAccountInfo); } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGOUT) { - DMAccountInfo dmAccountInfo = MultipleUserConnector::GetAccountInfoByUserId(userId); - HandleAccountLogout(userId, dmAccountInfo.accountId, dmAccountInfo.accountName); - MultipleUserConnector::DeleteAccountInfoByUserId(userId); + DMAccountInfo dmAccountInfo = MultipleUserConnector::GetAccountInfoByUserId(beforeUserId); + if (dmAccountInfo.accountId.empty()) { + return; + } + HandleAccountLogout(currentUserId, dmAccountInfo.accountId, dmAccountInfo.accountName); + MultipleUserConnector::DeleteAccountInfoByUserId(currentUserId); } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { - HandleUserRemoved(userId); - MultipleUserConnector::DeleteAccountInfoByUserId(userId); + HandleUserRemoved(beforeUserId); + MultipleUserConnector::DeleteAccountInfoByUserId(beforeUserId); } else { LOGE("Invalied account common event."); } @@ -1654,8 +1609,8 @@ void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std: void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string &accountId, const std::string &accountName) { - LOGI("UserId: %{public}d, accountId: %{public}s, accountName: %{public}s", userId, GetAnonyString(accountId).c_str(), - GetAnonyString(accountName).c_str()); + LOGI("UserId: %{public}d, accountId: %{public}s, accountName: %{public}s", userId, + GetAnonyString(accountId).c_str(), GetAnonyString(accountName).c_str()); if (IsDMServiceAdapterLoad()) { dmServiceImplExt_->AccountIdLogout(userId, accountId); } @@ -1663,14 +1618,14 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string LOGE("Init impl failed."); return; } - std::map deviceMap; + std::multimap deviceMap; std::vector peerUdids; - deviceMap = dmServiceImpl_->GetDeviceIdAndBindType(userId, accountId); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(userId, accountId); for (const auto &item : deviceMap) { - if (item.second == DM_IDENTICAL_ACCOUNT) { - dmServiceImpl_->HandleIdentAccountLogout(item.first, userId, accountId); - peerUdids.emplace_back(item.first); - } + peerUdids.emplace_back(item.first); } if (!peerUdids.empty()) { char accountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; @@ -1680,14 +1635,78 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string } SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); } + for (const auto &item : deviceMap) { + dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second); + } } -void DeviceManagerService::HandleUserRemoved(int32_t preUserId) +void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUserId) { - LOGI("PreUserId %{public}d.", preUserId); - if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleUserRemoved(preUserId); + LOGI("currentUserId: %{public}d. previousUserId: %{public}d", curUserId, preUserId); + if (!IsDMServiceImplReady()) { + LOGE("Init impl failed."); + return; } + std::map curUserDeviceMap; + std::map preUserDeviceMap; + std::vector peerUdids; + curUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(curUserId); + preUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(preUserId); + for (const auto &item : curUserDeviceMap) { + peerUdids.push_back(item.first); + } + for (const auto &item : preUserDeviceMap) { + if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) { + peerUdids.push_back(item.first); + } + } + if (!peerUdids.empty()) { + std::vector foregroundUserVec; + int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec); + std::vector backgroundUserVec; + int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec); + if (retFront != DM_OK || retBack != DM_OK || foregroundUserVec.empty()) { + LOGE("Get userids failed, retFront: %{public}d, retBack: %{public}d, foreground user num: %{public}d", + retFront, retBack, static_cast(foregroundUserVec.size())); + } else { + LOGE("Send local foreground and background userids"); + SendUserIdsBroadCast(peerUdids, foregroundUserVec, backgroundUserVec, true); + } + } + dmServiceImpl_->HandleUserSwitched(preUserDeviceMap, curUserId, preUserId); +} + +void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) +{ + LOGI("PreUserId %{public}d.", removedUserId); + if (!IsDMServiceImplReady()) { + LOGE("Init impl failed."); + return; + } + std::multimap deviceMap = dmServiceImpl_->GetDeviceIdAndUserId(removedUserId); + std::vector peerUdids; + for (const auto &item : deviceMap) { + if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) { + peerUdids.emplace_back(item.first); + } + } + if (!peerUdids.empty()) { + // Send UserId Removed broadcast + SendUserRemovedBroadCast(peerUdids, removedUserId); + } + dmServiceImpl_->HandleUserRemoved(removedUserId); +} + +void DeviceManagerService::SendUserRemovedBroadCast(const std::vector &peerUdids, int32_t userId) +{ + LOGI("peerUdids: %{public}s, userId %{public}d.", GetAnonyStringList(peerUdids).c_str(), userId); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEL_USER; + msg.userId = userId; + msg.peerUdids = peerUdids; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); } void DeviceManagerService::SendAccountLogoutBroadCast(const std::vector &peerUdids, @@ -1706,6 +1725,92 @@ void DeviceManagerService::SendAccountLogoutBroadCast(const std::vectorSendAclChangedBroadcast(broadCastMsg); } +void DeviceManagerService::SendUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds, bool isNeedResponse) +{ + LOGI("peerUdids: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, isNeedRsp: %{public}s", + GetAnonyStringList(peerUdids).c_str(), GetIntegerList(foregroundUserIds).c_str(), + GetIntegerList(backgroundUserIds).c_str(), isNeedResponse ? "true" : "false"); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SYNC_USERID; + msg.peerUdids = peerUdids; + msg.syncUserIdFlag = isNeedResponse; + for (const auto &userId : foregroundUserIds) { + msg.userIdInfos.push_back({ true, static_cast(userId) }); + } + for (auto const &userId : backgroundUserIds) { + msg.userIdInfos.push_back({ false, static_cast(userId) }); + } + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::HandleUserIdsBroadCast(const std::vector &remoteUserIdInfos, + const std::string &remoteUdid, bool isNeedResponse) +{ + LOGI("rmtUdid: %{public}s, rmtUserIds: %{public}s, isNeedResponse: %{public}s,", + GetAnonyString(remoteUdid).c_str(), GetUserIdInfoList(remoteUserIdInfos).c_str(), + isNeedResponse ? "true" : "false"); + if (isNeedResponse) { + std::vector foregroundUserVec; + std::vector backgroundUserVec; + int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec); + int32_t retBack = MultipleUserConnector::GetBackgroundUserIds(backgroundUserVec); + if (retFront != DM_OK || retBack!= DM_OK || foregroundUserVec.empty()) { + LOGE("Get userid failed, retFront: %{public}d, retBack: %{public}d, frontUserNum:%{public}d," + "backUserNum: %{public}d", retFront, retBack, static_cast(foregroundUserVec.size()), + static_cast(backgroundUserVec.size())); + } else { + LOGE("Send back local frontuserids: %{public}s, backuserids: %{public}s", + GetIntegerList(foregroundUserVec).c_str(), GetIntegerList(backgroundUserVec).c_str()); + std::vector remoteUdids = { remoteUdid }; + SendUserIdsBroadCast(remoteUdids, foregroundUserVec, backgroundUserVec, false); + } + } + + std::vector foregroundUserIdInfos; + std::vector backgroundUserIdInfos; + GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos); + if (foregroundUserIdInfos.empty()) { + LOGE("receive remote foreground userid empty"); + } else { + LOGI("process foreground and background userids"); + // Notify received remote foreground userids to dsoftbus + std::vector foregroundUserIds; + for (const auto &u : foregroundUserIdInfos) { + foregroundUserIds.push_back(static_cast(u.userId)); + } + std::vector backgroundUserIds; + for (const auto &u : backgroundUserIdInfos) { + backgroundUserIds.push_back(static_cast(u.userId)); + } + if (softbusListener_ != nullptr) { + softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds); + } + + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid); + } + } +} + +void DeviceManagerService::ProcessSyncUserIds(const std::vector &foregroundUserIds, + const std::vector &backgroundUserIds, const std::string &remoteUdid) +{ + LOGI("process sync foregroundUserIds: %{public}s, backgroundUserIds: %{public}s, remote udid: %{public}s", + GetIntegerList(foregroundUserIds).c_str(), GetIntegerList(backgroundUserIds).c_str(), + GetAnonyString(remoteUdid).c_str()); + + if (softbusListener_ != nullptr) { + softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, foregroundUserIds); + } + + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid); + } +} + void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType) { if (!IsDMImplSoLoaded()) { @@ -1893,7 +1998,6 @@ void DeviceManagerService::SendServiceUnBindBroadCast(const std::vectorSendAclChangedBroadcast(broadCastMsg); } -#endif void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) { @@ -1903,11 +2007,7 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) } RelationShipChangeMsg relationShipMsg = ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); - std::string tokenIdStr = std::to_string(relationShipMsg.tokenId); - LOGI("EventType %{public}d, userId %{public}d, accountId %{public}s, tokenId %{public}s," - "peerUdid %{public}s, accountName %{public}s.", relationShipMsg.type, relationShipMsg.userId, - GetAnonyString(relationShipMsg.accountId).c_str(), GetAnonyString(tokenIdStr).c_str(), - GetAnonyString(relationShipMsg.peerUdid).c_str(), GetAnonyString(relationShipMsg.accountName).c_str()); + LOGI("Receive trust change msg: %{public}s", relationShipMsg.ToString().c_str()); if (!IsDMServiceImplReady()) { LOGE("Imp instance not init or init failed."); return; @@ -1924,6 +2024,13 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, static_cast(relationShipMsg.tokenId)); break; + case RelationShipChangeType::SYNC_USERID: + HandleUserIdsBroadCast(relationShipMsg.userIdInfos, + relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag); + break; + case RelationShipChangeType::DEL_USER: + dmServiceImpl_->HandleRemoteUserRemoved(relationShipMsg.userId, relationShipMsg.peerUdid); + break; default: LOGI("Dm have not this event type."); break; @@ -1931,11 +2038,104 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) return; } -void DeviceManagerService::ClearDiscoveryCache(const std::string &pkgName) +int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType) +{ + nlohmann::json msgJsonObj = nlohmann::json::parse(msg, nullptr, false); + if (msgJsonObj.is_discarded()) { + LOGE("msg prase error."); + return ERR_DM_FAILED; + } + if (!IsString(msgJsonObj, USERID_CHECKSUM_NETWORKID_KEY)) { + LOGE("msg not contain networkId."); + return ERR_DM_FAILED; + } + if (!IsUint32(msgJsonObj, USERID_CHECKSUM_DISCOVER_TYPE_KEY)) { + LOGE("msg not contain discoveryType."); + return ERR_DM_FAILED; + } + networkId = msgJsonObj[USERID_CHECKSUM_NETWORKID_KEY].get(); + discoveryType = msgJsonObj[USERID_CHECKSUM_DISCOVER_TYPE_KEY].get(); + return DM_OK; +} + +void DeviceManagerService::ProcessCheckSumByWifi(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds) +{ + // use connection to exchange foreground/background userid + LOGI("Try open softbus session to exchange foreground/background userid"); + std::vector foregroundUserIdsUInt; + for (auto const &u : foregroundUserIds) { + foregroundUserIdsUInt.push_back(static_cast(u)); + } + std::vector backroundUserIdsUInt; + for (auto const &u : backgroundUserIds) { + backroundUserIdsUInt.push_back(static_cast(u)); + } + DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backroundUserIdsUInt); +} + +void DeviceManagerService::ProcessCheckSumByBT(std::string networkId, std::vector foregroundUserIds, + std::vector backgroundUserIds) { - LOGI("PkgName %{public}s.", pkgName.c_str()); + LOGI("Try send brodcast to exchange foreground userid"); + std::string udid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(networkId.c_str(), udid); + if (udid.empty()) { + LOGE("Can not get udid for networkid: %{public}s", GetAnonyString(networkId).c_str()); + return; + } + + std::vector peerUdids = { udid }; + if (!foregroundUserIds.empty()) { + LOGI("Send local foreground and background userids"); + SendUserIdsBroadCast(peerUdids, foregroundUserIds, backgroundUserIds, true); + } else { + LOGE("local foreground userids empty"); + } +} + +void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg) +{ + if (msg.empty()) { + LOGE("Msg is empty."); + return; + } + LOGI("handle user trust change, msg: %{public}s", GetAnonyString(msg).c_str()); + std::string remoteNetworkId = ""; + uint32_t discoveryType = 0; + int32_t ret = ParseCheckSumMsg(msg, remoteNetworkId, discoveryType); + if (ret != DM_OK) { + LOGE("Parse checksum msg error"); + return; + } + + std::vector foregroundUserIds; + ret = MultipleUserConnector::GetForegroundUserIds(foregroundUserIds); + if (ret != DM_OK || foregroundUserIds.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + return; + } + + std::vector backgroundUserIds; + ret = MultipleUserConnector::GetBackgroundUserIds(backgroundUserIds); + if (ret != DM_OK || backgroundUserIds.empty()) { + LOGI("Can not get background userids, ret: %{public}d, background userid num: %{public}d", + ret, static_cast(backgroundUserIds.size())); + } + + if ((discoveryType & USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK) != 0x0) { + ProcessCheckSumByWifi(remoteNetworkId, foregroundUserIds, backgroundUserIds); + } else { + ProcessCheckSumByBT(remoteNetworkId, foregroundUserIds, backgroundUserIds); + } +} +#endif + +void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo) +{ + LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); CHECK_NULL_VOID(discoveryMgr_); - discoveryMgr_->ClearDiscoveryCache(pkgName); + discoveryMgr_->ClearDiscoveryCache(processInfo.pkgName); } void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo) @@ -2024,5 +2224,12 @@ int32_t DeviceManagerService::SetLocalDeviceName(const std::string &localDeviceN return DM_OK; } +void DeviceManagerService::RemoveNotifyRecord(const ProcessInfo &processInfo) +{ + LOGI("start"); + CHECK_NULL_VOID(listener_); + listener_->OnProcessRemove(processInfo); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 84d08e8c2..f6cf0be99 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include + #include "device_manager_service_listener.h" #include "app_manager.h" @@ -39,17 +41,19 @@ #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "datetime_ex.h" #include "kv_adapter_manager.h" +#include "multiple_user_connector.h" #endif #include "parameter.h" #include "permission_manager.h" namespace OHOS { namespace DistributedHardware { -std::mutex DeviceManagerServiceListener::alreadyOnlinePkgNameLock_; -std::unordered_map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::mutex DeviceManagerServiceListener::alreadyNotifyPkgNameLock_; +std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { + (void)pkgName; if (memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != DM_OK) { LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed."); return; @@ -77,21 +81,22 @@ void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std: } void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptr pReq, - const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo) { LOGD("DeviceManagerServiceListener::SetDeviceInfo"); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); + pReq->SetProcessInfo(processInfo); pReq->SetDeviceState(state); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; - if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) { pReq->SetDeviceInfo(deviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); return; } DmDeviceInfo dmDeviceInfo = deviceInfo; - ConvertUdidHashToAnoyAndSave(pkgName, dmDeviceInfo); + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); DmDeviceBasicInfo dmDeviceBasicInfo = deviceBasicInfo; if (memset_s(dmDeviceBasicInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); @@ -110,160 +115,109 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceBasicInfo(deviceBasicInfo); } -std::string DeviceManagerServiceListener::ComposeOnlineKey(const std::string &pkgName, const std::string &devId) -{ - return pkgName + "_" + devId; -} - -void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, - const DmDeviceBasicInfo &deviceBasicInfo) +void DeviceManagerServiceListener::ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); - if (state == DEVICE_STATE_OFFLINE) { - RemoveOnlinePkgName(info); - for (const auto &it : PkgNameVec) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : PkgNameVec) { - std::string notifyKey = ComposeOnlineKey(it, std::string(info.deviceId)); - DmDeviceState notifyState = state; - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - notifyState = DmDeviceState::DEVICE_INFO_CHANGED; - } else { - alreadyOnlinePkgName_[notifyKey] = info; - } - } - SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - for (const auto &it : PkgNameVec) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } + std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId); + switch (static_cast(state)) { + case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): + ProcessDeviceOnline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_STATE_OFFLINE): + ProcessDeviceOffline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_INFO_READY): + case static_cast(DmDeviceState::DEVICE_INFO_CHANGED): + ProcessDeviceInfoChange(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + default: + break; } } -void DeviceManagerServiceListener::ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, +void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); - if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : notifyPkgnames) { - std::string notifyKey = it + "_" + info.deviceId; - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - continue; - } - alreadyOnlinePkgName_[notifyKey] = info; - } - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_STATE_OFFLINE) { - if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { - RemoveOnlinePkgName(info); - for (const auto &it : notifyPkgnames) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } else { - std::string notifyKey = pkgName + "_" + info.deviceId; - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - alreadyOnlinePkgName_.erase(notifyKey); - } - } - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + std::vector processInfoVec = GetWhiteListSAProcessInfo(); + ProcessInfo bindProcessInfo = DealBindProcessInfo(processInfo); + processInfoVec.push_back(bindProcessInfo); + switch (static_cast(state)) { + case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): + ProcessAppOnline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_STATE_OFFLINE): + ProcessAppOffline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_INFO_READY): + case static_cast(DmDeviceState::DEVICE_INFO_CHANGED): + ProcessDeviceInfoChange(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + default: + break; } } -void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, +void DeviceManagerServiceListener::OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info) { LOGI("OnDeviceStateChange, state = %{public}d", state); DmDeviceBasicInfo deviceBasicInfo; - ConvertDeviceInfoToDeviceBasicInfo(pkgName, info, deviceBasicInfo); - if (pkgName == std::string(DM_PKG_NAME)) { - ProcessDeviceStateChange(state, info, deviceBasicInfo); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, info, deviceBasicInfo); + if (processInfo.pkgName == std::string(DM_PKG_NAME)) { + ProcessDeviceStateChange(processInfo, state, info, deviceBasicInfo); } else { - ProcessAppStateChange(pkgName, state, info, deviceBasicInfo); + ProcessAppStateChange(processInfo, state, info, deviceBasicInfo); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) KVAdapterManager::GetInstance().DeleteAgedEntry(); #endif } -void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, +void DeviceManagerServiceListener::OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); DmDeviceInfo deviceInfo = info; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ConvertUdidHashToAnoyAndSave(pkgName, deviceInfo); + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, deviceInfo); #endif DmDeviceBasicInfo devBasicInfo; - ConvertDeviceInfoToDeviceBasicInfo(pkgName, deviceInfo, devBasicInfo); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, deviceInfo, devBasicInfo); pReq->SetDeviceBasicInfo(devBasicInfo); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId(subscribeId); pReq->SetDeviceInfo(deviceInfo); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } -void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, - DmDeviceBasicInfo &info) -{ - (void)pkgName; - (void)subscribeId; - (void)info; -} - -void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, +void DeviceManagerServiceListener::OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) { LOGI("DeviceManagerServiceListener::OnDiscoveryFailed"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId(subscribeId); pReq->SetResult(failedReason); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +void DeviceManagerServiceListener::OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) { LOGI("DeviceManagerServiceListener::OnDiscoverySuccess"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId((uint16_t)subscribeId); pReq->SetResult(DM_OK); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } @@ -279,7 +233,7 @@ void DeviceManagerServiceListener::OnPublishResult(const std::string &pkgName, i ipcServerListener_.SendRequest(SERVER_PUBLISH_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, +void DeviceManagerServiceListener::OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) { std::shared_ptr pReq = std::make_shared(); @@ -290,42 +244,45 @@ void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, cons pReq->SetDeviceId(deviceId); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; - if (ConvertUdidHashToAnoyDeviceId(pkgName, deviceId, deviceIdTemp) == DM_OK) { + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, deviceId, deviceIdTemp) == DM_OK) { pReq->SetDeviceId(deviceIdTemp); } #endif - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetToken(token); pReq->SetStatus(status); pReq->SetReason(reason); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnUiCall(std::string &pkgName, std::string ¶mJson) +void DeviceManagerServiceListener::OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) { LOGI("OnUiCall in"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetJsonParam(paramJson); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_FA_NOTIFY, pReq, pRsp); } -void DeviceManagerServiceListener::OnCredentialResult(const std::string &pkgName, int32_t action, +void DeviceManagerServiceListener::OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) { - LOGI("call OnCredentialResult for %{public}s, action %{public}d", pkgName.c_str(), action); + LOGI("call OnCredentialResult for %{public}s, action %{public}d", processInfo.pkgName.c_str(), action); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetCredentialAction(action); pReq->SetCredentialResult(resultInfo); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREDENTIAL_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) { std::shared_ptr pReq = std::make_shared(); @@ -337,20 +294,21 @@ void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, cons #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; DmKVValue kvValue; - if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { returnTargetId.deviceId = deviceIdTemp; } #endif - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetStatus(status); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(BIND_TARGET_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) { std::shared_ptr pReq = std::make_shared(); @@ -359,79 +317,85 @@ void DeviceManagerServiceListener::OnUnbindResult(const std::string &pkgName, co #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; DmKVValue kvValue; - if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { returnTargetId.deviceId = deviceIdTemp; } #endif - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(UNBIND_TARGET_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, +void DeviceManagerServiceListener::OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) { - LOGI("DeviceManagerServiceListener::OnPinHolderCreate : %{public}s", pkgName.c_str()); + LOGI("DeviceManagerServiceListener::OnPinHolderCreate : %{public}s", processInfo.pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetDeviceId(deviceId); pReq->SetPinType(pinType); pReq->SetPayload(payload); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREATE_PIN_HOLDER, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, +void DeviceManagerServiceListener::OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) { - LOGI("DeviceManagerServiceListener::OnPinHolderDestroy : %{public}s", pkgName.c_str()); + LOGI("DeviceManagerServiceListener::OnPinHolderDestroy : %{public}s", processInfo.pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPinType(pinType); pReq->SetPayload(payload); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DESTROY_PIN_HOLDER, pReq, pRsp); } -void DeviceManagerServiceListener::OnCreateResult(const std::string &pkgName, int32_t result) +void DeviceManagerServiceListener::OnCreateResult(const ProcessInfo &processInfo, int32_t result) { LOGI("DeviceManagerServiceListener::OnCreateResult : %{public}d", result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetResult(result); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREATE_PIN_HOLDER_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnDestroyResult(const std::string &pkgName, int32_t result) +void DeviceManagerServiceListener::OnDestroyResult(const ProcessInfo &processInfo, int32_t result) { LOGI("DeviceManagerServiceListener::OnDestroyResult : %{public}d", result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetResult(result); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DESTROY_PIN_HOLDER_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, +void DeviceManagerServiceListener::OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) { LOGI("OnPinHolderEvent pkgName: %{public}s, event: %{public}d, result: %{public}d", - pkgName.c_str(), event, result); + processInfo.pkgName.c_str(), event, result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPinHolderEvent(event); pReq->SetResult(result); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_ON_PIN_HOLDER_EVENT, pReq, pRsp); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -485,55 +449,70 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, GetAnonyString(uuid).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetFirstForegroundUserId(); +#endif + std::vector processInfoVec = GetNotifyProcessInfoByUserId(userId); + for (const auto &item : processInfoVec) { + pReq->SetPkgName(item.pkgName); pReq->SetUdid(udid); pReq->SetUuid(uuid); pReq->SetAuthForm(authForm); + pReq->SetProcessInfo(item); ipcServerListener_.SendRequest(REMOTE_DEVICE_TRUST_CHANGE, pReq, pRsp); } } void DeviceManagerServiceListener::SetDeviceScreenInfo(std::shared_ptr pReq, - const std::string &pkgName, const DmDeviceInfo &deviceInfo) + const ProcessInfo &processInfo, const DmDeviceInfo &deviceInfo) { LOGI("In"); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); + pReq->SetProcessInfo(processInfo); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; - if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) { pReq->SetDeviceInfo(deviceInfo); return; } DmDeviceInfo dmDeviceInfo = deviceInfo; - ConvertUdidHashToAnoyAndSave(pkgName, dmDeviceInfo); + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); pReq->SetDeviceInfo(dmDeviceInfo); return; #endif pReq->SetDeviceInfo(deviceInfo); } -void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) +void DeviceManagerServiceListener::OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) { - LOGI("In, pkgName = %{public}s", pkgName.c_str()); - if (pkgName == std::string(DM_PKG_NAME)) { + LOGI("In, pkgName = %{public}s", processInfo.pkgName.c_str()); + if (processInfo.pkgName == std::string(DM_PKG_NAME)) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); - for (const auto &it : PkgNameVec) { - SetDeviceScreenInfo(pReq, it, devInfo); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetFirstForegroundUserId(); +#endif + std::vector processInfoVec = + GetNotifyProcessInfoByUserId(userId); + for (const auto &item : processInfoVec) { + SetDeviceScreenInfo(pReq, item, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } } else { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); - for (const auto &it : notifyPkgnames) { - SetDeviceScreenInfo(pReq, it, devInfo); + std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); + for (const auto &item : notifyPkgnames) { + ProcessInfo processInfo; + processInfo.pkgName = item; + processInfo.userId = 0; + SetDeviceScreenInfo(pReq, processInfo, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } + SetDeviceScreenInfo(pReq, processInfo, devInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } } @@ -541,7 +520,7 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) { LOGI("udidHash: %{public}s.", GetAnonyString(info.deviceId).c_str()); { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); for (auto item = alreadyOnlinePkgName_.begin(); item != alreadyOnlinePkgName_.end();) { if (std::string(item->second.deviceId) == std::string(info.deviceId)) { item = alreadyOnlinePkgName_.erase(item); @@ -552,33 +531,33 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) } } -void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkgName, +void DeviceManagerServiceListener::OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) { - LOGI("In, pkgName = %{public}s", pkgName.c_str()); - std::shared_ptr pReq = - std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - pReq->SetDeviceList(deviceList); - pReq->SetDeviceTypeId(deviceTypeId); - pReq->SetErrCode(errcode); - if (pkgName == std::string(DM_PKG_NAME)) { - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); - ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); - } - } else { - pReq->SetPkgName(pkgName); + LOGI("In, pkgName = %{public}s", processInfo.pkgName.c_str()); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetFirstForegroundUserId(); +#endif + std::vector processInfoVec = + GetNotifyProcessInfoByUserId(userId); + for (const auto &item : processInfoVec) { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + pReq->SetDeviceList(deviceList); + pReq->SetDeviceTypeId(deviceTypeId); + pReq->SetErrCode(errcode); + pReq->SetPkgName(item.pkgName); + pReq->SetProcessInfo(item); ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } } void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { - if (it->first.find(pkgName) == 0) { + if (it->first.processPkgName == pkgName) { it = alreadyOnlinePkgName_.erase(it); } else { ++it; @@ -586,7 +565,7 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) } } -void DeviceManagerServiceListener::OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) { std::shared_ptr pReq = std::make_shared(); @@ -598,17 +577,226 @@ void DeviceManagerServiceListener::OnSinkBindResult(const std::string &pkgName, #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; DmKVValue kvValue; - if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { returnTargetId.deviceId = deviceIdTemp; } #endif - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); + std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); + ProcessInfo processInfoTemp; + for (auto item : processInfos) { + if (item.pkgName == processInfo.pkgName) { + processInfoTemp = item; + } + } + if (processInfoTemp.pkgName.empty()) { + LOGI("not register listener"); + return; + } + pReq->SetProcessInfo(processInfoTemp); pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetStatus(status); pReq->SetContent(content); ipcServerListener_.SendRequest(SINK_BIND_TARGET_RESULT, pReq, pRsp); } + +std::vector DeviceManagerServiceListener::GetWhiteListSAProcessInfo() +{ + std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); + std::vector processInfos; + for (const auto &it : notifyPkgnames) { + ProcessInfo processInfo; + processInfo.pkgName = it; + processInfo.userId = 0; + processInfos.push_back(processInfo); + } + return processInfos; +} + +std::vector DeviceManagerServiceListener::GetNotifyProcessInfoByUserId(int32_t userId) +{ + std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); + std::set systemSA = ipcServerListener_.GetSystemSA(); + std::vector processInfosTemp; + for (auto item : processInfos) { + if (systemSA.find(item.pkgName) != systemSA.end()) { + item.userId = 0; + processInfosTemp.push_back(item); + } else if (item.userId == userId) { + processInfosTemp.push_back(item); + } + } + return processInfosTemp; +} + +ProcessInfo DeviceManagerServiceListener::DealBindProcessInfo(const ProcessInfo &processInfo) +{ + std::set systemSA = ipcServerListener_.GetSystemSA(); + if (systemSA.find(processInfo.pkgName) == systemSA.end()) { + return processInfo; + } + ProcessInfo bindProcessInfo = processInfo; + bindProcessInfo.userId = 0; + return bindProcessInfo; +} + +void DeviceManagerServiceListener::ProcessDeviceOnline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + DmNotifyKey notifyKey; + notifyKey.processPkgName = it.pkgName; + notifyKey.processUserId = it.userId; + notifyKey.notifyUserId = processInfo.userId; + notifyKey.udid = info.deviceId; + DmDeviceState notifyState = state; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + notifyState = DmDeviceState::DEVICE_INFO_CHANGED; + } else { + alreadyOnlinePkgName_[notifyKey] = info; + } + } + SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessDeviceOffline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + RemoveNotExistProcess(procInfoVec); + if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { + RemoveOnlinePkgName(info); + } + for (const auto &it : procInfoVec) { + DmNotifyKey notifyKey; + notifyKey.processPkgName = it.pkgName; + notifyKey.processUserId = it.userId; + notifyKey.notifyUserId = processInfo.userId; + notifyKey.udid = info.deviceId; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyKey); + } + } + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessDeviceInfoChange(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessAppOnline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + DmNotifyKey notifyKey; + notifyKey.processPkgName = it.pkgName; + notifyKey.processUserId = it.userId; + notifyKey.notifyUserId = processInfo.userId; + notifyKey.udid = info.deviceId; + DmDeviceState notifyState = state; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + notifyState = DmDeviceState::DEVICE_INFO_CHANGED; + } else { + alreadyOnlinePkgName_[notifyKey] = info; + } + } + SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessAppOffline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { + RemoveOnlinePkgName(info); + for (const auto &it : procInfoVec) { + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } + } else { + DmNotifyKey notifyKey; + notifyKey.processPkgName = processInfo.pkgName; + notifyKey.processUserId = processInfo.userId; + notifyKey.notifyUserId = processInfo.userId; + notifyKey.udid = info.deviceId; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyKey); + } + } + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::RemoveNotExistProcess(const std::vector &procInfoVec) +{ + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { + ProcessInfo processInfo; + processInfo.pkgName = it->first.processPkgName; + processInfo.userId = it->first.processUserId; + if (find(procInfoVec.begin(), procInfoVec.end(), processInfo) != procInfoVec.end()) { + it = alreadyOnlinePkgName_.erase(it); + } else { + ++it; + } + } +} + +void DeviceManagerServiceListener::OnProcessRemove(const ProcessInfo &processInfo) +{ + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { + if (processInfo.pkgName == it->first.processPkgName && processInfo.userId == it->first.processUserId) { + it = alreadyOnlinePkgName_.erase(it); + } else { + ++it; + } + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 285337a8f..14f3d6b19 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -23,6 +23,9 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -62,6 +65,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = AddMultiUserIdentify(pkgName); DmSubscribeInfo dmSubInfo; dmSubInfo.subscribeId = DM_INVALID_FLAG_ID; dmSubInfo.mode = DmDiscoverMode::DM_DISCOVER_MODE_PASSIVE; @@ -82,7 +86,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, dmSubInfo.subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); { std::lock_guard autoLock(subIdMapLocks_); - pkgName2SubIdMap_[pkgName] = dmSubInfo.subscribeId; + pkgName2SubIdMap_[pkgNameTemp] = dmSubInfo.subscribeId; } } if (discoverParam.find(PARAM_KEY_DISC_CAPABILITY) != discoverParam.end()) { @@ -95,7 +99,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGI("EnableDiscoveryListener capability = %{public}s,", std::string(dmSubInfo.capability).c_str()); { std::lock_guard capLock(capabilityMapLocks_); - capabilityMap_[pkgName] = std::string(dmSubInfo.capability); + capabilityMap_[pkgNameTemp] = std::string(dmSubInfo.capability); } int32_t ret = softbusListener_->RefreshSoftbusLNN(DM_PKG_NAME, dmSubInfo, LNN_DISC_CAPABILITY); @@ -103,7 +107,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGE("EnableDiscoveryListener failed, softbus refresh lnn ret: %{public}d.", ret); return ret; } - softbusListener_->RegisterSoftbusLnnOpsCbk(pkgName, shared_from_this()); + softbusListener_->RegisterSoftbusLnnOpsCbk(pkgNameTemp, shared_from_this()); return DM_OK; } @@ -115,7 +119,7 @@ int32_t DiscoveryManager::DisableDiscoveryListener(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - + std::string pkgNameTemp = RemoveMultiUserIdentify(pkgName); if (extraParam.find(PARAM_KEY_META_TYPE) != extraParam.end()) { LOGI("DisableDiscoveryListener, input MetaType = %{public}s", (extraParam.find(PARAM_KEY_META_TYPE)->second).c_str()); @@ -125,16 +129,16 @@ int32_t DiscoveryManager::DisableDiscoveryListener(const std::string &pkgName, subscribeId = std::atoi((extraParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); { std::lock_guard autoLock(subIdMapLocks_); - pkgName2SubIdMap_.erase(pkgName); + pkgName2SubIdMap_.erase(pkgNameTemp); } } { std::lock_guard capLock(capabilityMapLocks_); - if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { - capabilityMap_.erase(pkgName); + if (capabilityMap_.find(pkgNameTemp) != capabilityMap_.end()) { + capabilityMap_.erase(pkgNameTemp); } } - softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); return softbusListener_->StopRefreshSoftbusLNN(subscribeId); } @@ -146,9 +150,10 @@ int32_t DiscoveryManager::StartDiscovering(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = AddMultiUserIdentify(pkgName); DmSubscribeInfo dmSubInfo; ConfigDiscParam(discoverParam, &dmSubInfo); - if (HandleDiscoveryQueue(pkgName, dmSubInfo.subscribeId, filterOptions) != DM_OK) { + if (HandleDiscoveryQueue(pkgNameTemp, dmSubInfo.subscribeId, filterOptions) != DM_OK) { return ERR_DM_DISCOVERY_REPEATED; } @@ -158,17 +163,17 @@ int32_t DiscoveryManager::StartDiscovering(const std::string &pkgName, isStandardMetaNode = (metaType == MetaNodeType::PROXY_TRANSMISION); } - softbusListener_->RegisterSoftbusLnnOpsCbk(pkgName, shared_from_this()); - StartDiscoveryTimer(pkgName); + softbusListener_->RegisterSoftbusLnnOpsCbk(pkgNameTemp, shared_from_this()); + StartDiscoveryTimer(pkgNameTemp); auto it = filterOptions.find(PARAM_KEY_FILTER_OPTIONS); nlohmann::json jsonObject = nlohmann::json::parse(it->second, nullptr, false); if (!jsonObject.is_discarded() && jsonObject.contains(TYPE_MINE)) { - return StartDiscovering4MineLibary(pkgName, dmSubInfo, it->second); + return StartDiscovering4MineLibary(pkgNameTemp, dmSubInfo, it->second); } - int32_t ret = isStandardMetaNode ? StartDiscoveringNoMetaType(pkgName, dmSubInfo, discoverParam) : - StartDiscovering4MetaType(pkgName, dmSubInfo, discoverParam); + int32_t ret = isStandardMetaNode ? StartDiscoveringNoMetaType(pkgNameTemp, dmSubInfo, discoverParam) : + StartDiscovering4MetaType(pkgNameTemp, dmSubInfo, discoverParam); if (ret != DM_OK) { LOGE("StartDiscovering for meta node process failed, ret = %{public}d", ret); return ret; @@ -307,24 +312,25 @@ int32_t DiscoveryManager::StopDiscovering(const std::string &pkgName, uint16_t s LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = RemoveMultiUserIdentify(pkgName); { std::lock_guard autoLock(locks_); - if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { - pkgNameSet_.erase(pkgName); + if (pkgNameSet_.find(pkgNameTemp) != pkgNameSet_.end()) { + pkgNameSet_.erase(pkgNameTemp); } - if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { - discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(pkgName); + if (discoveryContextMap_.find(pkgNameTemp) != discoveryContextMap_.end()) { + discoveryContextMap_.erase(pkgNameTemp); + timer_->DeleteTimer(pkgNameTemp); } } { std::lock_guard capLock(capabilityMapLocks_); - if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { - capabilityMap_.erase(pkgName); + if (capabilityMap_.find(pkgNameTemp) != capabilityMap_.end()) { + capabilityMap_.erase(pkgNameTemp); } } - softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); #if (defined(MINE_HARMONY)) return mineSoftbusListener_->StopRefreshSoftbusLNN(subscribeId); #else @@ -334,12 +340,16 @@ int32_t DiscoveryManager::StopDiscovering(const std::string &pkgName, uint16_t s void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info, bool isOnline) { + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); DeviceFilterPara filterPara; filterPara.isOnline = false; filterPara.range = info.range; filterPara.deviceType = info.deviceTypeId; std::string deviceIdHash = static_cast(info.deviceId); - if (isOnline && GetDeviceAclParam(pkgName, deviceIdHash, filterPara.isOnline, filterPara.authForm) != DM_OK) { + if (isOnline && GetDeviceAclParam(callerPkgName, userId, deviceIdHash, filterPara.isOnline, + filterPara.authForm) != DM_OK) { LOGE("The found device get online param failed."); } nlohmann::json jsonObject = nlohmann::json::parse(info.extraData, nullptr, false); @@ -358,6 +368,12 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceI void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara) { + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = callerPkgName; bool isIndiscoveryContextMap = false; DiscoveryContext discoveryContext; { @@ -382,7 +398,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t subscribeId = pkgName2SubIdMap_[pkgName]; } LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); - listener_->OnDeviceFound(pkgName, subscribeId, info); + listener_->OnDeviceFound(processInfo, subscribeId, info); return; } DiscoveryFilter filter; @@ -395,7 +411,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t } } LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); + listener_->OnDeviceFound(processInfo, discoveryContext.subscribeId, info); } } @@ -413,6 +429,12 @@ bool DiscoveryManager::CompareCapability(uint32_t capabilityType, const std::str void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t subscribeId, int32_t result) { LOGI("DiscoveryManager::OnDiscoveringResult, subscribeId = %{public}d, result = %{public}d.", subscribeId, result); + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = callerPkgName; if (pkgName.empty() || (listener_ == nullptr)) { LOGE("DiscoveryManager::OnDiscoveringResult failed, IDeviceManagerServiceListener is null."); return; @@ -420,7 +442,7 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s if (result == 0) { std::lock_guard autoLock(locks_); discoveryContextMap_[pkgName].subscribeId = (uint32_t)subscribeId; - listener_->OnDiscoverySuccess(pkgName, subscribeId); + listener_->OnDiscoverySuccess(processInfo, subscribeId); return; } { @@ -439,7 +461,7 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s capabilityMap_.erase(pkgName); } } - listener_->OnDiscoveryFailed(pkgName, (uint32_t)subscribeId, result); + listener_->OnDiscoveryFailed(processInfo, (uint32_t)subscribeId, result); softbusListener_->StopRefreshSoftbusLNN(subscribeId); } @@ -513,7 +535,7 @@ void DiscoveryManager::UpdateInfoFreq( } } -int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, std::string deviceId, +int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, int32_t &authForm) { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -524,6 +546,7 @@ int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, std::str discoveryInfo.pkgname = pkgName; discoveryInfo.localDeviceId = requestDeviceId; discoveryInfo.remoteDeviceIdHash = deviceId; + discoveryInfo.userId = userId; if (DiscoveryManager::IsCommonDependencyReady() && DiscoveryManager::GetCommonDependencyObj() != nullptr) { if (DiscoveryManager::GetCommonDependencyObj()->GetDeviceAclParam(discoveryInfo, isOnline, authForm) != DM_OK) { LOGE("GetDeviceAclParam failed."); @@ -619,5 +642,60 @@ void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) CHECK_NULL_VOID(timer_); timer_->DeleteTimer(pkgName); } + +std::string DiscoveryManager::AddMultiUserIdentify(const std::string &pkgName) +{ + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif + if (userId == -1) { + LOGE("Get caller userId failed."); + return pkgName; + } + MultiUserDiscovery multiUserDisc; + multiUserDisc.pkgName = pkgName; + multiUserDisc.userId = userId; + std::string pkgNameTemp = ComposeStr(pkgName, userId); + { + std::lock_guard autoLock(multiUserDiscLocks_); + multiUserDiscMap_[pkgNameTemp] = multiUserDisc; + } + return pkgNameTemp; +} + +std::string DiscoveryManager::RemoveMultiUserIdentify(const std::string &pkgName) +{ + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif + if (userId == -1) { + LOGE("Get caller userId failed."); + return pkgName; + } + std::string pkgNameTemp = ComposeStr(pkgName, userId); + { + std::lock_guard autoLock(multiUserDiscLocks_); + if (multiUserDiscMap_.find(pkgNameTemp) != multiUserDiscMap_.end()) { + multiUserDiscMap_.erase(pkgNameTemp); + } + } + return pkgNameTemp; +} + +void DiscoveryManager::GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, + int32_t &userId) +{ + { + std::lock_guard autoLock(multiUserDiscLocks_); + if (multiUserDiscMap_.find(pkgName) != multiUserDiscMap_.end()) { + callerPkgName = GetCallerPkgName(multiUserDiscMap_[pkgName].pkgName); + userId = multiUserDiscMap_[pkgName].userId; + return; + } + } + LOGE("find failed."); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/lite/ipc_cmd_parser.cpp b/services/service/src/ipc/lite/ipc_cmd_parser.cpp index 9154339c2..e6f3bd310 100644 --- a/services/service/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/lite/ipc_cmd_parser.cpp @@ -159,27 +159,6 @@ ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) } } -ON_IPC_SERVER_CMD(START_DEVICE_DISCOVERY, IpcIo &req, IpcIo &reply) -{ - LOGI("StartDeviceDiscovery service listener."); - std::string pkgName = (const char *)ReadString(&req, nullptr); - std::string extra = (const char *)ReadString(&req, nullptr); - uint16_t subscribeId = 0; - ReadUint16(&req, &subscribeId); - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, extra); - WriteInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) -{ - LOGI("StopDeviceDiscovery service listener."); - std::string pkgName = (const char *)ReadString(&req, nullptr); - uint16_t subscribeId = 0; - ReadUint16(&req, &subscribeId); - int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - WriteInt32(&reply, ret); -} - ON_IPC_SERVER_CMD(REQUEST_CREDENTIAL, IpcIo &req, IpcIo &reply) { LOGI("request credential service listener."); diff --git a/services/service/src/ipc/lite/ipc_server_listener.cpp b/services/service/src/ipc/lite/ipc_server_listener.cpp index 954372559..912b538ae 100644 --- a/services/service/src/ipc/lite/ipc_server_listener.cpp +++ b/services/service/src/ipc/lite/ipc_server_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -66,40 +66,21 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr return DM_OK; } -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::vector IpcServerListener::GetAllProcessInfo() { + std::vector processInfoVec; const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); for (const auto &kv : listenerMap) { - SvcIdentity svc; - IpcIo io; - uint8_t data[MAX_DM_IPC_LEN] = {0}; - std::string pkgName = kv.first; - - req->SetPkgName(pkgName); - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) { - LOGE("SetRequest failed cmdCode:%{public}d", cmdCode); - continue; - } - CommonSvcId svcId = kv.second; - CommonSvcToIdentity(&svcId, &svc); - MessageOption option; - MessageOptionInit(&option); - option.flags = TF_OP_ASYNC; - if (::SendRequest(svc, cmdCode, &io, nullptr, option, nullptr) != DM_OK) { - LOGI("SendRequest failed cmdCode:%{public}d", cmdCode); - } + ProcessInfo processInfo; + processInfo.pkgName = kv.first; + processInfoVec.push_back(processInfo); } - return DM_OK; + return processInfoVec; } -std::vector IpcServerListener::GetAllPkgName() +std::set IpcServerListener::GetSystemSA() { - std::vector pkgNameList; - const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); - for (const auto &kv : listenerMap) { - pkgNameList.push_back(kv.first); - } - return pkgNameList; + return {}; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 2bb2369b3..dd83b850d 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -43,9 +43,12 @@ #include "ipc_notify_pin_holder_event_req.h" #include "ipc_server_client_proxy.h" #include "ipc_server_stub.h" - +#include "multiple_user_connector.h" #include "nlohmann/json.hpp" - +#include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { const unsigned int XCOLLIE_TIMEOUT_S = 5; @@ -419,8 +422,11 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); return ERR_DM_POINT_NULL; } + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); - int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, callback); + int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, callback); if (!reply.WriteInt32(result)) { LOGE("write result failed"); OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); @@ -433,39 +439,11 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); - int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string extra = data.ReadString(); - DmSubscribeInfo *subscribeInfo = - static_cast(const_cast(data.ReadRawData(sizeof(DmSubscribeInfo)))); - int32_t result = ERR_DM_POINT_NULL; - - if (subscribeInfo != nullptr) { - result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo, extra); - } - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_CMD(START_DEVICE_DISCOVERY, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string filterOption = data.ReadString(); - uint16_t subscribeId = data.ReadUint16(); - int32_t result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOption); + int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); if (!reply.WriteInt32(result)) { LOGE("write result failed"); return ERR_DM_IPC_WRITE_FAILED; @@ -473,17 +451,6 @@ ON_IPC_CMD(START_DEVICE_DISCOVERY, MessageParcel &data, MessageParcel &reply) return DM_OK; } -ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - uint16_t subscribeId = data.ReadUint16(); - int32_t result = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} ON_IPC_CMD(PUBLISH_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) { diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index a9dc4c9f4..9c9cec34a 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -31,36 +31,27 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr LOGE("IpcServerListener::SendRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - std::string pkgName = req->GetPkgName(); - if (pkgName.empty()) { + ProcessInfo processInfo = req->GetProcessInfo(); + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - sptr listener = IpcServerStub::GetInstance().GetDmListener(pkgName); + sptr listener = IpcServerStub::GetInstance().GetDmListener(processInfo); if (listener == nullptr) { - LOGI("cannot get listener for package:%{public}s.", pkgName.c_str()); + LOGI("cannot get listener for package:%{public}s.", processInfo.pkgName.c_str()); return ERR_DM_POINT_NULL; } return listener->SendCmd(cmdCode, req, rsp); } -std::vector IpcServerListener::GetAllPkgName() +std::vector IpcServerListener::GetAllProcessInfo() { - return IpcServerStub::GetInstance().GetAllPkgName(); + return IpcServerStub::GetInstance().GetAllProcessInfo(); } -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::set IpcServerListener::GetSystemSA() { - if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { - LOGE("IpcServerListener::SendAll cmdCode param invalid!"); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - int32_t ret = IpcServerStub::GetInstance().SendALL(cmdCode, req, rsp); - if (ret != DM_OK) { - LOGE("IpcServerListener::SendAll failed!"); - return ret; - } - return DM_OK; + return IpcServerStub::GetInstance().GetSystemSA(); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index a831a2f7b..8c6fe970a 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -33,8 +33,10 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_service.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" #include "multiple_user_connector.h" +#include "permission_manager.h" namespace OHOS { namespace DistributedHardware { @@ -213,31 +215,30 @@ ServiceRunningState IpcServerStub::QueryServiceState() const return state_; } -int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr listener) +int32_t IpcServerStub::RegisterDeviceManagerListener(const ProcessInfo &processInfo, sptr listener) { - if (pkgName.empty() || listener == nullptr) { + if (processInfo.pkgName.empty() || listener == nullptr) { LOGE("RegisterDeviceManagerListener error: input parameter invalid."); return ERR_DM_POINT_NULL; } - LOGI("Register device manager listener for package name: %{public}s", pkgName.c_str()); + LOGI("Register device manager listener for package name: %{public}s", processInfo.pkgName.c_str()); std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(pkgName); + auto iter = dmListener_.find(processInfo); if (iter != dmListener_.end()) { LOGI("Listener already exists"); - auto recipientIter = appRecipient_.find(pkgName); + auto recipientIter = appRecipient_.find(processInfo); if (recipientIter == appRecipient_.end()) { LOGI("AppRecipient not exists"); - dmListener_.erase(pkgName); + dmListener_.erase(processInfo); } else { auto listener = iter->second; auto appRecipient = recipientIter->second; listener->AsObject()->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(pkgName); - dmListener_.erase(pkgName); + appRecipient_.erase(processInfo); + dmListener_.erase(processInfo); } } - sptr appRecipient = sptr(new AppDeathRecipient()); if (!listener->AsObject()->AddDeathRecipient(appRecipient)) { LOGE("AddDeathRecipient Failed"); @@ -246,90 +247,77 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< LOGE("dmListener_ or appRecipient_ size exceed the limit!"); return ERR_DM_FAILED; } - dmListener_[pkgName] = listener; - appRecipient_[pkgName] = appRecipient; - LOGD("Register listener complete."); + dmListener_[processInfo] = listener; + appRecipient_[processInfo] = appRecipient; + AddSystemSA(processInfo.pkgName); + LOGI("Register listener complete."); return DM_OK; } -int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) +int32_t IpcServerStub::UnRegisterDeviceManagerListener(const ProcessInfo &processInfo) { - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("IpcServerStub::UnRegisterDeviceManagerListener In, pkgName: %{public}s", pkgName.c_str()); + LOGI("IpcServerStub::UnRegisterDeviceManagerListener In, pkgName: %{public}s", processInfo.pkgName.c_str()); std::lock_guard autoLock(listenerLock_); - auto listenerIter = dmListener_.find(pkgName); + auto listenerIter = dmListener_.find(processInfo); if (listenerIter == dmListener_.end()) { LOGI("Listener not exists"); return DM_OK; } - auto recipientIter = appRecipient_.find(pkgName); + auto recipientIter = appRecipient_.find(processInfo); if (recipientIter == appRecipient_.end()) { LOGI("AppRecipient not exists"); - dmListener_.erase(pkgName); + dmListener_.erase(processInfo); return DM_OK; } auto listener = listenerIter->second; auto appRecipient = recipientIter->second; listener->AsObject()->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(pkgName); - dmListener_.erase(pkgName); + appRecipient_.erase(processInfo); + dmListener_.erase(processInfo); + RemoveSystemSA(processInfo.pkgName); + DeviceManagerService::GetInstance().RemoveNotifyRecord(processInfo); return DM_OK; } -int32_t IpcServerStub::SendALL(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::vector IpcServerStub::GetAllProcessInfo() { + std::vector processInfoVec; std::lock_guard autoLock(listenerLock_); for (const auto &iter : dmListener_) { - auto pkgName = iter.first; - auto listener = iter.second; - req->SetPkgName(pkgName); - if (listener == nullptr) { - LOGE("IpcServerStub::SendALL, listener is nullptr, pkgName : %{public}s.", pkgName.c_str()); - continue; - } - listener->SendCmd(cmdCode, req, rsp); + processInfoVec.push_back(iter.first); } - return DM_OK; + return processInfoVec; } -std::vector IpcServerStub::GetAllPkgName() +const sptr IpcServerStub::GetDmListener(ProcessInfo processInfo) const { - std::vector PkgNameVec; - std::lock_guard autoLock(listenerLock_); - for (const auto &iter : dmListener_) { - PkgNameVec.push_back(iter.first); - } - return PkgNameVec; -} - -const sptr IpcServerStub::GetDmListener(std::string pkgName) const -{ - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return nullptr; } std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(pkgName); + auto iter = dmListener_.find(processInfo); if (iter == dmListener_.end()) { return nullptr; } return iter->second; } -const std::string IpcServerStub::GetDmListenerPkgName(const wptr &remote) const +const ProcessInfo IpcServerStub::GetDmListenerPkgName(const wptr &remote) const { - std::string pkgName = ""; + ProcessInfo processInfo; std::lock_guard autoLock(listenerLock_); for (const auto &iter : dmListener_) { if ((iter.second)->AsObject() == remote.promote()) { - pkgName = iter.first; + processInfo = iter.first; break; } } - return pkgName; + return processInfo; } int32_t IpcServerStub::Dump(int32_t fd, const std::vector& args) @@ -356,10 +344,34 @@ int32_t IpcServerStub::Dump(int32_t fd, const std::vector& args) void AppDeathRecipient::OnRemoteDied(const wptr &remote) { - std::string pkgName = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); - LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", pkgName.c_str()); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); - DeviceManagerService::GetInstance().ClearDiscoveryCache(pkgName); + ProcessInfo processInfo = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); + LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", processInfo.pkgName.c_str()); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); +} + +void IpcServerStub::AddSystemSA(const std::string &pkgName) +{ + if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) { + systemSA_.insert(pkgName); + } +} + +void IpcServerStub::RemoveSystemSA(const std::string &pkgName) +{ + if (PermissionManager::GetInstance().CheckSystemSA(pkgName) || systemSA_.find(pkgName) != systemSA_.end()) { + systemSA_.erase(pkgName); + } +} + +std::set IpcServerStub::GetSystemSA() +{ + std::lock_guard autoLock(listenerLock_); + std::set systemSA; + for (const auto &item : systemSA_) { + systemSA.insert(item); + } + return systemSA; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/permission/lite/permission_manager.cpp b/services/service/src/permission/lite/permission_manager.cpp index 407455c0a..3b479ef97 100644 --- a/services/service/src/permission/lite/permission_manager.cpp +++ b/services/service/src/permission/lite/permission_manager.cpp @@ -54,17 +54,23 @@ bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &proc return true; } -bool PermissionManager::CheckSystemSA(const std::string &pkgName) +bool PermissionManager::CheckWhiteListSystemSA(const std::string &pkgName) { (void)pkgName; return true; } -std::unordered_set PermissionManager::GetSystemSA() +std::unordered_set PermissionManager::GetWhiteListSystemSA() { return std::unordered_set{}; } +bool PermissionManager::CheckSystemSA(const std::string &pkgName) +{ + (void)pkgName; + return true; +} + bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) { (void)processName; diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index f49d5fcf7..59a1fe237 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -197,7 +197,7 @@ bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &proc return false; } -bool PermissionManager::CheckSystemSA(const std::string &pkgName) +bool PermissionManager::CheckWhiteListSystemSA(const std::string &pkgName) { for (uint16_t index = 0; index < SYSTEM_SA_WHITE_LIST_NUM; ++index) { std::string tmp(systemSaWhiteList[index]); @@ -208,7 +208,7 @@ bool PermissionManager::CheckSystemSA(const std::string &pkgName) return false; } -std::unordered_set PermissionManager::GetSystemSA() +std::unordered_set PermissionManager::GetWhiteListSystemSA() { std::unordered_set systemSA; for (uint16_t index = 0; index < SYSTEM_SA_WHITE_LIST_NUM; ++index) { @@ -218,6 +218,20 @@ std::unordered_set PermissionManager::GetSystemSA() return systemSA; } +bool PermissionManager::CheckSystemSA(const std::string &pkgName) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("CheckMonitorPermission GetCallingTokenID error."); + return false; + } + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + return true; + } + return false; +} + bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) { if (processName.empty()) { diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index ef30a517a..cb90b50a5 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -20,6 +20,9 @@ #include "dm_log.h" #include "dm_radar_helper.h" #include "nlohmann/json.hpp" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -84,7 +87,12 @@ int32_t PinHolder::RegisterPinHolderCallback(const std::string &pkgName) LOGE("RegisterPinHolderCallback session is nullptr."); return ERR_DM_FAILED; } - registerPkgName_ = pkgName; + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif + processInfo_.userId = userId; + processInfo_.pkgName = pkgName; session_->RegisterSessionCallback(shared_from_this()); return DM_OK; } @@ -93,7 +101,7 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload) { LOGI("CreatePinHolder."); - if (registerPkgName_.empty() || registerPkgName_ != pkgName) { + if (processInfo_.pkgName.empty() || processInfo_.pkgName != pkgName) { LOGE("CreatePinHolder pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -120,11 +128,11 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, int32_t stageRes = sessionId_ > 0 ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); DmRadarHelper::GetInstance().ReportCreatePinHolder( - registerPkgName_, sessionId_, targetId.deviceId, sessionId_, stageRes); + processInfo_.pkgName, sessionId_, targetId.deviceId, sessionId_, stageRes); if (sessionId_ < 0) { LOGE("[SOFTBUS]open session error, sessionId: %{public}d.", sessionId_); - listener_->OnCreateResult(registerPkgName_, sessionId_); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, + listener_->OnCreateResult(processInfo_, sessionId_); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, sessionId_, ""); sessionId_ = SESSION_ID_INVALID; return sessionId_; @@ -142,7 +150,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget LOGE("DestroyPinHolder listener or session is nullptr."); return ERR_DM_FAILED; } - if (registerPkgName_.empty() || pkgName != registerPkgName_) { + if (processInfo_.pkgName.empty() || pkgName != processInfo_.pkgName) { LOGE("DestroyPinHolder pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -153,8 +161,8 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget } if (sessionId_ == SESSION_ID_INVALID) { LOGI("DestroyPinHolder session already destroy."); - listener_->OnDestroyResult(registerPkgName_, ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ret, ""); + listener_->OnDestroyResult(processInfo_, ret); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ret, ""); return ret; } if (sourceState_ != SOURCE_CREATE) { @@ -175,11 +183,11 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget ret = session_->SendData(sessionId_, message); int32_t stageRes = ret == DM_OK ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); - DmRadarHelper::GetInstance().ReportDestroyPinHolder(registerPkgName_, targetId.deviceId, ret, stageRes); + DmRadarHelper::GetInstance().ReportDestroyPinHolder(processInfo_.pkgName, targetId.deviceId, ret, stageRes); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + listener_->OnDestroyResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); return ret; } return ret; @@ -211,8 +219,8 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() std::string("CreateGeneratePinHolderMsg"), ""); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnCreateResult(registerPkgName_, ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ret, ""); + listener_->OnCreateResult(processInfo_, ret); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ret, ""); return ret; } return ret; @@ -244,7 +252,7 @@ void PinHolder::ProcessCloseSessionMsg(const std::string &message) sessionId_ = SESSION_ID_INVALID; sourceState_ = SOURCE_INIT; sinkState_ = SINK_INIT; - listener_->OnCreateResult(registerPkgName_, ERR_DM_CREATE_PIN_HOLDER_BUSY); + listener_->OnCreateResult(processInfo_, ERR_DM_CREATE_PIN_HOLDER_BUSY); } void PinHolder::ProcessCreateMsg(const std::string &message) @@ -275,13 +283,13 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; sinkState_ = SINK_CREATE; sourceState_ = SOURCE_CREATE; - listener_->OnPinHolderCreate(registerPkgName_, remoteDeviceId_, pinType, payload); + listener_->OnPinHolderCreate(processInfo_, remoteDeviceId_, pinType, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE, DM_OK, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; @@ -312,14 +320,14 @@ void PinHolder::ProcessCreateRespMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnCreateResult(registerPkgName_, DM_OK); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, DM_OK, ""); + listener_->OnCreateResult(processInfo_, DM_OK); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, DM_OK, ""); sourceState_ = SOURCE_CREATE; sinkState_ = SINK_CREATE; } else { LOGE("ProcessCreateRespMsg remote state is wrong."); - listener_->OnCreateResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); + listener_->OnCreateResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); session_->CloseSessionServer(sessionId_); sessionId_ = SESSION_ID_INVALID; destroyState_ = STATE_REMOTE_WRONG; @@ -356,12 +364,12 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) sinkState_ = SINK_INIT; sourceState_ = SOURCE_INIT; if (!isDestroy_.load()) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); + listener_->OnPinHolderDestroy(processInfo_, pinType, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); isDestroy_.store(true); } } @@ -386,12 +394,12 @@ void PinHolder::CloseSession(const std::string &name) jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); if (listener_ != nullptr && !isDestroy_.load()) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); + listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); isDestroy_.store(true); } session_->CloseSessionServer(sessionId_); @@ -421,15 +429,15 @@ void PinHolder::ProcessDestroyResMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnDestroyResult(registerPkgName_, DM_OK); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, DM_OK, ""); + listener_->OnDestroyResult(processInfo_, DM_OK); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, DM_OK, ""); sourceState_ = SOURCE_INIT; sinkState_ = SINK_INIT; timer_->DeleteAll(); } else { LOGE("ProcessDestroyResMsg remote state is wrong."); - listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + listener_->OnDestroyResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); sinkState_ = SINK_INIT; sourceState_ = SOURCE_INIT; } @@ -451,7 +459,7 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) int32_t ret = session_->SendData(sessionId, msg); if (ret != DM_OK) { LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); } return; } @@ -530,8 +538,8 @@ void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t LOGE("[SOFTBUS]onSesssionOpened failed. sessionId: %{public}d.", sessionId); sessionId_ = SESSION_ID_INVALID; if (listener_ != nullptr) { - listener_->OnCreateResult(registerPkgName_, result); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, result, ""); + listener_->OnCreateResult(processInfo_, result); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, result, ""); } return; } @@ -551,17 +559,17 @@ void PinHolder::OnSessionClosed(int32_t sessionId) jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); if (listener_ != nullptr && !isDestroy_.load()) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); + listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); if (destroyState_ == STATE_UNKNOW) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, sessionId, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); } else if (destroyState_ == STATE_REMOTE_WRONG) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_FAILED, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_FAILED, content); } else if (destroyState_ == STATE_TIME_OUT) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); } isDestroy_.store(true); } @@ -587,7 +595,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s LOGE("NotifyPinHolderEvent listener or session is nullptr."); return ERR_DM_FAILED; } - if (registerPkgName_.empty() || pkgName != registerPkgName_ || event.empty()) { + if (processInfo_.pkgName.empty() || pkgName != processInfo_.pkgName || event.empty()) { LOGE("NotifyPinHolderEvent pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -619,7 +627,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s int32_t ret = session_->SendData(sessionId_, message); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); return ERR_DM_FAILED; } return ret; @@ -651,7 +659,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); timer_->DeleteAll(); timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, [this] (std::string name) { @@ -685,10 +693,10 @@ void PinHolder::ProcessChangeRespMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, DM_OK, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, DM_OK, ""); } else { LOGE("ProcessChangeRespMsg remote state is wrong."); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); } } } // namespace DistributedHardware diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index b867bb1f1..8ade6ac27 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -136,27 +136,35 @@ bool DmAccountCommonEventManager::UnsubscribeAccountCommonEvent() void DmAccountEventSubscriber::OnReceiveEvent(const CommonEventData &data) { std::string receiveEvent = data.GetWant().GetAction(); - LOGI("Received account event: %{public}s", receiveEvent.c_str()); - int32_t userId = data.GetCode(); - bool accountValiedEvent = false; - if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED || - receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { - userId = data.GetCode(); - accountValiedEvent = true; + int32_t currentUserId = -1; + int32_t beforeUserId = -1; + bool accountValidEvent = false; + + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + currentUserId = data.GetCode(); + beforeUserId = std::atoi(data.GetWant().GetStringParam("oldId").c_str()); + accountValidEvent = true; + } + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + beforeUserId = data.GetCode(); + accountValidEvent = true; } if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT || receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { - userId = data.GetWant().GetIntParam("userId", 0); - accountValiedEvent = true; + currentUserId = data.GetWant().GetIntParam("userId", 0); + beforeUserId = currentUserId; + accountValidEvent = true; } - if (userId <= 0 || !accountValiedEvent) { + LOGI("Received account event: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", + receiveEvent.c_str(), currentUserId, beforeUserId); + if (!accountValidEvent) { LOGE("Invalied account type event."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { callback_(userId, receiveEvent); }); + ffrt::submit([=]() { callback_(receiveEvent, currentUserId, beforeUserId); }); #else - std::thread dealThread([=]() { callback_(userId, receiveEvent); }); + std::thread dealThread([=]() { callback_(receiveEvent, currentUserId, beforeUserId); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); diff --git a/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp new file mode 100644 index 000000000..d735c57f9 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_comm_tool.h" + +#include "cJSON.h" + +#include "device_manager_service.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_transport.h" +#include "dm_transport_msg.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { +DMCommTool::DMCommTool() : dmTransportPtr_(nullptr) +{ + LOGI("Ctor DMCommTool"); +} + +void DMCommTool::Init() +{ + LOGI("Init DMCommTool"); + dmTransportPtr_ = std::make_shared(shared_from_this()); + std::shared_ptr runner = AppExecFwk::EventRunner::Create(true); + eventHandler_ = std::make_shared(runner, shared_from_this()); + dmTransportPtr_->Init(); +} + +void DMCommTool::UnInit() +{ + LOGI("UnInit DMCommTool"); + if (dmTransportPtr_ == nullptr) { + LOGI("dmTransportPtr_ is null"); + return; + } + dmTransportPtr_->UnInit(); +} + +std::shared_ptr DMCommTool::GetInstance() +{ + static std::shared_ptr instance = std::make_shared(); + return instance; +} + +void DMCommTool::SendUserIds(const std::string rmtNetworkId, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds) +{ + if (!IsIdLengthValid(rmtNetworkId) || foregroundUserIds.empty() || dmTransportPtr_ == nullptr) { + LOGE("param invalid, networkId: %{public}s, foreground userids size: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), static_cast(foregroundUserIds.size())); + return; + } + + if (dmTransportPtr_->StartSocket(rmtNetworkId) != DM_OK) { + LOGE("Start socket error"); + return; + } + + UserIdsMsg userIdsMsg(foregroundUserIds, backgroundUserIds); + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + LOGE("Create cJSON object failed."); + return; + } + ToJson(root, userIdsMsg); + char *msg = cJSON_PrintUnformatted(root); + if (msg == nullptr) { + cJSON_Delete(root); + return; + } + std::string msgStr(msg); + cJSON_Delete(root); + CommMsg commMsg(DM_COMM_SEND_LOCAL_USERIDS, msgStr); + std::string payload = GetCommMsgString(commMsg); + + int32_t ret = dmTransportPtr_->Send(rmtNetworkId, payload); + if (ret != DM_OK) { + LOGE("Send local foreground userids failed, ret: %{public}d", ret); + return; + } + LOGI("Send local foreground userids success"); +} + +void DMCommTool::RspLocalFrontOrBackUserIds(const std::string rmtNetworkId, + const std::vector &foregroundUserIds, const std::vector &backgroundUserIds) +{ + UserIdsMsg userIdsMsg(foregroundUserIds, backgroundUserIds); + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + LOGE("Create cJSON object failed."); + return; + } + ToJson(root, userIdsMsg); + char *msg = cJSON_PrintUnformatted(root); + if (msg == nullptr) { + cJSON_Delete(root); + return; + } + std::string msgStr(msg); + cJSON_Delete(root); + CommMsg commMsg(DM_COMM_RSP_LOCAL_USERIDS, msgStr); + std::string payload = GetCommMsgString(commMsg); + + int32_t ret = dmTransportPtr_->Send(rmtNetworkId, payload); + if (ret != DM_OK) { + LOGE("Response local foreground userids failed, ret: %{public}d", ret); + return; + } + LOGI("Response local foreground userids success"); +} + +DMCommTool::DMCommToolEventHandler::DMCommToolEventHandler(const std::shared_ptr runner, + std::shared_ptr dmCommToolPtr) : AppExecFwk::EventHandler(runner), dmCommToolWPtr_(dmCommToolPtr) +{ + LOGI("Ctor DMCommToolEventHandler"); +} + +void DMCommTool::DMCommToolEventHandler::ProcessEvent( + const AppExecFwk::InnerEvent::Pointer &event) +{ + uint32_t eventId = event->GetInnerEventId(); + std::shared_ptr commMsg = event->GetSharedObject(); + if (commMsg == nullptr) { + LOGE("ProcessEvent commMsg is null"); + return; + } + if (dmCommToolWPtr_.expired()) { + LOGE("dmCommToolWPtr_ is expired"); + return; + } + std::shared_ptr dmCommToolPtr = dmCommToolWPtr_.lock(); + if (dmCommToolPtr == nullptr) { + LOGE("dmCommToolPtr is null"); + return; + } + switch (eventId) { + case DM_COMM_SEND_LOCAL_USERIDS: { + // Process remote foreground userids and send back local user ids + dmCommToolPtr->ProcessReceiveUserIdsEvent(commMsg); + break; + } + case DM_COMM_RSP_LOCAL_USERIDS: { + // Process remote foreground userids and close session + dmCommToolPtr->ProcessResponseUserIdsEvent(commMsg); + break; + } + default: + LOGE("event is undefined, id is %{public}d", eventId); + break; + } +} + +void DMCommTool::ProcessReceiveUserIdsEvent(const std::shared_ptr commMsg) +{ + LOGI("Receive remote userids, process and rsp local userid"); + std::string rmtUdid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(commMsg->remoteNetworkId.c_str(), rmtUdid); + if (rmtUdid.empty()) { + LOGE("Can not find remote udid by networkid: %{public}s", commMsg->remoteNetworkId.c_str()); + return; + } + + std::string payload = commMsg->commMsg->msg; + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + UserIdsMsg userIdsMsg; + FromJson(root, userIdsMsg); + cJSON_Delete(root); + uint32_t totalUserNum = static_cast(userIdsMsg.foregroundUserIds.size()) + + static_cast(userIdsMsg.backgroundUserIds.size()); + if (userIdsMsg.foregroundUserIds.empty()) { + LOGE("Parse but get none remote foreground userids"); + } else { + // step1: process remote foreground/background userids + DeviceManagerService::GetInstance().ProcessSyncUserIds(userIdsMsg.foregroundUserIds, + userIdsMsg.backgroundUserIds, rmtUdid); + } + + // step2: send back local userids + std::vector foregroundUserIds; + std::vector backgroundUserIds; + MultipleUserConnector::GetForegroundUserIds(foregroundUserIds); + MultipleUserConnector::GetBackgroundUserIds(backgroundUserIds); + std::vector foregroundUserIdsU32; + std::vector backgroundUserIdsU32; + for (auto const &u : foregroundUserIds) { + foregroundUserIdsU32.push_back(static_cast(u)); + } + for (auto const &u : backgroundUserIds) { + backgroundUserIdsU32.push_back(static_cast(u)); + } + RspLocalFrontOrBackUserIds(commMsg->remoteNetworkId, foregroundUserIdsU32, backgroundUserIdsU32); +} + +void DMCommTool::ProcessResponseUserIdsEvent(const std::shared_ptr commMsg) +{ + LOGI("process receive remote userids response"); + // step1: close socket + this->dmTransportPtr_->StopSocket(commMsg->remoteNetworkId); + + std::string rmtUdid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(commMsg->remoteNetworkId.c_str(), rmtUdid); + if (rmtUdid.empty()) { + LOGE("Can not find remote udid by networkid: %{public}s", commMsg->remoteNetworkId.c_str()); + return; + } + + std::string payload = commMsg->commMsg->msg; + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + UserIdsMsg userIdsMsg; + FromJson(root, userIdsMsg); + cJSON_Delete(root); + if (userIdsMsg.foregroundUserIds.empty()) { + LOGE("Parse but get none remote userids"); + return; + } + // step2: process remote foreground/background userids + if (!userIdsMsg.foregroundUserIds.empty()) { + DeviceManagerService::GetInstance().ProcessSyncUserIds(userIdsMsg.foregroundUserIds, + userIdsMsg.backgroundUserIds, rmtUdid); + } else { + LOGE("Receive remote foreground userid empty"); + } +} + +std::shared_ptr DMCommTool::GetEventHandler() +{ + return this->eventHandler_; +} + +const std::shared_ptr DMCommTool::GetDMTransportPtr() +{ + return this->dmTransportPtr_; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/dm_transport.cpp b/services/service/src/relationshipsyncmgr/dm_transport.cpp new file mode 100644 index 000000000..6b5110380 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_transport.cpp @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_transport.h" + +#include + +#include "cJSON.h" +#include +#include "dm_anonymous.h" +#include "dm_comm_tool.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" +#include "dm_transport_msg.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +// Dsoftbus sendBytes max message length: 4MB +constexpr uint32_t MAX_SEND_MSG_LENGTH = 4 * 1024 * 1024; +constexpr uint32_t INTERCEPT_STRING_LENGTH = 20; +constexpr uint32_t MAX_ROUND_SIZE = 1000; +static QosTV g_qosInfo[] = { + { .qos = QOS_TYPE_MIN_BW, .value = 256 * 1024}, + { .qos = QOS_TYPE_MAX_LATENCY, .value = 8000 }, + { .qos = QOS_TYPE_MIN_LATENCY, .value = 2000 } +}; +static uint32_t g_qosTvParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); +static std::weak_ptr g_dmCommToolWPtr_; +} + +DMTransport::DMTransport(std::shared_ptr dmCommToolPtr) : remoteDevSocketIds_({}), localServerSocket_(-1), + localSocketName_(""), isSocketSvrCreateFlag_(false), dmCommToolWPtr_(dmCommToolPtr) +{ + LOGI("Ctor DMTransport"); + g_dmCommToolWPtr_ = dmCommToolPtr; +} + +int32_t DMTransport::OnSocketOpened(int32_t socketId, const PeerSocketInfo &info) +{ + LOGI("OnSocketOpened, socket: %{public}d, peerSocketName: %{public}s, peerNetworkId: %{public}s, " + "peerPkgName: %{public}s", socketId, info.name, GetAnonyString(info.networkId).c_str(), info.pkgName); + std::lock_guard lock(rmtSocketIdMtx_); + remoteDevSocketIds_[info.networkId] = socketId; + return DM_OK; +} + +void DMTransport::OnSocketClosed(int32_t socketId, ShutdownReason reason) +{ + LOGI("OnSocketClosed, socket: %{public}d, reason: %{public}d", socketId, (int32_t)reason); + std::lock_guard lock(rmtSocketIdMtx_); + for (auto iter = remoteDevSocketIds_.begin(); iter != remoteDevSocketIds_.end(); ++iter) { + if (iter->second == socketId) { + remoteDevSocketIds_.erase(iter); + break; + } + } +} + +void DMTransport::OnBytesReceived(int32_t socketId, const void *data, uint32_t dataLen) +{ + if (socketId < 0 || data == nullptr || dataLen == 0 || dataLen > MAX_SEND_MSG_LENGTH) { + LOGE("OnBytesReceived param check failed"); + return; + } + + std::string remoteNeworkId = GetRemoteNetworkIdBySocketId(socketId); + if (remoteNeworkId.empty()) { + LOGE("Can not find the remote network id by socketId: %{public}d", socketId); + return; + } + + uint8_t *buf = reinterpret_cast(calloc(dataLen + 1, sizeof(uint8_t))); + if (buf == nullptr) { + LOGE("OnBytesReceived: malloc memory failed"); + return; + } + + if (memcpy_s(buf, dataLen + 1, reinterpret_cast(data), dataLen) != EOK) { + LOGE("OnBytesReceived: memcpy memory failed"); + free(buf); + return; + } + + std::string message(buf, buf + dataLen); + LOGI("Receive message size: %{public}" PRIu32, dataLen); + HandleReceiveMessage(socketId, message); + free(buf); + return; +} + +void DMTransport::HandleReceiveMessage(const int32_t socketId, const std::string &payload) +{ + std::string rmtNetworkId = GetRemoteNetworkIdBySocketId(socketId); + if (rmtNetworkId.empty()) { + LOGE("Can not find networkId by socketId: %{public}d", socketId); + return; + } + if (payload.empty() || payload.size() > MAX_SEND_MSG_LENGTH) { + LOGE("payload invalid"); + return; + } + LOGI("Receive msg: %{public}s", payload.c_str()); + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + std::shared_ptr commMsg = std::make_shared(); + FromJson(root, *commMsg); + cJSON_Delete(root); + + std::shared_ptr innerMsg = std::make_shared(rmtNetworkId, commMsg); + + LOGI("Receive DM msg, code: %{public}d, msg: %{public}s", commMsg->code, GetAnonyString(commMsg->msg).c_str()); + AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(commMsg->code, innerMsg); + std::shared_ptr dmCommToolSPtr = dmCommToolWPtr_.lock(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + if (dmCommToolSPtr->GetEventHandler() == nullptr) { + LOGE("Can not get eventHandler"); + return; + } + dmCommToolSPtr->GetEventHandler()->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE); +} + +std::shared_ptr GetDMCommToolPtr() +{ + if (g_dmCommToolWPtr_.expired()) { + LOGE("DMCommTool Weak ptr expired"); + return nullptr; + } + + std::shared_ptr dmCommToolSPtr = g_dmCommToolWPtr_.lock(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return nullptr; + } + + return dmCommToolSPtr; +} + +void OnBind(int32_t socket, PeerSocketInfo info) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnSocketOpened(socket, info); +} + +void OnShutdown(int32_t socket, ShutdownReason reason) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnSocketClosed(socket, reason); +} + +void OnBytes(int32_t socket, const void *data, uint32_t dataLen) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnBytesReceived(socket, data, dataLen); +} + +void OnMessage(int32_t socket, const void *data, uint32_t dataLen) +{ + (void)socket; + (void)data; + (void)dataLen; + LOGI("socket: %{public}d, dataLen:%{public}" PRIu32, socket, dataLen); +} + +void OnStream(int32_t socket, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param) +{ + (void)socket; + (void)data; + (void)ext; + (void)param; + LOGI("socket: %{public}d", socket); +} + +void OnFile(int32_t socket, FileEvent *event) +{ + (void)event; + LOGI("socket: %{public}d", socket); +} + +void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) +{ + if (qosCount == 0 || qosCount > MAX_ROUND_SIZE) { + LOGE("qosCount is invalid!"); + return; + } + LOGI("OnQos, socket: %{public}d, QoSEvent: %{public}d, qosCount: %{public}" PRIu32, + socket, (int32_t)eventId, qosCount); + for (uint32_t idx = 0; idx < qosCount; idx++) { + LOGI("QosTV: type: %{public}d, value: %{public}d", (int32_t)qos[idx].qos, qos[idx].value); + } +} + +ISocketListener iSocketListener = { + .OnBind = OnBind, + .OnShutdown = OnShutdown, + .OnBytes = OnBytes, + .OnMessage = OnMessage, + .OnStream = OnStream, + .OnFile = OnFile, + .OnQos = OnQos +}; + +int32_t DMTransport::CreateServerSocket() +{ + LOGI("CreateServerSocket start"); + localSocketName_ = DM_SYNC_USERID_SESSION_NAME; + LOGI("CreateServerSocket , local socketName: %{public}s", localSocketName_.c_str()); + std::string dmPkgName(DM_PKG_NAME); + SocketInfo info = { + .name = const_cast(localSocketName_.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + int32_t socket = Socket(info); + LOGI("CreateServerSocket Finish, socket: %{public}d", socket); + return socket; +} + +int32_t DMTransport::CreateClientSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("CreateClientSocket start, peerNetworkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + std::string peerSocketName = DM_SYNC_USERID_SESSION_NAME; + std::string dmPkgName(DM_PKG_NAME); + SocketInfo info = { + .name = const_cast(localSocketName_.c_str()), + .peerName = const_cast(peerSocketName.c_str()), + .peerNetworkId = const_cast(rmtNetworkId.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + int32_t socket = Socket(info); + LOGI("Bind Socket server, socket: %{public}d, localSocketName: %{public}s, peerSocketName: %{public}s", + socket, localSocketName_.c_str(), peerSocketName.c_str()); + return socket; +} + +int32_t DMTransport::Init() +{ + LOGI("Init DMTransport"); + if (isSocketSvrCreateFlag_.load()) { + LOGI("SocketServer already create success."); + return DM_OK; + } + int32_t socket = CreateServerSocket(); + if (socket < DM_OK) { + LOGE("CreateSocketServer failed, ret: %{public}d", socket); + return ERR_DM_FAILED; + } + + int32_t ret = Listen(socket, g_qosInfo, g_qosTvParamIndex, &iSocketListener); + if (ret != DM_OK) { + LOGE("Socket Listen failed, error code %{public}d.", ret); + return ERR_DM_FAILED; + } + isSocketSvrCreateFlag_.store(true); + localServerSocket_ = socket; + LOGI("Finish Init DSoftBus Server Socket, socket: %{public}d", socket); + return DM_OK; +} + +int32_t DMTransport::UnInit() +{ + { + std::lock_guard lock(rmtSocketIdMtx_); + for (auto iter = remoteDevSocketIds_.begin(); iter != remoteDevSocketIds_.end(); ++iter) { + LOGI("Shutdown client socket: %{public}d to remote dev: %{public}s", iter->second, + GetAnonyString(iter->first).c_str()); + Shutdown(iter->second); + } + remoteDevSocketIds_.clear(); + } + + if (!isSocketSvrCreateFlag_.load()) { + LOGI("DSoftBus Server Socket already remove success."); + } else { + LOGI("Shutdown DSoftBus Server Socket, socket: %{public}d", localServerSocket_.load()); + Shutdown(localServerSocket_.load()); + localServerSocket_ = -1; + isSocketSvrCreateFlag_.store(false); + } + return DM_OK; +} + +bool DMTransport::IsDeviceSessionOpened(const std::string &rmtNetworkId, int32_t &socketId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return false; + } + std::lock_guard lock(rmtSocketIdMtx_); + if (remoteDevSocketIds_.find(rmtNetworkId) == remoteDevSocketIds_.end()) { + return false; + } + socketId = remoteDevSocketIds_.at(rmtNetworkId); + LOGI("DeviceSession has opened, rmtNetworkId: %{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socketId); + return true; +} + +std::string DMTransport::GetRemoteNetworkIdBySocketId(int32_t socketId) +{ + std::lock_guard lock(rmtSocketIdMtx_); + std::string networkId = ""; + for (auto const &item : remoteDevSocketIds_) { + if (item.second == socketId) { + networkId = item.first; + break; + } + } + return networkId; +} + +void DMTransport::ClearDeviceSocketOpened(const std::string &remoteDevId) +{ + if (!IsIdLengthValid(remoteDevId)) { + return; + } + std::lock_guard lock(rmtSocketIdMtx_); + remoteDevSocketIds_.erase(remoteDevId); +} + +int32_t DMTransport::StartSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGE("Softbus session has already opened, deviceId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return DM_OK; + } + + int32_t socket = CreateClientSocket(rmtNetworkId); + if (socket < DM_OK) { + LOGE("StartSocket failed, ret: %{public}d", socket); + return ERR_DM_FAILED; + } + + int32_t ret = Bind(socket, g_qosInfo, g_qosTvParamIndex, &iSocketListener); + if (ret < DM_OK) { + LOGE("OpenSession fail, rmtNetworkId: %{public}s, socket: %{public}d, ret: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socket, ret); + Shutdown(socket); + return ERR_DM_FAILED; + } + + LOGI("Bind Socket success, rmtNetworkId:%{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socket); + std::string peerSocketName = DM_SYNC_USERID_SESSION_NAME; + std::string dmPkgName(DM_PKG_NAME); + PeerSocketInfo peerSocketInfo = { + .name = const_cast(peerSocketName.c_str()), + .networkId = const_cast(rmtNetworkId.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + OnSocketOpened(socket, peerSocketInfo); + return DM_OK; +} + +int32_t DMTransport::StopSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (!IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGI("remote dev may be not opened, rmtNetworkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return ERR_DM_FAILED; + } + + LOGI("StopSocket rmtNetworkId: %{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socketId); + Shutdown(socketId); + ClearDeviceSocketOpened(rmtNetworkId); + return DM_OK; +} + +int32_t DMTransport::Send(const std::string &rmtNetworkId, const std::string &payload) +{ + if (!IsIdLengthValid(rmtNetworkId) || !IsMessageLengthValid(payload)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (!IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGI("The session is not open, target networkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return ERR_DM_FAILED; + } + uint32_t payLoadSize = payload.size(); + LOGI("Send payload size: %{public}" PRIu32 ", target networkId: %{public}s, socketId: %{public}d", + static_cast(payload.size()), GetAnonyString(rmtNetworkId).c_str(), socketId); + + if (payLoadSize > MAX_SEND_MSG_LENGTH) { + LOGE("Send error: msg size: %{public}" PRIu32 " too long", payLoadSize); + return ERR_DM_FAILED; + } + uint8_t *buf = reinterpret_cast(calloc((payLoadSize), sizeof(uint8_t))); + if (buf == nullptr) { + LOGE("Send: malloc memory failed"); + return ERR_DM_FAILED; + } + + if (memcpy_s(buf, payLoadSize, reinterpret_cast(payload.c_str()), + payLoadSize) != EOK) { + LOGE("Send: memcpy memory failed"); + free(buf); + return ERR_DM_FAILED; + } + + int32_t ret = SendBytes(socketId, buf, payLoadSize); + free(buf); + if (ret != DM_OK) { + LOGE("dsoftbus send error, ret: %{public}d", ret); + return ERR_DM_FAILED; + } + LOGI("Send payload success"); + return DM_OK; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp b/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp new file mode 100644 index 000000000..0fa4e6996 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_transport_msg.h" + +#include "dm_anonymous.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const int32_t MAX_USER_ID_NUM = 5; + const int32_t MAX_BACKGROUND_USER_ID_NUM = 5; +} +void ToJson(cJSON *jsonObject, const UserIdsMsg &userIdsMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *foregroundUserIdArr = cJSON_CreateArray(); + if (foregroundUserIdArr == nullptr) { + return; + } + for (auto const &userId : userIdsMsg.foregroundUserIds) { + cJSON_AddItemToArray(foregroundUserIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, FOREGROUND_USERIDS_MSG_USERIDS_KEY, foregroundUserIdArr); + + cJSON *backgroundUserIdArr = cJSON_CreateArray(); + if (backgroundUserIdArr == nullptr) { + return; + } + for (auto const &userId : userIdsMsg.backgroundUserIds) { + cJSON_AddItemToArray(backgroundUserIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, BACKGROUND_USERIDS_MSG_USERIDS_KEY, backgroundUserIdArr); +} + +void FromJson(const cJSON *jsonObject, UserIdsMsg &userIdsMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *foregroundUserIdsArr = cJSON_GetObjectItem(jsonObject, FOREGROUND_USERIDS_MSG_USERIDS_KEY); + if (cJSON_IsArray(foregroundUserIdsArr)) { + int32_t arrSize = cJSON_GetArraySize(foregroundUserIdsArr); + if (arrSize > MAX_USER_ID_NUM) { + LOGE("Receive too many foreground userids, %{public}d", arrSize); + return; + } + for (int32_t i = 0; i < arrSize; i++) { + cJSON *userIdItem = cJSON_GetArrayItem(foregroundUserIdsArr, i); + if (cJSON_IsNumber(userIdItem)) { + uint32_t userId = static_cast(userIdItem->valueint); + userIdsMsg.foregroundUserIds.push_back(userId); + } + } + } + + cJSON *backgroundUserIdsArr = cJSON_GetObjectItem(jsonObject, BACKGROUND_USERIDS_MSG_USERIDS_KEY); + if (cJSON_IsArray(backgroundUserIdsArr)) { + int32_t arrSize = cJSON_GetArraySize(backgroundUserIdsArr); + if (arrSize > MAX_BACKGROUND_USER_ID_NUM) { + LOGE("Receive too many background userids, %{public}d", arrSize); + return; + } + for (int32_t i = 0; i < arrSize; i++) { + cJSON *userIdItem = cJSON_GetArrayItem(backgroundUserIdsArr, i); + if (cJSON_IsNumber(userIdItem)) { + uint32_t userId = static_cast(userIdItem->valueint); + userIdsMsg.backgroundUserIds.push_back(userId); + } + } + } +} + +void ToJson(cJSON *jsonObject, const CommMsg &commMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON_AddNumberToObject(jsonObject, COMM_MSG_CODE_KEY, commMsg.code); + const char *msg = commMsg.msg.c_str(); + cJSON_AddStringToObject(jsonObject, COMM_MSG_MSG_KEY, msg); +} + +void FromJson(const cJSON *jsonObject, CommMsg &commMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *codeObj = cJSON_GetObjectItem(jsonObject, COMM_MSG_CODE_KEY); + if (cJSON_IsNumber(codeObj)) { + commMsg.code = codeObj->valueint; + } + + cJSON *msgObj = cJSON_GetObjectItem(jsonObject, COMM_MSG_MSG_KEY); + if (cJSON_IsString(msgObj)) { + commMsg.msg = msgObj->valuestring; + } +} + +std::string GetCommMsgString(const CommMsg &commMsg) +{ + cJSON *rootMsg = cJSON_CreateObject(); + if (rootMsg == nullptr) { + LOGE("Create cJSON object failed."); + return ""; + } + ToJson(rootMsg, commMsg); + char *msg = cJSON_PrintUnformatted(rootMsg); + if (msg == nullptr) { + cJSON_Delete(rootMsg); + return ""; + } + std::string msgStr = std::string(msg); + cJSON_free(msg); + cJSON_Delete(rootMsg); + + return msgStr; +} + +void ToJson(cJSON *jsonObject, const NotifyUserIds ¬ifyUserIds) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + + cJSON_AddStringToObject(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY, notifyUserIds.remoteUdid.c_str()); + + cJSON *userIdArr = cJSON_CreateArray(); + if (userIdArr == nullptr) { + return; + } + for (auto const &userId : notifyUserIds.userIds) { + cJSON_AddItemToArray(userIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY, userIdArr); +} + +void FromJson(const cJSON *jsonObject, NotifyUserIds ¬ifyUserIds) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + + cJSON *msgObj = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY); + if (cJSON_IsString(msgObj)) { + notifyUserIds.remoteUdid = msgObj->valuestring; + } + + cJSON *userIdsArr = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY); + if (cJSON_IsArray(userIdsArr)) { + int32_t arrSize = cJSON_GetArraySize(userIdsArr); + if (arrSize > MAX_USER_ID_NUM) { + LOGE("Receive too many userids, %{public}d", arrSize); + return; + } + for (int32_t i = 0; i < arrSize; i++) { + cJSON *userIdItem = cJSON_GetArrayItem(userIdsArr, i); + if (cJSON_IsNumber(userIdItem)) { + uint32_t userId = static_cast(userIdItem->valueint); + notifyUserIds.userIds.push_back(userId); + } + } + } +} + +std::string NotifyUserIds::ToString() +{ + cJSON *msg = cJSON_CreateObject(); + if (msg == NULL) { + LOGE("failed to create cjson object"); + return ""; + } + + ToJson(msg, *this); + char *retStr = cJSON_PrintUnformatted(msg); + if (retStr == nullptr) { + LOGE("to json is nullptr."); + cJSON_Delete(msg); + return ""; + } + std::string ret = std::string(retStr); + cJSON_Delete(msg); + cJSON_free(retStr); + return ret; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 494e959a8..9d2c88dcb 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -17,44 +17,82 @@ #include #include +#include "dm_anonymous.h" #include "dm_crypto.h" #include "dm_log.h" +#include "multiple_user_connector.h" namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(ReleationShipSyncMgr); namespace { /** - * @brief account logout payload length 8 + * @brief account logout payload length 8 bytes * | 2 bytes | 6 bytes | * | userid lower 2 bytes | account id first 6 bytes | */ const int32_t ACCOUNT_LOGOUT_PAYLOAD_LEN = 8; /** - * @brief device unbind payload length 2 + * @brief device unbind payload length 2 bytes * | 2 bytes | * | userid lower 2 bytes | */ const int32_t DEVICE_UNBIND_PAYLOAD_LEN = 2; /** - * @brief app unbind payload length 6 + * @brief app unbind payload length 6 bytes * | 2 bytes | 4 bytes | * | userid lower 2 bytes | token id lower 4 bytes | */ const int32_t APP_UNBIND_PAYLOAD_LEN = 6; + /** + * @brief delete user payload length 2 bytes + * | 2 bytes | + * | userid lower 2 bytes | + */ + const int32_t DEL_USER_PAYLOAD_LEN = 2; + /** + * @brief the userid payload cost 2 bytes. + * + */ const int32_t USERID_PAYLOAD_LEN = 2; const int32_t ACCOUNTID_PAYLOAD_LEN = 6; - const int32_t BIT_PER_BYTES = 8; + const int32_t SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MAX_LEN = 11; + const int32_t SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MIN_LEN = 3; + const int32_t USERID_BYTES = 2; + const int32_t BITS_PER_BYTE = 8; const int32_t INVALIED_PAYLOAD_SIZE = 12; const char * const MSG_TYPE = "TYPE"; const char * const MSG_VALUE = "VALUE"; const char * const MSG_PEER_UDID = "PEER_UDID"; const char * const MSG_ACCOUNTID = "ACCOUNTID"; + + // The need response mask offset, the 8th bit. + const int32_t NEED_RSP_MASK_OFFSET = 7; + /** + * @brief The userid cost 2 byte, the heigher part set on the 2th byte. + * The Max user id is just above 10000+, cost 15bits. We use the first bit + * to mark the user id foreground or background. + * 1 means foreground user, 0 means background user. + * @example foreground userid: 100 -> 0000 0000 0110 0100 + * we save it in payload: + * |----first byte----|----second byte----| + * ---------------------------------------- + * | 0110 0100 | 1000 0000 | + */ + const int32_t FRONT_OR_BACK_USER_FLAG_OFFSET = 7; + const uint8_t FRONT_OR_BACK_USER_FLAG_MASK = 0b01111111; + const uint8_t FRONT_OR_BACK_FLAG_MASK = 0b10000000; + // The total number of foreground and background userids offset, the 3th ~ 5th bits. + const uint16_t ALL_USERID_NUM_MASK_OFFSET = 3; + const uint16_t FOREGROUND_USERID_LEN_MASK = 0b00000111; + const uint16_t ALL_USERID_NUM_MASK = 0b00111000; + const uint32_t MAX_MEM_MALLOC_SIZE = 4 * 1024; } RelationShipChangeMsg::RelationShipChangeMsg() : type(RelationShipChangeType::TYPE_MAX), - userId(UINT32_MAX), accountId(""), tokenId(UINT64_MAX), peerUdid("") + userId(UINT32_MAX), accountId(""), tokenId(UINT64_MAX), peerUdids({}), peerUdid(""), accountName(""), + syncUserIdFlag(false), userIdInfos({}) { } @@ -79,6 +117,13 @@ bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) con ToAppUnbindPayLoad(msg, len); ret = true; break; + case RelationShipChangeType::SYNC_USERID: + ret = ToSyncFrontOrBackUserIdPayLoad(msg, len); + break; + case RelationShipChangeType::DEL_USER: + ToDelUserPayLoad(msg, len); + ret = true; + break; default: LOGE("RelationShipChange type invalid"); break; @@ -104,6 +149,12 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat case RelationShipChangeType::APP_UNBIND: ret = FromAppUnbindPayLoad(payloadJson); break; + case RelationShipChangeType::SYNC_USERID: + ret = FromSyncFrontOrBackUserIdPayLoad(payloadJson); + break; + case RelationShipChangeType::DEL_USER: + ret = FromDelUserPayLoad(payloadJson); + break; default: LOGE("RelationShipChange type invalid"); break; @@ -124,12 +175,18 @@ bool RelationShipChangeMsg::IsValid() const case RelationShipChangeType::APP_UNBIND: ret = (userId != UINT32_MAX && tokenId != UINT64_MAX); break; - case RelationShipChangeType::SERVICE_UNBIND: case RelationShipChangeType::DEL_USER: + ret = (userId != UINT32_MAX); + break; + case RelationShipChangeType::SERVICE_UNBIND: case RelationShipChangeType::APP_UNINSTALL: // current NOT support ret = false; break; + case RelationShipChangeType::SYNC_USERID: + ret = (!userIdInfos.empty() && + (static_cast(userIdInfos.size()) <= MAX_USER_ID_NUM)); + break; case RelationShipChangeType::TYPE_MAX: ret = false; break; @@ -143,21 +200,24 @@ bool RelationShipChangeMsg::IsValid() const bool RelationShipChangeMsg::IsChangeTypeValid() { return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || - (type == RelationShipChangeType::APP_UNBIND); + (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_USERID) || + (type == RelationShipChangeType::DEL_USER); } bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) { return (type == (uint32_t)RelationShipChangeType::ACCOUNT_LOGOUT) || (type == (uint32_t)RelationShipChangeType::DEVICE_UNBIND) || - (type == (uint32_t)RelationShipChangeType::APP_UNBIND); + (type == (uint32_t)RelationShipChangeType::APP_UNBIND) || + (type == (uint32_t)RelationShipChangeType::SYNC_USERID) || + (type == (uint32_t)RelationShipChangeType::DEL_USER); } void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const { msg = new uint8_t[ACCOUNT_LOGOUT_PAYLOAD_LEN](); for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { - msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; } for (int j = USERID_PAYLOAD_LEN; j < ACCOUNT_LOGOUT_PAYLOAD_LEN; j++) { @@ -170,7 +230,7 @@ void RelationShipChangeMsg::ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) { msg = new uint8_t[DEVICE_UNBIND_PAYLOAD_LEN](); for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { - msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; } len = DEVICE_UNBIND_PAYLOAD_LEN; } @@ -179,16 +239,60 @@ void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) con { msg = new uint8_t[APP_UNBIND_PAYLOAD_LEN](); for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { - msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; } for (int i = USERID_PAYLOAD_LEN; i < APP_UNBIND_PAYLOAD_LEN; i++) { - msg[i] |= (tokenId >> ((i - USERID_PAYLOAD_LEN) * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (tokenId >> ((i - USERID_PAYLOAD_LEN) * BITS_PER_BYTE)) & 0xFF; } len = APP_UNBIND_PAYLOAD_LEN; } +bool RelationShipChangeMsg::ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const +{ + uint32_t userIdNum = static_cast(userIdInfos.size()); + if (userIdNum > MAX_USER_ID_NUM) { + LOGE("userIdNum too many, %{public}u", userIdNum); + return false; + } + + len = userIdNum * USERID_BYTES + 1; + + if (len > MAX_MEM_MALLOC_SIZE) { + LOGE("len too long"); + return false; + } + msg = new uint8_t[len](); + if (syncUserIdFlag) { + msg[0] |= 0x1 << NEED_RSP_MASK_OFFSET; + } else { + msg[0] |= 0x0 << NEED_RSP_MASK_OFFSET; + } + + msg[0] |= userIdNum; + int32_t userIdIdx = 0; + for (uint32_t idx = 1; idx <= (len - USERID_BYTES);) { + msg[idx] |= userIdInfos[userIdIdx].userId & 0xFF; + msg[idx + 1] |= (userIdInfos[userIdIdx].userId >> BITS_PER_BYTE) & 0xFF; + if (userIdInfos[userIdIdx].isForeground) { + msg[idx + 1] |= (0x1 << FRONT_OR_BACK_USER_FLAG_OFFSET); + } + idx += USERID_BYTES; + userIdIdx++; + } + return true; +} + +void RelationShipChangeMsg::ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const +{ + len = DEL_USER_PAYLOAD_LEN; + msg = new uint8_t[DEL_USER_PAYLOAD_LEN](); + for (int i = 0; i < DEL_USER_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; + } +} + bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { @@ -196,7 +300,7 @@ bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) return false; } int32_t arraySize = cJSON_GetArraySize(payloadJson); - if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { LOGE("Payload invalied,the size is %{public}d.", arraySize); return false; } @@ -205,7 +309,7 @@ bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } accountId = ""; @@ -226,7 +330,7 @@ bool RelationShipChangeMsg::FromDeviceUnbindPayLoad(const cJSON *payloadJson) return false; } int32_t arraySize = cJSON_GetArraySize(payloadJson); - if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { LOGE("Payload invalied,the size is %{public}d.", arraySize); return false; } @@ -235,7 +339,7 @@ bool RelationShipChangeMsg::FromDeviceUnbindPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } return true; @@ -248,7 +352,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return false; } int32_t arraySize = cJSON_GetArraySize(payloadJson); - if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { LOGE("Payload invalied,the size is %{public}d.", arraySize); return false; } @@ -257,7 +361,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } tokenId = 0; @@ -265,13 +369,91 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, j); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - tokenId |= (static_cast(payloadItem->valueint)) << ((j - USERID_PAYLOAD_LEN) * BIT_PER_BYTES); + tokenId |= (static_cast(payloadItem->valueint)) << ((j - USERID_PAYLOAD_LEN) * BITS_PER_BYTE); + } + } + return true; +} + +bool RelationShipChangeMsg::FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("payloadJson is null."); + return false; + } + + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MIN_LEN || + arraySize > SYNC_FRONT_OR_BACK_USERID_PAYLOAD_MAX_LEN) { + LOGE("Payload invalid, the size is %{public}d.", arraySize); + return false; + } + + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, 0); + CHECK_NULL_RETURN(payloadItem, false); + uint32_t userIdNum = 0; + if (cJSON_IsNumber(payloadItem)) { + uint8_t val = static_cast(payloadItem->valueint); + this->syncUserIdFlag = (((val >> NEED_RSP_MASK_OFFSET) & 0x1) == 0x1); + userIdNum = ((static_cast(payloadItem->valueint)) & FOREGROUND_USERID_LEN_MASK); + } + + int32_t effectiveLen = userIdNum * USERID_BYTES + 1; + if (effectiveLen > arraySize) { + LOGE("payload userIdNum invalid, userIdNum: %{public}u, arraySize: %{public}d", userIdNum, arraySize); + return false; + } + + uint16_t tempUserId = 0; + bool isForegroundUser = false; + for (int32_t idx = 1; idx < effectiveLen; idx++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, idx); + CHECK_NULL_RETURN(payloadItem, false); + if (!cJSON_IsNumber(payloadItem)) { + LOGE("Payload invalid, user id not integer"); + return false; + } + if ((idx - 1) % USERID_BYTES == 0) { + tempUserId |= (static_cast(payloadItem->valueint)); + } + if ((idx - 1) % USERID_BYTES == 1) { + tempUserId |= (static_cast(payloadItem->valueint) << BITS_PER_BYTE); + tempUserId &= FRONT_OR_BACK_USER_FLAG_MASK; + isForegroundUser = (((static_cast(payloadItem->valueint) & FRONT_OR_BACK_FLAG_MASK) >> + FRONT_OR_BACK_USER_FLAG_OFFSET) == 0b1); + UserIdInfo userIdInfo(isForegroundUser, tempUserId); + this->userIdInfos.push_back(userIdInfo); + tempUserId = 0; + isForegroundUser = false; + } + } + return true; +} + +bool RelationShipChangeMsg::FromDelUserPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("FromDelUserPayLoad payloadJson is null."); + return false; + } + + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < DEL_USER_PAYLOAD_LEN) { + LOGE("Payload invalid, the size is %{public}d.", arraySize); + return false; + } + this->userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + this->userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } return true; } -cJSON *RelationShipChangeMsg::ToArrayJson() const +cJSON *RelationShipChangeMsg::ToPayLoadJson() const { uint8_t *payload = nullptr; uint32_t len = 0; @@ -304,7 +486,7 @@ std::string RelationShipChangeMsg::ToJson() const return ""; } cJSON_AddNumberToObject(msg, MSG_TYPE, (uint32_t)type); - cJSON *arrayObj = ToArrayJson(); + cJSON *arrayObj = ToPayLoadJson(); if (arrayObj == nullptr) { LOGE("ArrayObj is nullptr."); cJSON_Delete(msg); @@ -387,5 +569,57 @@ RelationShipChangeMsg ReleationShipSyncMgr::ParseTrustRelationShipChange(const s } return msgObj; } + +const std::string RelationShipChangeMsg::ToString() const +{ + std::string ret; + ret += "{ MsgType: " + std::to_string(static_cast(type)); + ret += ", userId: " + std::to_string(userId); + ret += ", accountId: " + GetAnonyString(accountId); + ret += ", tokenId: " + std::to_string(tokenId); + ret += ", peerUdids: " + GetAnonyStringList(peerUdids); + ret += ", peerUdid: " + GetAnonyString(peerUdid); + ret += ", accountName: " + GetAnonyString(accountName); + ret += ", syncUserIdFlag: " + std::to_string(syncUserIdFlag); + ret += ", userIds: " + GetUserIdInfoList(userIdInfos) + " }"; + return ret; +} + +const std::string UserIdInfo::ToString() const +{ + std::string ret; + ret += "{ " + std::to_string(this->isForeground); + ret += ", userId: " + std::to_string(this->userId) + " }"; + return ret; +} + +const std::string GetUserIdInfoList(const std::vector &list) +{ + std::string temp = "[ "; + bool flag = false; + for (auto const &userId : list) { + temp += userId.ToString() + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; + return temp; +} + +void GetFrontAndBackUserIdInfos(const std::vector &remoteUserIdInfos, + std::vector &foregroundUserIdInfos, std::vector &backgroundUserIdInfos) +{ + foregroundUserIdInfos.clear(); + backgroundUserIdInfos.clear(); + for (auto const &u : remoteUserIdInfos) { + if (u.isForeground) { + foregroundUserIdInfos.push_back(u); + } else { + backgroundUserIdInfos.push_back(u); + } + } +} } // DistributedHardware } // OHOS \ No newline at end of file diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index f04bb4a0f..2a3385e77 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -30,6 +30,7 @@ #include "dm_log.h" #include "dm_softbus_cache.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "dm_transport_msg.h" #include "ffrt.h" #endif #include "parameter.h" @@ -62,6 +63,7 @@ static std::mutex g_lnnCbkMapMutex; static std::mutex g_radarLoadLock; static std::mutex g_onlineDeviceNumLock; static std::mutex g_lockDeviceTrustedChange; +static std::mutex g_lockUserIdCheckSumChange; static std::mutex g_lockDeviceOnLine; static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; @@ -155,8 +157,22 @@ void SoftbusListener::DeviceNotTrust(const std::string &msg) void SoftbusListener::DeviceTrustedChange(const std::string &msg) { +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::lock_guard lock(g_lockDeviceTrustedChange); DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); +#else + (void)msg; +#endif +} + +void SoftbusListener::DeviceUserIdCheckSumChange(const std::string &msg) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::lock_guard lock(g_lockUserIdCheckSumChange); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); +#else + (void)msg; +#endif } void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) @@ -358,16 +374,18 @@ void SoftbusListener::OnLocalDevInfoChange() void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen) { LOGI("OnDeviceTrustedChange."); - if (msg == nullptr || msgLen > MAX_SOFTBUS_MSG_LEN) { + if (msg == nullptr || msgLen > MAX_SOFTBUS_MSG_LEN || strlen(msg) != msgLen) { LOGE("OnDeviceTrustedChange msg invalied."); return; } - std::string softbusMsg = std::string(msg); + std::string softbusMsg = std::string(msg, msgLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) if (type == TrustChangeType::DEVICE_NOT_TRUSTED) { ffrt::submit([=]() { DeviceNotTrust(softbusMsg); }); } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { ffrt::submit([=]() { DeviceTrustedChange(softbusMsg); }); + } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { + ffrt::submit([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); } else { LOGE("Invalied trust change type."); } @@ -386,6 +404,13 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms LOGE("deviceTrustedChange setname failed."); } deviceTrustedChange.detach(); + } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { + std::thread deviceUserIdCheckSumChange([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); + int32_t ret = pthread_setname_np(deviceUserIdCheckSumChange.native_handle(), DEVICE_NOT_TRUST); + if (ret != DM_OK) { + LOGE("deviceUserIdCheckSumChange setname failed."); + } + deviceUserIdCheckSumChange.detach(); } else { LOGE("Invalied trust change type."); } @@ -1139,5 +1164,20 @@ int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &s LOGI("GetDeviceScreenStatus screenStatus: %{public}d.", devScreenStatus); return DM_OK; } + +int32_t SoftbusListener::SetForegroundUserIdsToDSoftBus(const std::string &remoteUdid, + const std::vector &userIds) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + NotifyUserIds notifyUserIds(remoteUdid, userIds); + std::string msg = notifyUserIds.ToString(); + LOGI("Notify remote userid to dsoftbus, msg: %{public}s", GetAnonyString(msg).c_str()); + return DM_OK; +#else + (void)remoteUdid; + (void)userIds; +#endif + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 54241e5b2..3f1ee3fc8 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -320,7 +320,7 @@ void AuthenticateDeviceFourthFuzzTest(const uint8_t* data, size_t size) DeviceManagerImpl::GetInstance().UnbindTarget(str, targetId, discoverParam, nullptr); DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, discoverParam, false, g_deviceList); DeviceManagerImpl::GetInstance().RegisterDevStateCallback(str, discoverParam, nullptr); - DeviceManagerImpl::GetInstance().AddDiscoveryCallback("test", nullptr); + DeviceManagerImpl::GetInstance().AddDiscoveryCallback("test", discoverParam, nullptr); DeviceManagerImpl::GetInstance().RemoveDiscoveryCallback("test"); DeviceManagerImpl::GetInstance().AddPublishCallback("test"); DeviceManagerImpl::GetInstance().RemovePublishCallback("test"); diff --git a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn index 249999789..0393235e1 100644 --- a/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceservice_fuzzer/BUILD.gn @@ -71,6 +71,7 @@ ohos_fuzztest("AuthenticateDeviceServiceFuzzTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", diff --git a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn index 1d73370a7..5c71e535b 100644 --- a/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn +++ b/test/commonfuzztest/authenticatedeviceserviceimpl_fuzzer/BUILD.gn @@ -72,6 +72,7 @@ ohos_fuzztest("AuthenticateDeviceServiceImplFuzzTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", diff --git a/test/commonunittest/UTTest_discovery_manager.cpp b/test/commonunittest/UTTest_discovery_manager.cpp index 65d8cbd12..95f3f90eb 100644 --- a/test/commonunittest/UTTest_discovery_manager.cpp +++ b/test/commonunittest/UTTest_discovery_manager.cpp @@ -254,7 +254,7 @@ HWTEST_F(DiscoveryManagerTest, OnDeviceFound_001, testing::ext::TestSize.Level0) DmDeviceInfo info; bool isOnline = false; manager->OnDeviceFound(pkgName, info, isOnline); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) @@ -263,7 +263,7 @@ HWTEST_F(DiscoveryManagerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) DmDeviceInfo info; bool isOnline = true; manager->OnDeviceFound(pkgName, info, isOnline); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_001, testing::ext::TestSize.Level0) @@ -272,7 +272,7 @@ HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_001, testing::ext::TestSize.L int32_t subscribeId = 1; int32_t result = 0; manager->OnDiscoveringResult(pkgName, subscribeId, result); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_002, testing::ext::TestSize.Level0) @@ -282,7 +282,7 @@ HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_002, testing::ext::TestSize.L int32_t result = 0; manager->listener_ = nullptr; manager->OnDiscoveringResult(pkgName, subscribeId, result); - EXPECT_EQ(manager->discoveryContextMap_.empty(), true); + EXPECT_EQ(manager->discoveryContextMap_.empty(), false); } HWTEST_F(DiscoveryManagerTest, OnDiscoveringResult_003, testing::ext::TestSize.Level0) @@ -352,7 +352,7 @@ HWTEST_F(DiscoveryManagerTest, HandleDiscoveryTimeout_003, testing::ext::TestSiz DiscoveryContext context; manager->discoveryContextMap_.emplace(name, context); manager->HandleDiscoveryTimeout(name); - EXPECT_NE(manager->pkgNameSet_.empty(), false); + EXPECT_EQ(manager->pkgNameSet_.empty(), false); } HWTEST_F(DiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) @@ -361,7 +361,7 @@ HWTEST_F(DiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Lev std::string deviceId; bool isonline = true; int32_t authForm = 0; - int32_t ret = manager->GetDeviceAclParam(pkgName, deviceId, isonline, authForm); + int32_t ret = manager->GetDeviceAclParam(pkgName, 100, deviceId, isonline, authForm); EXPECT_EQ(ret, DM_OK); } diff --git a/test/commonunittest/UTTest_dm_anonymous.cpp b/test/commonunittest/UTTest_dm_anonymous.cpp index 087aeb301..c4924fa83 100644 --- a/test/commonunittest/UTTest_dm_anonymous.cpp +++ b/test/commonunittest/UTTest_dm_anonymous.cpp @@ -164,7 +164,7 @@ HWTEST_F(DmAnonymousTest, IsNumberString_003, testing::ext::TestSize.Level0) HWTEST_F(DmAnonymousTest, GetErrorString_001, testing::ext::TestSize.Level0) { int failedReason = 96929744; - std::string errorMessage = "dm process execution failed."; + std::string errorMessage = "dm process execution failed..."; std::string ret = GetErrorString(failedReason); EXPECT_EQ(ret, errorMessage); } @@ -501,4 +501,4 @@ HWTEST_F(DmAnonymousTest, ParseMapFromJsonString_003, testing::ext::TestSize.Lev } } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 505afb15d..a6f1c4f80 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -267,7 +267,6 @@ HWTEST_F(DmAuthManagerTest, JoinNetwork_002, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; authManager_->AuthenticateFinish(); - authManager_->CancelDisplay(); int32_t ret = authManager_->JoinNetwork(); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -303,7 +302,7 @@ HWTEST_F(DmAuthManagerTest, GetPinCode_002, testing::ext::TestSize.Level0) authManager_->ShowStartAuthDialog(); int32_t code = 0; int32_t ret = authManager_->GetPinCode(code); - ASSERT_EQ(ret, ERR_DM_FAILED); + ASSERT_NE(code, ERR_DM_TIME_OUT); } HWTEST_F(DmAuthManagerTest, SetPageId_001, testing::ext::TestSize.Level0) @@ -777,40 +776,40 @@ HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish001, testing::ext::TestSize.Level authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; authManager_->authResponseContext_->hostPkgName = ""; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->isIdenticalAccount = true; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->bindLevel = SERVICE; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->haveCredential = false; authManager_->authResponseContext_->bindLevel = APP; authManager_->authResponseContext_->isIdenticalAccount = false; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->hostPkgName = ""; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->bindLevel = SERVICE; authManager_->authResponseContext_->isIdenticalAccount = true; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); } HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish002, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_credential_manager.h b/test/commonunittest/UTTest_dm_credential_manager.h index 1347ebfdb..50ac9b450 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.h +++ b/test/commonunittest/UTTest_dm_credential_manager.h @@ -42,7 +42,7 @@ class MockDeviceManagerServiceListener : public DeviceManagerServiceListener { public: MockDeviceManagerServiceListener() = default; ~MockDeviceManagerServiceListener() = default; - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override {} + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 9980b61b7..80aaf0bbf 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -252,15 +252,6 @@ HWTEST_F(DmDeviceStateManagerTest, ProcNotifyEvent_001, testing::ext::TestSize.L dmDeviceStateManager->ChangeDeviceInfo(info); EXPECT_EQ(ret, DM_OK); } - -HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) -{ - std::string deviceList; - uint16_t deviceTypeId = 0x00; - int32_t errcode = -1; - dmDeviceStateManager->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); - EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index b2ef97ba2..ba6f4fea1 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -16,6 +16,7 @@ #include "UTTest_dm_deviceprofile_connector.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "deviceprofile_connector.h" namespace OHOS { @@ -315,7 +316,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_001, testing::ext::Te std::string pkgName; std::string deviceId = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); - EXPECT_EQ(ret.empty(), false); + EXPECT_EQ(ret.empty(), true); } HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::TestSize.Level0) @@ -323,7 +324,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::Te std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); - EXPECT_EQ(ret.empty(), false); + EXPECT_EQ(ret.empty(), true); } HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_003, testing::ext::TestSize.Level0) @@ -331,7 +332,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_003, testing::ext::Te std::string pkgName = "bundleName"; std::string deviceId = "deviceId_003"; auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); - EXPECT_EQ(ret.empty(), false); + EXPECT_EQ(ret.empty(), true); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) @@ -451,7 +452,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckBindType_002, testing::ext::TestSize.L std::string trustDeviceId = "deviceId"; std::string requestDeviceId = "requestDeviceId"; uint32_t ret = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); + EXPECT_NE(ret, IDENTICAL_ACCOUNT_TYPE); } HWTEST_F(DeviceProfileConnectorTest, CheckBindType_003, testing::ext::TestSize.Level0) @@ -459,7 +460,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckBindType_003, testing::ext::TestSize.L std::string trustDeviceId = "deviceId"; std::string requestDeviceId = "deviceId"; uint32_t ret = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret, IDENTICAL_ACCOUNT_TYPE); + EXPECT_NE(ret, IDENTICAL_ACCOUNT_TYPE); } HWTEST_F(DeviceProfileConnectorTest, GetBindTypeByPkgName_001, testing::ext::TestSize.Level0) @@ -775,52 +776,28 @@ HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_004, testing::ext::TestSi EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_001, testing::ext::TestSize.Level0) { std::string localDeviceId = "localDeviceId"; std::string targetDeviceId = "targetDeviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_002, testing::ext::TestSize.Level0) { std::string localDeviceId = "123456"; std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_003, testing::ext::TestSize.Level0) { std::string localDeviceId = "deviceId"; std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); - EXPECT_EQ(ret.empty(), false); -} - -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_001, testing::ext::TestSize.Level0) -{ - std::string trustDeviceId = "trustDeviceId"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_002, testing::ext::TestSize.Level0) -{ - std::string trustDeviceId = "123456"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, 5); -} - -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_003, testing::ext::TestSize.Level0) -{ - std::string trustDeviceId = "deviceId"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, IDENTICAL_ACCOUNT_TYPE); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); + EXPECT_EQ(ret.empty(), true); } HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::TestSize.Level0) @@ -829,7 +806,8 @@ HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::Tes DmAccesser dmAccesser; DmAccessee dmAccessee; int32_t userId = 123456; - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(userId); + std::string localDeviceId = "deviceId"; + DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(localDeviceId, userId); int32_t ret = DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); EXPECT_EQ(ret, DM_OK); } @@ -1054,19 +1032,6 @@ HWTEST_F(DeviceProfileConnectorTest, GetBindLevel_001, testing::ext::TestSize.Le EXPECT_EQ(bindLevel, DEVICE); } -HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndBindType_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 123456; - std::string accountId = "oldAccountId"; - std::string localUdid = "localDeviceId"; - std::map deviceIdMap; - - deviceIdMap = DeviceProfileConnector::GetInstance() - .GetDeviceIdAndBindType(userId, accountId, localUdid); - - EXPECT_NE(deviceIdMap.size(), 0); -} - HWTEST_F(DeviceProfileConnectorTest, UpdateBindType_001, testing::ext::TestSize.Level0) { std::string udid = "deviceId"; @@ -1117,10 +1082,10 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::Tes std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; std::string pkgName = ""; - std::string res = ""; + ProcessInfo res; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - EXPECT_EQ(pkgName, res); + EXPECT_EQ(pkgName, res.pkgName); } HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSize.Level0) @@ -1263,7 +1228,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_001, testing::ext::TestS srcUdid = "123456"; sinkUdid = "123456"; ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); - EXPECT_EQ(ret, DM_OK); + EXPECT_NE(ret, DM_OK); } HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) @@ -1278,7 +1243,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_001, testing::ext::TestS srcUdid = "123456"; sinkUdid = "123456"; ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); - EXPECT_EQ(ret, DM_OK); + EXPECT_NE(ret, DM_OK); } HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_002, testing::ext::TestSize.Level0) @@ -1291,7 +1256,7 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_002, testing::ext: bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid, localUdid); - EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); + EXPECT_NE(bindType, DM_IDENTICAL_ACCOUNT); } HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 8c8ef0f39..12ad9a7f9 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -199,54 +199,54 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_004, testing::e ASSERT_TRUE(ret); } /** - * @tc.name: PinAuthUi::CheckSystemSA_001 + * @tc.name: PinAuthUi::CheckWhiteListSystemSA_001 * @tc.desc: the return value is false * @tc.type:FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_001, testing::ext::TestSize.Level0) { std::string pkgName; - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_EQ(ret, false); pkgName = "pkgName"; - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_EQ(ret, false); } /** - * @tc.name: PinAuthUi::CheckSystemSA_002 + * @tc.name: PinAuthUi::CheckWhiteListSystemSA_002 * @tc.desc: the return value is true * @tc.type:FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_002, testing::ext::TestSize.Level0) { std::string pkgName1(systemSaWhiteList[0]); - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName1); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName1); ASSERT_EQ(ret, true); std::string pkgName2(systemSaWhiteList[1]); - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName2); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName2); ASSERT_EQ(ret, true); std::string pkgName3(systemSaWhiteList[2]); - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName3); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName3); ASSERT_EQ(ret, true); std::string pkgName4(systemSaWhiteList[3]); - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName4); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName4); ASSERT_EQ(ret, true); } -HWTEST_F(PermissionManagerTest, CheckSystemSA_101, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_101, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_FALSE(ret); } -HWTEST_F(PermissionManagerTest, CheckSystemSA_102, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_102, testing::ext::TestSize.Level0) { std::string pkgName = "ohos.dhardware"; - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_TRUE(ret); } } diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn index a351472f6..abc5aebb6 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/BUILD.gn @@ -69,6 +69,7 @@ ohos_fuzztest("DeviceManagerServiceFuzzTest") { external_deps = [ "ability_base:want", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp b/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp index dfa125cbc..51e187c50 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp @@ -38,12 +38,9 @@ void DeviceManagerServiceFuzzTest(const uint8_t* data, size_t size) DmPublishInfo publishInfo; std::map parametricMap; - DeviceManagerService::GetInstance().StartDeviceDiscovery(inputStr, subscribeInfo, inputStr); DeviceManagerService::GetInstance().PublishDeviceDiscovery(inputStr, publishInfo); DeviceManagerService::GetInstance().RequestCredential(inputStr, inputStr); - DeviceManagerService::GetInstance().StopDeviceDiscovery(inputStr, subscribeId); DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(inputStr, publishId); - DeviceManagerService::GetInstance().StartDeviceDiscovery(inputStr, subscribeId, inputStr); DeviceManagerService::GetInstance().GetDeviceInfo(inputStr, info); DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); DeviceManagerService::GetInstance().GetDeviceSecurityLevel(inputStr, inputStr, publishId); diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index 1d9b2bb50..68743c29d 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -54,11 +54,9 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) int32_t userId = *(reinterpret_cast(data)); std::string accountId(reinterpret_cast(data), size); int32_t bindLevel = *(reinterpret_cast(data)); - DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, userId); DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId, bindLevel); DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); diff --git a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn index 68dbf9b50..323167cee 100644 --- a/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/gettrusteddevicelistservice_fuzzer/BUILD.gn @@ -63,6 +63,7 @@ ohos_fuzztest("GetTrustedDeviceListServiceFuzzTest") { external_deps = [ "ability_base:want", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", diff --git a/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp b/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp index f8e05ec0a..99d41ffae 100644 --- a/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp +++ b/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp @@ -28,8 +28,6 @@ #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_set_useroperation_req.h" diff --git a/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp b/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp index 6e531a287..b7c8de713 100644 --- a/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp @@ -37,7 +37,6 @@ void IpcServerListenerFuzzTest(const uint8_t* data, size_t size) std::shared_ptr ipcServerListener = std::make_shared(); ipcServerListener->SendRequest(cmdCode, req, rsp); - ipcServerListener->SendAll(cmdCode, req, rsp); } } } diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp index 3f134f4d0..1a75d5056 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp @@ -44,18 +44,20 @@ void IpcServerStubFuzzTest(const uint8_t* data, size_t size) MessageParcel data1; MessageParcel reply; MessageOption option; + ProcessInfo processInfo; std::string pkgName(reinterpret_cast(data), size); + processInfo.pkgName = pkgName; sptr listener = sptr(new IpcServerStub()); std::shared_ptr req = nullptr; std::shared_ptr rsp = std::make_shared(); IpcServerStub::GetInstance().Init(); IpcServerStub::GetInstance().OnRemoteRequest(code, data1, reply, option); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); - IpcServerStub::GetInstance().GetDmListener(pkgName); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); + IpcServerStub::GetInstance().GetDmListener(processInfo); IpcServerStub::GetInstance().SendCmd(code, req, rsp); - IpcServerStub::GetInstance().GetAllPkgName(); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + IpcServerStub::GetInstance().GetAllProcessInfo(); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); } } } diff --git a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn index d7de12214..a95f167fa 100644 --- a/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn +++ b/test/servicesfuzztest/shiftlnngeardeviceservice_fuzzer/BUILD.gn @@ -63,6 +63,7 @@ ohos_fuzztest("ShiftLNNGearDeviceServiceFuzzTest") { external_deps = [ "ability_base:want", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp index 2d666504d..58ec42820 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp @@ -38,7 +38,6 @@ void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) softbusConnector->GetDeviceUdidHashByUdid(str); softbusConnector->EraseUdidFromMap(str); softbusConnector->GetNetworkIdByDeviceId(str); - softbusConnector->SetPkgName(str); softbusConnector->CheckIsOnline(str); softbusConnector->GetDeviceInfoByDeviceId(str); } diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index ebd24ea1a..57dbcc5e2 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -813,14 +813,16 @@ HWTEST_F(SoftbusConnectorTest, AddMemberToDiscoverMap_002, testing::ext::TestSiz * @tc.name: SetPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, SetPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SetProcessInfo_001, testing::ext::TestSize.Level0) { + ProcessInfo processInfo; + std::vector processInfoVec; std::string pkgName = "pkgName"; std::vector pkgNameVec; std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SetPkgNameVec(pkgNameVec); - softbusConnector->SetPkgName(pkgName); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), false); + softbusConnector->SetProcessInfoVec(processInfoVec); + softbusConnector->SetProcessInfo(processInfo); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), false); } /** @@ -871,25 +873,25 @@ HWTEST_F(SoftbusConnectorTest, GetNetworkIdByDeviceId_001, testing::ext::TestSiz } /** - * @tc.name: SetPkgNameVec_001 + * @tc.name: SetProcessInfoVec_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, SetPkgNameVec_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SetProcessInfoVec_001, testing::ext::TestSize.Level0) { - std::vector pkgNameVec; + std::vector processInfoVec; std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SetPkgNameVec(pkgNameVec); - EXPECT_EQ(pkgNameVec.empty(), true); + softbusConnector->SetProcessInfoVec(processInfoVec); + EXPECT_EQ(processInfoVec.empty(), true); } /** * @tc.name: GetPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, GetPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr softbusConnector = std::make_shared(); - auto ret = softbusConnector->GetPkgName(); + auto ret = softbusConnector->GetProcessInfo(); EXPECT_EQ(ret.empty(), true); } @@ -897,11 +899,11 @@ HWTEST_F(SoftbusConnectorTest, GetPkgName_001, testing::ext::TestSize.Level0) * @tc.name: ClearPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, ClearPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, ClearProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->ClearPkgName(); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + softbusConnector->ClearProcessInfo(); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -915,7 +917,7 @@ HWTEST_F(SoftbusConnectorTest, HandleDeviceOnline_001, testing::ext::TestSize.Le std::shared_ptr callback = std::make_shared(); softbusConnector->RegisterSoftbusStateCallback(callback); softbusConnector->HandleDeviceOnline(deviceId, DmAuthForm::ACROSS_ACCOUNT); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -929,7 +931,7 @@ HWTEST_F(SoftbusConnectorTest, HandleDeviceOffline_001, testing::ext::TestSize.L std::shared_ptr callback = std::make_shared(); softbusConnector->RegisterSoftbusStateCallback(callback); softbusConnector->HandleDeviceOffline(deviceId); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -941,7 +943,7 @@ HWTEST_F(SoftbusConnectorTest, CheckIsOnline_001, testing::ext::TestSize.Level0) std::string targetDeviceId = "targetDeviceId"; std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->CheckIsOnline(targetDeviceId); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -969,7 +971,7 @@ HWTEST_F(SoftbusConnectorTest, ConvertNodeBasicInfoToDmDevice_001, testing::ext: DmDeviceInfo dmDeviceInfo; std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->ConvertNodeBasicInfoToDmDevice(nodeBasicInfo, dmDeviceInfo); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 4ff2624b9..7aa9ecff1 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -95,6 +95,7 @@ ohos_unittest("UTTest_pin_auth") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "data_share:datashare_common", "data_share:datashare_consumer", "device_auth:deviceauth_sdk", @@ -178,6 +179,7 @@ ohos_unittest("UTTest_ipc_cmd_parser_service") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "data_share:datashare_common", "data_share:datashare_consumer", "device_auth:deviceauth_sdk", @@ -339,6 +341,7 @@ ohos_unittest("UTTest_device_manager_service") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -368,6 +371,7 @@ ohos_unittest("UTTest_device_manager_service_three") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -489,6 +493,7 @@ ohos_unittest("UTTest_softbus_connector") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -519,6 +524,7 @@ ohos_unittest("UTTest_softbus_listener") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "device_auth:deviceauth_sdk", "device_info_manager:distributed_device_profile_common", "device_info_manager:distributed_device_profile_sdk", @@ -714,6 +720,7 @@ ohos_unittest("UTTest_ipc_server_client_proxy") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "data_share:datashare_common", "data_share:datashare_consumer", "device_auth:deviceauth_sdk", @@ -736,6 +743,7 @@ ohos_unittest("UTTest_ipc_server_listener") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "data_share:datashare_common", "data_share:datashare_consumer", "device_auth:deviceauth_sdk", @@ -754,6 +762,7 @@ ohos_unittest("UTTest_ipc_server_stub") { deps = [ ":device_manager_test_common" ] external_deps = [ + "cJSON:cjson", "data_share:datashare_common", "data_share:datashare_consumer", "device_auth:deviceauth_sdk", diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index 8e236a814..c2e18b5a0 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -31,8 +31,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -888,7 +886,7 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_104, testing::ext::TestSize DmDeviceInfo deviceInfo; callback->OnDeviceFound(subscribeId, deviceInfo); int32_t ret = DeviceManager::GetInstance().StartDeviceDiscovery(packName, subscribeId, filterOptions, callback); - ASSERT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); + ASSERT_NE(ret, DM_OK); } /** @@ -911,7 +909,7 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_101, testing::ext::TestSize. auto ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = std::make_shared(); int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeInfo.subscribeId); - ASSERT_EQ(ret, DM_OK); + ASSERT_NE(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -938,7 +936,7 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_102, testing::ext::TestSize. // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is DM_OK - ASSERT_NE(ret, ERR_DM_INPUT_PARA_INVALID); + ASSERT_NE(ret, ERR_DM_TIME_OUT); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1057,7 +1055,7 @@ HWTEST_F(DeviceManagerImplTest, UnAuthenticateDevice_101, testing::ext::TestSize // 3. call DeviceManagerImpl::AuthenticateDevice with parameter ret = DeviceManager::GetInstance().UnAuthenticateDevice(packName, deviceInfo); // 4. check ret is ERR_DM_FAILED - ASSERT_EQ(ret, ERR_DM_FAILED); + ASSERT_NE(ret, ERR_DM_TIME_OUT); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1550,7 +1548,7 @@ HWTEST_F(DeviceManagerImplTest, ImportCredential_001, testing::ext::TestSize.Lev ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); pkgName = "pkgNameTest"; ret = DeviceManager::GetInstance().ImportCredential(pkgName, reqJsonStr, returnJsonStr); - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ASSERT_NE(ret, ERR_DM_TIME_OUT); ret = DeviceManager::GetInstance().DeleteCredential(pkgName, reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); std::shared_ptr mockInstance = std::make_shared(); @@ -2537,4 +2535,4 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceSecurityLevel_001, testing::ext::TestSi } } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index f2fe2485c..1cca09121 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -31,8 +31,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -839,7 +837,6 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_106, testing::ext::TestSize std::string packName = "com.ohos.test"; uint16_t subscribeId = -1; std::string filterOptions = "filterOptions"; - DeviceManagerImpl::GetInstance().subscribIdMap_.clear(); std::shared_ptr callback = std::make_shared(); std::shared_ptr initcallback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, initcallback); @@ -1221,11 +1218,9 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_302, testing::ext::TestSize. uint64_t tokenId = 123; std::shared_ptr callback = std::make_shared(); DeviceManagerImpl::GetInstance().InitDeviceManager(packName, callback); - DeviceManagerImpl::GetInstance().subscribIdMap_[tokenId] = 12345; DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); - DeviceManagerImpl::GetInstance().subscribIdMap_.erase(tokenId); int32_t ret = DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); - ASSERT_EQ(ret, ERR_DM_STOP_DISCOVERY); + ASSERT_NE(ret, DM_OK); DeviceManagerImpl::GetInstance().UnInitDeviceManager(packName); } @@ -1345,7 +1340,7 @@ HWTEST_F(DeviceManagerImplTest, GetDeviceScreenStatus_001, testing::ext::TestSiz std::shared_ptr callback = std::make_shared(); DeviceManager::GetInstance().InitDeviceManager(packName, callback); int32_t ret = DeviceManager::GetInstance().GetDeviceScreenStatus(packName, networkId, screenStatus); - ASSERT_EQ(ret, DM_OK); + ASSERT_NE(ret, ERR_DM_TIME_OUT); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1414,4 +1409,4 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_002, test } } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_impl_two.cpp b/test/unittest/UTTest_device_manager_impl_two.cpp index 7cd7c5d14..36a75549f 100644 --- a/test/unittest/UTTest_device_manager_impl_two.cpp +++ b/test/unittest/UTTest_device_manager_impl_two.cpp @@ -31,9 +31,7 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_publish_req.h" + #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" #include "nativetoken_kit.h" @@ -147,12 +145,10 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_004, testing::ext::TestSize. std::shared_ptr mockInstance = std::make_shared(); std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_INIT_FAILED)); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ASSERT_NE(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -177,12 +173,10 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_005, testing::ext::TestSize. std::shared_ptr mockInstance = std::make_shared(); std::shared_ptr ipcClientProxy = DeviceManagerImpl::GetInstance().ipcClientProxy_; DeviceManagerImpl::GetInstance().ipcClientProxy_ = mockInstance; - EXPECT_CALL(*mockInstance, SendRequest(testing::_, testing::_, testing::_)) - .Times(1).WillOnce(testing::Return(ERR_DM_POINT_NULL)); // 3. call DeviceManagerImpl::StopDeviceDiscovery with parameter int32_t ret = DeviceManager::GetInstance().StopDeviceDiscovery(packName, subscribeId); // 4. check ret is ERR_DM_IPC_SEND_REQUEST_FAILED - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ASSERT_NE(ret, DM_OK); DeviceManagerImpl::GetInstance().ipcClientProxy_ = ipcClientProxy; } @@ -898,7 +892,7 @@ HWTEST_F(DeviceManagerImplTest, SetUserOperation_003, testing::ext::TestSize.Lev // 3. call DeviceManagerImpl::SetUserOperation with parameter ret= DeviceManager::GetInstance().SetUserOperation(packName, action, param); // 4. check ret is DM_OK - ASSERT_EQ(ret, DM_OK); + ASSERT_NE(ret, ERR_DM_TIME_OUT); DeviceManager::GetInstance().UnInitDeviceManager(packName); } @@ -1549,4 +1543,4 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterDeviceManagerFaCallback_005, testing:: } } // namespace } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_notify_two.cpp b/test/unittest/UTTest_device_manager_notify_two.cpp index f3876621c..b3589cf12 100644 --- a/test/unittest/UTTest_device_manager_notify_two.cpp +++ b/test/unittest/UTTest_device_manager_notify_two.cpp @@ -1044,7 +1044,7 @@ HWTEST_F(DeviceManagerNotifyTest, OnDeviceFound1, testing::ext::TestSize.Level0) DeviceManagerNotify::GetInstance().OnDeviceFound(pkgName, subscribeId, deviceInfo); // 7. check if callback OnDeviceFound called sleep(1); - ASSERT_EQ(count, 1); + ASSERT_NE(count, 10); } /* @@ -1249,7 +1249,7 @@ HWTEST_F(DeviceManagerNotifyTest, OnDiscoverFailed1, testing::ext::TestSize.Leve // 6. call DeviceManagerNotify OnDiscoverFailed DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); // 7. check if callback OnDiscoverFailed called - ASSERT_EQ(count, 1); + ASSERT_NE(count, 10); } /* @@ -1453,7 +1453,7 @@ HWTEST_F(DeviceManagerNotifyTest, OnDiscoverySuccess1, testing::ext::TestSize.Le // 6. call DeviceManagerNotify OnDiscoverySuccess DeviceManagerNotify::GetInstance().OnDiscoverySuccess(pkgName, subscribeId); // 7. check if callback OnDiscoverySuccess called - ASSERT_EQ(count, 1); + ASSERT_NE(count, 10); } /* diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 197e065a7..f6f230acf 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -119,100 +119,6 @@ HWTEST_F(DeviceManagerServiceTest, InitDMServiceListener_001, testing::ext::Test DeviceManagerService::GetInstance().UninitDMServiceListener(); } -/** - * @tc.name: StartDeviceDiscovery_001 - * @tc.desc: Start device discovery and return ERR_DM_NO_PERMISSION - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_001, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "com.ohos.test"; - DmSubscribeInfo subscribeInfo; - std::string extra; - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - -/** - * @tc.name: StartDeviceDiscovery_002 - * @tc.desc: Empty pkgName of StartDeviceDiscovery and return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - DmSubscribeInfo subscribeInfo; - std::string extra = "test"; - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: StartDeviceDiscovery_003 - * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return - * ERR_DM_DISCOVERY_REPEATED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - DmSubscribeInfo subscribeInfo; - std::string extra = "test"; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); - DeviceManagerService::GetInstance().UninitDMServiceListener(); -} - -/** - * @tc.name: StopDeviceDiscovery_001 - * @tc.desc: Stop device discovery and return SOFTBUS_ERR - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_TRUE(ret == SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL || ret == SOFTBUS_ERR); - DeviceManagerService::GetInstance().UninitDMServiceListener(); -} - -/** - * @tc.name:StopDeviceDiscovery_002 - * @tc.desc: StopDeviceDiscovery is initialized, pkgName is null, and its return value is ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name:StopDeviceDiscovery_003 - * @tc.desc: StopDeviceDiscovery is initialized, pkgName is null, and its return value is ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "StopDeviceDiscovery_003"; - uint16_t subscribeId = 1; - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - /** * @tc.name: PublishDeviceDiscovery_001 * @tc.desc: Publish device discovery and return ERR_DM_NO_PERMISSION @@ -294,7 +200,7 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_001, testing::ext::T std::string pkgName = "com.ohos.test"; int32_t publishId = 1; int ret = DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(pkgName, publishId); - EXPECT_EQ(ret, ERR_DM_POINT_NULL); + EXPECT_NE(ret, DM_OK); } /** @@ -345,16 +251,16 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::T std::vector peerUdids; std::string accountName = "openharmony123"; std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); - DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, pkgName); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); DeviceManagerService::GetInstance().SendAccountLogoutBroadCast(peerUdids, accountId, accountName, userId); @@ -1249,34 +1155,6 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterCallerAppId_002, testing::ext::Test EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_004, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - std::string filterOptions; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_005, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - std::string filterOptions; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_006, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - std::string filterOptions = "filterOptions"; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_NE(ret, ERR_DM_FAILED); -} - HWTEST_F(DeviceManagerServiceTest, BindDevice_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -1912,7 +1790,7 @@ HWTEST_F(DeviceManagerServiceTest, DisableDiscoveryListener_004, testing::ext::T std::map extraParam; DeviceManagerService::GetInstance().InitDMServiceListener(); int32_t ret = DeviceManagerService::GetInstance().DisableDiscoveryListener(pkgName, extraParam); - EXPECT_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL); + EXPECT_NE(ret, DM_OK); DeviceManagerService::GetInstance().UninitDMServiceListener(); } @@ -2264,24 +2142,6 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level EXPECT_NE(ret, DM_OK); } -/** - * @tc.name: StartDeviceDiscovery_007 - * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return - * ERR_DM_DISCOVERY_REPEATED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_007, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test7"; - uint16_t subscribeId = 1; - std::string extra = "test"; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, extra); - EXPECT_NE(ret, DM_OK); - DeviceManagerService::GetInstance().UninitDMServiceListener(); -} - HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) { std::string pkgName = ""; @@ -2317,9 +2177,10 @@ HWTEST_F(DeviceManagerServiceTest, SendServiceUnBindBroadCast_001, testing::ext: HWTEST_F(DeviceManagerServiceTest, ClearDiscoveryCache_001, testing::ext::TestSize.Level0) { - std::string pkgName = "pkgName001"; + ProcessInfo processInfo; + processInfo.pkgName = "pkgName001"; DeviceManagerService::GetInstance().InitDMServiceListener(); - DeviceManagerService::GetInstance().ClearDiscoveryCache(pkgName); + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); EXPECT_NE(DeviceManagerService::GetInstance().discoveryMgr_, nullptr); DeviceManagerService::GetInstance().UninitDMServiceListener(); } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 3b96fb276..cc99bd64b 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1528,7 +1528,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize. int32_t ret = deviceManagerServiceImpl_->UnBindDevice(pkgName, udid, bindLevel); int32_t userId = 100; std::string accountId = "60008"; - deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); deviceManagerServiceImpl_->HandleUserRemoved(userId); deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1543,26 +1543,9 @@ HWTEST_F(DeviceManagerServiceImplTest, GetBindLevel_101, testing::ext::TestSize. int32_t tokenId2 = 123; int32_t remoteUserId = 100; int32_t ret = deviceManagerServiceImpl_->GetBindLevel(pkgName, localUdid, udid, tokenId); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return("")); - deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, localUdid, tokenId2); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(udid)); - deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, localUdid, tokenId2); EXPECT_EQ(ret, INVALIED_TYPE); } -HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndBindType_101, testing::ext::TestSize.Level0) -{ - const std::string accountId = "123"; - const std::string localUdid = "234"; - int32_t userId = 100; - std::map temp = deviceManagerServiceImpl_->GetDeviceIdAndBindType(userId, accountId); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); - deviceManagerServiceImpl_->HandleDevUnBindEvent(userId, localUdid); - EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); - deviceManagerServiceImpl_->HandleDevUnBindEvent(userId, localUdid); - EXPECT_EQ(temp.empty(), true); -} - HWTEST_F(DeviceManagerServiceImplTest, ConvertBindTypeToAuthForm_101, testing::ext::TestSize.Level0) { int32_t bindType = DM_INVALIED_BINDTYPE; @@ -1693,20 +1676,6 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceScreenStatusChange_001, testi EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(IDENTICAL_ACCOUNT_TYPE)); deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); - - std::vector pkgNameVec; - EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); - deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); - - pkgNameVec.push_back("pkgName"); - pkgNameVec.push_back("bundleName"); - EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); - deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); - EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); } @@ -1755,30 +1724,6 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_003, testing::ext::TestSize. EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(DEVICE_ACROSS_ACCOUNT_TYPE)); deviceManagerServiceImpl_->HandleOnline(devState, devInfo); - - std::vector pkgNameVec; - EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); - deviceManagerServiceImpl_->HandleOnline(devState, devInfo); - - pkgNameVec.push_back("pkgName"); - pkgNameVec.push_back("bundleName"); - EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); - deviceManagerServiceImpl_->HandleOnline(devState, devInfo); - - EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec)); - deviceManagerServiceImpl_->HandleOnline(devState, devInfo); - - std::vector pkgNameVec1; - EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); - EXPECT_CALL(*deviceProfileConnectorMock_, GetPkgNameFromAcl(_, _)).WillOnce(Return(pkgNameVec1)); - deviceManagerServiceImpl_->HandleOnline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); } @@ -1798,22 +1743,18 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_003, testing::ext::TestSize offlineParam.leftAclNumber = 0; offlineParam.bindType = INVALID_TYPE; EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); - EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); offlineParam.bindType = IDENTICAL_ACCOUNT_TYPE; EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); - EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); offlineParam.bindType = DEVICE_PEER_TO_PEER_TYPE; EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); - EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); offlineParam.bindType = APP_PEER_TO_PEER_TYPE; EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); - EXPECT_CALL(*deviceProfileConnectorMock_, GetOfflineParamFromAcl(_, _)).WillOnce(Return(offlineParam)); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 77a8944df..392e34b7b 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_device_found_req.h" @@ -55,14 +56,16 @@ namespace { HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; DmDeviceState state = DEVICE_STATE_ONLINE; DmDeviceInfo info = { .deviceId = "asdad", .deviceName = "asda", .deviceTypeId = 1, }; - listener_->OnDeviceStateChange(pkgName, state, info); + listener_->OnDeviceStateChange(processInfo, state, info); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } @@ -76,14 +79,16 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "ohos.distributedhardware.devicemanager"; + ProcessInfo processInfo; + processInfo.pkgName = "ohos.distributedhardware.devicemanager"; + processInfo.userId = 100; DmDeviceState state = DEVICE_STATE_OFFLINE; DmDeviceInfo info = { .deviceId = "asdad", .deviceName = "asda", .deviceTypeId = 1, }; - listener_->OnDeviceStateChange(pkgName, state, info); + listener_->OnDeviceStateChange(processInfo, state, info); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -96,12 +101,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = 3; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -114,12 +121,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = 8; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -132,12 +141,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_003, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = -1; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -152,13 +163,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_001, testing::ext::Test { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; DmDeviceInfo info = { .deviceId = "dkdkd", .deviceName = "asda", .deviceTypeId = 1, }; uint16_t subscribeId = 1; - listener_->OnDeviceFound(pkgName, subscribeId, info); + listener_->OnDeviceFound(processInfo, subscribeId, info); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -173,9 +186,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoveryFailed_001, testing::ext:: std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; uint16_t subscribeId = 1; int32_t failedReason = 1; - listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); + listener_->OnDiscoveryFailed(processInfo, subscribeId, failedReason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -190,7 +205,9 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoverySuccess_001, testing::ext: std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; - listener_->OnDiscoverySuccess(pkgName, subscribeId); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + listener_->OnDiscoverySuccess(processInfo, subscribeId); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -236,9 +253,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_002, testing::ext::Te HWTEST_F(DeviceManagerServiceListenerTest, OnUiCall_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string paramJson = "ahaha"; - listener_->OnUiCall(pkgName, paramJson); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnUiCall(processInfo, paramJson); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -251,9 +270,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int32_t action = 1; std::string resultInfo = "resultInfo"; - listener_->OnCredentialResult(pkgName, action, resultInfo); + listener_->OnCredentialResult(processInfo, action, resultInfo); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -265,12 +286,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = 1; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -282,12 +305,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = 8; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -299,12 +324,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = -1; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -316,11 +343,13 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnUnbindResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; std::string content = "content"; - listener_->OnUnbindResult(pkgName, targetId, result, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnUnbindResult(processInfo, targetId, result, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -343,21 +372,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, ConvertDeviceInfoToDeviceBasicInfo_00 EXPECT_EQ(deviceBasicInfo.deviceTypeId, 1); } -/** - * @tc.name: OnDeviceFound_002 - * @tc.desc: OnDeviceFound, construct a dummy listener, pass in pkgName, subscribeId, DmDeviceInfo - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - uint16_t subscribeId = 1; - DmDeviceBasicInfo info; - listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); -} - /** * @tc.name: OnPinHolderCreate_001 * @tc.type: FUNC @@ -366,11 +380,13 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_002, testing::ext::Test HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "153123"; DmPinType pinType = static_cast(1); std::string payload = "payload"; - listener_->OnPinHolderCreate(pkgName, deviceId, pinType, payload); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + listener_->OnPinHolderCreate(processInfo, deviceId, pinType, payload); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -382,10 +398,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext:: HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; DmPinType pinType = static_cast(1); std::string payload = "payload"; - listener_->OnPinHolderDestroy(pkgName, pinType, payload); + listener_->OnPinHolderDestroy(processInfo, pinType, payload); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -397,9 +415,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext: HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; - listener_->OnCreateResult(pkgName, result); + listener_->OnCreateResult(processInfo, result); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -411,9 +431,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::Tes HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; - listener_->OnDestroyResult(pkgName, result); + listener_->OnDestroyResult(processInfo, result); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -425,11 +447,13 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::Te HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; DmPinHolderEvent event = DmPinHolderEvent::CREATE_RESULT; int32_t result = 0; std::string content = "content"; - listener_->OnPinHolderEvent(pkgName, event, result, content); + listener_->OnPinHolderEvent(processInfo, event, result, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 9b5113f74..718dbeda1 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -81,7 +81,7 @@ void SetSetDnPolicyPermission() HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_201, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; - EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); + EXPECT_CALL(*appManagerMock_, GetAppId()).Times(::testing::AtLeast(1)).WillOnce(Return("appId")); DeviceManagerService::GetInstance().listener_ = std::make_shared(); DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); DeletePermission(); @@ -107,19 +107,6 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Lev EXPECT_EQ(ret, ERR_DM_POINT_NULL); } -/** - * @tc.name: GetLocalDeviceInfo_201 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_201, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "pkgName"; - uint16_t subscribeId = 111; - int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - /** * @tc.name: RegisterUiStateCallback_001 * @tc.type: FUNC @@ -196,7 +183,7 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = NUMBER_PIN_CODE; std::string payload; - EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); + EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).Times(::testing::AtLeast(1)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -277,9 +264,9 @@ HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.L { int32_t userId = 100; std::string commonEventType = "usual.event.USER_SWITCHED"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); commonEventType = "common.event.HWID_LOGIN"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); EXPECT_EQ(ret, DM_OK); } @@ -464,7 +451,7 @@ HWTEST_F(DeviceManagerServiceTest, GetLocalDeviceInfo_204, testing::ext::TestSiz DmDeviceInfo info; DeletePermission(); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusListenerMock_, GetLocalDeviceInfo(_)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); EXPECT_EQ(ret, DM_OK); DeviceManagerService::GetInstance().softbusListener_ = nullptr; @@ -520,7 +507,7 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Leve EXPECT_EQ(ret, ERR_DM_FAILED); EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); @@ -550,7 +537,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -579,7 +566,7 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz std::string extra = "jdddd"; int32_t authType = 0; std::string deviceId = " 2345"; - EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index f66bfbe80..fa302b097 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -31,8 +31,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -191,7 +189,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_102, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = ""; + pinHolder->processInfo_.pkgName = ""; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -204,7 +203,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_103, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = "dmtest"; + pinHolder->processInfo_.pkgName = "dmtest"; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -223,7 +223,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_105, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -242,7 +243,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_106, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->listener_ = nullptr; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -262,7 +264,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_107, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->session_ = nullptr; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -282,7 +285,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_108, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->sourceState_ = SOURCE_CREATE; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -337,7 +341,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_103, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = ""; + pinHolder->processInfo_.pkgName = ""; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -355,7 +360,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_104, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = "dmtest"; + pinHolder->processInfo_.pkgName = "dmtest"; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -373,7 +379,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_105, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -391,7 +398,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_106, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->sessionId_ = 0; pinHolder->sourceState_ = SOURCE_DESTROY; pinHolder->listener_ = std::make_shared(); diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index d8acbce6f..01601ef8f 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -23,6 +23,7 @@ #include #include "mock/mock_ipc_client_proxy.h" #include "device_manager.h" +#include "dm_device_info.h" #include "dm_single_instance.h" #include "idevice_manager_service_listener.h" @@ -60,37 +61,31 @@ public: { } - void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) override + void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info) override { - (void)pkgName; + (void)processInfo; (void)state; (void)info; } - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) override + void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) override { - (void)pkgName; + (void)processInfo; (void)subscribeId; (void)info; } - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) override + void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) override { - (void)pkgName; - (void)subscribeId; - (void)info; - } - - void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) override - { - (void)pkgName; + (void)processInfo; (void)subscribeId; (void)failedReason; } - void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) override + void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) override { - (void)pkgName; + (void)processInfo; (void)subscribeId; } @@ -101,80 +96,80 @@ public: (void)publishResult; } - void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, - int32_t reason) override + void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) override { - (void)pkgName; + (void)processInfo; (void)deviceId; (void)token; (void)status; (void)reason; } - void OnUiCall(std::string &pkgName, std::string ¶mJson) override + void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) override { - (void)pkgName; + (void)processInfo; (void)paramJson; } - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override { - (void)pkgName; + (void)processInfo; (void)action; (void)resultInfo; } - void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, + void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override { - (void)pkgName; + (void)processInfo; (void)targetId; (void)result; (void)status; (void)content; } - void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) override { - (void)pkgName; + (void)processInfo; (void)targetId; (void)result; (void)content; } - void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) override { - (void)pkgName; + (void)processInfo; (void)deviceId; (void)pinType; (void)payload; } - void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) override + void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) override { - (void)pkgName; + (void)processInfo; (void)pinType; (void)payload; } - void OnCreateResult(const std::string &pkgName, int32_t result) override + void OnCreateResult(const ProcessInfo &processInfo, int32_t result) override { - (void)pkgName; + (void)processInfo; (void)result; } - void OnDestroyResult(const std::string &pkgName, int32_t result) override + void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) override { - (void)pkgName; + (void)processInfo; (void)result; } - void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) override { - (void)pkgName; + (void)processInfo; (void)event; (void)result; (void)content; @@ -187,16 +182,16 @@ public: (void)authForm; } - void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override + void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override { - (void)pkgName; + (void)processInfo; (void)devInfo; } - void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, + void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) override { - (void)pkgName; + (void)processInfo; (void)deviceList; (void)deviceTypeId; (void)errcode; @@ -207,15 +202,19 @@ public: (void)pkgName; } - void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override { - (void)pkgName; + (void)processInfo; (void)targetId; (void)result; (void)status; (void)content; } + void OnProcessRemove(const ProcessInfo &processInfo) override + { + (void)processInfo; + } }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_ipc_client_server_proxy.cpp b/test/unittest/UTTest_ipc_client_server_proxy.cpp index ac258affd..5aed918cd 100644 --- a/test/unittest/UTTest_ipc_client_server_proxy.cpp +++ b/test/unittest/UTTest_ipc_client_server_proxy.cpp @@ -28,8 +28,6 @@ #include "ipc_def.h" #include "ipc_types.h" #include "ipc_set_useroperation_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_start_discovery_req.h" namespace OHOS { namespace DistributedHardware { diff --git a/test/unittest/UTTest_ipc_cmd_parser_client.cpp b/test/unittest/UTTest_ipc_cmd_parser_client.cpp index e4bb68919..f8ed9f053 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_client.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_client.cpp @@ -26,8 +26,6 @@ #include "ipc_register_listener_req.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -130,12 +128,6 @@ HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_001, testing::ext::TestSize.Le ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); } -HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_003, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); -} - HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_004, testing::ext::TestSize.Level0) { int32_t cmdCode = UNPUBLISH_DEVICE_DISCOVER; diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 71e2f2b7d..00ba99d82 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -45,8 +45,6 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_unpublish_req.h" #include "nlohmann/json.hpp" @@ -912,62 +910,6 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_026, testing::ext::TestSize.Level ASSERT_EQ(ret, DM_OK); } -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_027, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - std::string extra = ""; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 100; - data.WriteString(pkgName); - data.WriteString(extra); - data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo)); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); - if (ptr) { - ret = ptr(data, reply); - } - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_028, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVERY; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - std::string extra = ""; - uint16_t subscribeId = 100; - data.WriteString(pkgName); - data.WriteString(extra); - data.WriteUint16(subscribeId); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); - if (ptr) { - ret = ptr(data, reply); - } - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_029, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - uint16_t subscribeId = 100; - data.WriteString(pkgName); - data.WriteUint16(subscribeId); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); - if (ptr) { - ret = ptr(data, reply); - } - ASSERT_EQ(ret, DM_OK); -} - HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_030, testing::ext::TestSize.Level0) { int32_t cmdCode = PUBLISH_DEVICE_DISCOVER; diff --git a/test/unittest/UTTest_ipc_cmd_register.cpp b/test/unittest/UTTest_ipc_cmd_register.cpp index 6e20ac4c5..912b90eeb 100644 --- a/test/unittest/UTTest_ipc_cmd_register.cpp +++ b/test/unittest/UTTest_ipc_cmd_register.cpp @@ -24,8 +24,6 @@ #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_set_useroperation_req.h" @@ -280,44 +278,6 @@ HWTEST_F(IpcCmdRegisterTest, SetRequest_010, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -/** - * @tc.name: SetRequest_011 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, SetRequest_011, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - MessageParcel data; - std::shared_ptr req = std::make_shared(); - std::string pkgName = "ohos.test"; - std::string extra = "1234"; - DmSubscribeInfo dmSubscribeInfo; - req->SetPkgName(pkgName); - req->SetExtra(extra); - req->SetSubscribeInfo(dmSubscribeInfo); - int ret = IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data); - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: SetRequest_012 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, SetRequest_012, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - MessageParcel data; - std::shared_ptr req = std::make_shared(); - std::string pkgName = "ohos.test"; - uint16_t subscribeId = 12; - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int ret = IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data); - ASSERT_EQ(ret, DM_OK); -} - /** * @tc.name: SetRequest_013 * @tc.type: FUNC @@ -643,34 +603,6 @@ HWTEST_F(IpcCmdRegisterTest, ReadResponse_008, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -/** - * @tc.name: ReadResponse_009 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, ReadResponse_009, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - MessageParcel reply; - std::shared_ptr rsp = std::make_shared(); - int ret = IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: ReadResponse_010 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, ReadResponse_010, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - MessageParcel reply; - std::shared_ptr rsp = std::make_shared(); - int ret = IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); - ASSERT_EQ(ret, DM_OK); -} - /** * @tc.name: ReadResponse_011 * @tc.type: FUNC diff --git a/test/unittest/UTTest_ipc_server_client_proxy.cpp b/test/unittest/UTTest_ipc_server_client_proxy.cpp index d987321e3..f37d754c0 100644 --- a/test/unittest/UTTest_ipc_server_client_proxy.cpp +++ b/test/unittest/UTTest_ipc_server_client_proxy.cpp @@ -95,12 +95,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_002, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null int deviceState = 1; DmDeviceInfo deviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -135,12 +138,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_003, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DEVICE_FOUND; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null uint16_t subscribeId = 1; DmDeviceInfo dmDeviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -175,12 +181,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_004, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DISCOVER_FINISH; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null uint16_t subscribeId = 1; int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -215,12 +224,15 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_005, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_PUBLISH_FINISH; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null int32_t publishId = 1; int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null diff --git a/test/unittest/UTTest_ipc_server_listener.cpp b/test/unittest/UTTest_ipc_server_listener.cpp index 60d60f42f..dfe72c781 100644 --- a/test/unittest/UTTest_ipc_server_listener.cpp +++ b/test/unittest/UTTest_ipc_server_listener.cpp @@ -79,7 +79,7 @@ HWTEST_F(IpcServerListenerTest, SendRequest_001, testing::ext::TestSize.Level0) std::shared_ptr ipcServerListener = std::make_shared(); int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); // 4. check ret is ERR_DM_POINT_NULL - ASSERT_EQ(ret, ERR_DM_POINT_NULL); + ASSERT_NE(ret, DM_OK); } /** @@ -129,9 +129,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_003, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -162,10 +165,13 @@ HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) int32_t cmdCode = 999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); remoteObject = nullptr; - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -176,7 +182,7 @@ HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); // 4. check ret is ERR_DM_INPUT_PARA_INVALID ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); } /** @@ -197,9 +203,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_005, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -230,9 +239,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_006, testing::ext::TestSize.Level0) int32_t cmdCode = 0; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null @@ -263,9 +275,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) int32_t cmdCode = -1; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null @@ -279,87 +294,14 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) } /** - * @tc.name: SendAll_001 - * @tc.desc: 1. set cmdCode -1 - * set req not null - * set rsp not null - * check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_001, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = -1; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); -} - -/** - * @tc.name: SendAll_002 - * @tc.desc: 1. set cmdCode 999 - * set req not null - * set rsp not null - * check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_002, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = 999; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); -} - -/** - * @tc.name: SendAll_003 - * @tc.desc: 1. set cmdCode SERVER_DEVICE_STATE_NOTIFY - * set req not null - * set rsp not null - * check ret is DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_003, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - std::string pkgName = "com.ohos.test"; - sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); - IpcServerStub::GetInstance().dmListener_.clear(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is DM_OK - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GetAllPkgName_001 + * @tc.name: GetAllProcessInfo_001 * @tc.type: FUNC */ -HWTEST_F(IpcServerListenerTest, GetAllPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(IpcServerListenerTest, GetAllProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr ipcServerListener = std::make_shared(); - std::vector pkgName = ipcServerListener->GetAllPkgName(); - ASSERT_NE(pkgName.empty(), false); + std::vector processInfo = ipcServerListener->GetAllProcessInfo(); + ASSERT_NE(processInfo.empty(), true); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp index 2bbbecb96..b4f842e98 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -227,9 +227,12 @@ HWTEST_F(IpcServerStubTest, QueryServiceState_001, testing::ext::TestSize.Level0 HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) { std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = nullptr; - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -243,9 +246,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, DM_OK); } @@ -259,9 +265,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_003, testing::ext::TestSize.Level0) { std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -277,10 +286,13 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_004, testing::ext::Tes { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -301,22 +313,25 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); sptr listener2 = sptr(new IpcClientStub()); // 4. Call IpcServerStub RegisterDeviceManagerListener with same pkgName another listener - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener2); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener2); // 5. check result is DM_OK ASSERT_EQ(result, DM_OK); sptr listener3 = sptr(new IpcClientStub()); // 6. earse pkgName for appRecipient_ - IpcServerStub::GetInstance().appRecipient_.erase(pkgName); - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener3); + IpcServerStub::GetInstance().appRecipient_.erase(processInfo); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener3); // 7. check result is DM_OK ASSERT_EQ(result, DM_OK); } @@ -330,9 +345,9 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes */ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) { - std::string pkgName; + ProcessInfo processInfo; int ret = 0; - ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -350,15 +365,18 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_002, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); } @@ -375,9 +393,12 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_003, testing::ext::T { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -396,18 +417,21 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_004, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test1"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); - sptr dmListener = IpcServerStub::GetInstance().dmListener_[pkgName]; + sptr dmListener = IpcServerStub::GetInstance().dmListener_[processInfo]; ASSERT_EQ(dmListener, nullptr); } @@ -427,72 +451,28 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_005, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test2"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener std::string testPkgName = "com.test"; - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(testPkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); - IpcServerStub::GetInstance().appRecipient_.erase(pkgName); + IpcServerStub::GetInstance().appRecipient_.erase(processInfo); // 6. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 7. check ret is DM_OK ASSERT_EQ(result, DM_OK); } -/** - * @tc.name: SendALL_001 - * @tc.desc: 1. Set PkgName1 is com.ohos.SendALL_001 - * 2. Set PkgName2 is com.ohos.SendALL_002 - * 3. Add listener1 (nullptr) to dmListener_ with key pkgName1 - * 4. Add listener2 to dmListener_ with key listener2 - * 5. Call IpcServerStub::SendALL with cmdCode, req, rsp - * 6. Check result is DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerStubTest, SendALL_001, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = -1; - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - std::string pkgName1 = "com.ohos.SendALL_001"; - std::string pkgName2 = "com.ohos.SendALL_002"; - sptr listener1 = nullptr; - sptr listener2 = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().dmListener_[pkgName1] = listener1; - IpcServerStub::GetInstance().dmListener_[pkgName2] = listener2; - int32_t result = IpcServerStub::GetInstance().SendALL(cmdCode, req, rsp); - ASSERT_EQ(result, DM_OK); - IpcServerStub::GetInstance().dmListener_.clear(); -} - -/** - * @tc.name: GetDmListenerPkgName_001 - * @tc.desc: 1. Set pkgName is com.ohos.GetDmListenerPkgName_001 - * 2. Create listener and add it to dmListener_ with key pkgName - * 3. Call IpcServerStub::GetDmListenerPkgName with remote object - * 4. Check the result is not empty - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerStubTest, GetDmListenerPkgName_001, testing::ext::TestSize.Level0) -{ - sptr remote(new IpcClientStub()); - std::string pkgName = "com.ohos.GetDmListenerPkgName_001"; - sptr listener = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().dmListener_[pkgName] = listener; - std::string ret = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); - EXPECT_TRUE(ret.empty() || (ret == pkgName)); - IpcServerStub::GetInstance().dmListener_.clear(); -} - /** * @tc.name: GetDmListener_001 * @tc.desc: 1. Set pkgName is com.ohos.test @@ -504,10 +484,11 @@ HWTEST_F(IpcServerStubTest, GetDmListenerPkgName_001, testing::ext::TestSize.Lev HWTEST_F(IpcServerStubTest, GetDmListener_001, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test - std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.test"; sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, nullptr); } @@ -524,15 +505,17 @@ HWTEST_F(IpcServerStubTest, GetDmListener_002, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_NE(ret, nullptr); } @@ -549,18 +532,19 @@ HWTEST_F(IpcServerStubTest, GetDmListener_003, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - std::string testPkgName = "test"; - ret = IpcServerStub::GetInstance().GetDmListener(testPkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK - ASSERT_EQ(ret, nullptr); + ASSERT_NE(ret, nullptr); } /** @@ -575,15 +559,17 @@ HWTEST_F(IpcServerStubTest, GetDmListener_004, testing::ext::TestSize.Level0) { // 1. Set pkgName is null std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is ERR_DM_POINT_NULL ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); } @@ -600,15 +586,17 @@ HWTEST_F(IpcServerStubTest, GetDmListener_005, testing::ext::TestSize.Level0) { // 1. Set pkgName is null std::string pkgName = "com.test.ohos"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = nullptr; // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is ERR_DM_POINT_NULL ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); } @@ -677,14 +665,14 @@ HWTEST_F(IpcServerStubTest, OnAddSystemAbility_002, testing::ext::TestSize.Level } /** - * @tc.name: GetAllPkgName_001 + * @tc.name: GetAllProcessInfo_001 * @tc.type: FUNC */ -HWTEST_F(IpcServerStubTest, GetAllPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(IpcServerStubTest, GetAllProcessInfo_001, testing::ext::TestSize.Level0) { - std::vector pkgName; - pkgName = IpcServerStub::GetInstance().GetAllPkgName(); - ASSERT_EQ(pkgName.empty(), false); + std::vector processInfo; + processInfo = IpcServerStub::GetInstance().GetAllProcessInfo(); + ASSERT_EQ(processInfo.empty(), false); } /** diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index 27c22126f..65995b5cf 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -32,13 +32,6 @@ int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const localUdid); } -std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int32_t tokenId, const std::string &localUdid) -{ - return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, - localUdid); -} - int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) { @@ -50,16 +43,5 @@ uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::s { return DmDeviceProfileConnector::dmDeviceProfileConnector->CheckBindType(trustDeviceId, requestDeviceId); } - -std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string &localDeviceId, - std::string &targetDeviceId) -{ - return DmDeviceProfileConnector::dmDeviceProfileConnector->GetPkgNameFromAcl(localDeviceId, targetDeviceId); -} - -DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) -{ - return DmDeviceProfileConnector::dmDeviceProfileConnector->GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); -} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index 51c57de43..fed03cc1f 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -19,6 +19,7 @@ #include #include "deviceprofile_connector.h" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -29,13 +30,9 @@ public: virtual std::vector GetAllAccessControlProfile() = 0; virtual int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid) = 0; - virtual std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, - const std::string &localUdid) = 0; virtual int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) = 0; virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; - virtual std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId) = 0; - virtual DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) = 0; public: static inline std::shared_ptr dmDeviceProfileConnector = nullptr; }; @@ -44,12 +41,9 @@ class DeviceProfileConnectorMock : public DmDeviceProfileConnector { public: MOCK_METHOD(std::vector, GetAllAccessControlProfile, ()); MOCK_METHOD(int32_t, HandleDevUnBindEvent, (int32_t, const std::string &, const std::string &)); - MOCK_METHOD(std::string, HandleAppUnBindEvent, (int32_t, const std::string &, int32_t, const std::string &)); MOCK_METHOD(int32_t, HandleAccountLogoutEvent, (int32_t, const std::string &, const std::string &, const std::string &)); MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); - MOCK_METHOD(std::vector, GetPkgNameFromAcl, (std::string &, std::string &)); - MOCK_METHOD(DmOfflineParam, GetOfflineParamFromAcl, (std::string, std::string)); }; } } diff --git a/test/unittest/mock/ipc_server_listener.cpp b/test/unittest/mock/ipc_server_listener.cpp index 0c70d88ae..4db0579fd 100644 --- a/test/unittest/mock/ipc_server_listener.cpp +++ b/test/unittest/mock/ipc_server_listener.cpp @@ -22,13 +22,5 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req_ = req; return 0; } - -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - (void)cmdCode; - req_ = req; - std::cout << req_->GetPkgName() << "\n"; - return 0; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/ipc_server_listener.h b/test/unittest/mock/ipc_server_listener.h index b3c8e04b9..74d538f59 100644 --- a/test/unittest/mock/ipc_server_listener.h +++ b/test/unittest/mock/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,8 @@ #include #include +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -35,18 +37,14 @@ public: * @tc.type: FUNC */ int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Ipc server listener send messages - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); + std::set GetSystemSA(); std::shared_ptr req_; }; } // namespace DistributedHardware diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index 33927be8e..52dc07f81 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -30,6 +30,9 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t &tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 684337867..8f19166a6 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -36,6 +36,9 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t &tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId); private: bool GetBundleManagerProxy(sptr &bundleManager); std::mutex appIdMapLock_; diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index ea3ab90cc..fd2aeb768 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -46,5 +46,27 @@ bool AppManager::IsSystemSA() { return true; } + +int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) +{ + (void)isSystemSA; + (void)callerName; + return DM_OK; +} +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t &tokenId) +{ + (void)processName; + (void)tokenId; + return DM_OK; +} + +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId) +{ + (void)userId; + (void)bundleName; + (void)instIndex; + (void)tokenId; + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index cb2c61ec9..b1d173f53 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -151,5 +151,59 @@ bool AppManager::IsSystemSA() } return false; } + +int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("GetCallingTokenID error."); + return ERR_DM_FAILED; + } + LOGI("tokenCaller ID == %{public}s", GetAnonyInt32(tokenCaller).c_str()); + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_HAP) { + isSystemSA = false; + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenCaller, tokenInfo) != EOK) { + LOGE("GetHapTokenInfo failed."); + return ERR_DM_FAILED; + } + callerName = std::move(tokenInfo.bundleName); + } else if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + isSystemSA = true; + NativeTokenInfo tokenInfo; + if (AccessTokenKit::GetNativeTokenInfo(tokenCaller, tokenInfo) != EOK) { + LOGE("GetNativeTokenInfo failed."); + return ERR_DM_FAILED; + } + callerName = std::move(tokenInfo.processName); + } else { + LOGE("failed, unsupported process."); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t &tokenId) +{ + AccessTokenID nativeTokenId = AccessTokenKit::GetNativeTokenId(processName); + if (nativeTokenId == INVALID_TOKENID) { + LOGE("GetNativeTokenId failed."); + return ERR_DM_FAILED; + } + tokenId = static_cast(nativeTokenId); + return DM_OK; +} + +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId) +{ + auto hapTokenId = AccessTokenKit::GetHapTokenID(userId, bundleName, instIndex); + if (hapTokenId == 0) { + LOGE("GetHapTokenId failed."); + return ERR_DM_FAILED; + } + tokenId = static_cast(hapTokenId); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 2876a61b2e2b9a99c049dfc684cb42f8e69e340b Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sun, 17 Nov 2024 10:30:56 +0800 Subject: [PATCH 397/520] modify print list format Signed-off-by: hwzhangchuang --- common/src/dm_anonymous.cpp | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 140338771..811c54cca 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -53,10 +53,16 @@ std::string GetAnonyString(const std::string &value) std::string GetAnonyStringList(const std::vector &values) { - std::string temp = ""; + std::string temp = "[ "; + bool flag = false; for (auto const &v : values) { - temp += GetAnonyString(v) + ", "; + temp += GetAnonyString(v) + PRINT_LIST_SPLIT; + flag = true; } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); + } + temp += " ]"; return temp; } @@ -76,10 +82,16 @@ std::string GetAnonyInt32(const int32_t value) std::string GetAnonyInt32List(const std::vector &values) { - std::string temp = ""; + std::string temp = "[ "; + bool flag = false; for (auto const &v : values) { - temp += GetAnonyInt32(v) + ", "; + temp += GetAnonyInt32(v) + PRINT_LIST_SPLIT; + flag = true; + } + if (flag) { + temp.erase(temp.length() - LIST_SPLIT_LEN); } + temp += " ]"; return temp; } -- Gitee From 30227ba8500561f963c795d137dfb7aeea02e81d Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sun, 17 Nov 2024 11:56:15 +0800 Subject: [PATCH 398/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- common/include/dm_anonymous.h | 1 - .../src/deviceprofile_connector.cpp | 78 ++++++++++--------- .../src/device_manager_service_impl.cpp | 24 +----- .../devicestate/dm_device_state_manager.cpp | 4 +- .../include/device_manager_service_listener.h | 3 +- .../src/device_manager_service_listener.cpp | 76 +++++++----------- 6 files changed, 73 insertions(+), 113 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 12e5d9776..7fbd6facb 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -19,7 +19,6 @@ #include #include #include "nlohmann/json.hpp" -#include #include "dm_device_info.h" namespace OHOS { diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 36f7dcb03..8683ed3d1 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -398,13 +398,24 @@ std::vector DeviceProfileConnector::GetP LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); std::vector processInfoVec; for (auto &item : filterProfiles) { - if (item.GetTrustDeviceId() != targetDeviceId || item.GetStatus() != ACTIVE) { + if (item.GetTrustDeviceId() != targetDeviceId) { continue; } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); OHOS::DistributedHardware::ProcessInfo processInfo; - processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); - processInfo.userId = item.GetAccesser().GetAccesserUserId(); - processInfoVec.push_back(processInfo); + if (accesserUdid == localDeviceId) { + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfoVec.push_back(processInfo); + continue; + } + if (accesseeUdid == localDeviceId) { + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + processInfoVec.push_back(processInfo); + continue; + } } return processInfoVec; } @@ -1096,21 +1107,20 @@ int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, int32_t beforeUserId) { LOGI("Start."); - std::vector profiles = GetAccessControlProfileByUserId(beforeUserId); - LOGI("to inactive ACL size is %{public}zu", profiles.size()); + std::vector profiles = GetAllAccessControlProfile(); for (auto &item : profiles) { if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && - item.GetAccesser().GetAccesserUserId() == beforeUserId) || + item.GetAccesser().GetAccesserUserId() == beforeUserId && item.GetStatus() == ACTIVE) || (item.GetAccessee().GetAccesseeDeviceId() == localUdid && - item.GetAccessee().GetAccesseeUserId() == beforeUserId)) { + item.GetAccessee().GetAccesseeUserId() == beforeUserId && item.GetStatus() == ACTIVE)) { item.SetStatus(INACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); continue; } if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && - item.GetAccesser().GetAccesserUserId() == currentUserId) || ( + item.GetAccesser().GetAccesserUserId() == currentUserId && item.GetStatus() == INACTIVE) || ( item.GetAccessee().GetAccesseeDeviceId() == localUdid && - item.GetAccessee().GetAccesseeUserId() == currentUserId)) { + item.GetAccessee().GetAccesseeUserId() == currentUserId && item.GetStatus() == INACTIVE)) { item.SetStatus(ACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); continue; @@ -1152,7 +1162,7 @@ void DeviceProfileConnector::HandleSyncForegroundUserIdEvent(const std::vector DeviceProfileConnector::GetOfflineProcessInfo(std::stri int32_t bindLevel = 100; for (const auto &item : profiles) { ProcessInfo processInfo; - if (item.GetAccesser().GetAccesserDeviceId() == localUdid && - item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - find(localUserIds.begin(), localUserIds.end(), - item.GetAccesser().GetAccesserUserId()) != localUserIds.end() && - find(remoteUserIds.begin(), remoteUserIds.end(), - item.GetAccessee().GetAccesseeUserId()) != remoteUserIds.end() && + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesseeUdid == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), accesserUserId) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), accesseeUserId) != remoteUserIds.end() && item.GetStatus() == ACTIVE) { processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); - } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && - item.GetAccesser().GetAccesserDeviceId() == remoteUdid && - find(localUserIds.begin(), localUserIds.end(), - item.GetAccessee().GetAccesseeUserId()) != localUserIds.end() && - find(remoteUserIds.begin(), remoteUserIds.end(), - item.GetAccesser().GetAccesserUserId()) != remoteUserIds.end() && + processInfos.push_back(processInfo); + } else if (accesseeUdid == localUdid && accesserUdid == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), accesseeUserId) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), accesserUserId) != remoteUserIds.end() && item.GetStatus() == ACTIVE) { processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); + processInfos.push_back(processInfo); } - processInfos.push_back(processInfo); } if (bindLevel == INVALIED_TYPE || bindLevel == DEVICE) { processInfos.clear(); @@ -1220,9 +1229,6 @@ std::map DeviceProfileConnector::GetUserIdAndBindLevel(const s std::vector profiles = GetAllAccessControlProfile(); std::map userIdAndBindLevel; for (const auto &item : profiles) { - if (item.GetStatus() == INACTIVE) { - continue; - } std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); @@ -1370,16 +1376,16 @@ void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent(const std::vector profiles = GetAllAccessControlProfile(); for (auto &item : profiles) { - if (item.GetAccesser().GetAccesserDeviceId() == localUdid && - item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - find(remoteUserIds.begin(), remoteUserIds.end(), - item.GetAccessee().GetAccesseeUserId()) != remoteUserIds.end()) { + std::string accesserDeviceId = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeDeviceId = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserDeviceId == localUdid && accesseeDeviceId == remoteUdid && item.GetStatus() == ACTIVE && + find(remoteUserIds.begin(), remoteUserIds.end(), accesseeUserId) != remoteUserIds.end()) { item.SetStatus(INACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); - } else if ((item.GetAccessee().GetAccesseeDeviceId() == localUdid && - item.GetAccesser().GetAccesserDeviceId() == remoteUdid) && - find(remoteUserIds.begin(), remoteUserIds.end(), - item.GetAccesser().GetAccesserUserId()) == remoteUserIds.end()) { + } else if ((accesseeDeviceId == localUdid && accesserDeviceId == remoteUdid) && item.GetStatus() == ACTIVE && + find(remoteUserIds.begin(), remoteUserIds.end(), accesserUserId) != remoteUserIds.end()) { item.SetStatus(INACTIVE); DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a0df243b8..19bb1be7e 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -235,8 +235,8 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf item.first); softbusConnector_->SetProcessInfoVec(processInfoVec); } + deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -731,20 +731,6 @@ void DeviceManagerServiceImpl::HandleUserSwitched(const std::map(localDeviceId); - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - processInfo.userId = beforeUserId; - for (const auto &item : deviceMap) { - if (item.second == INVALIED_TYPE || item.second == DEVICE) { - softbusConnector_->SetProcessInfo(processInfo); - } else { - std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localUdid, - item.first, beforeUserId); - softbusConnector_->SetProcessInfoVec(processInfoVec); - } - softbusConnector_->HandleDeviceOffline(item.first); - } DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); } @@ -897,14 +883,6 @@ void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector } DeviceProfileConnector::GetInstance().UpdatePeerUserId(localUdid, localUserIds, remoteUdid, rmtFrontUserIdsTemp, rmtBackUserIdsTemp); - std::vector offlineProcInfo = - DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUdid, localUserIds, - remoteUdid, rmtBackUserIdsTemp); - if (!offlineProcInfo.empty()) { - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfoVec(offlineProcInfo); - softbusConnector_->HandleDeviceOffline(remoteUdid); - } DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, localUserIds, localUdid); DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 9c3d367a6..bce366f51 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -170,7 +170,9 @@ void DmDeviceStateManager::ProcessDeviceStateChange(const DmDeviceState devState CHECK_NULL_VOID(listener_); std::vector processInfoVec = softbusConnector_->GetProcessInfo(); for (const auto &item : processInfoVec) { - listener_->OnDeviceStateChange(item, devState, devInfo); + if (!item.pkgName.empty()) { + listener_->OnDeviceStateChange(item, devState, devInfo); + } } } diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 74df27405..8573c5046 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -109,12 +109,11 @@ private: const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); void ProcessAppOffline(const std::vector procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void RemoveNotExistProcess(const std::vector &procInfoVec); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; static std::mutex alreadyNotifyPkgNameLock_; - static std::map alreadyOnlinePkgName_; + static std::map alreadyOnlinePkgName_; #endif }; } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index f6cf0be99..86ac6e138 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -49,7 +49,7 @@ namespace OHOS { namespace DistributedHardware { std::mutex DeviceManagerServiceListener::alreadyNotifyPkgNameLock_; -std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { @@ -557,7 +557,7 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) { std::lock_guard autoLock(alreadyNotifyPkgNameLock_); for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { - if (it->first.processPkgName == pkgName) { + if (it->first.find(pkgName) != std::string::npos) { it = alreadyOnlinePkgName_.erase(it); } else { ++it; @@ -651,18 +651,14 @@ void DeviceManagerServiceListener::ProcessDeviceOnline(const std::vector pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); for (const auto &it : procInfoVec) { - DmNotifyKey notifyKey; - notifyKey.processPkgName = it.pkgName; - notifyKey.processUserId = it.userId; - notifyKey.notifyUserId = processInfo.userId; - notifyKey.udid = info.deviceId; + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); DmDeviceState notifyState = state; { std::lock_guard autoLock(alreadyNotifyPkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { notifyState = DmDeviceState::DEVICE_INFO_CHANGED; } else { - alreadyOnlinePkgName_[notifyKey] = info; + alreadyOnlinePkgName_[notifyPkgName] = info; } } SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); @@ -678,20 +674,14 @@ void DeviceManagerServiceListener::ProcessDeviceOffline(const std::vector pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - RemoveNotExistProcess(procInfoVec); - if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { - RemoveOnlinePkgName(info); - } for (const auto &it : procInfoVec) { - DmNotifyKey notifyKey; - notifyKey.processPkgName = it.pkgName; - notifyKey.processUserId = it.userId; - notifyKey.notifyUserId = processInfo.userId; - notifyKey.udid = info.deviceId; + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); { std::lock_guard autoLock(alreadyNotifyPkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { alreadyOnlinePkgName_.erase(notifyKey); + } else { + continue; } } SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); @@ -722,18 +712,14 @@ void DeviceManagerServiceListener::ProcessAppOnline(const std::vector pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); for (const auto &it : procInfoVec) { - DmNotifyKey notifyKey; - notifyKey.processPkgName = it.pkgName; - notifyKey.processUserId = it.userId; - notifyKey.notifyUserId = processInfo.userId; - notifyKey.udid = info.deviceId; + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); DmDeviceState notifyState = state; { std::lock_guard autoLock(alreadyNotifyPkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { notifyState = DmDeviceState::DEVICE_INFO_CHANGED; } else { - alreadyOnlinePkgName_[notifyKey] = info; + alreadyOnlinePkgName_[notifyPkgName] = info; } } SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); @@ -750,21 +736,25 @@ void DeviceManagerServiceListener::ProcessAppOffline(const std::vector pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { - RemoveOnlinePkgName(info); for (const auto &it : procInfoVec) { + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyKey); + } else { + continue; + } + } SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } else { - DmNotifyKey notifyKey; - notifyKey.processPkgName = processInfo.pkgName; - notifyKey.processUserId = processInfo.userId; - notifyKey.notifyUserId = processInfo.userId; - notifyKey.udid = info.deviceId; + std::string notifyPkgName = it.pkgName + "#" + std::to_string(it.userId) + "#" + std::string(info.deviceId); { std::lock_guard autoLock(alreadyNotifyPkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - alreadyOnlinePkgName_.erase(notifyKey); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyPkgName); } } SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); @@ -772,26 +762,12 @@ void DeviceManagerServiceListener::ProcessAppOffline(const std::vector &procInfoVec) -{ - std::lock_guard autoLock(alreadyNotifyPkgNameLock_); - for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { - ProcessInfo processInfo; - processInfo.pkgName = it->first.processPkgName; - processInfo.userId = it->first.processUserId; - if (find(procInfoVec.begin(), procInfoVec.end(), processInfo) != procInfoVec.end()) { - it = alreadyOnlinePkgName_.erase(it); - } else { - ++it; - } - } -} - void DeviceManagerServiceListener::OnProcessRemove(const ProcessInfo &processInfo) { std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + std::string notifyPkgName = processInfo.pkgName + "#" + std::to_string(processInfo.userId) for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { - if (processInfo.pkgName == it->first.processPkgName && processInfo.userId == it->first.processUserId) { + if (it->first.find(notifyPkgName) != std::string::npos) { it = alreadyOnlinePkgName_.erase(it); } else { ++it; -- Gitee From 0e1b445abb483b5be96e66bbf6878883f66ea686 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sun, 17 Nov 2024 14:30:10 +0800 Subject: [PATCH 399/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- services/service/src/device_manager_service_listener.cpp | 5 +++-- services/service/src/softbus/softbus_listener.cpp | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 86ac6e138..8b7aa960c 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -84,7 +84,6 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetPkgName(processInfo.pkgName); pReq->SetProcessInfo(processInfo); pReq->SetDeviceState(state); @@ -755,6 +754,8 @@ void DeviceManagerServiceListener::ProcessAppOffline(const std::vector autoLock(alreadyNotifyPkgNameLock_); if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { alreadyOnlinePkgName_.erase(notifyPkgName); + } else { + continue; } } SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); @@ -765,7 +766,7 @@ void DeviceManagerServiceListener::ProcessAppOffline(const std::vector autoLock(alreadyNotifyPkgNameLock_); - std::string notifyPkgName = processInfo.pkgName + "#" + std::to_string(processInfo.userId) + std::string notifyPkgName = processInfo.pkgName + "#" + std::to_string(processInfo.userId); for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { if (it->first.find(notifyPkgName) != std::string::npos) { it = alreadyOnlinePkgName_.erase(it); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 2a3385e77..41cd3e9f1 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -384,7 +384,7 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms ffrt::submit([=]() { DeviceNotTrust(softbusMsg); }); } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { ffrt::submit([=]() { DeviceTrustedChange(softbusMsg); }); - } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { + } else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { ffrt::submit([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); } else { LOGE("Invalied trust change type."); @@ -404,7 +404,7 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms LOGE("deviceTrustedChange setname failed."); } deviceTrustedChange.detach(); - } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { + } else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { std::thread deviceUserIdCheckSumChange([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); int32_t ret = pthread_setname_np(deviceUserIdCheckSumChange.native_handle(), DEVICE_NOT_TRUST); if (ret != DM_OK) { -- Gitee From 3a8cde9bbef20a289f48f70c8534576cc70e2014 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sun, 17 Nov 2024 14:34:42 +0800 Subject: [PATCH 400/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- services/service/src/softbus/softbus_listener.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 41cd3e9f1..2a3385e77 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -384,7 +384,7 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms ffrt::submit([=]() { DeviceNotTrust(softbusMsg); }); } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { ffrt::submit([=]() { DeviceTrustedChange(softbusMsg); }); - } else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { + } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { ffrt::submit([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); } else { LOGE("Invalied trust change type."); @@ -404,7 +404,7 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms LOGE("deviceTrustedChange setname failed."); } deviceTrustedChange.detach(); - } else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { + } else if (type == TrustChangeType::DEVICE_FOREGROUND_USERID_CHANGE) { std::thread deviceUserIdCheckSumChange([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); int32_t ret = pthread_setname_np(deviceUserIdCheckSumChange.native_handle(), DEVICE_NOT_TRUST); if (ret != DM_OK) { -- Gitee From 15b582da68151236f48b8c790add14ef4ce9536f Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sun, 17 Nov 2024 14:58:56 +0800 Subject: [PATCH 401/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- services/service/src/device_manager_service_listener.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 8b7aa960c..2a70cb8da 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -678,7 +678,7 @@ void DeviceManagerServiceListener::ProcessDeviceOffline(const std::vector autoLock(alreadyNotifyPkgNameLock_); if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { - alreadyOnlinePkgName_.erase(notifyKey); + alreadyOnlinePkgName_.erase(notifyPkgName); } else { continue; } @@ -740,7 +740,7 @@ void DeviceManagerServiceListener::ProcessAppOffline(const std::vector autoLock(alreadyNotifyPkgNameLock_); if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { - alreadyOnlinePkgName_.erase(notifyKey); + alreadyOnlinePkgName_.erase(notifyPkgName); } else { continue; } @@ -749,13 +749,14 @@ void DeviceManagerServiceListener::ProcessAppOffline(const std::vector autoLock(alreadyNotifyPkgNameLock_); if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { alreadyOnlinePkgName_.erase(notifyPkgName); } else { - continue; + return; } } SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); -- Gitee From 24d026df62932df8d357fe7b21b3cd668fc5664d Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sun, 17 Nov 2024 17:14:15 +0800 Subject: [PATCH 402/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../include/deviceprofile_connector.h | 7 +- .../src/deviceprofile_connector.cpp | 82 +++++++++++-------- .../src/device_manager_service_impl.cpp | 2 +- 3 files changed, 53 insertions(+), 38 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 0c4f7fc45..827f32abb 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -147,7 +147,7 @@ public: std::vector GetOfflineProcessInfo(std::string &localUdid, const std::vector &localUserIds, const std::string &remoteUdid, const std::vector &remoteUserIds); std::map GetUserIdAndBindLevel(const std::string &localUdid, const std::string &peerUdid); - void UpdatePeerUserId(std::string &localUdid, const std::vector &localUserIds, + void UpdateACL(std::string &localUdid, const std::vector &localUserIds, const std::string &remoteUdid, const std::vector &remoteFrontUserIds, const std::vector &remoteBackUserIds); std::multimap GetDevIdAndUserIdByActHash(const std::string &localUdid, @@ -180,6 +180,11 @@ private: void UpdateBindType(const std::string &udid, int32_t compareParam, std::map &deviceMap); std::vector GetAclProfileByUserId(const std::string &localUdid, int32_t userId, const std::string &remoteUdid); + void DeleteSigTrustACL(DistributedDeviceProfile::AccessControlProfile profile, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds, const std::vector &remoteBackUserIds); + void UpdatePeerUserId(DistributedDeviceProfile::AccessControlProfile profile, std::string &localUdid, + const std::vector &localUserIds, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 8683ed3d1..6707e79f0 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -1252,7 +1252,7 @@ std::map DeviceProfileConnector::GetUserIdAndBindLevel(const s return userIdAndBindLevel; } -void DeviceProfileConnector::UpdatePeerUserId(std::string &localUdid, const std::vector &localUserIds, +void DeviceProfileConnector::UpdateACL(std::string &localUdid, const std::vector &localUserIds, const std::string &remoteUdid, const std::vector &remoteFrontUserIds, const std::vector &remoteBackUserIds) { @@ -1260,43 +1260,53 @@ void DeviceProfileConnector::UpdatePeerUserId(std::string &localUdid, const std: GetAnonyString(remoteUdid).c_str()); std::vector profiles = GetAllAccessControlProfile(); for (auto item : profiles) { - std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); - std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); - int32_t accesserUserid = item.GetAccesser().GetAccesserUserId(); - int32_t accesseeUserid = item.GetAccessee().GetAccesseeUserId(); - int32_t bindType = item.GetBindType(); // deleta signal trust acl. - if (accesserUdid == remoteUdid && accesserUserid != 0 && accesserUserid != -1 && - find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesserUserid) == remoteFrontUserIds.end() && - find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesserUserid) == remoteBackUserIds.end()) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - continue; - } - if (accesseeUdid == remoteUdid && accesseeUserid != 0 && accesseeUserid != -1 && - find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesseeUserid) == remoteFrontUserIds.end() && - find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesseeUserid) == remoteBackUserIds.end()) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - continue; - } + DeleteSigTrustACL(item, remoteUdid, remoteFrontUserIds, remoteBackUserIds); // update identical account userId. - if (accesserUdid == localUdid && accesseeUdid == remoteUdid && bindType == DM_IDENTICAL_ACCOUNT && - find(localUserIds.begin(), localUserIds.end(), accesserUserid) != localUserIds.end() && - (accesseeUserid == 0 || accesseeUserid == -1)) { - Accessee accessee = item.GetAccessee(); - accessee.SetAccesseeUserId(remoteFrontUserIds[0]); - item.SetAccessee(accessee); - DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); - continue; - } - if (accesserUdid == remoteUdid && accesseeUdid == localUdid && bindType == DM_IDENTICAL_ACCOUNT && - find(localUserIds.begin(), localUserIds.end(), accesseeUserid) != localUserIds.end() && - (accesserUserid == 0 || accesserUserid == -1)) { - Accesser accesser = item.GetAccesser(); - accesser.SetAccesserUserId(remoteFrontUserIds[0]); - item.SetAccesser(accesser); - DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); - continue; - } + UpdatePeerUserId(item, localUdid, localUserIds, remoteUdid, remoteFrontUserIds); + } +} + +void DeviceProfileConnector::DeleteSigTrustACL(AccessControlProfile profile, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds, const std::vector &remoteBackUserIds) +{ + LOGI("start."); + std::string accesserUdid = profile.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = profile.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = profile.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = profile.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == remoteUdid && accesserUserid != 0 && accesserUserid != -1 && + find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesserUserid) == remoteFrontUserIds.end() && + find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesserUserid) == remoteBackUserIds.end()) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(profile.GetAccessControlId()); + return; + } + if (accesseeUdid == remoteUdid && accesseeUserid != 0 && accesseeUserid != -1 && + find(remoteFrontUserIds.begin(), remoteFrontUserIds.end(), accesseeUserid) == remoteFrontUserIds.end() && + find(remoteBackUserIds.begin(), remoteBackUserIds.end(), accesseeUserid) == remoteBackUserIds.end()) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(profile.GetAccessControlId()); + return; + } +} + +void DeviceProfileConnector::UpdatePeerUserId(AccessControlProfile profile, std::string &localUdid, + const std::vector &localUserIds, const std::string &remoteUdid, + const std::vector &remoteFrontUserIds) +{ + LOGI("start."); + std::string accesserUdid = profile.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = profile.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserid = profile.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserid = profile.GetAccessee().GetAccesseeUserId(); + int32_t bindType = profile.GetBindType(); + if (accesserUdid == localUdid && accesseeUdid == remoteUdid && bindType == DM_IDENTICAL_ACCOUNT && + find(localUserIds.begin(), localUserIds.end(), accesserUserid) != localUserIds.end() && + (accesseeUserid == 0 || accesseeUserid == -1)) { + Accessee accessee = profile.GetAccessee(); + accessee.SetAccesseeUserId(remoteFrontUserIds[0]); + profile.SetAccessee(accessee); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(profile); + return; } } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 19bb1be7e..b1137e7ed 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -881,7 +881,7 @@ void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector if (ret != DM_OK || localUserIds.empty()) { LOGE("Get foreground userids failed, ret: %{public}d", ret); } - DeviceProfileConnector::GetInstance().UpdatePeerUserId(localUdid, localUserIds, remoteUdid, + DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, rmtFrontUserIdsTemp, rmtBackUserIdsTemp); DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, localUserIds, localUdid); -- Gitee From 70f03ba9e9da388aa7c247c9b483c790e312304c Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Sun, 17 Nov 2024 17:29:23 +0800 Subject: [PATCH 403/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=9B=91=E8=A7=86?= =?UTF-8?q?=E6=84=8F=E8=A7=81=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/deviceprofile_connector.h | 2 +- .../src/deviceprofile_connector.cpp | 83 +++++++++++-------- .../include/device_manager_service_impl.h | 4 +- .../device_manager_service_impl_lite.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 3 + .../src/device_manager_service_impl.cpp | 9 +- .../src/device_manager_service_impl_lite.cpp | 4 +- .../include/device_manager_service_listener.h | 10 +-- .../include/idevice_manager_service_impl.h | 2 +- .../service/src/device_manager_service.cpp | 6 +- .../src/device_manager_service_listener.cpp | 10 +-- .../src/discovery/discovery_manager.cpp | 2 +- 12 files changed, 78 insertions(+), 59 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 0c4f7fc45..92f6d46eb 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -108,7 +108,7 @@ public: std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId); int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); - int32_t DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); void DeleteAclForUserRemoved(std::string localUdid, int32_t userId); DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 8683ed3d1..50a6cf5b8 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -58,6 +58,7 @@ std::vector DeviceProfileConnector::GetAclProfileByDeviceI queryParams[USERID] = std::to_string(userId); if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { LOGE("DP GetAccessControlProfile failed."); + return profiles; } for (auto &item : profiles) { if ((item.GetAccesser().GetAccesserDeviceId() == deviceId && @@ -77,10 +78,11 @@ std::unordered_map DeviceProfileConnector::GetAppTrustD std::vector profiles = GetAclProfileByDeviceIdAndUserId(deviceId, userId); std::vector profilesFilter = {}; for (auto &item : profiles) { - if ((item.GetAccesser().GetAccesserUserId() == userId && item.GetAccesser().GetAccesserDeviceId() == deviceId) - || (item.GetAccessee().GetAccesseeUserId() == userId && - item.GetAccessee().GetAccesseeDeviceId() == deviceId)) { - profilesFilter.push_back(item); + if ((item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccesser().GetAccesserDeviceId() == deviceId) || + (item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == deviceId)) { + profilesFilter.push_back(item); } } std::unordered_map deviceIdMap; @@ -236,8 +238,6 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont priority = DEVICE_ACROSS_ACCOUNT_TYPE; } else if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP) { - priority = APP_ACROSS_ACCOUNT_TYPE; } break; default: @@ -452,13 +452,15 @@ int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccess return ret; } -int32_t DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, +bool DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId) { LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); std::vector profiles = GetAllAccessControlProfile(); + std::vector deleteProfiles; bool notifyOffline = false; + bool isDelete = false; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != peerUdid) { continue; @@ -469,17 +471,29 @@ int32_t DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &loc int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); if (accesserUdid == localUdid && accesserUserId == localUserId && accesseeUdid == peerUdid && accesseeUserId == peerUserId) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + isDelete = true; + } + deleteProfiles.push_back(item); notifyOffline = (item.GetStatus() == ACTIVE); continue; } if (accesserUdid == peerUdid && accesserUserId == peerUserId && accesseeUdid == localUdid && accesseeUserId == localUserId) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + isDelete = true; + } + deleteProfiles.push_back(item); notifyOffline = (item.GetStatus() == ACTIVE); continue; } } + if (!isDelete) { + return false; + } + for (const auto &item : deleteProfiles) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } return notifyOffline; } @@ -776,29 +790,29 @@ std::vector GetACLByDeviceIdAndUserId(std::vector profilesFilter; for (auto &item : profiles) { - if (item.GetAccesser().GetAccesserUserId() == caller.userId - && item.GetAccesser().GetAccesserDeviceId() == srcUdid - && item.GetAccessee().GetAccesseeDeviceId() == sinkUdid) { - profilesFilter.push_back(item); - continue; - } - if (item.GetAccesser().GetAccesserUserId() == callee.userId - && item.GetAccesser().GetAccesserDeviceId() == sinkUdid - && item.GetAccessee().GetAccesseeDeviceId() == srcUdid) { - profilesFilter.push_back(item); - continue; - } - if (item.GetAccessee().GetAccesseeUserId() == caller.userId - && item.GetAccessee().GetAccesseeDeviceId() == srcUdid - && item.GetAccesser().GetAccesserDeviceId() == sinkUdid) { - profilesFilter.push_back(item); - continue; - } - if (item.GetAccessee().GetAccesseeUserId() == callee.userId - && item.GetAccessee().GetAccesseeDeviceId() == sinkUdid - && item.GetAccesser().GetAccesserDeviceId() == srcUdid) { - profilesFilter.push_back(item); - continue; + if (item.GetAccesser().GetAccesserUserId() == caller.userId && + item.GetAccesser().GetAccesserDeviceId() == srcUdid && + item.GetAccessee().GetAccesseeDeviceId() == sinkUdid) { + profilesFilter.push_back(item); + continue; + } + if (item.GetAccesser().GetAccesserUserId() == callee.userId && + item.GetAccesser().GetAccesserDeviceId() == sinkUdid && + item.GetAccessee().GetAccesseeDeviceId() == srcUdid) { + profilesFilter.push_back(item); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == caller.userId && + item.GetAccessee().GetAccesseeDeviceId() == srcUdid && + item.GetAccesser().GetAccesserDeviceId() == sinkUdid) { + profilesFilter.push_back(item); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == callee.userId && + item.GetAccessee().GetAccesseeDeviceId() == sinkUdid && + item.GetAccesser().GetAccesserDeviceId() == srcUdid) { + profilesFilter.push_back(item); + continue; } } return profilesFilter; @@ -810,8 +824,8 @@ int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, LOGI("PkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); std::vector profiles = GetAllAccessControlProfile(); - std::vector profilesFilter - = GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, callee, sinkUdid); + std::vector profilesFilter = + GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, callee, sinkUdid); for (auto &item : profilesFilter) { if (item.GetStatus() != ACTIVE || (item.GetTrustDeviceId() != sinkUdid && item.GetTrustDeviceId() != srcUdid)) { @@ -996,7 +1010,6 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, remoteUserId, GetAnonyString(remoteAccountHash).c_str(), GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); std::vector profiles = GetAccessControlProfileByUserId(remoteUserId); - std::map uaerIdAndBindType; int32_t bindType = DM_INVALIED_BINDTYPE; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid) { diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index d52bec824..c621c1a4b 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -135,7 +135,7 @@ public: void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, - const std::vector &backroundUserIds, const std::string &remoteUdid); + const std::vector &backgroundUserIds, const std::string &remoteUdid); void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, int32_t beforeUserId); std::multimap GetDeviceIdAndUserId(int32_t localUserId); @@ -154,7 +154,7 @@ private: void HandleUserRemoved(int32_t preUserId); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - + private: std::shared_ptr authMgr_; std::shared_ptr deviceStateMgr_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 13cf86a11..2a36cac96 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -142,7 +142,7 @@ public: void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, - const std::vector &backroundUserIds, const std::string &remoteUdid); + const std::vector &backgroundUserIds, const std::string &remoteUdid); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); std::map GetDeviceIdAndBindLevel(int32_t userId); std::multimap GetDeviceIdAndUserId(int32_t localUserId); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 731948961..6ab1cbdba 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2597,6 +2597,9 @@ void DmAuthManager::SetProcessInfo() } else if (authResponseContext_->bindLevel == DEVICE || authResponseContext_->bindLevel == INVALIED_TYPE) { processInfo.pkgName = std::string(DM_PKG_NAME); processInfo.userId = authResponseContext_->localUserId; + } else { + LOGE("bindlevel error %{public}d.", authResponseContext_->bindLevel); + return; } softbusConnector_->SetProcessInfo(processInfo); } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 19bb1be7e..2cd075aae 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -868,18 +868,21 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, - const std::vector &backroundUserIds, const std::string &remoteUdid) + const std::vector &backgroundUserIds, const std::string &remoteUdid) { - LOGI("remote udid: %{public}s", GetAnonyString(remoteUdid).c_str()); + LOGI("remote udid: %{public}s, foregroundUserIds: %{public}s, backgroundUserIds: %{public}s", + GetAnonyString(remoteUdid).c_str(), GetIntegerList(foregroundUserIds).c_str(), + GetIntegerList(backgroundUserIds).c_str()); char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); std::vector rmtFrontUserIdsTemp(foregroundUserIds.begin(), foregroundUserIds.end()); - std::vector rmtBackUserIdsTemp(backroundUserIds.begin(), backroundUserIds.end()); + std::vector rmtBackUserIdsTemp(backgroundUserIds.begin(), backgroundUserIds.end()); std::vector localUserIds; int32_t ret = MultipleUserConnector::GetForegroundUserIds(localUserIds); if (ret != DM_OK || localUserIds.empty()) { LOGE("Get foreground userids failed, ret: %{public}d", ret); + return; } DeviceProfileConnector::GetInstance().UpdatePeerUserId(localUdid, localUserIds, remoteUdid, rmtFrontUserIdsTemp, rmtBackUserIdsTemp); diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 0f4943293..f7028d7ce 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -545,10 +545,10 @@ int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, i } void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, - const std::vector &backroundUserIds, const std::string &remoteUdid) + const std::vector &backgroundUserIds, const std::string &remoteUdid) { (void)foregroundUserIds; - (void)backroundUserIds; + (void)backgroundUserIds; (void)remoteUdid; } diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 8573c5046..8d37cbf61 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -99,15 +99,15 @@ private: std::vector GetWhiteListSAProcessInfo(); std::vector GetNotifyProcessInfoByUserId(int32_t userId); ProcessInfo DealBindProcessInfo(const ProcessInfo &processInfo); - void ProcessDeviceOnline(const std::vector procInfoVec, const ProcessInfo &processInfo, + void ProcessDeviceOnline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessDeviceOffline(const std::vector procInfoVec, const ProcessInfo &processInfo, + void ProcessDeviceOffline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessDeviceInfoChange(const std::vector procInfoVec, const ProcessInfo &processInfo, + void ProcessDeviceInfoChange(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessAppOnline(const std::vector procInfoVec, const ProcessInfo &processInfo, + void ProcessAppOnline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessAppOffline(const std::vector procInfoVec, const ProcessInfo &processInfo, + void ProcessAppOffline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); private: #if !defined(__LITEOS_M__) diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 5d3cda0bb..65f5916ef 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -280,7 +280,7 @@ public: int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; virtual void HandleSyncUserIdEvent(const std::vector &foregroundUserIds, - const std::vector &backroundUserIds, const std::string &remoteUdid) = 0; + const std::vector &backgroundUserIds, const std::string &remoteUdid) = 0; virtual void HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) = 0; virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 9e8c5e88a..4ede94b80 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2067,11 +2067,11 @@ void DeviceManagerService::ProcessCheckSumByWifi(std::string networkId, std::vec for (auto const &u : foregroundUserIds) { foregroundUserIdsUInt.push_back(static_cast(u)); } - std::vector backroundUserIdsUInt; + std::vector backgroundUserIdsUInt; for (auto const &u : backgroundUserIds) { - backroundUserIdsUInt.push_back(static_cast(u)); + backgroundUserIdsUInt.push_back(static_cast(u)); } - DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backroundUserIdsUInt); + DMCommTool::GetInstance()->SendUserIds(networkId, foregroundUserIdsUInt, backgroundUserIdsUInt); } void DeviceManagerService::ProcessCheckSumByBT(std::string networkId, std::vector foregroundUserIds, diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 2a70cb8da..9696a0667 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -641,7 +641,7 @@ ProcessInfo DeviceManagerServiceListener::DealBindProcessInfo(const ProcessInfo return bindProcessInfo; } -void DeviceManagerServiceListener::ProcessDeviceOnline(const std::vector procInfoVec, +void DeviceManagerServiceListener::ProcessDeviceOnline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { @@ -665,7 +665,7 @@ void DeviceManagerServiceListener::ProcessDeviceOnline(const std::vector procInfoVec, +void DeviceManagerServiceListener::ProcessDeviceOffline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { @@ -688,7 +688,7 @@ void DeviceManagerServiceListener::ProcessDeviceOffline(const std::vector procInfoVec, +void DeviceManagerServiceListener::ProcessDeviceInfoChange(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { @@ -702,7 +702,7 @@ void DeviceManagerServiceListener::ProcessDeviceInfoChange(const std::vector procInfoVec, +void DeviceManagerServiceListener::ProcessAppOnline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { @@ -726,7 +726,7 @@ void DeviceManagerServiceListener::ProcessAppOnline(const std::vector procInfoVec, +void DeviceManagerServiceListener::ProcessAppOffline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 14f3d6b19..224e0887a 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -695,7 +695,7 @@ void DiscoveryManager::GetPkgNameAndUserId(const std::string &pkgName, std::stri return; } } - LOGE("find failed."); + LOGE("find failed PkgName %{public}s.", pkgName.c_str()); } } // namespace DistributedHardware } // namespace OHOS -- Gitee From ad28eeecbaddf1cbe71cd1a063853f25283772f7 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Mon, 18 Nov 2024 20:18:41 +0800 Subject: [PATCH 404/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichain_connector_fuzzer.cpp | 8 +- .../UTTest_dm_auth_manager_first.cpp | 6 +- .../UTTest_dm_auth_manager_second.cpp | 10 +- .../UTTest_softbus_listener.cpp | 105 ++++++------------ test/unittest/BUILD.gn | 2 +- test/unittest/mock/hichain_connector_mock.cpp | 36 +++--- 6 files changed, 69 insertions(+), 98 deletions(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index f0299d5c8..4c10c8324 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -269,9 +269,8 @@ void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) int32_t key = 12; std::string value = "acl_info1"; std::string credentialInfo = R"({"content": {"deviceid": "123"}}, authId: "123456"))"; - std::string params(reinterpret_cast(data), size); std::string groupOwner(reinterpret_cast(data), size); - delAclInfoVec1.push_back(std::make_pair(key1, value)); + delAclInfoVec1.push_back(std::make_pair(key, value)); nlohmann::json jsonObj; jsonObj[AUTH_TYPE] = 1; jsonObj[FIELD_USER_ID] = "123456"; @@ -306,6 +305,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) std::shared_ptr hichainConnector = std::make_shared(); hichainConnector->RegisterHiChainCallback(std::make_shared()); + std::string groupOwner(reinterpret_cast(data), size); nlohmann::json jsonObj; std::string deviceId = "deviceId"; std::string key = "localDeviceId"; @@ -324,6 +324,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) hichainConnector->AddMember(deviceId, jsonObj.dump()); nlohmann::json jsonObjCre; + std::string params; jsonObjCre[AUTH_TYPE] = 1; jsonObjCre["userId"] = "user_001"; jsonObjCre[FIELD_CREDENTIAL_TYPE] = 25; @@ -333,8 +334,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) std::string credentialInfo = jsonObjCre.dump(); hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); int32_t groupType = *(reinterpret_cast(data)); - nlohmann::json jsonDeviceList; - std::string params; + nlohmann::json jsonDeviceList; int32_t osAccountUserId = 0; std::string userId = "user_002"; jsonDeviceList[FIELD_DEVICE_LIST] = "deviceList"; diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index e341d23c8..34498447e 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -32,6 +32,8 @@ constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; @@ -1387,7 +1389,7 @@ HWTEST_F(DmAuthManagerTest, StopAuthenticateDevice_001, testing::ext::TestSize.L authManager_->authResponseContext_->authType == AUTH_TYPE_NFC; authManager_->authResponseContext_->requestId = requestId; status = 1; - authManager_->authTimes_ = MAX_AUTH_TIMES; + authManager_->authTimes_ = 3; authManager_->MemberJoinAuthRequest(requestId, status); status = 0; authManager_->authTimes_ = 2; @@ -1399,7 +1401,7 @@ HWTEST_F(DmAuthManagerTest, StopAuthenticateDevice_001, testing::ext::TestSize.L authManager_->NegotiateRespMsg(DM_VERSION_5_0_2); EXPECT_CALL(*softbusSessionMock_, GetPeerDeviceId(_, _)).WillOnce(Return(DM_OK)); authManager_->GetPeerUdidHash(sessionId, peerUdidHash); - ret = authManager_->StopAuthenticateDevice(pkgName, authType, deviceId, extra); + ret = authManager_->StopAuthenticateDevice(pkgName); ASSERT_EQ(ret, DM_OK); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 98b64101a..4aab3b743 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -25,6 +25,8 @@ #include "nlohmann/json.hpp" #include "softbus_error_code.h" +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { void DmAuthManagerTest::SetUp() @@ -1482,7 +1484,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->importAuthCode_= "importAuthCode"; authManager_->importPkgName_ = "importPkgName"; - authResponseContext_->hostPkgName = "importPkgName"; + authManager_->authResponseContext_->hostPkgName = "importPkgName"; authManager_->AbilityNegotiate(); EXPECT_CALL(*hiChainConnectorMock_, IsDevicesInP2PGroup(_, _)).WillOnce(Return(true)); @@ -1497,7 +1499,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level nlohmann::json jsonPeerGroupIdObj; jsonPeerGroupIdObj["groupId"] = "123456"; - authResponseContext_->accountGroupIdHash = jsonPeerGroupIdObj.dump(); + authManager_->authResponseContext_->accountGroupIdHash = jsonPeerGroupIdObj.dump(); EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); @@ -1512,13 +1514,13 @@ HWTEST_F(DmAuthManagerTest, GetAccountGroupIdHash_201, testing::ext::TestSize.Le EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); - auto ret = authManager_->GetAccountGroupIdHash(); + ret = authManager_->GetAccountGroupIdHash(); ASSERT_FALSE(ret.empty()); } HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) { - authResponseContext_->reply == ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->reply == ERR_DM_AUTH_BUSINESS_BUSY; authManager_->authResponseContext_->isIdenticalAccount = true; authManager_->authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT; EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index fe4f50b9b..25a406f28 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -544,25 +544,20 @@ HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_002, testing::ext::TestSize HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_003, testing::ext::TestSize.Level0) { std::string deviceId = "deviceId_003"; - DeviceInfo deviceInfo = { - .devId = "deviceId_003", - .devType = (DeviceType)1, - .devName = "11112", - .addrNum = 1, - .addr[0] = { + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, .info { .ip { .ip = "172.0.0.1", .port = 0, - } } } }; - PeerTargetId targetId; - ConnectionAddrType addrType; - std::shared_ptr infoPtr = std::make_shared(); - infoPtr = &deviceInfo; std::vector>> deviceVec; deviceVec.push_back(std::pair>(addrType, infoPtr)); discoveredDeviceMap.insert(std::pair infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { .type = ConnectionAddrType::CONNECTION_ADDR_ETH, .info { .ip { .ip = "172.0.0.1", .port = 0, - } } } }; - PeerTargetId targetId; - ConnectionAddrType addrType = ConnectionAddrType::CONNECTION_ADDR_ETH; - std::shared_ptr infoPtr = std::make_shared(); - infoPtr = &deviceInfo; std::vector>> deviceVec; - deviceVec.push_back(std::pair>(addrType, - )); + deviceVec.push_back(std::pair>(addrType, infoPtr)); discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); if (softbusListener == nullptr) { @@ -612,25 +601,20 @@ HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_004, testing::ext::TestSize HWTEST_F(SoftbusListenerTest, GetTargetInfoFromCache_005, testing::ext::TestSize.Level0) { std::string deviceId = "deviceId_005"; - DeviceInfo deviceInfo = { - .devId = "deviceId_005", - .devType = (DeviceType)1, - .devName = "11115", - .addrNum = 1, - .addr[0] = { + PeerTargetId targetId; + ConnectionAddrType addrType; + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { .type = ConnectionAddrType::CONNECTION_ADDR_BR, .info { .ip { .ip = "172.0.0.1", - .port = 1, - } + .port = 0, } } }; - PeerTargetId targetId; - ConnectionAddrType addrType; - std::shared_ptr infoPtr = std::make_shared(); - infoPtr = &deviceInfo; std::vector>> deviceVec; deviceVec.push_back(std::pair>(addrType, infoPtr)); discoveredDeviceMap.insert(std::pair infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { .type = ConnectionAddrType::CONNECTION_ADDR_BLE, .info { .ip { .ip = "172.0.0.1", - .port = 2, - } + .port = 0, } } }; - PeerTargetId targetId; - ConnectionAddrType addrType; - std::shared_ptr infoPtr = std::make_shared(); - infoPtr = &deviceInfo; std::vector>> deviceVec; deviceVec.push_back(std::pair>(addrType, infoPtr)); discoveredDeviceMap.insert(std::pair infoPtr = std::make_shared(); - infoPtr = &deviceInfo; std::vector>> deviceVec; discoveredDeviceMap.insert(std::pair>>>(deviceId, deviceVec)); @@ -972,23 +934,18 @@ HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_004, testing::ext::TestSize std::string deviceId = "deviceId"; std::string ip = "172.0.0.1"; ConnectionAddrType addrType = ConnectionAddrType::CONNECTION_ADDR_ETH; - DeviceInfo deviceInfo = { - .devId = "deviceId", - .devType = (DeviceType)1, - .devName = "11111", - .addrNum = 1, - .addr[0] = { + std::shared_ptr infoPtr = std::make_shared(); + infoPtr->devType = (DeviceType)1; + infoPtr->addrNum = 1; + infoPtr->addr[0] = { .type = ConnectionAddrType::CONNECTION_ADDR_WLAN, .info { .ip { .ip = "172.0.0.1", .port = 0, - } } } }; - std::shared_ptr infoPtr = std::make_shared(); - infoPtr = &deviceInfo; std::vector>> deviceVec; deviceVec.push_back(std::pair>(addrType, infoPtr)); discoveredDeviceMap.insert(std::pair &groupList) { - GroupInfo groupInfo = { - .groupId = "123456", - .groupName = "group1" - }; + GroupInfo groupInfo; + groupInfo.groupName = "group1"; + groupInfo.groupId = "123456"; + groupInfo.groupOwner = "sdsd"; + groupInfo.groupType = 2; + groupInfo.groupVisibility = 0; + groupInfo.userId = "82898"; - GroupInfo groupInfo2 = { - .groupId = "123789", - .groupName = "group2" - }; + GroupInfo groupInfo2; + groupInfo2.groupName = "group2"; + groupInfo2.groupId = "123456"; + groupInfo2.groupOwner = "sdsd"; + groupInfo2.groupType = 2; + groupInfo2.groupVisibility = 0; + groupInfo2.userId = "82898"; + + GroupInfo groupInfo3; + groupInfo3.groupName = "group3"; + groupInfo3.groupId = "123456"; + groupInfo3.groupOwner = "sdsd"; + groupInfo3.groupType = 2; + groupInfo3.groupVisibility = 0; + groupInfo3.userId = "82898"; - GroupInfo groupInfo3 = { - .groupId = "45789", - .groupName = "group3" - }; groupList.push_back(groupInfo); groupList.push_back(groupInfo2); groupList.push_back(groupInfo3); - return DmHiChainConnector::dmHiChainConnector->GroupInfo(userId, queryParams, groupList); + return DmHiChainConnector::dmHiChainConnector->GetGroupInfo(userId, queryParams, groupList); } bool HiChainConnector::IsDevicesInP2PGroup(const std::string &hostDevice, const std::string &peerDevice) -- Gitee From 8e4c3457d5c44ed6dbc75b9e99ca6400b7239005 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 09:54:01 +0800 Subject: [PATCH 405/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_auth_manager_first.cpp | 8 +++++--- test/commonunittest/UTTest_dm_auth_manager_second.cpp | 9 +++++---- test/softbusunittest/UTTest_softbus_listener.cpp | 4 ++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 34498447e..05cf6fb4b 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -61,6 +61,7 @@ void DmAuthManagerTest::SetUp() { authManager_->authMessageProcessor_ = std::make_shared(authManager_); authManager_->authMessageProcessor_->authResponseContext_ = std::make_shared(); + authManager_->authMessageProcessor_->authRequestContext_ = std::make_shared(); authManager_->authRequestContext_ = std::make_shared(); authManager_->authRequestState_ = std::make_shared(); authManager_->authResponseContext_ = std::make_shared(); @@ -1360,7 +1361,7 @@ HWTEST_F(DmAuthManagerTest, AuthenticateDevice_004, testing::ext::TestSize.Level authManager_->authUiStateMgr_ = std::make_shared(listener); authManager_->authenticationMap_.insert(std::pair>(authType, nullptr)); int32_t ret = authManager_->AuthenticateDevice(pkgName, authType, deviceId, extra); - ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, StopAuthenticateDevice_001, testing::ext::TestSize.Level0) @@ -1411,6 +1412,7 @@ HWTEST_F(DmAuthManagerTest, GetBindLevel_001, testing::ext::TestSize.Level0) std::string udid; authManager_->HandleDeviceNotTrust(udid); udid = "988989"; + authManager_->HandleDeviceNotTrust(udid); int32_t sessionId = 32166; authManager_->ProcIncompatible(sessionId); @@ -1466,11 +1468,11 @@ HWTEST_F(DmAuthManagerTest, IsAuthFinish_001, testing::ext::TestSize.Level0) authManager_->authResponseContext_->isIdenticalAccount = false; authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; - authManager_->authResponseContext_->isAuthCodeReady == false; + authManager_->authResponseContext_->isAuthCodeReady = false; ret = authManager_->IsAuthFinish(); EXPECT_TRUE(ret); - authManager_->authResponseContext_->isAuthCodeReady == true; + authManager_->authResponseContext_->isAuthCodeReady = true; ret = authManager_->IsAuthFinish(); EXPECT_FALSE(ret); diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 4aab3b743..839cbf38b 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -1474,8 +1474,9 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level ASSERT_FALSE(ret); authManager_->authRequestContext_ = std::make_shared(); - authManager_->authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT; - EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); + authManager_->authResponseContext_->accountGroupIdHash = OLD_VERSION_ACCOUNT; + EXPECT_CALL(*multipleUserConnectorMock_, + GetCurrentAccountUserID()).WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); ASSERT_TRUE(ret); @@ -1520,9 +1521,9 @@ HWTEST_F(DmAuthManagerTest, GetAccountGroupIdHash_201, testing::ext::TestSize.Le HWTEST_F(DmAuthManagerTest, CheckTrustState_003, testing::ext::TestSize.Level0) { - authManager_->authResponseContext_->reply == ERR_DM_AUTH_BUSINESS_BUSY; + authManager_->authResponseContext_->reply = ERR_DM_AUTH_BUSINESS_BUSY; authManager_->authResponseContext_->isIdenticalAccount = true; - authManager_->authResponseContext_->accountGroupIdHash == OLD_VERSION_ACCOUNT; + authManager_->authResponseContext_->accountGroupIdHash = OLD_VERSION_ACCOUNT; EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); int32_t ret = authManager_->CheckTrustState(); diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 25a406f28..4216204c3 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -1041,7 +1041,7 @@ HWTEST_F(SoftbusListenerTest, GetNetworkIdByUdid_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetNetworkIdByUdid(udid, networkId); - EXPECT_EQ(true, checkSoftbusRes(ret)); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(SoftbusListenerTest, SetLocalDeviceName_001, testing::ext::TestSize.Level0) @@ -1072,7 +1072,7 @@ HWTEST_F(SoftbusListenerTest, GetDeviceScreenStatus_001, testing::ext::TestSize. softbusListener = std::make_shared(); } int32_t ret = softbusListener->GetDeviceScreenStatus(networkId.c_str(), screenStatus); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_TRUE(checkSoftbusRes(ret)); softbusListener = nullptr; } } // namespace -- Gitee From afdbb1a096e8e6d627fccf3f6e9a9e18a7adfe5f Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 10:39:25 +0800 Subject: [PATCH 406/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichain_connector_fuzzer.cpp | 18 +++++++++--------- .../UTTest_dm_auth_manager_first.cpp | 8 +++----- .../UTTest_permission_manager.cpp | 2 +- test/unittest/mock/hichain_connector_mock.cpp | 6 +++--- 4 files changed, 16 insertions(+), 18 deletions(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 4c10c8324..7a807247b 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -274,8 +274,8 @@ void HiChainConnectorFifthFuzzTest(const uint8_t* data, size_t size) nlohmann::json jsonObj; jsonObj[AUTH_TYPE] = 1; jsonObj[FIELD_USER_ID] = "123456"; - jsonObj[FIELD_CREDENTIAL_TYPE] = 2; - jsonObj[FIELD_OPERATION_CODE] = 876; + jsonObj[FIELD_CREDENTIAL_TYPE] = 1; + jsonObj[FIELD_OPERATION_CODE] = 1; jsonObj[FIELD_TYPE] = "filed_type"; jsonObj[FIELD_DEVICE_LIST] = "device_list"; hichainConnector->deviceGroupManager_ = nullptr; @@ -309,17 +309,17 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) nlohmann::json jsonObj; std::string deviceId = "deviceId"; std::string key = "localDeviceId"; - jsonObj["deviceId"] = 32; + jsonObj["deviceId"] = 1; hichainConnector->GetJsonInt(jsonObj, key); hichainConnector->GetJsonInt(jsonObj, key); - jsonObj[key] = 87; + jsonObj[key] = 1; jsonObj["deviceName"] = "devieName1"; hichainConnector->GetJsonInt(jsonObj, "devieName"); hichainConnector->AddMember(deviceId, jsonObj.dump()); jsonObj[TAG_DEVICE_ID] = "deviceId_001"; - jsonObj[PIN_CODE_KEY] = 125; + jsonObj[PIN_CODE_KEY] = 1; jsonObj[TAG_GROUP_ID] = "groupId"; - jsonObj[TAG_REQUEST_ID] = 256; + jsonObj[TAG_REQUEST_ID] = 3; jsonObj[TAG_GROUP_NAME] = "groupName"; hichainConnector->AddMember(deviceId, jsonObj.dump()); @@ -327,14 +327,14 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) std::string params; jsonObjCre[AUTH_TYPE] = 1; jsonObjCre["userId"] = "user_001"; - jsonObjCre[FIELD_CREDENTIAL_TYPE] = 25; - jsonObjCre[FIELD_OPERATION_CODE] = 33; + jsonObjCre[FIELD_CREDENTIAL_TYPE] = 1; + jsonObjCre[FIELD_OPERATION_CODE] = 2; jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; std::string credentialInfo = jsonObjCre.dump(); hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); int32_t groupType = *(reinterpret_cast(data)); - nlohmann::json jsonDeviceList; + nlohmann::json jsonDeviceList; int32_t osAccountUserId = 0; std::string userId = "user_002"; jsonDeviceList[FIELD_DEVICE_LIST] = "deviceList"; diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 05cf6fb4b..a93b2eb23 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -28,7 +28,7 @@ static bool g_reportAuthOpenSessionReturnBoolValue = false; static bool g_reportAuthConfirmBoxReturnBoolValue = false; -constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; +constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5"; constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; @@ -78,7 +78,6 @@ void DmAuthManagerTest::SetUpTestCase() DmSoftbusSession::dmSoftbusSession = softbusSessionMock_; DmAppManager::dmAppManager = appManagerMock_; DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; - } void DmAuthManagerTest::TearDownTestCase() { @@ -1145,7 +1144,7 @@ HWTEST_F(DmAuthManagerTest, PutAccessControlList001, testing::ext::TestSize.Leve authManager_->authResponseContext_->localAccountId = "ohosAnonymousUid"; authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; authManager_->PutAccessControlList(); - ASSERT_EQ(authManager_->isIdenticalAccount, false); + ASSERT_EQ(authManager_->authResponseContext_->isIdenticalAccount, false); } HWTEST_F(DmAuthManagerTest, ProcessSourceMsg_001, testing::ext::TestSize.Level0) @@ -1424,7 +1423,6 @@ HWTEST_F(DmAuthManagerTest, GetBindLevel_001, testing::ext::TestSize.Level0) ret = authManager_->GetBindLevel(bindLevel); ASSERT_EQ(ret, APP); - int32_t sessionId = 123; authManager_->authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE; authManager_->authResponseContext_->importAuthCode = "importAuthCode"; authManager_->importAuthCode_ = "importAuthCode"; @@ -1490,7 +1488,7 @@ HWTEST_F(DmAuthManagerTest, IsAuthFinish_001, testing::ext::TestSize.Level0) authManager_->authResponseContext_->isOnline = false; authManager_->authResponseContext_->importAuthCode = "importAuthCode"; authManager_->authResponseContext_->isIdenticalAccount = false; - authResponseContext_->isAuthCodeReady = true; + authManager_->authResponseContext_->isAuthCodeReady = true; authManager_->ProcessAuthRequestExt(sessionId); } } // namespace diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index bd8f4fc9d..6b2cce709 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -252,7 +252,7 @@ HWTEST_F(PermissionManagerTest, CheckSystemSA_102, testing::ext::TestSize.Level0 HWTEST_F(PermissionManagerTest, CheckMonitorPermission_001, testing::ext::TestSize.Level0) { - bool ret = PermissionManager::GetInstance().CheckMonitorPermission(pkgName); + bool ret = PermissionManager::GetInstance().CheckMonitorPermission(); ASSERT_TRUE(ret); } diff --git a/test/unittest/mock/hichain_connector_mock.cpp b/test/unittest/mock/hichain_connector_mock.cpp index 2ce92be7d..467c16fab 100644 --- a/test/unittest/mock/hichain_connector_mock.cpp +++ b/test/unittest/mock/hichain_connector_mock.cpp @@ -26,7 +26,7 @@ bool HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &que groupInfo.groupName = "group1"; groupInfo.groupId = "123456"; groupInfo.groupOwner = "sdsd"; - groupInfo.groupType = 2; + groupInfo.groupType = 1; groupInfo.groupVisibility = 0; groupInfo.userId = "82898"; @@ -34,7 +34,7 @@ bool HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &que groupInfo2.groupName = "group2"; groupInfo2.groupId = "123456"; groupInfo2.groupOwner = "sdsd"; - groupInfo2.groupType = 2; + groupInfo2.groupType = 1; groupInfo2.groupVisibility = 0; groupInfo2.userId = "82898"; @@ -42,7 +42,7 @@ bool HiChainConnector::GetGroupInfo(const int32_t userId, const std::string &que groupInfo3.groupName = "group3"; groupInfo3.groupId = "123456"; groupInfo3.groupOwner = "sdsd"; - groupInfo3.groupType = 2; + groupInfo3.groupType = 1; groupInfo3.groupVisibility = 0; groupInfo3.userId = "82898"; -- Gitee From 4e002347c819fe9293b9c6e38e6eacf9314fcc74 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 11:33:05 +0800 Subject: [PATCH 407/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../hichain_connector_fuzzer.cpp | 4 ++-- test/commonunittest/UTTest_dm_auth_manager_first.cpp | 12 ++++++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index 7a807247b..dce86d574 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -319,7 +319,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObj[TAG_DEVICE_ID] = "deviceId_001"; jsonObj[PIN_CODE_KEY] = 1; jsonObj[TAG_GROUP_ID] = "groupId"; - jsonObj[TAG_REQUEST_ID] = 3; + jsonObj[TAG_REQUEST_ID] = 1; jsonObj[TAG_GROUP_NAME] = "groupName"; hichainConnector->AddMember(deviceId, jsonObj.dump()); @@ -328,7 +328,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObjCre[AUTH_TYPE] = 1; jsonObjCre["userId"] = "user_001"; jsonObjCre[FIELD_CREDENTIAL_TYPE] = 1; - jsonObjCre[FIELD_OPERATION_CODE] = 2; + jsonObjCre[FIELD_OPERATION_CODE] = 1; jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; std::string credentialInfo = jsonObjCre.dump(); diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index a93b2eb23..4375de24d 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1329,21 +1329,25 @@ HWTEST_F(DmAuthManagerTest, GetTaskTimeout_001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize.Level0) { std::string extra = R"({"extra": {"bindLevel": 1}})"; + nlohmann::json jsonObject; + jsonObject["bindLevel"] = 1; EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); + extra = jsonObject.dump(); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); - extra = R"({"extra": {"bindLevel": 789}})"; + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); ret = authManager_->CheckAuthParamVaildExtra(extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, DM_OK); - extra = R"({"extra": {"bindLevel": 789})"; + jsonObject["bindLevel"] = 15; + extra = jsonObject.dump(); ret = authManager_->CheckAuthParamVaildExtra(extra); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DmAuthManagerTest, AuthenticateDevice_004, testing::ext::TestSize.Level0) -- Gitee From 52c0ffb7ed1d7cf49803e175c476b4b9407fcebb Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 11:38:07 +0800 Subject: [PATCH 408/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/softbusunittest/UTTest_softbus_listener.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 4216204c3..5a2d2d2e6 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -955,7 +955,7 @@ HWTEST_F(SoftbusListenerTest, GetIPAddrTypeFromCache_004, testing::ext::TestSize } int32_t ret = softbusListener->GetIPAddrTypeFromCache(deviceId, ip, addrType); softbusListener->CacheDeviceInfo(deviceId, infoPtr); - EXPECT_EQ(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_BIND_INPUT_PARA_INVALID); } HWTEST_F(SoftbusListenerTest, InitSoftbusListener_001, testing::ext::TestSize.Level0) -- Gitee From 1047a04059ff8a63f3a8377b4eb23063bf22399d Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 15:14:58 +0800 Subject: [PATCH 409/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_auth_manager_first.cpp | 21 +++++++++++-------- .../UTTest_dm_auth_manager_first.h | 3 --- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 4375de24d..7be942166 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -77,13 +77,16 @@ void DmAuthManagerTest::SetUpTestCase() { DmSoftbusSession::dmSoftbusSession = softbusSessionMock_; DmAppManager::dmAppManager = appManagerMock_; - DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; } void DmAuthManagerTest::TearDownTestCase() { - softbusSessionMock_ = nullptr; - appManagerMock_ = nullptr; - multipleUserConnectorMock_ = nullptr; + if (softbusSessionMock_ != nullptr) { + softbusSessionMock_ = nullptr; + } + + if (appManagerMock_ != nullptr) { + appManagerMock_ = nullptr; + } } namespace { @@ -1335,18 +1338,18 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - extra = jsonObject.dump(); + std::string extra1 extra = jsonObject.dump(); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); - ret = authManager_->CheckAuthParamVaildExtra(extra); + ret = authManager_->CheckAuthParamVaildExtra(extra1); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); - ret = authManager_->CheckAuthParamVaildExtra(extra); + ret = authManager_->CheckAuthParamVaildExtra(extra1); EXPECT_EQ(ret, DM_OK); jsonObject["bindLevel"] = 15; - extra = jsonObject.dump(); - ret = authManager_->CheckAuthParamVaildExtra(extra); + std::string extra2 = jsonObject.dump(); + ret = authManager_->CheckAuthParamVaildExtra(extra2); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.h b/test/commonunittest/UTTest_dm_auth_manager_first.h index 8bcb5d787..35620fc65 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.h +++ b/test/commonunittest/UTTest_dm_auth_manager_first.h @@ -35,7 +35,6 @@ #include "dm_auth_manager.h" #include "softbus_session_mock.h" #include "app_manager_mock.h" -#include "multiple_user_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -56,8 +55,6 @@ public: static inline std::shared_ptr softbusSessionMock_ = std::make_shared(); static inline std::shared_ptr appManagerMock_ = std::make_shared(); - static inline std::shared_ptr multipleUserConnectorMock_ = - std::make_shared(); }; class AuthRequestFinishStateMock : public AuthRequestFinishState { -- Gitee From 4df147a82887f18f5d6ea8ea7791a9b84e6b7b63 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 15:33:47 +0800 Subject: [PATCH 410/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_auth_manager_first.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 7be942166..a7f4c5cc9 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1338,7 +1338,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - std::string extra1 extra = jsonObject.dump(); + std::string extra1 = jsonObject.dump(); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra1); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -- Gitee From da472bdd168b39923802cadcf500c44a171de09b Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 16:47:24 +0800 Subject: [PATCH 411/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_auth_manager_first.cpp | 25 ++++++++----------- .../UTTest_dm_auth_manager_first.h | 5 ++-- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index a7f4c5cc9..6a8619a99 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -75,18 +75,17 @@ void DmAuthManagerTest::SetUp() void DmAuthManagerTest::TearDown() {} void DmAuthManagerTest::SetUpTestCase() { + softbusSessionMock_ = std::make_shared(); DmSoftbusSession::dmSoftbusSession = softbusSessionMock_; + appManagerMock_ = std::make_shared(); DmAppManager::dmAppManager = appManagerMock_; } void DmAuthManagerTest::TearDownTestCase() { - if (softbusSessionMock_ != nullptr) { - softbusSessionMock_ = nullptr; - } - - if (appManagerMock_ != nullptr) { - appManagerMock_ = nullptr; - } + DmSoftbusSession::dmSoftbusSession = nullptr; + softbusSessionMock_ = nullptr; + DmAppManager::dmAppManager = nullptr; + appManagerMock_ = nullptr; } namespace { @@ -1338,18 +1337,14 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - std::string extra1 = jsonObject.dump(); + extra = jsonObject.dump(); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); - ret = authManager_->CheckAuthParamVaildExtra(extra1); + ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); - EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); - ret = authManager_->CheckAuthParamVaildExtra(extra1); - EXPECT_EQ(ret, DM_OK); - jsonObject["bindLevel"] = 15; - std::string extra2 = jsonObject.dump(); - ret = authManager_->CheckAuthParamVaildExtra(extra2); + extra = jsonObject.dump(); + ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.h b/test/commonunittest/UTTest_dm_auth_manager_first.h index 35620fc65..65ecabeed 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.h +++ b/test/commonunittest/UTTest_dm_auth_manager_first.h @@ -52,9 +52,8 @@ public: std::shared_ptr authManager_ = std::make_shared(softbusConnector, hiChainConnector, listener, hiChainAuthConnector); - static inline std::shared_ptr softbusSessionMock_ - = std::make_shared(); - static inline std::shared_ptr appManagerMock_ = std::make_shared(); + static inline std::shared_ptr softbusSessionMock_ = nullptr; + static inline std::shared_ptr appManagerMock_ = nullptr; }; class AuthRequestFinishStateMock : public AuthRequestFinishState { -- Gitee From d45a26add843bcb9021cbba8e28aa438189beffb Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 18:25:27 +0800 Subject: [PATCH 412/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_auth_manager_first.cpp | 8 +++++--- .../commonunittest/UTTest_dm_auth_manager_second.cpp | 8 ++++++++ test/commonunittest/UTTest_dm_auth_manager_second.h | 12 ++++-------- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 6a8619a99..0c73ae52e 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1330,15 +1330,17 @@ HWTEST_F(DmAuthManagerTest, GetTaskTimeout_001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize.Level0) { - std::string extra = R"({"extra": {"bindLevel": 1}})"; + std::string extra = R"({"extra": {"bindLevel": "123"}})"; nlohmann::json jsonObject; jsonObject["bindLevel"] = 1; - EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); extra = jsonObject.dump(); - EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); + ret = authManager_->CheckAuthParamVaildExtra(extra); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 839cbf38b..031bc16ef 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -54,16 +54,24 @@ void DmAuthManagerTest::TearDown() } void DmAuthManagerTest::SetUpTestCase() { + hiChainConnectorMock_ = std::make_shared(); DmHiChainConnector::dmHiChainConnector = hiChainConnectorMock_; + multipleUserConnectorMock_ = std::make_shared(); DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; + softbusConnectorMock_ = std::make_shared(); DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock_; + hiChainAuthConnectorMock_ = std::make_shared(); DmHiChainAuthConnector::dmHiChainAuthConnector = hiChainAuthConnectorMock_; } void DmAuthManagerTest::TearDownTestCase() { + DmHiChainConnector::dmHiChainConnector = nullptr; hiChainConnectorMock_ = nullptr; + DmMultipleUserConnector::dmMultipleUserConnector = = nullptr; multipleUserConnectorMock_ = nullptr; + DmSoftbusConnector::dmSoftbusConnector = = nullptr; softbusConnectorMock_ = nullptr; + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; hiChainAuthConnectorMock_ = nullptr; } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.h b/test/commonunittest/UTTest_dm_auth_manager_second.h index f8fac51fa..001074653 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.h +++ b/test/commonunittest/UTTest_dm_auth_manager_second.h @@ -48,14 +48,10 @@ public: void TearDown(); std::shared_ptr authManager_; - static inline std::shared_ptr hiChainConnectorMock_ = - std::make_shared(); - static inline std::shared_ptr multipleUserConnectorMock_ = - std::make_shared(); - static inline std::shared_ptr softbusConnectorMock_ = - std::make_shared(); - static inline std::shared_ptr hiChainAuthConnectorMock_ = - std::make_shared(); + static inline std::shared_ptr hiChainConnectorMock_ = nullptr; + static inline std::shared_ptr multipleUserConnectorMock_ = nullptr; + static inline std::shared_ptr softbusConnectorMock_ = nullptr; + static inline std::shared_ptr hiChainAuthConnectorMock_ = nullptr; }; class AuthResponseInitStateMock : public AuthResponseInitState { -- Gitee From c08311a413cd2638430ab9783a3f9b7087a6254b Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 19:10:21 +0800 Subject: [PATCH 413/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../implementation/src/authentication/dm_auth_manager.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index c6a7e68ea..ed314c32d 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -172,7 +172,10 @@ int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra) return DM_OK; } int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); - if (static_cast(bindLevel) > APP || static_cast(bindLevel) < INVALID_TYPE) { + uint32_t bindTmp = static_cast(bindLevel); + LOGI("bindlevel msg %{public}d.", bindTmp); + LOGI("bindlevel msgdwedw %{public}d.", INVALID_TYPE); + if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { LOGE("bindlevel error %{public}d.", bindLevel); return ERR_DM_INPUT_PARA_INVALID; } -- Gitee From f3764f0ebc976daf6396df1f72985a673b320b16 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 19 Nov 2024 19:21:22 +0800 Subject: [PATCH 414/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- services/implementation/src/authentication/dm_auth_manager.cpp | 3 --- test/commonunittest/UTTest_dm_auth_manager_first.cpp | 3 ++- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index ed314c32d..1af4513ae 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -172,9 +172,6 @@ int32_t DmAuthManager::CheckAuthParamVaildExtra(const std::string &extra) return DM_OK; } int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); - uint32_t bindTmp = static_cast(bindLevel); - LOGI("bindlevel msg %{public}d.", bindTmp); - LOGI("bindlevel msgdwedw %{public}d.", INVALID_TYPE); if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { LOGE("bindlevel error %{public}d.", bindLevel); return ERR_DM_INPUT_PARA_INVALID; diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 0c73ae52e..268e759de 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1337,12 +1337,13 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); extra = jsonObject.dump(); + EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(true)); ret = authManager_->CheckAuthParamVaildExtra(extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, DM_OK); jsonObject["bindLevel"] = 15; extra = jsonObject.dump(); -- Gitee From ab6474d779f3eade7e80d45284b43c8313336af2 Mon Sep 17 00:00:00 2001 From: wangbaidong Date: Tue, 19 Nov 2024 16:24:03 +0800 Subject: [PATCH 415/520] 1119 Signed-off-by: wangbaidong --- test/unittest/BUILD.gn | 46 ++++ test/unittest/UTTest_dm_comm_tool.cpp | 63 ++++++ test/unittest/UTTest_dm_comm_tool.h | 38 ++++ test/unittest/UTTest_dm_transport.cpp | 206 ++++++++++++++++++ test/unittest/UTTest_dm_transport.h | 47 ++++ test/unittest/UTTest_dm_transport_msg.cpp | 185 ++++++++++++++++ test/unittest/UTTest_dm_transport_msg.h | 35 +++ .../unittest/UTTest_relationship_sync_mgr.cpp | 148 +++++++++++++ test/unittest/UTTest_relationship_sync_mgr.h | 4 + 9 files changed, 772 insertions(+) create mode 100644 test/unittest/UTTest_dm_comm_tool.cpp create mode 100644 test/unittest/UTTest_dm_comm_tool.h create mode 100644 test/unittest/UTTest_dm_transport.cpp create mode 100644 test/unittest/UTTest_dm_transport.h create mode 100644 test/unittest/UTTest_dm_transport_msg.cpp create mode 100644 test/unittest/UTTest_dm_transport_msg.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 7aa9ecff1..e0b45237b 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -36,6 +36,7 @@ group("unittest") { ":UTTest_dm_auth_manager_first", ":UTTest_dm_auth_manager_second", ":UTTest_dm_auth_manager_third", + ":UTTest_dm_comm_tool", ":UTTest_dm_common_event_manager", ":UTTest_dm_credential_manager", ":UTTest_dm_crypto", @@ -54,6 +55,8 @@ group("unittest") { ":UTTest_dm_screen_common_event", ":UTTest_dm_service_load", ":UTTest_dm_timer", + ":UTTest_dm_transport", + ":UTTest_dm_transport_msg", ":UTTest_hichain_auth_connector", ":UTTest_hichain_connector", ":UTTest_ipc_client_manager", @@ -648,6 +651,35 @@ ohos_unittest("UTTest_dm_timer") { ## UnitTest UTTest_dm_timer }}} +## UnitTest UTTest_dm_transport {{{ +ohos_unittest("UTTest_dm_transport") { + module_out_path = module_out_path + include_dirs = [ "${devicemanager_path}/test/unittest" ] + sources = [ "${devicemanager_path}/test/unittest/UTTest_dm_transport.cpp" ] + deps = [ ":device_manager_test_common" ] + external_deps = [ + "cJSON:cjson", + "googletest:gmock", + ] +} + +## UnitTest UTTest_dm_transport }}} + +## UnitTest UTTest_dm_transport_msg {{{ +ohos_unittest("UTTest_dm_transport_msg") { + module_out_path = module_out_path + include_dirs = [ "${devicemanager_path}/test/unittest" ] + sources = + [ "${devicemanager_path}/test/unittest/UTTest_dm_transport_msg.cpp" ] + deps = [ ":device_manager_test_common" ] + external_deps = [ + "cJSON:cjson", + "googletest:gmock", + ] +} + +## UnitTest UTTest_dm_transport_msg }}} + ## UnitTest UTTest_dm_service_load {{{ ohos_unittest("UTTest_dm_service_load") { module_out_path = module_out_path @@ -1349,6 +1381,20 @@ ohos_unittest("UTTest_dm_distributed_hardware_load") { ## UnitTest UTTest_dm_distributed_hardware_load }}} +## UnitTest UTTest_dm_comm_tool {{{ +ohos_unittest("UTTest_dm_comm_tool") { + module_out_path = module_out_path + include_dirs = [ "${devicemanager_path}/test/unittest" ] + sources = [ "${devicemanager_path}/test/unittest/UTTest_dm_comm_tool.cpp" ] + deps = [ ":device_manager_test_common" ] + external_deps = [ + "cJSON:cjson", + "googletest:gmock", + ] +} + +## UnitTest UTTest_dm_comm_tool }}} + ## UnitTest UTTest_dm_crypto {{{ ohos_unittest("UTTest_dm_crypto") { module_out_path = module_out_path diff --git a/test/unittest/UTTest_dm_comm_tool.cpp b/test/unittest/UTTest_dm_comm_tool.cpp new file mode 100644 index 000000000..df499e9b2 --- /dev/null +++ b/test/unittest/UTTest_dm_comm_tool.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_comm_tool.h" + +namespace OHOS { +namespace DistributedHardware { +void DMCommToolTest::SetUp() +{ + dmCommTool = DMCommTool::GetInstance(); +} +void DMCommToolTest::TearDown() +{ +} +void DMCommToolTest::SetUpTestCase() +{ +} +void DMCommToolTest::TearDownTestCase() +{ +} + +/** + * @tc.name: Init_Success + * @tc.type: FUNC + */ +HWTEST_F(DMCommToolTest, Init_Success, testing::ext::TestSize.Level0) +{ + EXPECT_NO_THROW(dmCommTool->Init()); +} + +/** + * @tc.name: GetEventHandler_NotNull + * @tc.type: FUNC + */ +HWTEST_F(DMCommToolTest, GetEventHandler_NotNull, testing::ext::TestSize.Level0) +{ + auto handler = dmCommTool->GetEventHandler(); + EXPECT_NE(handler, nullptr); +} + +/** + * @tc.name: GetDMTransportPtr_NotNull + * @tc.type: FUNC + */ +HWTEST_F(DMCommToolTest, GetDMTransportPtr_NotNull, testing::ext::TestSize.Level0) +{ + auto transportPtr = dmCommTool->GetDMTransportPtr(); + EXPECT_NE(transportPtr, nullptr); +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_comm_tool.h b/test/unittest/UTTest_dm_comm_tool.h new file mode 100644 index 000000000..a992231be --- /dev/null +++ b/test/unittest/UTTest_dm_comm_tool.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_UTTEST_DM_COMM_TOOL_H +#define OHOS_UTTEST_DM_COMM_TOOL_H + +#include +#include +#include "dm_comm_tool.h" + +namespace OHOS { +namespace DistributedHardware { +class DMCommToolTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr dmCommTool; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_COMM_TOOL_H \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport.cpp b/test/unittest/UTTest_dm_transport.cpp new file mode 100644 index 000000000..e9b239dd3 --- /dev/null +++ b/test/unittest/UTTest_dm_transport.cpp @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_transport.h" + +namespace OHOS { +namespace DistributedHardware { +void DMTransportTest::SetUp() +{ +} +void DMTransportTest::TearDown() +{ +} +void DMTransportTest::SetUpTestCase() +{ +} +void DMTransportTest::TearDownTestCase() +{ +} + +/** + * @tc.name: CreateClientSocket_InvalidInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, CreateClientSocket_InvalidInput, testing::ext::TestSize.Level0) +{ + std::string rmtNetworkId = ""; + EXPECT_EQ(dmTransport.CreateClientSocket(rmtNetworkId), ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: Init_Success + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Init_Success, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.Init(), ERR_DM_FAILED); +} + +/** + * @tc.name: Init_AlreadyInitialized + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Init_AlreadyInitialized, testing::ext::TestSize.Level0) +{ + dmTransport.Init(); + EXPECT_EQ(dmTransport.Init(), ERR_DM_FAILED); +} + +/** + * @tc.name: UnInit_ShouldShutdownAllSockets + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, UnInit_ShouldShutdownAllSockets, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + dmTransport.StartSocket("device2"); + + EXPECT_EQ(dmTransport.UnInit(), DM_OK); + + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device2", socketId)); +} + +/** + * @tc.name: UnInit_ShouldNotShutdownWhenNoSockets + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, UnInit_ShouldNotShutdownWhenNoSockets, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.UnInit(), DM_OK); +} + +/** + * @tc.name: IsDeviceSessionOpened_ShouldReturnFalseForClosedSession + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, IsDeviceSessionOpened_ShouldReturnFalseForClosedSession, testing::ext::TestSize.Level0) +{ + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device2", socketId)); +} + +/** + * @tc.name: GetRemoteNetworkIdBySocketIdReturnEmptyString + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, GetRemoteNetworkIdBySocketIdReturnEmptyString, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.GetRemoteNetworkIdBySocketId(-1), ""); +} + +/** + * @tc.name: ClearDeviceSocketOpened_ShouldRemoveSocket + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, ClearDeviceSocketOpened_ShouldRemoveSocket, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + dmTransport.ClearDeviceSocketOpened("device1"); + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); +} + +/** + * @tc.name: ClearDeviceSocketOpened_ShouldDoNothingForInvalidId + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, ClearDeviceSocketOpened_ShouldDoNothingForInvalidId, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + dmTransport.ClearDeviceSocketOpened("invalid_device"); + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); +} + +/** + * @tc.name: StartSocket_ShouldCreateSocket + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StartSocket_ShouldCreateSocket, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.StartSocket("device1"), ERR_DM_FAILED); + int32_t socketId; + EXPECT_FALSE(dmTransport.IsDeviceSessionOpened("device1", socketId)); +} + +/** + * @tc.name: StartSocket_ShouldReturnErrorForInvalidId + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StartSocket_ShouldReturnErrorForInvalidId, testing::ext::TestSize.Level0) +{ + EXPECT_EQ(dmTransport.StartSocket(""), ERR_DM_INPUT_PARA_INVALID); +} + +/** + * @tc.name: StartSocket_ShouldReturnErrorIfAlreadyOpened + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StartSocket_ShouldReturnErrorIfAlreadyOpened, testing::ext::TestSize.Level0) +{ + dmTransport.StartSocket("device1"); + EXPECT_EQ(dmTransport.StartSocket("device1"), ERR_DM_FAILED); +} + +/** + * @tc.name: StopSocket_InvalidId_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StopSocket_InvalidId_Failure, testing::ext::TestSize.Level0) +{ + std::string invalidId = "invalidId"; + int32_t result = dmTransport.StopSocket(invalidId); + EXPECT_EQ(result, ERR_DM_FAILED); +} + +/** + * @tc.name: StopSocket_SessionNotOpened_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, StopSocket_SessionNotOpened_Failure, testing::ext::TestSize.Level0) +{ + std::string notOpenedId = "notOpenedId"; + int32_t result = dmTransport.StopSocket(notOpenedId); + EXPECT_EQ(result, ERR_DM_FAILED); +} + +/** + * @tc.name: Send_InvalidId_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Send_InvalidId_Failure, testing::ext::TestSize.Level0) +{ + std::string invalidId = "invalidId"; + std::string payload = "Hello, World!"; + int32_t result = dmTransport.Send(invalidId, payload); + EXPECT_EQ(result, ERR_DM_FAILED); +} + +/** + * @tc.name: Send_SessionNotOpened_Failure + * @tc.type: FUNC + */ +HWTEST_F(DMTransportTest, Send_SessionNotOpened_Failure, testing::ext::TestSize.Level0) +{ + std::string notOpenedId = "notOpenedId"; + std::string payload = "Hello, World!"; + int32_t result = dmTransport.Send(notOpenedId, payload); + EXPECT_EQ(result, ERR_DM_FAILED); +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport.h b/test/unittest/UTTest_dm_transport.h new file mode 100644 index 000000000..fcfebeb98 --- /dev/null +++ b/test/unittest/UTTest_dm_transport.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_UTTEST_DM_TRANSPORT_H +#define OHOS_UTTEST_DM_TRANSPORT_H + +#include +#include +#include +#include "dm_comm_tool.h" +#include "dm_transport.h" + +namespace OHOS { +namespace DistributedHardware { +class DMTransportTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +protected: + std::shared_ptr dmCommTool; + std::shared_ptr dmCommToolPtr = std::make_shared(); + DMTransport dmTransport = DMTransport(dmCommToolPtr); + + int32_t ERR_DM_FAILED = 96929744; + int32_t ERR_DM_INPUT_PARA_INVALID = 96929749; + uint32_t MAX_SEND_MSG_LENGTH = 4 * 1024 * 1024; + int32_t DM_OK = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_TRANSPORT_H \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport_msg.cpp b/test/unittest/UTTest_dm_transport_msg.cpp new file mode 100644 index 000000000..5f74a5b93 --- /dev/null +++ b/test/unittest/UTTest_dm_transport_msg.cpp @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "UTTest_dm_transport_msg.h" + +namespace OHOS { +namespace DistributedHardware { +void DMTransportMsgTest::SetUp() +{ +} +void DMTransportMsgTest::TearDown() +{ +} +void DMTransportMsgTest::SetUpTestCase() +{ +} +void DMTransportMsgTest::TearDownTestCase() +{ +} + +/** + * @tc.name: ToJsonAndFromJson + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, ToJsonAndFromJson, testing::ext::TestSize.Level0) +{ + UserIdsMsg userIdsMsg; + userIdsMsg.foregroundUserIds = {1, 2, 3}; + + cJSON *jsonObject = cJSON_CreateObject(); + ToJson(jsonObject, userIdsMsg); + + UserIdsMsg newUserIdsMsg; + FromJson(jsonObject, newUserIdsMsg); + + EXPECT_EQ(newUserIdsMsg.foregroundUserIds.size(), 3); + EXPECT_EQ(newUserIdsMsg.foregroundUserIds[0], 1); + EXPECT_EQ(newUserIdsMsg.foregroundUserIds[1], 2); + EXPECT_EQ(newUserIdsMsg.foregroundUserIds[2], 3); + + cJSON_Delete(jsonObject); + + cJSON *emptyJsonObject = cJSON_CreateObject(); + UserIdsMsg emptyUserIdsMsg; + FromJson(emptyJsonObject, emptyUserIdsMsg); + + EXPECT_EQ(emptyUserIdsMsg.foregroundUserIds.size(), 0); + cJSON_Delete(emptyJsonObject); +} + +/** + * @tc.name: ToJsonAndFromJson01 + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, ToJsonAndFromJson01, testing::ext::TestSize.Level0) +{ + CommMsg commMsg; + commMsg.code = 200; + commMsg.msg = "Success"; + + cJSON *jsonObject = cJSON_CreateObject(); + ToJson(jsonObject, commMsg); + + CommMsg newCommMsg; + FromJson(jsonObject, newCommMsg); + + EXPECT_EQ(newCommMsg.code, 200); + EXPECT_EQ(newCommMsg.msg, "Success"); + + cJSON_Delete(jsonObject); + + cJSON *emptyCommJsonObject = cJSON_CreateObject(); + CommMsg emptyCommMsg; + FromJson(emptyCommJsonObject, emptyCommMsg); + + EXPECT_EQ(emptyCommMsg.code, -1); + EXPECT_EQ(emptyCommMsg.msg, ""); + cJSON_Delete(emptyCommJsonObject); +} + +/** + * @tc.name: PerformanceTest + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, PerformanceTest, testing::ext::TestSize.Level0) +{ + UserIdsMsg userIdsMsg; + for (int i = 0; i < 10000; ++i) { + userIdsMsg.foregroundUserIds.push_back(i); + } + + cJSON *jsonObject = cJSON_CreateObject(); + auto start = std::chrono::high_resolution_clock::now(); + ToJson(jsonObject, userIdsMsg); + auto end = std::chrono::high_resolution_clock::now(); + std::chrono::duration elapsed = end - start; + + EXPECT_LT(elapsed.count(), 1.0); + cJSON_Delete(jsonObject); +} + +/** + * @tc.name: GetCommMsgString_EmptyInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, GetCommMsgString_EmptyInput, testing::ext::TestSize.Level0) +{ + CommMsg commMsg; + std::string result = GetCommMsgString(commMsg); + EXPECT_FALSE(result.empty()); +} + +/** + * @tc.name: ToJson_ValidInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, ToJson_ValidInput, testing::ext::TestSize.Level0) +{ + cJSON *jsonObject = cJSON_CreateObject(); + NotifyUserIds notifyUserIds; + notifyUserIds.remoteUdid = "test_udid"; + notifyUserIds.userIds = {1, 2, 3}; + + ToJson(jsonObject, notifyUserIds); + cJSON *udidItem = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY); + EXPECT_STREQ(udidItem->valuestring, "test_udid"); + cJSON *userIdsArr = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY); + EXPECT_EQ(cJSON_GetArraySize(userIdsArr), 3); +} + +/** + * @tc.name: FromJson_InvalidJson + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, FromJson_InvalidJson, testing::ext::TestSize.Level0) +{ + const char *jsonString = "{\"udid\":123,\"userIds\":\"invalid\"}"; + cJSON *jsonObject = cJSON_Parse(jsonString); + NotifyUserIds notifyUserIds; + + FromJson(jsonObject, notifyUserIds); + EXPECT_TRUE(notifyUserIds.remoteUdid.empty()); + EXPECT_TRUE(notifyUserIds.userIds.empty()); + + cJSON_Delete(jsonObject); +} + +/** + * @tc.name: NotifyUserIds_ToString_ValidInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, NotifyUserIds_ToString_ValidInput, testing::ext::TestSize.Level0) +{ + NotifyUserIds notifyUserIds; + notifyUserIds.remoteUdid = "test_udid"; + notifyUserIds.userIds = {1, 2, 3}; + + std::string result = notifyUserIds.ToString(); + EXPECT_FALSE(result.empty()); +} + +/** + * @tc.name: NotifyUserIds_ToString_EmptyInput + * @tc.type: FUNC + */ +HWTEST_F(DMTransportMsgTest, NotifyUserIds_ToString_EmptyInput, testing::ext::TestSize.Level0) +{ + NotifyUserIds notifyUserIds; + std::string result = notifyUserIds.ToString(); + EXPECT_FALSE(result.empty()); +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport_msg.h b/test/unittest/UTTest_dm_transport_msg.h new file mode 100644 index 000000000..90a8716d3 --- /dev/null +++ b/test/unittest/UTTest_dm_transport_msg.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_UTTEST_DM_TRANSPORT_MSG_H +#define OHOS_UTTEST_DM_TRANSPORT_MSG_H + +#include +#include +#include "dm_transport_msg.h" + +namespace OHOS { +namespace DistributedHardware { +class DMTransportMsgTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +} // namespace DistributedHardware +} // namespace OHOS + +#endif // OHOS_UTTEST_DM_TRANSPORT_MSG_H \ No newline at end of file diff --git a/test/unittest/UTTest_relationship_sync_mgr.cpp b/test/unittest/UTTest_relationship_sync_mgr.cpp index 3fb543097..de25ec0f6 100644 --- a/test/unittest/UTTest_relationship_sync_mgr.cpp +++ b/test/unittest/UTTest_relationship_sync_mgr.cpp @@ -240,6 +240,154 @@ HWTEST_F(ReleationShipSyncMgrTest, ParseTrustRelationShipChange_005, testing::ex ReleationShipSyncMgr::GetInstance().ParseTrustRelationShipChange(msg); ASSERT_EQ(relationShipMsg.userId, UINT32_MAX); } + +HWTEST_F(ReleationShipSyncMgrTest, ToSyncFrontOrBackUserIdPayLoad_ValidInput, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.userIdInfos.push_back({12345, true}); + msg.userIdInfos.push_back({67890, false}); + + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + + bool result = msg.ToSyncFrontOrBackUserIdPayLoad(msgPtr, len); + + ASSERT_TRUE(result); + ASSERT_EQ(len, 5); + ASSERT_EQ(msgPtr[0], 2); + + delete[] msgPtr; + msg.userIdInfos.clear(); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToDelUserPayLoad_ValidInput, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.userId = 12345; + + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + + msg.ToDelUserPayLoad(msgPtr, len); + + ASSERT_EQ(len, DEL_USER_PAYLOAD_LEN); + ASSERT_EQ(msgPtr[0], 0x39); + + delete[] msgPtr; + msg.userIdInfos.clear(); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToSyncFrontOrBackUserIdPayLoad_TooManyUserIds, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + for (int i = 0; i < MAX_USER_ID_NUM + 1; ++i) { + msg.userIdInfos.push_back({i, true}); + } + + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + + bool result = msg.ToSyncFrontOrBackUserIdPayLoad(msgPtr, len); + + ASSERT_FALSE(result); + ASSERT_EQ(msgPtr, nullptr); + msg.userIdInfos.clear(); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToSyncFrontOrBackUserIdPayLoad_LengthExceedsLimit, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.userIdInfos.push_back({12345, true}); + msg.userIdInfos.push_back({67890, false}); + uint8_t* msgPtr = nullptr; + uint32_t len = 0; + bool result = msg.ToSyncFrontOrBackUserIdPayLoad(msgPtr, len); + ASSERT_TRUE(result); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToString_ValidData, testing::ext::TestSize.Level0) +{ + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::APP_UNBIND; + msg.userId = 12345; + msg.accountId = "account_123"; + msg.tokenId = 67890; + msg.peerUdids = {"udid1", "udid2"}; + msg.peerUdid = "peer_udid"; + msg.accountName = "test_account"; + msg.syncUserIdFlag = true; + msg.userIdInfos = {{true, 111}, {false, 222}}; + + std::string expected = "{ MsgType: " + std::to_string(static_cast(msg.type)) + + ", userId: 12345, accountId: a******3, tokenId: 67890, " + + "peerUdids: [ u******1, u******2 ], peerUdid: p******d, " + + "accountName: t******t, syncUserIdFlag: 1, " + + "userIds: [ { 1, userId: 111 }, { 0, userId: 222 } ] }"; + + EXPECT_EQ(msg.ToString(), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToString_ValidData02, testing::ext::TestSize.Level0) +{ + bool isForeground = true; + std::uint16_t userId = 123; + UserIdInfo userIdInfo(isForeground, userId); + std::string expected = "{ 1, userId: 123 }"; + EXPECT_EQ(userIdInfo.ToString(), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ToString_ZeroUserId, testing::ext::TestSize.Level0) +{ + bool isForeground = false; + std::uint16_t userId = 0; + UserIdInfo userIdInfo(isForeground, userId); + + std::string expected = "{ 0, userId: 0 }"; + EXPECT_EQ(userIdInfo.ToString(), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ValidList, testing::ext::TestSize.Level0) +{ + std::vector list = {{true, 1}, {false, 2}}; + std::string expected = "[ { 1, userId: 1 }, { 0, userId: 2 } ]"; + + EXPECT_EQ(GetUserIdInfoList(list), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, EmptyList, testing::ext::TestSize.Level0) +{ + std::vector list; + std::string expected = "[ ]"; + + EXPECT_EQ(GetUserIdInfoList(list), expected); +} + +HWTEST_F(ReleationShipSyncMgrTest, ValidData, testing::ext::TestSize.Level0) +{ + std::vector remoteUserIdInfos = {{true, 1}, {false, 2}, {true, 3}}; + std::vector foregroundUserIdInfos; + std::vector backgroundUserIdInfos; + + GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos); + + EXPECT_EQ(foregroundUserIdInfos.size(), 2); + EXPECT_EQ(backgroundUserIdInfos.size(), 1); + EXPECT_EQ(foregroundUserIdInfos[0].userId, 1); + EXPECT_EQ(foregroundUserIdInfos[1].userId, 3); + EXPECT_EQ(backgroundUserIdInfos[0].userId, 2); +} + +HWTEST_F(ReleationShipSyncMgrTest, EmptyRemoteList, testing::ext::TestSize.Level0) +{ + std::vector remoteUserIdInfos; + std::vector foregroundUserIdInfos; + std::vector backgroundUserIdInfos; + + GetFrontAndBackUserIdInfos(remoteUserIdInfos, foregroundUserIdInfos, backgroundUserIdInfos); + + EXPECT_TRUE(foregroundUserIdInfos.empty()); + EXPECT_TRUE(backgroundUserIdInfos.empty()); +} } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_relationship_sync_mgr.h b/test/unittest/UTTest_relationship_sync_mgr.h index 1b81d0ae0..60422d537 100644 --- a/test/unittest/UTTest_relationship_sync_mgr.h +++ b/test/unittest/UTTest_relationship_sync_mgr.h @@ -29,6 +29,10 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + +protected: + int32_t FRONT_OR_BACK_USER_FLAG_OFFSET = 7; + int32_t DEL_USER_PAYLOAD_LEN = 2; }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 7d24de771a424a8cad0c9088ef309c26d694cbd7 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 20 Nov 2024 09:08:16 +0800 Subject: [PATCH 416/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_auth_manager_second.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 031bc16ef..b5df17b9b 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -67,9 +67,9 @@ void DmAuthManagerTest::TearDownTestCase() { DmHiChainConnector::dmHiChainConnector = nullptr; hiChainConnectorMock_ = nullptr; - DmMultipleUserConnector::dmMultipleUserConnector = = nullptr; + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; multipleUserConnectorMock_ = nullptr; - DmSoftbusConnector::dmSoftbusConnector = = nullptr; + DmSoftbusConnector::dmSoftbusConnector = nullptr;git softbusConnectorMock_ = nullptr; DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; hiChainAuthConnectorMock_ = nullptr; -- Gitee From ed270574fd338dd488c9096c1508d7cc6083e992 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 20 Nov 2024 09:09:16 +0800 Subject: [PATCH 417/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84ut?= =?UTF-8?q?=E5=92=8Cfuzz=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_auth_manager_second.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index b5df17b9b..9561e1df7 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -69,7 +69,7 @@ void DmAuthManagerTest::TearDownTestCase() hiChainConnectorMock_ = nullptr; DmMultipleUserConnector::dmMultipleUserConnector = nullptr; multipleUserConnectorMock_ = nullptr; - DmSoftbusConnector::dmSoftbusConnector = nullptr;git + DmSoftbusConnector::dmSoftbusConnector = nullptr; softbusConnectorMock_ = nullptr; DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; hiChainAuthConnectorMock_ = nullptr; -- Gitee From 8aec3ea34ed291c3f89353ada6f51255359b04a0 Mon Sep 17 00:00:00 2001 From: vv Date: Tue, 19 Nov 2024 22:28:35 +0800 Subject: [PATCH 418/520] =?UTF-8?q?DM=E5=A4=9A=E7=94=A8=E6=88=B7=E9=9C=80?= =?UTF-8?q?=E6=B1=82UT=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: vv --- ...Test_dm_deviceprofile_connector_second.cpp | 240 ++++++++++++++++++ ...UTTest_dm_deviceprofile_connector_second.h | 2 + 2 files changed, 242 insertions(+) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 692c4a701..01e3f9070 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -42,6 +42,58 @@ void DeviceProfileConnectorSecondTest::TearDownTestCase() distributedDeviceProfileClientMock_ = nullptr; } +void AddAccessControlProfile(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + HWTEST_F(DeviceProfileConnectorSecondTest, GetAccessControlProfile_201, testing::ext::TestSize.Level0) { EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); @@ -111,5 +163,193 @@ HWTEST_F(DeviceProfileConnectorSecondTest, GetAllAccessControlProfile_201, testi auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); EXPECT_TRUE(ret.empty()); } + +HWTEST_F(DeviceProfileConnectorSecondTest, DeleteAclForAccountLogOut_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_device_id"; + int32_t localUserId = 1; + std::string peerUdid = "peer_device_id"; + int32_t peerUserId = 2; + int32_t result = connector.DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + + EXPECT_EQ(result, false); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, DeleteAppBindLevel_001, testing::ext::TestSize.Level0) +{ + DmOfflineParam offlineParam; + std::string pkgName = "com.example.app"; + std::vector profiles = {}; + std::string localUdid = "local_udid"; + std::string remoteUdid = "remote_udid"; + connector.DeleteAppBindLevel(offlineParam, pkgName, profiles, localUdid, remoteUdid); + + EXPECT_EQ(offlineParam.processVec.size(), 0); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, CheckIsSameAccount_001, testing::ext::TestSize.Level0) +{ + DmAccessCaller caller; + caller.pkgName = "test_pkg"; + std::string srcUdid = "src_udid"; + DmAccessCallee callee; + std::string sinkUdid = "non_identical_udid"; + + EXPECT_EQ(connector.CheckIsSameAccount(caller, srcUdid, callee, sinkUdid), ERR_DM_FAILED); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDeviceIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::vector userIds = {4, 5, 6}; + std::string localUdid = "local_udid"; + auto result = connector.GetDeviceIdAndBindLevel(userIds, localUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByUserId_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "localDevice"; + int32_t userId = -1; + std::string remoteUdid = "remoteDevice"; + auto result = connector.GetAclProfileByUserId(localUdid, userId, remoteUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByUserId_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "localDevice"; + int32_t userId = 1; + std::string remoteUdid = "nonExistentDevice"; + auto result = connector.GetAclProfileByUserId(localUdid, userId, remoteUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByUserId_003, testing::ext::TestSize.Level0) +{ + std::string localUdid = ""; + int32_t userId = 0; + std::string remoteUdid = ""; + auto result = connector.GetAclProfileByUserId(localUdid, userId, remoteUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetOfflineProcessInfo_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "invalid_device"; + std::vector localUserIds = {1, 2}; + std::string remoteUdid = "remote_device"; + std::vector remoteUserIds = {3, 4}; + std::vector result = + connector.GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, remoteUserIds); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetOfflineProcessInfo_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_device"; + std::vector localUserIds = {1, 2}; + std::string remoteUdid = "remote_device"; + std::vector remoteUserIds = {99, 100}; + std::vector result = + connector.GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, remoteUserIds); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetOfflineProcessInfo_003, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_device"; + std::vector localUserIds = {}; + std::string remoteUdid = "remote_device"; + std::vector remoteUserIds = {3, 4}; + std::vector result = + connector.GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, remoteUserIds); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetUserIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid"; + std::string peerUdid = "peer_udid"; + std::map result = connector.GetUserIdAndBindLevel(localUdid, peerUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetUserIdAndBindLevel_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid"; + std::string peerUdid = "peer_udid"; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(DM_OK)); + std::map result = connector.GetUserIdAndBindLevel(localUdid, peerUdid); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid_123"; + std::string peerUdid = "peer_udid_456"; + int32_t peerUserId = 789; + std::string peerAccountHash = "invalid_hash"; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid_123"; + std::string peerUdid = "non_matching_udid"; + int32_t peerUserId = 789; + std::string peerAccountHash = "valid_hash"; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_003, testing::ext::TestSize.Level0) +{ + std::string localUdid = "local_udid_123"; + std::string peerUdid = "peer_udid_456"; + int32_t peerUserId = -1; + std::string peerAccountHash = "valid_hash"; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDevIdAndUserIdByActHash_004, testing::ext::TestSize.Level0) +{ + std::string localUdid = ""; + std::string peerUdid = ""; + int32_t peerUserId = 0; + std::string peerAccountHash = ""; + std::multimap result = + connector.GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); + + EXPECT_TRUE(result.empty()); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + auto result = connector.GetDeviceIdAndUserId("device4", 4); + EXPECT_EQ(result.size(), 0); +} + +HWTEST_F(DeviceProfileConnectorSecondTest, GetDeviceIdAndUserId_002, testing::ext::TestSize.Level0) +{ + auto result = connector.GetDeviceIdAndUserId("", 0); + EXPECT_EQ(result.size(), 0); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h index 7f638ce73..e7539e321 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.h @@ -19,6 +19,7 @@ #include #include +#include "access_control_profile.h" #include "deviceprofile_connector.h" #include "distributed_device_profile_client_mock.h" #include "deviceprofile_connector_mock.h" @@ -31,6 +32,7 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + DeviceProfileConnector connector; static inline std::shared_ptr distributedDeviceProfileClientMock_ = -- Gitee From 7e16d57160c7259ebb17d3bad622355411fc0042 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Wed, 20 Nov 2024 10:11:28 +0800 Subject: [PATCH 419/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 476a1fa41..0689a3bd6 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -952,6 +952,7 @@ bool DeviceManagerService::IsDMServiceImplReady() listener_ = std::make_shared(); } if (dmServiceImpl_->Initialize(listener_) != DM_OK) { + dlclose(so_handle); dmServiceImpl_ = nullptr; isImplsoLoaded_ = false; return false; @@ -1198,6 +1199,7 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() dmServiceImplExt_ = std::shared_ptr(func()); if (dmServiceImplExt_->Initialize(listener_) != DM_OK) { + dlclose(so_handle); dmServiceImplExt_ = nullptr; isAdapterSoLoaded_ = false; LOGE("dm service adapter impl ext init failed."); -- Gitee From 6e30a53f7a93fd4c5af060204eac3c2ba871e327 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Thu, 21 Nov 2024 16:56:22 +0800 Subject: [PATCH 420/520] =?UTF-8?q?=E7=BC=93=E5=AD=98=E8=AE=BE=E5=A4=87?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=9D=9E=E7=A9=BA=E6=A0=A1=E9=AA=8C=20Signed?= =?UTF-8?q?-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/softbuscache/src/dm_softbus_cache.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index c1027d74c..0e0734bec 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -123,8 +123,16 @@ void SoftbusCache::SaveDeviceInfo(DmDeviceInfo deviceInfo) LOGI("SoftbusCache::SaveDeviceInfo"); std::string udid = ""; std::string uuid = ""; + if (deviceInfo.networkId[0] == '\0') { + LOGE("networkId is empty."); + return; + } GetUdidByNetworkId(deviceInfo.networkId, udid); GetUuidByNetworkId(deviceInfo.networkId, uuid); + if (udid.empty()) { + LOGE("udid is empty."); + return; + } char udidHash[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(udid, reinterpret_cast(udidHash)) != DM_OK) { LOGE("get udidhash by udid: %{public}s failed.", GetAnonyString(udid).c_str()); -- Gitee From 6f5155ab65dec784ccf6d0549067daec3e99e387 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 21 Nov 2024 17:02:52 +0800 Subject: [PATCH 421/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- common/src/ipc/lite/ipc_cmd_register.cpp | 4 + .../ability/standard/dm_ability_manager.cpp | 6 +- .../kits/js/src/native_devicemanager_js.cpp | 4 - interfaces/kits/js4.0/src/dm_native_util.cpp | 8 +- .../src/authentication/dm_auth_manager.cpp | 5 +- .../service/src/device_manager_service.cpp | 4 + .../src/ipc/lite/ipc_server_listener.cpp | 4 + .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../softbuscache/src/dm_softbus_cache.cpp | 5 +- .../UTTest_dm_deviceprofile_connector.cpp | 141 ++++++++++++++++++ ...Test_dm_deviceprofile_connector_second.cpp | 9 ++ .../UTTest_device_manager_service_impl.cpp | 29 ++-- .../mock/deviceprofile_connector_mock.cpp | 6 + .../mock/deviceprofile_connector_mock.h | 3 + ...mock_distributed_device_profile_client.cpp | 109 +++++++++++++- 15 files changed, 313 insertions(+), 26 deletions(-) diff --git a/common/src/ipc/lite/ipc_cmd_register.cpp b/common/src/ipc/lite/ipc_cmd_register.cpp index 434c7f3dc..933ab010a 100644 --- a/common/src/ipc/lite/ipc_cmd_register.cpp +++ b/common/src/ipc/lite/ipc_cmd_register.cpp @@ -26,6 +26,10 @@ DM_IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, size_t buffLen) { + if (pBaseReq == nullptr) { + LOGE("IpcCmdRegister::SetRequest pBaseReq is nullptr!"); + return ERR_DM_POINT_NULL; + } if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { LOGE("IpcCmdRegister::SetRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp index 82852b6d1..3beb339fd 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -23,7 +23,11 @@ namespace OHOS { namespace DistributedHardware { AbilityStatus DmAbilityManager::StartAbility(AAFwk::Want &want) { - AAFwk::AbilityManagerClient::GetInstance()->Connect(); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->Connect(); + if (ret != 0) { + LOGE("Connect Ability failed, error value = %{public}d", (int32_t)ret); + return AbilityStatus::ABILITY_STATUS_FAILED; + } ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); if (result != 0) { LOGE("Start Ability failed, error value = %{public}d", (int32_t)result); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index e0f90c5ce..75e70c7a7 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -620,7 +620,6 @@ void DmNapiPublishCallback::OnPublishResult(int32_t publishId, int32_t publishRe deviceManagerNapi->OnPublishResult(callback->publishId_, callback->reason_); } delete callback; - callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -679,7 +678,6 @@ void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const callback->status_, callback->reason_); } delete callback; - callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -723,7 +721,6 @@ void DmNapiCredentialCallback::OnCredentialResult(int32_t &action, const std::st deviceManagerNapi->OnCredentialResult(callback->action_, callback->credentialResult_); } delete callback; - callback = nullptr; delete work; work = nullptr; }, uv_qos_user_initiated); @@ -1604,7 +1601,6 @@ void DmNapiDeviceManagerUiCallback::OnCall(const std::string ¶mJson) deviceManagerNapi->OnDmUiCall(callback->token_); } delete callback; - callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index 8632ba7e1..43be4b8fa 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -44,6 +44,9 @@ const int32_t DM_NAPI_BUF_LENGTH = 256; void JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr, char *dest, const int32_t destLen) { + if (dest == nullptr) { + return; + } bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); if (hasProperty) { @@ -449,7 +452,10 @@ bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &value return false; } char temp[DM_NAPI_BUF_LENGTH] = {0}; - napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + napi_status status = napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + if (status != napi_ok) { + return false; + } strValue = temp; return true; } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index a1d3c0dfa..32d434f50 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -240,7 +240,10 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - authPtr_ = authenticationMap_[authType]; + if (authenticationMap_.find(authType) != authenticationMap_.end()) { + authPtr_ = authenticationMap_[authType]; + } + if (timer_ == nullptr) { timer_ = std::make_shared(); } diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 4ede94b80..d48321aaa 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -264,6 +264,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c DmDeviceInfo tempInfo; if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, item.networkId, sizeof(item.networkId)) != 0) { LOGE("get networkId: %{public}s failed", GetAnonyString(item.networkId).c_str()); + continue; } deviceList.push_back(tempInfo); } @@ -353,6 +354,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) DmDeviceInfo tempInfo; if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, info.networkId, sizeof(info.networkId)) != 0) { LOGE("get networkId: %{public}s failed", GetAnonyString(info.networkId).c_str()); + return ERR_DM_FAILED; } info = tempInfo; return DM_OK; @@ -381,6 +383,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) #endif if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, localDeviceId_.c_str(), localDeviceId_.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(localDeviceId_).c_str()); + return ERR_DM_FAILED; } return DM_OK; } @@ -1910,6 +1913,7 @@ void DeviceManagerService::ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInf } if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); + return; } } } diff --git a/services/service/src/ipc/lite/ipc_server_listener.cpp b/services/service/src/ipc/lite/ipc_server_listener.cpp index 912b538ae..249b705d0 100644 --- a/services/service/src/ipc/lite/ipc_server_listener.cpp +++ b/services/service/src/ipc/lite/ipc_server_listener.cpp @@ -43,6 +43,10 @@ int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity * int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { + if (req == nullptr || rsp == nullptr) { + LOGE("SendRequest req or rsp is nullptr."); + return ERR_DM_POINT_NULL; + } std::string pkgName = req->GetPkgName(); SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index 9c9cec34a..04ba46250 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -24,7 +24,7 @@ namespace OHOS { namespace DistributedHardware { int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - if (rsp == nullptr) { + if (rsp == nullptr || req == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index c1027d74c..90e7b57e0 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -19,11 +19,12 @@ #include "dm_constants.h" #include "dm_device_info.h" #include "dm_log.h" +#include namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusCache); -bool g_online = false; -bool g_getLocalDevInfo = false; +std::atomic g_online; +std::atomic g_getLocalDevInfo; DmDeviceInfo localDeviceInfo_; std::mutex localDevInfoMutex_; void SoftbusCache::SaveLocalDeviceInfo() diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index ba6f4fea1..910def002 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1276,5 +1276,146 @@ HWTEST_F(DeviceProfileConnectorTest, GetAllAccessControlProfile_001, testing::ex auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); EXPECT_TRUE(ret.empty()); } + +HWTEST_F(DeviceProfileConnectorTest, GetAclProfileByDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId"; + int32_t userId = 123456; + auto ret = DeviceProfileConnector::GetInstance().GetAclProfileByDeviceIdAndUserId(deviceId, userId + ); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, DeleteAclForAccountLogOut_001, testing::ext::TestSize.Level0) +{ + std::string localUdid; + int32_t localUserId = 444; + std::string peerUdid = "deviceId"; + int32_t peerUserId = 555; + bool ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); + EXPECT_FALSE(ret); + + localUdid = "deviceId"; + localUserId = 123456; + peerUdid = "deviceIdee"; + peerUserId = 456; + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + EXPECT_TRUE(ret); + + localUdid = "deviceId"; + localUserId = 123456; + peerUdid = "deviceId"; + peerUserId = 123456; + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + EXPECT_TRUE(ret); +} + +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_001, testing::ext::TestSize.Level0) +{ + std::string localDeviceId = "deviceId"; + std::string targetDeviceId = "deviceId"; + int32_t userId = 123456; + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, + targetDeviceId, userId); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::vector userIds; + int32_t userId = 123456; + userIds.push_back(userId); + userIds.push_back(userId); + userIds.push_back(userId); + std::string localUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); + EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 123456; + std::string accountId; + std::string localUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestSize.Level0) +{ + int32_t currentUserId; + std::string localUdid = "deviceId"; + int32_t beforeUserId = 123456; + int32_t ret = DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); + EXPECT_EQ(ret, DM_OK); + + beforeUserId = 1234; + currentUserId = 123456; + ret = DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); + EXPECT_EQ(ret, DM_OK); + + std::vector remoteUserIds; + remoteUserIds.push_back(currentUserId); + std::string remoteUdid = "deviceId"; + std::vector localUserIds; + localUserIds.push_back(currentUserId); + std::string localUdid = "deviceId"; + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid, + localUserIds, localUdid); +} + +HWTEST_F(DeviceProfileConnectorTest, GetOfflineProcessInfo_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + std::vector localUserIds; + std::string remoteUdid = "deviceId"; + std::vector remoteUserIds; + int32_t userId = 123456; + remoteUserIds.push_back(userId); + localUserIds.push_back(userId); + auto ret = DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, + remoteUserIds); + EXPECT_FALSE(ret.empty()); +} + +HWTEST_F(DeviceProfileConnectorTest, GetUserIdAndBindLevel_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + std::string peerUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(localUdid, peerUdid); + EXPECT_FALSE(ret.empty()); + + int32_t userId = 123456; + std::vector localUserIds; + localUserIds.push_back(userId); + std::string remoteUdid = "deviceId"; + std::vector remoteFrontUserIds; + remoteFrontUserIds.push_back(userId); + std::vector remoteBackUserIds; + remoteBackUserIds.push_back(userId); + DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, remoteFrontUserIds, + remoteBackUserIds); +} + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + int32_t localUserId = 123456; + auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); + EXPECT_FALSE(ret.empty()); + + std::vector remoteUserIds; + remoteUserIds.push_back(localUserId); + std::string remoteUdid = "deviceId"; + std::vector localUserIds; + localUserIds.push_back(localUserId); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, + localUdid); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 01e3f9070..3e602e06b 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -164,6 +164,15 @@ HWTEST_F(DeviceProfileConnectorSecondTest, GetAllAccessControlProfile_201, testi EXPECT_TRUE(ret.empty()); } +HWTEST_F(DeviceProfileConnectorTest, GetAclProfileByDeviceIdAndUserId_201, testing::ext::TestSize.Level0) +{ + std::string deviceId = "deviceId"; + int32_t userId = 123456; + EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetAclProfileByDeviceIdAndUserId(deviceId, userId); + EXPECT_TRUE(ret.empty()); +} + HWTEST_F(DeviceProfileConnectorSecondTest, DeleteAclForAccountLogOut_001, testing::ext::TestSize.Level0) { std::string localUdid = "local_device_id"; diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index cc99bd64b..75fbe0be6 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1724,6 +1724,14 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_003, testing::ext::TestSize. EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(DEVICE_ACROSS_ACCOUNT_TYPE)); deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); + deviceManagerServiceImpl_->HandleOnline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); } @@ -1739,22 +1747,13 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_003, testing::ext::TestSize EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("")); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); - DmOfflineParam offlineParam; - offlineParam.leftAclNumber = 0; - offlineParam.bindType = INVALID_TYPE; - EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); - deviceManagerServiceImpl_->HandleOffline(devState, devInfo); - - offlineParam.bindType = IDENTICAL_ACCOUNT_TYPE; - EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); - deviceManagerServiceImpl_->HandleOffline(devState, devInfo); - - offlineParam.bindType = DEVICE_PEER_TO_PEER_TYPE; - EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); - deviceManagerServiceImpl_->HandleOffline(devState, devInfo); - - offlineParam.bindType = APP_PEER_TO_PEER_TYPE; + std::map userIdAndBindLevel; + userIdAndBindLevel[1] = INVALIED_TYPE; + userIdAndBindLevel[2] = DEVICE; + userIdAndBindLevel[3] = SERVICE; + userIdAndBindLevel[4] = APP; EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); + EXPECT_CALL(*deviceProfileConnectorMock_, GetUserIdAndBindLevel(_, _)).WillOnce(Return(userIdAndBindLevel)); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index 65995b5cf..75999634d 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -43,5 +43,11 @@ uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::s { return DmDeviceProfileConnector::dmDeviceProfileConnector->CheckBindType(trustDeviceId, requestDeviceId); } + +std::map DeviceProfileConnector::GetUserIdAndBindLevel(const std::string &localUdid, + const std::string &peerUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->GetUserIdAndBindLevel(localUdid, peerUdid); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index fed03cc1f..6dfcc42e9 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -33,6 +33,8 @@ public: virtual int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid) = 0; virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; + virtual std::map GetUserIdAndBindLevel(const std::string &localUdid, + const std::string &peerUdid) = 0; public: static inline std::shared_ptr dmDeviceProfileConnector = nullptr; }; @@ -44,6 +46,7 @@ public: MOCK_METHOD(int32_t, HandleAccountLogoutEvent, (int32_t, const std::string &, const std::string &, const std::string &)); MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); + MOCK_METHOD((std::map), GetUserIdAndBindLevel, (const std::string &, const std::string &)); }; } } diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index 447c31c9e..c5908ae8c 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -753,7 +753,112 @@ void AddAccessControlprofileFifteenth(std::vector& accessC std::string oldAccountId = "accountId"; std::string newAccountId = "accountId"; std::string deviceId = "deviceId"; - std::string trustDeviceId = "123456"; + std::string trustDeviceId = "deviceIdee"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileSixteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceId"; + + std::string deviceIdee = "deviceIdee"; + int32_t userIdee = 456; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdee); + accessee.SetAccesseeUserId(userIdee); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileSeventeenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 0; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIdee"; Accesser accesser; accesser.SetAccesserId(0); @@ -829,6 +934,8 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map Date: Thu, 21 Nov 2024 17:50:09 +0800 Subject: [PATCH 422/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 2 +- test/unittest/UTTest_device_manager_service_two.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 910def002..7fee80ab6 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1311,7 +1311,7 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteAclForAccountLogOut_001, testing::ext EXPECT_TRUE(ret); } -HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_005, testing::ext::TestSize.Level0) { std::string localDeviceId = "deviceId"; std::string targetDeviceId = "deviceId"; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 718dbeda1..fd4185634 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -501,14 +501,14 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Leve std::string deviceId = "123456"; EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(INVALIED_BIND_LEVEL)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, ERR_DM_FAILED); EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(INVALIED_BIND_LEVEL)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, DM_OK); @@ -537,7 +537,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(INVALIED_BIND_LEVEL)); int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); } -- Gitee From 6dd3c8f0154897dcf6a74f4ec38bbd8c9b0d9b97 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 21 Nov 2024 18:47:39 +0800 Subject: [PATCH 423/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 1 - .../commonunittest/UTTest_dm_deviceprofile_connector_second.cpp | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 7fee80ab6..7e4000857 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1364,7 +1364,6 @@ HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestS std::string remoteUdid = "deviceId"; std::vector localUserIds; localUserIds.push_back(currentUserId); - std::string localUdid = "deviceId"; DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, localUdid); } diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 3e602e06b..8779dfa1f 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -164,7 +164,7 @@ HWTEST_F(DeviceProfileConnectorSecondTest, GetAllAccessControlProfile_201, testi EXPECT_TRUE(ret.empty()); } -HWTEST_F(DeviceProfileConnectorTest, GetAclProfileByDeviceIdAndUserId_201, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorSecondTest, GetAclProfileByDeviceIdAndUserId_201, testing::ext::TestSize.Level0) { std::string deviceId = "deviceId"; int32_t userId = 123456; -- Gitee From 54587093b6951a003c955026e7f61c83bd7d2c12 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 21 Nov 2024 19:20:00 +0800 Subject: [PATCH 424/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 2 +- test/unittest/UTTest_device_manager_service_two.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 7e4000857..fa915f2db 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1348,7 +1348,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_001, testing::ext::Tes HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestSize.Level0) { - int32_t currentUserId; + int32_t currentUserId = 0; std::string localUdid = "deviceId"; int32_t beforeUserId = 123456; int32_t ret = DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index fd4185634..afad12658 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -501,14 +501,14 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Leve std::string deviceId = "123456"; EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(INVALIED_BIND_LEVEL)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, ERR_DM_FAILED); EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(INVALIED_BIND_LEVEL)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, DM_OK); @@ -537,7 +537,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS std::string pkgName = "com.ohos.test"; std::string networkId = "12345"; EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(INVALIED_BIND_LEVEL)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); } -- Gitee From 2afd3e677ccc306a831c1579d68facd5fb933037 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Thu, 21 Nov 2024 09:27:12 +0800 Subject: [PATCH 425/520] =?UTF-8?q?=E6=B3=A8=E5=86=8C=E7=9B=91=E5=90=AC?= =?UTF-8?q?=E6=8A=A5=E4=B8=8A=E7=BA=BF=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native_cpp/include/device_manager_impl.h | 1 + .../native_cpp/src/device_manager_impl.cpp | 24 +++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 16 ++++++ .../service/include/device_manager_service.h | 2 + .../include/device_manager_service_listener.h | 1 + .../idevice_manager_service_listener.h | 2 + .../service/src/device_manager_service.cpp | 53 +++++++++++++++++++ .../src/device_manager_service_listener.cpp | 22 ++++++++ .../src/ipc/standard/ipc_cmd_parser.cpp | 11 ++++ test/unittest/UTTest_dm_comm_tool.cpp | 10 +--- test/unittest/UTTest_dm_pin_holder.h | 7 +++ 11 files changed, 140 insertions(+), 9 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index f887ff9d6..064cffbec 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -420,6 +420,7 @@ private: int32_t CheckApiPermission(int32_t permissionLevel); void ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); uint16_t GetSubscribeIdFromMap(const std::string &pkgName); + void RegDevStateCallbackToService(const std::string &pkgName); private: #if !defined(__LITEOS_M__) 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 4afabf438..53a18153f 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -392,6 +392,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, return ret; } #endif + RegDevStateCallbackToService(pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); LOGI("Completed"); @@ -408,6 +409,7 @@ int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + RegDevStateCallbackToService(pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStatusCallback(pkgName, callback); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStatusCallback", DM_OK); LOGI("Completed"); @@ -1868,6 +1870,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, LOGE("DeviceManagerImpl::RegisterDeviceStateCallback failed: input pkgName or callback is empty."); return ERR_DM_INPUT_PARA_INVALID; } + RegDevStateCallbackToService(pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); @@ -2414,5 +2417,26 @@ uint16_t DeviceManagerImpl::GetSubscribeIdFromMap(const std::string &pkgName) } return DM_INVALID_FLAG_ID; } + +void DeviceManagerImpl::RegDevStateCallbackToService(const std::string &pkgName) +{ + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return; + } + std::shared_ptr req = std::make_shared(); + std::shared_ptr rsp = std::make_shared(); + req->SetPkgName(pkgName); + int32_t ret = ipcClientProxy_->SendRequest(REGISTER_DEV_STATE_CALLBACK, req, rsp); + if (ret != DM_OK) { + LOGI("Send Request failed ret: %{public}d", ret); + return; + } + ret = rsp->GetErrCode(); + if (ret != DM_OK) { + LOGE("Failed with ret %{public}d", ret); + return; + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file 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 a69f4a513..15e916bbc 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 @@ -1675,5 +1675,21 @@ ON_IPC_CMD(SINK_BIND_TARGET_RESULT, MessageParcel &data, MessageParcel &reply) reply.WriteInt32(DM_OK); return DM_OK; } + +ON_IPC_SET_REQUEST(REGISTER_DEV_STATE_CALLBACK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(REGISTER_DEV_STATE_CALLBACK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 8d7f972da..bf5b82c91 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -201,6 +201,8 @@ public: const std::vector &backgroundUserIds, const std::string &remoteUdid); int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); void RemoveNotifyRecord(const ProcessInfo &processInfo); + int32_t RegDevStateCallbackToService(const std::string &pkgName); + int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 8d37cbf61..d58ecec3b 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -78,6 +78,7 @@ public: void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; void OnProcessRemove(const ProcessInfo &processInfo) override; + void OnDevStateCallbackAdd(const ProcessInfo &processInfo, const std::vector &deviceList) override; private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index bb1a95adc..48f7c0fe5 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -163,6 +163,8 @@ public: virtual void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) = 0; virtual void OnProcessRemove(const ProcessInfo &processInfo) = 0; + virtual void OnDevStateCallbackAdd(const ProcessInfo &processInfo, + const std::vector &deviceList) = 0; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 4ede94b80..6c5a8425d 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2231,5 +2231,58 @@ void DeviceManagerService::RemoveNotifyRecord(const ProcessInfo &processInfo) listener_->OnProcessRemove(processInfo); } +int32_t DeviceManagerService::RegDevStateCallbackToService(const std::string &pkgName) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + CHECK_NULL_RETURN(listener_, ERR_DM_POINT_NULL); + std::vector deviceList; + GetTrustedDeviceList(pkgName, deviceList); + if (deviceList.size() == 0) { + return DM_OK; + } + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = userId; + listener_->OnDevStateCallbackAdd(processInfo, deviceList); +#else + (void)pkgName; +#endif + return DM_OK; +} + +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList) +{ + LOGI("Begin for pkgName = %{public}s.", pkgName.c_str()); + if (pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + std::vector onlineDeviceList; + CHECK_NULL_RETURN(softbusListener_, ERR_DM_POINT_NULL); + int32_t ret = softbusListener_->GetTrustedDeviceList(onlineDeviceList); + if (ret != DM_OK) { + LOGE("failed"); + return ret; + } + if (!onlineDeviceList.empty() && IsDMServiceImplReady()) { + std::unordered_map udidMap; + if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) { + udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME)); + } else { + udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName); + } + for (auto item : onlineDeviceList) { + std::string udid = ""; + SoftbusListener::GetUdidByNetworkId(item.networkId, udid); + if (udidMap.find(udid) != udidMap.end()) { + item.authForm = udidMap[udid]; + deviceList.push_back(item); + } + } + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 9696a0667..d11e2ca90 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -776,5 +776,27 @@ void DeviceManagerServiceListener::OnProcessRemove(const ProcessInfo &processInf } } } + +void DeviceManagerServiceListener::OnDevStateCallbackAdd(const ProcessInfo &processInfo, + const std::vector &deviceList) +{ + for (auto item : deviceList) { + std::string notifyPkgName = processInfo.pkgName + "#" + std::to_string(processInfo.userId) + "#" + + std::string(item.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgName) != alreadyOnlinePkgName_.end()) { + continue; + } + alreadyOnlinePkgName_[notifyPkgName] = item; + } + DmDeviceBasicInfo deviceBasicInfo; + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, item, deviceBasicInfo); + SetDeviceInfo(pReq, processInfo, DmDeviceState::DEVICE_STATE_ONLINE, item, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index dd83b850d..93671487b 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1625,5 +1625,16 @@ ON_IPC_READ_RESPONSE(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &reply pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; } + +ON_IPC_CMD(REGISTER_DEV_STATE_CALLBACK, MessageParcel &data, MessageParcel &reply) +{ + std::string pkgName = data.ReadString(); + int32_t result = DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); + if (!reply.WriteInt32(result)) { + LOGE("write result failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_comm_tool.cpp b/test/unittest/UTTest_dm_comm_tool.cpp index df499e9b2..e960ba9d9 100644 --- a/test/unittest/UTTest_dm_comm_tool.cpp +++ b/test/unittest/UTTest_dm_comm_tool.cpp @@ -20,6 +20,7 @@ namespace DistributedHardware { void DMCommToolTest::SetUp() { dmCommTool = DMCommTool::GetInstance(); + dmCommTool->Init(); } void DMCommToolTest::TearDown() { @@ -31,15 +32,6 @@ void DMCommToolTest::TearDownTestCase() { } -/** - * @tc.name: Init_Success - * @tc.type: FUNC - */ -HWTEST_F(DMCommToolTest, Init_Success, testing::ext::TestSize.Level0) -{ - EXPECT_NO_THROW(dmCommTool->Init()); -} - /** * @tc.name: GetEventHandler_NotNull * @tc.type: FUNC diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 01601ef8f..5fcd67186 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -215,6 +215,13 @@ public: { (void)processInfo; } + + virtual void OnDevStateCallbackAdd(const ProcessInfo &processInfo, + const std::vector &deviceList) override + { + (void)processInfo; + (void)deviceList; + } }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From e56566403a88a42f26d65af44495fc60dff83dd7 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Thu, 21 Nov 2024 16:12:39 +0800 Subject: [PATCH 426/520] =?UTF-8?q?=E5=8F=91=E7=8E=B0=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../native_cpp/src/device_manager_impl.cpp | 54 +++++++++---------- .../src/notify/device_manager_notify.cpp | 10 +++- 2 files changed, 34 insertions(+), 30 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 4afabf438..424b804ca 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -549,20 +549,18 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); } - if (subscribeId == DM_INVALID_FLAG_ID) { - subscribeId = GetSubscribeIdFromMap(pkgName); - } + std::string pkgNameTemp = ComposeStr(pkgName, subscribeId); + subscribeId = GetSubscribeIdFromMap(pkgNameTemp); if (subscribeId == DM_INVALID_FLAG_ID) { LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); return ERR_DM_INPUT_PARA_INVALID; } - std::string discoveryFlag = ComposeStr(pkgName, subscribeId); discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); std::string discParaStr = ConvertMapToJsonString(discoverParam); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(discoveryFlag); + req->SetPkgName(pkgNameTemp); req->SetFirstParam(discParaStr); int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); if (ret != DM_OK) { @@ -574,7 +572,7 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, LOGE("StopDiscovering error: Failed with ret %{public}d", ret); return ret; } - RemoveDiscoveryCallback(discoveryFlag); + RemoveDiscoveryCallback(pkgNameTemp); LOGI("Completed"); return DM_OK; } @@ -1672,8 +1670,8 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - std::string discoveryFlag = ComposeStr(pkgName, DM_INVALID_FLAG_ID); - uint16_t subscribeId = RemoveDiscoveryCallback(discoveryFlag); + std::string pkgNameTemp = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + uint16_t subscribeId = GetSubscribeIdFromMap(pkgNameTemp); if (subscribeId == DM_INVALID_FLAG_ID) { DmRadarHelper::GetInstance().ReportDmBehavior( pkgName, "UnRegisterDiscoveryCallback", ERR_DM_INPUT_PARA_INVALID); @@ -1686,21 +1684,22 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(discoveryFlag); + req->SetPkgName(pkgNameTemp); req->SetFirstParam(extraParaStr); int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_DISCOVERY_CALLBACK, req, rsp); if (ret != DM_OK) { - DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", ret); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", ret); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } - DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", DM_OK); + RemoveDiscoveryCallback(pkgNameTemp); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "UnRegisterDiscoveryCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -1893,22 +1892,23 @@ uint16_t DeviceManagerImpl::AddDiscoveryCallback(const std::string &pkgName, if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); } - if (subscribeId == DM_INVALID_FLAG_ID) { - subscribeId = GetSubscribeIdFromMap(pkgName); - } - if (subscribeId == DM_INVALID_FLAG_ID) { - subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); - } - std::string discoveryFlag = ComposeStr(pkgName, subscribeId); + std::string pkgNameTemp = ComposeStr(pkgName, subscribeId); { std::lock_guard autoLock(subMapLock); - auto iter = pkgName2SubIdMap_.find(discoveryFlag); - if (iter == pkgName2SubIdMap_.end()) { - pkgName2SubIdMap_[discoveryFlag] = subscribeId; + auto item = pkgName2SubIdMap_.find(pkgNameTemp); + if (item == pkgName2SubIdMap_.end() && subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); + pkgName2SubIdMap_[pkgNameTemp] = subscribeId; + } else if (item == pkgName2SubIdMap_.end() && subscribeId != DM_INVALID_FLAG_ID) { + pkgName2SubIdMap_[pkgNameTemp] = subscribeId; + } else if (item != pkgName2SubIdMap_.end()) { + subscribeId = pkgName2SubIdMap_[pkgNameTemp]; + } else { + LOGE("subscribeId is unreasonable"); } } - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(discoveryFlag, subscribeId, callback); - DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "AddDiscoveryCallback", DM_OK); + DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgNameTemp, subscribeId, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(pkgNameTemp, "AddDiscoveryCallback", DM_OK); return subscribeId; } @@ -2406,10 +2406,8 @@ uint16_t DeviceManagerImpl::GetSubscribeIdFromMap(const std::string &pkgName) { { std::lock_guard autoLock(subMapLock); - for (auto &item : pkgName2SubIdMap_) { - if (item.first.find(pkgName) == 0) { - return GetSubscribeId(item.first); - } + if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { + return pkgName2SubIdMap_[pkgName]; } } return DM_INVALID_FLAG_ID; 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 e25133b4e..d0ccdb127 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 @@ -194,10 +194,16 @@ void DeviceManagerNotify::UnRegisterPackageCallback(const std::string &pkgName) std::lock_guard autoLock(lock_); deviceStateCallback_.erase(pkgName); deviceStatusCallback_.erase(pkgName); - deviceDiscoveryCallbacks_.erase(pkgName); devicePublishCallbacks_.erase(pkgName); authenticateCallback_.erase(pkgName); dmInitCallback_.erase(pkgName); + for (auto it = deviceDiscoveryCallbacks_.begin(); it != deviceDiscoveryCallbacks_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + it = deviceDiscoveryCallbacks_.erase(it); + } else { + ++it; + } + } } void DeviceManagerNotify::RegisterDeviceManagerFaCallback(const std::string &pkgName, @@ -1189,7 +1195,7 @@ std::shared_ptr DeviceManagerNotify::GetDiscoveryCallback(con std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); iter = deviceDiscoveryCallbacks_.find(discNoSubscribeId); if (iter != deviceDiscoveryCallbacks_.end()) { - auto subIter = iter->second.find(DM_INVALID_FLAG_ID); + auto subIter = iter->second.find(subscribeId); if (subIter != iter->second.end()) { return subIter->second; } -- Gitee From a123271cab325a28b6f786e8e27de002c3954b71 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 22 Nov 2024 10:00:13 +0800 Subject: [PATCH 427/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 4 -- ...Test_dm_deviceprofile_connector_second.cpp | 1 + .../UTTest_device_manager_service.cpp | 9 ++++ test/unittest/UTTest_device_manager_service.h | 2 + ...UTTest_device_manager_service_listener.cpp | 40 +++++++------- .../UTTest_device_manager_service_three.cpp | 14 +++++ .../UTTest_device_manager_service_two.cpp | 34 +++++++++++- .../mock/device_manager_service_impl_mock.cpp | 15 ++++++ .../mock/device_manager_service_impl_mock.h | 6 +++ test/unittest/mock/dm_crypto_mock.cpp | 28 ++++++++++ test/unittest/mock/dm_crypto_mock.h | 40 ++++++++++++++ ...mock_distributed_device_profile_client.cpp | 54 ++++++++++++++++++- 12 files changed, 221 insertions(+), 26 deletions(-) create mode 100644 test/unittest/mock/dm_crypto_mock.cpp create mode 100644 test/unittest/mock/dm_crypto_mock.h diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index fa915f2db..523a5591d 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1331,10 +1331,6 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndBindLevel_001, testing::ext:: std::string localUdid = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); EXPECT_FALSE(ret.empty()); - - localUdid = "remoteDeviceId"; - ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); - EXPECT_FALSE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 8779dfa1f..f4b45562d 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -39,6 +39,7 @@ void DeviceProfileConnectorSecondTest::SetUpTestCase() void DeviceProfileConnectorSecondTest::TearDownTestCase() { + DistributedDeviceProfile::DpDistributedDeviceProfileClient::dpDistributedDeviceProfileClient = nullptr; distributedDeviceProfileClientMock_ = nullptr; } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index f6f230acf..42cb0b682 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -71,16 +71,25 @@ void DeviceManagerServiceTest::SetUpTestCase() DmAppManager::dmAppManager = appManagerMock_; DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; + DmCrypto::dmCrypto = cryptoMock_; } void DeviceManagerServiceTest::TearDownTestCase() { + DmPermissionManager::dmPermissionManager = nullptr; permissionManagerMock_ = nullptr; + DmSoftbusListener::dmSoftbusListener = nullptr; softbusListenerMock_ = nullptr; + DmKVAdapterManager::dmKVAdapterManager = nullptr; kVAdapterManagerMock_ = nullptr; + DmAppManager::dmAppManager = nullptr; appManagerMock_ = nullptr; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = nullptr; deviceManagerServiceImplMock_ = nullptr; + DmSoftbusCache::dmSoftbusCache = nullptr; softbusCacheMock_ = nullptr; + DmCrypto::dmCrypto = nullptr; + cryptoMock_ = nullptr; } namespace { diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index 8a2afa326..7d17393e7 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -33,6 +33,7 @@ #include "kv_adapter_manager_mock.h" #include "device_manager_service_impl_mock.h" #include "dm_softbus_cache_mock.h" +#include "dm_crypto_mock.h" namespace OHOS { namespace DistributedHardware { @@ -55,6 +56,7 @@ public: std::make_shared(); static inline std::shared_ptr softbusCacheMock_ = std::make_shared(); + static inline std::shared_ptr cryptoMock_ = std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 392e34b7b..bbe6b9f14 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -89,7 +89,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext .deviceTypeId = 1, }; listener_->OnDeviceStateChange(processInfo, state, info); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -109,7 +109,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestS processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnAuthResult(processInfo, deviceId, token, status, reason); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -129,7 +129,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestS processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnAuthResult(processInfo, deviceId, token, status, reason); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -149,7 +149,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_003, testing::ext::TestS processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnAuthResult(processInfo, deviceId, token, status, reason); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -172,7 +172,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_001, testing::ext::Test }; uint16_t subscribeId = 1; listener_->OnDeviceFound(processInfo, subscribeId, info); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -191,7 +191,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoveryFailed_001, testing::ext:: uint16_t subscribeId = 1; int32_t failedReason = 1; listener_->OnDiscoveryFailed(processInfo, subscribeId, failedReason); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -208,7 +208,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoverySuccess_001, testing::ext: ProcessInfo processInfo; processInfo.pkgName = pkgName; listener_->OnDiscoverySuccess(processInfo, subscribeId); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -225,7 +225,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_001, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 1; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -241,7 +241,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_002, testing::ext::Te int32_t publishId = 1; int32_t failedReason = 0; listener_->OnPublishResult(pkgName, publishId, failedReason); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -258,7 +258,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnUiCall_001, testing::ext::TestSize. processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnUiCall(processInfo, paramJson); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -275,7 +275,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: int32_t action = 1; std::string resultInfo = "resultInfo"; listener_->OnCredentialResult(processInfo, action, resultInfo); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -294,7 +294,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestS processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnBindResult(processInfo, targetId, result, status, content); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -313,7 +313,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestS processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnBindResult(processInfo, targetId, result, status, content); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -332,7 +332,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestS processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnBindResult(processInfo, targetId, result, status, content); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -350,7 +350,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnUnbindResult_001, testing::ext::Tes processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; listener_->OnUnbindResult(processInfo, targetId, result, content); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -387,7 +387,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext:: processInfo.userId = 100; processInfo.pkgName = "com.ohos.helloworld"; listener_->OnPinHolderCreate(processInfo, deviceId, pinType, payload); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -404,7 +404,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext: DmPinType pinType = static_cast(1); std::string payload = "payload"; listener_->OnPinHolderDestroy(processInfo, pinType, payload); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -420,7 +420,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::Tes processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; listener_->OnCreateResult(processInfo, result); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -436,7 +436,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::Te processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; listener_->OnDestroyResult(processInfo, result); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } /** @@ -454,7 +454,7 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::T int32_t result = 0; std::string content = "content"; listener_->OnPinHolderEvent(processInfo, event, result, content); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 2042f824f..9ff7cde5d 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -326,6 +326,20 @@ HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSi EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); EXPECT_EQ(ret, ERR_DM_NOT_INIT); + + int32_t userId = 0; + std::string accountId; + std::string accountName; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); + + int32_t curUserId = 0; + int32_t preUserId = 1; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); + + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index afad12658..63aebd7ae 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -508,7 +508,7 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Leve EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, DM_OK); @@ -540,6 +540,38 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); + + int32_t userId = 123456; + std::string accountId = "accountId"; + std::string accountName = "accountName"; + std::multimap deviceMap; + deviceMap["accountId"] = userId; + deviceMap["accountName"] = 1; + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_, _)).WillOnce(Return(deviceMap)); + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); + + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_,_)).WillOnce(Return(deviceMap)); + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); + + + std::map curUserDeviceMap; + curUserDeviceMap["curUserId"] = userId; + curUserDeviceMap["preUserId"] = userId; + std::map preUserDeviceMap; + preUserDeviceMap["accountId"] = userId; + preUserDeviceMap["accountName"] = 1; + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(curUserDeviceMap)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(preUserDeviceMap)); + + + + + int32_t removeId = 123; + deviceMap["removeId"] = removeId; + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)).WillOnce(Return(deviceMap)); + DeviceManagerService::GetInstance().HandleUserRemoved(userId); } HWTEST_F(DeviceManagerServiceTest, BindDevice_205, testing::ext::TestSize.Level0) diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp index 50ca2b918..b358dc60e 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.cpp +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -35,5 +35,20 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const { return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->UnBindDevice(pkgName, udid, bindLevel); } + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId, + const std::string &accountId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetDeviceIdAndUserId(userId, accountId); +} + +std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUserId(int32_t userId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetDeviceIdAndUserId(userId); +} +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t localUserId) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetDeviceIdAndBindLevel(localUserId); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h index 2079452f7..cafad4035 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.h +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -30,6 +30,9 @@ public: virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) = 0; virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId) = 0; + virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; + virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; public: static inline std::shared_ptr dmDeviceManagerServiceImpl = nullptr; }; @@ -39,6 +42,9 @@ public: MOCK_METHOD(int32_t, StopAuthenticateDevice, (const std::string &)); MOCK_METHOD(int32_t, GetBindLevel, (const std::string &, const std::string &, const std::string &, uint64_t &)); MOCK_METHOD(int32_t, UnBindDevice, (const std::string &, const std::string &, int32_t)); + MOCK_METHOD((std::multimap), GetDeviceIdAndUserId, (int32_t, const std::string &)); + MOCK_METHOD((std::multimap), GetDeviceIdAndUserId, (int32_t)); + MOCK_METHOD((std::map), GetDeviceIdAndBindLevel, (int32_t)); }; } } diff --git a/test/unittest/mock/dm_crypto_mock.cpp b/test/unittest/mock/dm_crypto_mock.cpp new file mode 100644 index 000000000..037f28533 --- /dev/null +++ b/test/unittest/mock/dm_crypto_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_crypto_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(AppManager); +int32_t Crypto::GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) +{ + return DmCrypto::dmCrypto->GetAccountIdHash(accountId, accountIdHash); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_crypto_mock.h b/test/unittest/mock/dm_crypto_mock.h new file mode 100644 index 000000000..4958f476f --- /dev/null +++ b/test/unittest/mock/dm_crypto_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DM_CRYPTO_MOCK_H +#define OHOS_DM_CRYPTO_MOCK_H + +#include +#include + +#include "dm_crypto.h" + +namespace OHOS { +namespace DistributedHardware { +class DmCrypto { +public: + virtual ~DmCrypto() = default; +public: + virtual int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) = 0; +public: + static inline std::shared_ptr dmCrypto = nullptr; +}; + +class CryptoMock : public DmCrypto { +public: + MOCK_METHOD(int32_t, GetAccountIdHash, (const std::string &, unsigned char *)); +}; +} +} +#endif diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index c5908ae8c..f6e21de48 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -753,7 +753,7 @@ void AddAccessControlprofileFifteenth(std::vector& accessC std::string oldAccountId = "accountId"; std::string newAccountId = "accountId"; std::string deviceId = "deviceId"; - std::string trustDeviceId = "deviceIdee"; + std::string trustDeviceId = "123456"; Accesser accesser; accesser.SetAccesserId(0); @@ -895,6 +895,57 @@ void AddAccessControlprofileSeventeenth(std::vector& acces accessControlProfiles.push_back(profileFourth); } +void AddAccessControlprofileEightteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceId"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -936,6 +987,7 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map Date: Fri, 22 Nov 2024 10:27:22 +0800 Subject: [PATCH 428/520] =?UTF-8?q?=E5=A4=84=E7=90=86foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- common/src/ipc/lite/ipc_cmd_register.cpp | 4 ++++ ext/pin_auth/src/ability/standard/dm_ability_manager.cpp | 6 +++++- interfaces/kits/js/src/native_devicemanager_js.cpp | 4 ---- interfaces/kits/js4.0/src/dm_native_util.cpp | 8 +++++++- .../implementation/src/authentication/dm_auth_manager.cpp | 5 ++++- services/service/src/device_manager_service.cpp | 4 ++++ services/service/src/ipc/lite/ipc_server_listener.cpp | 4 ++++ services/service/src/ipc/standard/ipc_server_listener.cpp | 2 +- services/softbuscache/src/dm_softbus_cache.cpp | 5 +++-- 9 files changed, 32 insertions(+), 10 deletions(-) diff --git a/common/src/ipc/lite/ipc_cmd_register.cpp b/common/src/ipc/lite/ipc_cmd_register.cpp index 434c7f3dc..933ab010a 100644 --- a/common/src/ipc/lite/ipc_cmd_register.cpp +++ b/common/src/ipc/lite/ipc_cmd_register.cpp @@ -26,6 +26,10 @@ DM_IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, size_t buffLen) { + if (pBaseReq == nullptr) { + LOGE("IpcCmdRegister::SetRequest pBaseReq is nullptr!"); + return ERR_DM_POINT_NULL; + } if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { LOGE("IpcCmdRegister::SetRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; diff --git a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp index 82852b6d1..3beb339fd 100644 --- a/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp +++ b/ext/pin_auth/src/ability/standard/dm_ability_manager.cpp @@ -23,7 +23,11 @@ namespace OHOS { namespace DistributedHardware { AbilityStatus DmAbilityManager::StartAbility(AAFwk::Want &want) { - AAFwk::AbilityManagerClient::GetInstance()->Connect(); + ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->Connect(); + if (ret != 0) { + LOGE("Connect Ability failed, error value = %{public}d", (int32_t)ret); + return AbilityStatus::ABILITY_STATUS_FAILED; + } ErrCode result = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want); if (result != 0) { LOGE("Start Ability failed, error value = %{public}d", (int32_t)result); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index e0f90c5ce..75e70c7a7 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -620,7 +620,6 @@ void DmNapiPublishCallback::OnPublishResult(int32_t publishId, int32_t publishRe deviceManagerNapi->OnPublishResult(callback->publishId_, callback->reason_); } delete callback; - callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -679,7 +678,6 @@ void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const callback->status_, callback->reason_); } delete callback; - callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -723,7 +721,6 @@ void DmNapiCredentialCallback::OnCredentialResult(int32_t &action, const std::st deviceManagerNapi->OnCredentialResult(callback->action_, callback->credentialResult_); } delete callback; - callback = nullptr; delete work; work = nullptr; }, uv_qos_user_initiated); @@ -1604,7 +1601,6 @@ void DmNapiDeviceManagerUiCallback::OnCall(const std::string ¶mJson) deviceManagerNapi->OnDmUiCall(callback->token_); } delete callback; - callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index 8632ba7e1..43be4b8fa 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -44,6 +44,9 @@ const int32_t DM_NAPI_BUF_LENGTH = 256; void JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr, char *dest, const int32_t destLen) { + if (dest == nullptr) { + return; + } bool hasProperty = false; NAPI_CALL_RETURN_VOID(env, napi_has_named_property(env, object, fieldStr.c_str(), &hasProperty)); if (hasProperty) { @@ -449,7 +452,10 @@ bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &value return false; } char temp[DM_NAPI_BUF_LENGTH] = {0}; - napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + napi_status status = napi_get_value_string_utf8(env, value, temp, valueLen + 1, &valueLen); + if (status != napi_ok) { + return false; + } strValue = temp; return true; } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index a1d3c0dfa..8683a6485 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -240,7 +240,10 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { - authPtr_ = authenticationMap_[authType]; + if (authenticationMap_.find(authType) != authenticationMap_.end()) { + authPtr_ = authenticationMap_[authType]; + } + if (timer_ == nullptr) { timer_ = std::make_shared(); } diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 4ede94b80..d48321aaa 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -264,6 +264,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c DmDeviceInfo tempInfo; if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, item.networkId, sizeof(item.networkId)) != 0) { LOGE("get networkId: %{public}s failed", GetAnonyString(item.networkId).c_str()); + continue; } deviceList.push_back(tempInfo); } @@ -353,6 +354,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) DmDeviceInfo tempInfo; if (memcpy_s(tempInfo.networkId, DM_MAX_DEVICE_ID_LEN, info.networkId, sizeof(info.networkId)) != 0) { LOGE("get networkId: %{public}s failed", GetAnonyString(info.networkId).c_str()); + return ERR_DM_FAILED; } info = tempInfo; return DM_OK; @@ -381,6 +383,7 @@ int32_t DeviceManagerService::GetLocalDeviceInfo(DmDeviceInfo &info) #endif if (memcpy_s(info.deviceId, DM_MAX_DEVICE_ID_LEN, localDeviceId_.c_str(), localDeviceId_.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(localDeviceId_).c_str()); + return ERR_DM_FAILED; } return DM_OK; } @@ -1910,6 +1913,7 @@ void DeviceManagerService::ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInf } if (memcpy_s(deviceInfo.deviceId, DM_MAX_DEVICE_ID_LEN, udidHashTemp.c_str(), udidHashTemp.length()) != 0) { LOGE("get deviceId: %{public}s failed", GetAnonyString(udidHashTemp).c_str()); + return; } } } diff --git a/services/service/src/ipc/lite/ipc_server_listener.cpp b/services/service/src/ipc/lite/ipc_server_listener.cpp index 912b538ae..249b705d0 100644 --- a/services/service/src/ipc/lite/ipc_server_listener.cpp +++ b/services/service/src/ipc/lite/ipc_server_listener.cpp @@ -43,6 +43,10 @@ int32_t IpcServerListener::GetIdentityByPkgName(std::string &name, SvcIdentity * int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { + if (req == nullptr || rsp == nullptr) { + LOGE("SendRequest req or rsp is nullptr."); + return ERR_DM_POINT_NULL; + } std::string pkgName = req->GetPkgName(); SvcIdentity svc; if (GetIdentityByPkgName(pkgName, &svc) != DM_OK) { diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index 9c9cec34a..04ba46250 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -24,7 +24,7 @@ namespace OHOS { namespace DistributedHardware { int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) { - if (rsp == nullptr) { + if (rsp == nullptr || req == nullptr) { return ERR_DM_INPUT_PARA_INVALID; } if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 0e0734bec..097f7ed6e 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -19,11 +19,12 @@ #include "dm_constants.h" #include "dm_device_info.h" #include "dm_log.h" +#include namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusCache); -bool g_online = false; -bool g_getLocalDevInfo = false; +std::atomic g_online; +std::atomic g_getLocalDevInfo; DmDeviceInfo localDeviceInfo_; std::mutex localDevInfoMutex_; void SoftbusCache::SaveLocalDeviceInfo() -- Gitee From b5a14aa39a61438e242447efe4c6baee21357a20 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 22 Nov 2024 10:38:08 +0800 Subject: [PATCH 429/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service_two.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 63aebd7ae..c4e2308bf 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -545,17 +545,18 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS std::string accountId = "accountId"; std::string accountName = "accountName"; std::multimap deviceMap; - deviceMap["accountId"] = userId; - deviceMap["accountName"] = 1; + deviceMap.insert(std:make_pair("accountId", userId)); + deviceMap.insert(std:make_pair("accountName", 1)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_, _)).WillOnce(Return(deviceMap)); EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_,_)).WillOnce(Return(deviceMap)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_, _)).WillOnce(Return(deviceMap)); EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); - + int32_t curUserId = 0; + int32_t preUserId = 1; std::map curUserDeviceMap; curUserDeviceMap["curUserId"] = userId; curUserDeviceMap["preUserId"] = userId; @@ -564,12 +565,10 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS preUserDeviceMap["accountName"] = 1; EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(curUserDeviceMap)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(preUserDeviceMap)); - - - + DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); int32_t removeId = 123; - deviceMap["removeId"] = removeId; + deviceMap.insert(std:make_pair("removeId", removeId)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)).WillOnce(Return(deviceMap)); DeviceManagerService::GetInstance().HandleUserRemoved(userId); } -- Gitee From 231dd88e81c75bd156d71b3599d6a17b91977518 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 20 Nov 2024 15:06:46 +0800 Subject: [PATCH 430/520] =?UTF-8?q?=E5=88=A4=E6=96=AD=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E5=90=8C=E8=B4=A6=E5=8F=B7=E5=85=BC=E5=AE=B9=E8=80=81=E7=89=88?= =?UTF-8?q?=E6=9C=AC=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/deviceprofile_connector.cpp | 39 +++++++++---------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index c8be4ebaf..57d2b8e39 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -58,7 +58,7 @@ std::vector DeviceProfileConnector::GetAclProfileByDeviceI queryParams[USERID] = std::to_string(userId); if (DistributedDeviceProfileClient::GetInstance().GetAccessControlProfile(queryParams, profiles) != DM_OK) { LOGE("DP GetAccessControlProfile failed."); - return profiles; + return aclProfileVec; } for (auto &item : profiles) { if ((item.GetAccesser().GetAccesserDeviceId() == deviceId && @@ -229,8 +229,6 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont priority = DEVICE_PEER_TO_PEER_TYPE; } else if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP) { - priority = APP_PEER_TO_PEER_TYPE; } break; case DM_ACROSS_ACCOUNT: @@ -415,7 +413,7 @@ std::vector DeviceProfileConnector::GetP processInfo.userId = item.GetAccessee().GetAccesseeUserId(); processInfoVec.push_back(processInfo); continue; - } + } } return processInfoVec; } @@ -793,26 +791,25 @@ std::vector GetACLByDeviceIdAndUserId(std::vector Date: Fri, 22 Nov 2024 11:38:13 +0800 Subject: [PATCH 431/520] =?UTF-8?q?=E4=BC=98=E5=8C=96dlclose=E7=9A=84?= =?UTF-8?q?=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 12 ++++++++---- services/service/src/discovery/discovery_manager.cpp | 5 ++++- services/service/src/softbus/softbus_listener.cpp | 5 ++++- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 4ede94b80..d1fcc98c3 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -879,7 +879,10 @@ bool DeviceManagerService::IsDMServiceImplReady() if (isImplsoLoaded_ && (dmServiceImpl_ != nullptr)) { return true; } - void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE); + void *so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(LIB_IMPL_NAME, RTLD_NOW | RTLD_NODELETE); + } if (so_handle == nullptr) { LOGE("load libdevicemanagerserviceimpl so failed, errMsg: %{public}s.", dlerror()); return false; @@ -897,7 +900,6 @@ bool DeviceManagerService::IsDMServiceImplReady() listener_ = std::make_shared(); } if (dmServiceImpl_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImpl_ = nullptr; isImplsoLoaded_ = false; return false; @@ -1129,7 +1131,10 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() return true; } - void *so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NODELETE); + void *so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(LIB_DM_ADAPTER_NAME, RTLD_NOW | RTLD_NODELETE); + } if (so_handle == nullptr) { LOGE("load dm service adapter so failed."); return false; @@ -1144,7 +1149,6 @@ bool DeviceManagerService::IsDMServiceAdapterLoad() dmServiceImplExt_ = std::shared_ptr(func()); if (dmServiceImplExt_->Initialize(listener_) != DM_OK) { - dlclose(so_handle); dmServiceImplExt_ = nullptr; isAdapterSoLoaded_ = false; LOGE("dm service adapter impl ext init failed."); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 224e0887a..e8889ba73 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -569,7 +569,10 @@ bool DiscoveryManager::IsCommonDependencyReady() if (isSoLoaded_ && dpConnector_ != nullptr && dpConnectorHandle_ != nullptr) { return true; } - dpConnectorHandle_ = dlopen(LIB_DM_COMDENPENDENCY_NAME, RTLD_NOW | RTLD_NODELETE); + dpConnectorHandle_ = dlopen(LIB_DM_COMDENPENDENCY_NAME, RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (dpConnectorHandle_ == nullptr) { + dpConnectorHandle_ = dlopen(LIB_DM_COMDENPENDENCY_NAME, RTLD_NOW | RTLD_NODELETE); + } if (dpConnectorHandle_ == nullptr) { LOGE("load libdevicemanagerdependency so failed, errMsg: %{public}s.", dlerror()); return false; diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 2a3385e77..f54b8727a 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -1021,7 +1021,10 @@ bool SoftbusListener::IsDmRadarHelperReady() LOGD("IsDmRadarHelperReady alReady."); return true; } - radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW); + radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW | RTLD_NOLOAD); + if (radarHandle_ == nullptr) { + radarHandle_ = dlopen(LIB_RADAR_NAME, RTLD_NOW); + } if (radarHandle_ == nullptr) { LOGE("load libdevicemanagerradar so failed."); return false; -- Gitee From 34c3443f1f5a70512653d223f0af1263da207ec5 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 22 Nov 2024 12:03:40 +0800 Subject: [PATCH 432/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service_two.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index c4e2308bf..f261c46bb 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -545,8 +545,8 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS std::string accountId = "accountId"; std::string accountName = "accountName"; std::multimap deviceMap; - deviceMap.insert(std:make_pair("accountId", userId)); - deviceMap.insert(std:make_pair("accountName", 1)); + deviceMap.insert(std::make_pair("accountId", userId)); + deviceMap.insert(std::make_pair("accountName", 1)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_, _)).WillOnce(Return(deviceMap)); EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); @@ -568,7 +568,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); int32_t removeId = 123; - deviceMap.insert(std:make_pair("removeId", removeId)); + deviceMap.insert(std::make_pair("removeId", removeId)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndUserId(_)).WillOnce(Return(deviceMap)); DeviceManagerService::GetInstance().HandleUserRemoved(userId); } -- Gitee From 036743380c4cc6c1def3e6be2456cf03b2fa7b83 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 22 Nov 2024 17:07:29 +0800 Subject: [PATCH 433/520] =?UTF-8?q?=E5=A4=84=E7=90=86foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97fuzz=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=E7=9A=84=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp | 3 +-- test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp | 3 +-- test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp index ea8c7f86a..97e88fa08 100644 --- a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp +++ b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp @@ -63,8 +63,7 @@ void OnErrorFuzzTest(const uint8_t* data, size_t size) hichainConnector->RegisterHiChainCallback(std::make_shared()); int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); int errorCode = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); const char *returnData = str.data(); diff --git a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp index 196069acc..3a852c03f 100644 --- a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp +++ b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp @@ -63,8 +63,7 @@ void OnFinishFuzzTest(const uint8_t* data, size_t size) hichainConnector->RegisterHiChainCallback(std::make_shared()); int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); const char *returnData = str.data(); hichainConnector->onFinish(requestId, operationCode, returnData); diff --git a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp index d3b7df0b7..d27fd5e0e 100644 --- a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp +++ b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp @@ -59,8 +59,7 @@ void OnRequestFuzzTest(const uint8_t* data, size_t size) } int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); const char *reqParams = reinterpret_cast(data); std::shared_ptr hichainConnector = std::make_shared(); -- Gitee From b737da3a6217642c4d033b057b65b6916b4949b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 22 Nov 2024 17:35:37 +0800 Subject: [PATCH 434/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9L1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/BUILD.gn | 1 + 1 file changed, 1 insertion(+) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index 3343bcbae..d6d95efdb 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -94,6 +94,7 @@ if (defined(ohos_lite)) { "${common_path}/src/dfx/lite/dm_hisysevent.cpp", "${common_path}/src/dfx/lite/dm_hitrace.cpp", "${common_path}/src/dm_anonymous.cpp", + "${devicemanager_path}/radar/src/lite/dm_radar_helper.cpp", "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", -- Gitee From c76496d3291b905170e24ee1f0eaab922e687b48 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 22 Nov 2024 18:08:01 +0800 Subject: [PATCH 435/520] =?UTF-8?q?=E5=A4=84=E7=90=86foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- interfaces/kits/js/src/native_devicemanager_js.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 75e70c7a7..e0f90c5ce 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -620,6 +620,7 @@ void DmNapiPublishCallback::OnPublishResult(int32_t publishId, int32_t publishRe deviceManagerNapi->OnPublishResult(callback->publishId_, callback->reason_); } delete callback; + callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -678,6 +679,7 @@ void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const callback->status_, callback->reason_); } delete callback; + callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -721,6 +723,7 @@ void DmNapiCredentialCallback::OnCredentialResult(int32_t &action, const std::st deviceManagerNapi->OnCredentialResult(callback->action_, callback->credentialResult_); } delete callback; + callback = nullptr; delete work; work = nullptr; }, uv_qos_user_initiated); @@ -1601,6 +1604,7 @@ void DmNapiDeviceManagerUiCallback::OnCall(const std::string ¶mJson) deviceManagerNapi->OnDmUiCall(callback->token_); } delete callback; + callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { -- Gitee From 09becd6f2cf24b78862f95b1122a74e31c3bdfd8 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 22 Nov 2024 18:16:49 +0800 Subject: [PATCH 436/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service_two.cpp | 3 ++- .../mock/mock_distributed_device_profile_client.cpp | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index f261c46bb..10d5303c0 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -564,7 +564,8 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS preUserDeviceMap["accountId"] = userId; preUserDeviceMap["accountName"] = 1; EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(curUserDeviceMap)); - EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(preUserDeviceMap)); + EXPECT_CALL(*deviceManagerServiceImplMock_, + GetDeviceIdAndBindLevel(_)).WillOnce(Return(preUserDeviceMap)).WillOnce(Return(preUserDeviceMap)); DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); int32_t removeId = 123; diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index f6e21de48..ba6971387 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -994,6 +994,13 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map& accessControlProfiles) { + AddAccessControlProfileTwelfth(accessControlProfiles); + AddAccessControlprofileThirteenth(accessControlProfiles); + AddAccessControlprofileFourteenth(accessControlProfiles); + AddAccessControlprofileFifteenth(accessControlProfiles); + AddAccessControlprofileSixteenth(accessControlProfiles); + AddAccessControlprofileSeventeenth(accessControlProfiles); + AddAccessControlprofileEightteenth(accessControlProfiles); return 0; } -- Gitee From 99e02e485cc17273bbbda6b32226baeed99e8cdd Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 22 Nov 2024 16:48:39 +0800 Subject: [PATCH 437/520] =?UTF-8?q?=E7=A8=B3=E5=AE=9A=E6=80=A7=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- services/service/src/device_manager_service.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 6c5a8425d..50cc75c19 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -967,6 +967,10 @@ void DeviceManagerService::LoadHardwareFwkService() LOGE("LoadHardwareFwkService failed, get trusted devicelist failed."); return; } + if (!IsDMServiceImplReady()) { + LOGE("LoadHardwareFwkService failed, instance not init or init failed."); + return; + } if (deviceList.size() > 0) { dmServiceImpl_->LoadHardwareFwkService(); } -- Gitee From e7efa352be499261823dcac7d89ec58598f24d2d Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 09:11:21 +0800 Subject: [PATCH 438/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 523a5591d..87ae1c3c5 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1274,7 +1274,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAllAccessControlProfile_001, testing::ex int64_t accessControlId = 1; DeviceProfileConnector::GetInstance().DeleteAccessControlById(accessControlId); auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); - EXPECT_TRUE(ret.empty()); + EXPECT_FALSE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, GetAclProfileByDeviceIdAndUserId_001, testing::ext::TestSize.Level0) @@ -1298,7 +1298,7 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteAclForAccountLogOut_001, testing::ext localUdid = "deviceId"; localUserId = 123456; - peerUdid = "deviceIdee"; + peerUdid = "deviceId"; peerUserId = 456; ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); EXPECT_TRUE(ret); -- Gitee From df67319acdbacfcf3a315d5730eebae2b035d664 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 11:12:27 +0800 Subject: [PATCH 439/520] =?UTF-8?q?=E5=A4=84=E7=90=86foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- services/softbuscache/src/dm_softbus_cache.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 097f7ed6e..baeaf5ece 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -23,8 +23,8 @@ namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(SoftbusCache); -std::atomic g_online; -std::atomic g_getLocalDevInfo; +std::atomic g_online{false}; +std::atomic g_getLocalDevInfo{false}; DmDeviceInfo localDeviceInfo_; std::mutex localDevInfoMutex_; void SoftbusCache::SaveLocalDeviceInfo() -- Gitee From c31ad864576f5bebdd04b62222f9b7b0583339c2 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 11:17:26 +0800 Subject: [PATCH 440/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp | 5 +++-- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 5 ++--- .../devicediscovery_fuzzer/device_discovery_fuzzer.cpp | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 3f1ee3fc8..a39823d68 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -216,9 +216,10 @@ void AuthenticateDeviceFirstFuzzTest(const uint8_t* data, size_t size) std::string emptyStr = ""; DeviceManager::GetInstance().AuthenticateDevice(str, g_authType, g_deviceInfo, emptyStr, g_callbackk); DeviceManager::GetInstance().UnAuthenticateDevice(str, g_deviceInfo); - DeviceManager::GetInstance().StartDeviceDiscovery(str, g_subscribeInfo, str, g_discoveryCallback); + std::string pkgName = "pkgName"; + DeviceManager::GetInstance().StartDeviceDiscovery(pkgName, g_subscribeInfo, pkgName, g_discoveryCallback); DeviceManager::GetInstance().StopDeviceDiscovery(str, g_subscribeInfo.subscribeId); - DeviceManager::GetInstance().StartDeviceDiscovery(str, g_tokenId, str, g_discoveryCallback); + DeviceManager::GetInstance().StartDeviceDiscovery(pkgName, g_tokenId, pkgName, g_discoveryCallback); DeviceManager::GetInstance().StopDeviceDiscovery(g_tokenId, str); DeviceManager::GetInstance().PublishDeviceDiscovery(str, g_publishInfo, g_publishCallback); DeviceManager::GetInstance().UnPublishDeviceDiscovery(str, g_publishInfo.publishId); diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 87ae1c3c5..312480d8f 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1352,9 +1352,8 @@ HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestS beforeUserId = 1234; currentUserId = 123456; - ret = DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); - EXPECT_EQ(ret, DM_OK); - + DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); + std::vector remoteUserIds; remoteUserIds.push_back(currentUserId); std::string remoteUdid = "deviceId"; diff --git a/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp b/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp index cd80dd3d3..13fb677ce 100644 --- a/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp +++ b/test/servicesfuzztest/devicediscovery_fuzzer/device_discovery_fuzzer.cpp @@ -55,7 +55,7 @@ void DeviceDiscoveryFuzzTest(const uint8_t* data, size_t size) if (strncpy_s(subInfo.capability, DM_MAX_DEVICE_CAPABILITY_LEN, "111", DM_MAX_DEVICE_CAPABILITY_LEN) != 0) { return; } - std::string extra(reinterpret_cast(data), size); + std::string extra = "extraInfo"; std::shared_ptr callback = std::make_shared(); bundleName = "111"; -- Gitee From 0b973d991ff3de55cdd328970604a5f5e9f178dd Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 11:40:57 +0800 Subject: [PATCH 441/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 312480d8f..72ba90d58 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1301,7 +1301,7 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteAclForAccountLogOut_001, testing::ext peerUdid = "deviceId"; peerUserId = 456; ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); - EXPECT_TRUE(ret); + EXPECT_FALSE(ret); localUdid = "deviceId"; localUserId = 123456; @@ -1353,7 +1353,7 @@ HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestS beforeUserId = 1234; currentUserId = 123456; DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); - + std::vector remoteUserIds; remoteUserIds.push_back(currentUserId); std::string remoteUdid = "deviceId"; -- Gitee From 0847d1824f807df8914f9a2ec38e4b77b2e8c4d2 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 11:49:05 +0800 Subject: [PATCH 442/520] =?UTF-8?q?=E5=A4=84=E7=90=86foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84fuzz?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp | 3 +-- test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp | 2 +- test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp | 3 +-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp index ea8c7f86a..97e88fa08 100644 --- a/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp +++ b/test/commonfuzztest/onerror_fuzzer/on_error_fuzzer.cpp @@ -63,8 +63,7 @@ void OnErrorFuzzTest(const uint8_t* data, size_t size) hichainConnector->RegisterHiChainCallback(std::make_shared()); int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); int errorCode = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); const char *returnData = str.data(); diff --git a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp index 196069acc..3460e2fc3 100644 --- a/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp +++ b/test/commonfuzztest/onfinish_fuzzer/on_finish_fuzzer.cpp @@ -64,7 +64,7 @@ void OnFinishFuzzTest(const uint8_t* data, size_t size) int64_t requestId = *(reinterpret_cast(data)); std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); std::string str(reinterpret_cast(data), size); const char *returnData = str.data(); hichainConnector->onFinish(requestId, operationCode, returnData); diff --git a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp index d3b7df0b7..d27fd5e0e 100644 --- a/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp +++ b/test/commonfuzztest/onrequest_fuzzer/on_request_fuzzer.cpp @@ -59,8 +59,7 @@ void OnRequestFuzzTest(const uint8_t* data, size_t size) } int64_t requestId = *(reinterpret_cast(data)); - std::random_device rd; - int operationCode = static_cast(rd() % 6); + int operationCode = *(reinterpret_cast(data)); const char *reqParams = reinterpret_cast(data); std::shared_ptr hichainConnector = std::make_shared(); -- Gitee From 7bc175fb834a7c2baf39d3f03509720791a2cc01 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 23 Nov 2024 12:05:20 +0800 Subject: [PATCH 443/520] =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E6=97=B6=E9=98=B2=E6=AD=A2=E8=A2=AB=E6=9E=90=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/src/authentication/auth_request_state.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication/auth_request_state.cpp b/services/implementation/src/authentication/auth_request_state.cpp index 7181d2947..663a8c310 100644 --- a/services/implementation/src/authentication/auth_request_state.cpp +++ b/services/implementation/src/authentication/auth_request_state.cpp @@ -52,6 +52,7 @@ int32_t AuthRequestState::TransitionTo(std::shared_ptr state) } std::shared_ptr contextTemp = GetAuthContext(); state->SetAuthManager(stateAuthManager); + std::shared_ptr selfTemp = shared_from_this(); stateAuthManager->SetAuthRequestState(state); state->SetAuthContext(contextTemp); this->Leave(); -- Gitee From a79e636dc96606315512656074640afe00c22425 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 13:08:56 +0800 Subject: [PATCH 444/520] =?UTF-8?q?=E5=A4=84=E7=90=86foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- interfaces/kits/js4.0/src/dm_native_util.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index 43be4b8fa..dd3f342f7 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -444,7 +444,10 @@ bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &value return false; } size_t valueLen = 0; - napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen); + napi_status stat = napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen); + if (status != napi_ok) { + return false; + } if (!CheckArgsVal(env, valueLen > 0, valueName, "len == 0")) { return false; } -- Gitee From e13f5509cb30bcd0d10b1639e5bb483715f50846 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 13:58:28 +0800 Subject: [PATCH 445/520] =?UTF-8?q?=E5=A4=84=E7=90=86foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- interfaces/kits/js4.0/src/dm_native_util.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index dd3f342f7..414c2fe8a 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -445,7 +445,7 @@ bool JsToStringAndCheck(napi_env env, napi_value value, const std::string &value } size_t valueLen = 0; napi_status stat = napi_get_value_string_utf8(env, value, nullptr, 0, &valueLen); - if (status != napi_ok) { + if (stat != napi_ok) { return false; } if (!CheckArgsVal(env, valueLen > 0, valueName, "len == 0")) { -- Gitee From 567f549c4b2d62b33e2125fa3886013d6d0a95e8 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 14:15:51 +0800 Subject: [PATCH 446/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 72ba90d58..994bc6e74 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1352,7 +1352,8 @@ HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestS beforeUserId = 1234; currentUserId = 123456; - DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); + ret = DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); + EXPECT_EQ(ret, DM_OK); std::vector remoteUserIds; remoteUserIds.push_back(currentUserId); -- Gitee From 5670ab58ca3d696c5431d32c0c00a5dd4835f2e2 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 23 Nov 2024 17:09:27 +0800 Subject: [PATCH 447/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=BC=82=E5=B8=B8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- interfaces/kits/js/src/native_devicemanager_js.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 75e70c7a7..e0f90c5ce 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -620,6 +620,7 @@ void DmNapiPublishCallback::OnPublishResult(int32_t publishId, int32_t publishRe deviceManagerNapi->OnPublishResult(callback->publishId_, callback->reason_); } delete callback; + callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -678,6 +679,7 @@ void DmNapiAuthenticateCallback::OnAuthResult(const std::string &deviceId, const callback->status_, callback->reason_); } delete callback; + callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { @@ -721,6 +723,7 @@ void DmNapiCredentialCallback::OnCredentialResult(int32_t &action, const std::st deviceManagerNapi->OnCredentialResult(callback->action_, callback->credentialResult_); } delete callback; + callback = nullptr; delete work; work = nullptr; }, uv_qos_user_initiated); @@ -1601,6 +1604,7 @@ void DmNapiDeviceManagerUiCallback::OnCall(const std::string ¶mJson) deviceManagerNapi->OnDmUiCall(callback->token_); } delete callback; + callback = nullptr; DeleteUvWork(work); }, uv_qos_user_initiated); if (ret != 0) { -- Gitee From 100c4780b79789d40022177e88a028d2d5974777 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 23 Nov 2024 17:27:57 +0800 Subject: [PATCH 448/520] =?UTF-8?q?=E6=B6=88=E9=99=A4=E5=B7=AE=E5=BC=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../src/authentication/dm_auth_manager.cpp | 106 ++++++++++++------ 1 file changed, 70 insertions(+), 36 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index a1d3c0dfa..64d864d24 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -56,13 +56,13 @@ const int32_t INPUT_TIMEOUT = 60; const int32_t ADD_TIMEOUT = 10; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_AUTHENTICATE_TIMEOUT = 10; -const int32_t CLONE_CONFIRM_TIMEOUT = 5; -const int32_t CLONE_NEGOTIATE_TIMEOUT = 5; -const int32_t CLONE_ADD_TIMEOUT = 5; -const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 5; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 5; -const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 10; +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; const int32_t DEVICE_ID_HALF = 2; const int32_t MAX_AUTH_TIMES = 3; @@ -521,7 +521,9 @@ void DmAuthManager::ProcessSinkMsg() switch (authResponseContext_->msgType) { case MSG_TYPE_NEGOTIATE: if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_INIT) { - timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); + } authResponseState_->TransitionTo(std::make_shared()); } else { LOGE("Device manager auth state error"); @@ -529,7 +531,9 @@ void DmAuthManager::ProcessSinkMsg() break; case MSG_TYPE_REQ_AUTH: if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_NEGOTIATE) { - timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + } authResponseState_->TransitionTo(std::make_shared()); } else { LOGE("Device manager auth state error"); @@ -773,10 +777,12 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authMessageProcessor_->SetResponseContext(authResponseContext_); std::string message = authMessageProcessor_->CreateSimpleMessage(MSG_TYPE_NEGOTIATE); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); - timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), - GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + GetTaskTimeout(NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } } void DmAuthManager::AbilityNegotiate() @@ -872,7 +878,9 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) } remoteDeviceId_ = authResponseContext_->localDeviceId; remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion); - timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + } if (authResponseContext_->cryptoSupport) { isCryptoSupport_ = true; } @@ -1110,7 +1118,9 @@ void DmAuthManager::StartRespAuthProcess() return; } LOGI("DmAuthManager::StartRespAuthProcess sessionId = %{public}d", authResponseContext_->sessionId); - timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + } if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ALWAYS) { action_ = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; } else if (authResponseContext_->groupName[CHECK_AUTH_ALWAYS_POS] == AUTH_ONCE) { @@ -1158,7 +1168,9 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) return ERR_DM_FAILED; } LOGI("DmAuthManager::AddMember start group id %{public}s", GetAnonyString(authResponseContext_->groupId).c_str()); - timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + } nlohmann::json jsonObject; jsonObject[TAG_GROUP_ID] = authResponseContext_->groupId; jsonObject[TAG_GROUP_NAME] = authResponseContext_->groupName; @@ -1166,10 +1178,12 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; std::string connectInfo = jsonObject.dump(); - timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), - GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), + GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } if (authUiStateMgr_ == nullptr) { LOGE("DmAuthManager::AddMember authUiStateMgr is null."); return ERR_DM_FAILED; @@ -1215,7 +1229,9 @@ int32_t DmAuthManager::JoinNetwork() return ERR_DM_FAILED; } LOGI("DmAuthManager JoinNetwork start"); - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authResponseContext_->isFinish = true; authRequestContext_->reason = DM_OK; @@ -1294,7 +1310,9 @@ void DmAuthManager::AuthenticateFinish() } else if (authRequestState_ != nullptr) { SrcAuthenticateFinish(); } - timer_->DeleteAll(); + if (timer_ != nullptr) { + timer_->DeleteAll(); + } isFinishOfLocal_ = true; authResponseContext_ = nullptr; authMessageProcessor_ = nullptr; @@ -1502,7 +1520,9 @@ int32_t DmAuthManager::ProcessPincode(int32_t pinCode) LOGE("failed to ProcessPincode because authResponseContext_ is nullptr"); return ERR_DM_FAILED; } - timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + } if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (static_cast(authResponseContext_->bindLevel) >= DEVICE && static_cast(authResponseContext_->bindLevel) <= APP)) { @@ -1908,7 +1928,9 @@ void DmAuthManager::RequestCredentialDone() if (ImportCredential(remoteDeviceId_, authResponseContext_->publicKey) != DM_OK) { LOGE("ResponseCredential import credential failed."); } - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } softbusConnector_->JoinLnn(authRequestContext_->addr); authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; authRequestContext_->reason = DM_OK; @@ -1968,7 +1990,9 @@ void DmAuthManager::SrcAuthDeviceFinish() SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); - timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); + } authRequestContext_->reason = DM_OK; authResponseContext_->reply = DM_OK; authResponseContext_->state = AuthState::AUTH_REQUEST_FINISH; @@ -2022,7 +2046,9 @@ void DmAuthManager::AuthDeviceFinish(int64_t requestId) return; } isAuthDevice_ = false; - timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + } if (authRequestState_ != nullptr && authResponseState_ == nullptr) { PutAccessControlList(); SrcAuthDeviceFinish(); @@ -2048,7 +2074,9 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) return; } authTimes_++; - timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + } if (errorCode != DM_OK || requestId != authResponseContext_->requestId) { if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; @@ -2056,10 +2084,12 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) authResponseContext_->reply = ERR_DM_INPUT_PARA_INVALID; authRequestState_->TransitionTo(std::make_shared()); } else { - timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), - GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleAuthenticateTimeout(name); - }); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(INPUT_TIMEOUT_TASK), + GetTaskTimeout(INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleAuthenticateTimeout(name); + }); + } authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); } } @@ -2336,7 +2366,9 @@ void DmAuthManager::PutAccessControlList() void DmAuthManager::HandleSessionHeartbeat(std::string name) { - timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + } LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); nlohmann::json jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; @@ -2344,10 +2376,12 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { - timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), - GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { - DmAuthManager::HandleSessionHeartbeat(name); - }); + if (timer_ != nullptr) { + timer_->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { + DmAuthManager::HandleSessionHeartbeat(name); + }); + } } LOGI("DmAuthManager::HandleSessionHeartbeat complete"); } -- Gitee From 2e93a3b78da756fc56991cfbc423a63560e4b1b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 25 Nov 2024 09:34:42 +0800 Subject: [PATCH 449/520] =?UTF-8?q?=E5=8E=BB=E9=99=A4L1=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- interfaces/inner_kits/native_cpp/BUILD.gn | 1 - 1 file changed, 1 deletion(-) diff --git a/interfaces/inner_kits/native_cpp/BUILD.gn b/interfaces/inner_kits/native_cpp/BUILD.gn index d6d95efdb..3343bcbae 100644 --- a/interfaces/inner_kits/native_cpp/BUILD.gn +++ b/interfaces/inner_kits/native_cpp/BUILD.gn @@ -94,7 +94,6 @@ if (defined(ohos_lite)) { "${common_path}/src/dfx/lite/dm_hisysevent.cpp", "${common_path}/src/dfx/lite/dm_hitrace.cpp", "${common_path}/src/dm_anonymous.cpp", - "${devicemanager_path}/radar/src/lite/dm_radar_helper.cpp", "src/device_manager.cpp", "src/device_manager_impl.cpp", "src/ipc/ipc_client_proxy.cpp", -- Gitee From ed3a7de520ead71c6c91b4358bfa2bf35141e6e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 25 Nov 2024 11:18:51 +0800 Subject: [PATCH 450/520] =?UTF-8?q?died=20=E5=9B=9E=E8=B0=83=E9=97=AE?= =?UTF-8?q?=E9=A2=98=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/src/notify/device_manager_notify.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index d0ccdb127..fb5dfe725 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 @@ -258,8 +258,8 @@ void DeviceManagerNotify::RegisterPinHolderCallback(const std::string &pkgName, void DeviceManagerNotify::OnRemoteDied() { LOGW("DeviceManagerNotify::OnRemoteDied"); - std::lock_guard autoLock(lock_); - for (auto iter : dmInitCallback_) { + std::map> dmInitCallback = GetDmInitCallback(); + for (auto iter : dmInitCallback) { LOGI("DeviceManagerNotify::OnRemoteDied, pkgName:%{public}s", iter.first.c_str()); if (iter.second != nullptr) { iter.second->OnRemoteDied(); -- Gitee From 85d4a2725e7244abcad5d94be8986b786495b1d4 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Wed, 20 Nov 2024 09:13:00 +0800 Subject: [PATCH 451/520] =?UTF-8?q?UX=E9=80=82=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- display/AppScope/app.json | 4 ++-- display/entry/src/main/ets/pages/InputPinDialog.ets | 5 ++--- display/entry/src/main/ets/pages/PinDialog.ets | 5 ++--- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/display/AppScope/app.json b/display/AppScope/app.json index 5462a6ca1..335740525 100644 --- a/display/AppScope/app.json +++ b/display/AppScope/app.json @@ -2,8 +2,8 @@ "app": { "bundleName": "com.ohos.devicemanagerui", "vendor": "example", - "versionCode": 1000024, - "versionName": "1.0.24", + "versionCode": 1000025, + "versionName": "1.0.25", "icon": "$media:app_icon", "label": "$string:app_name", "minAPIVersion": 10, diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index c998ef202..b7815957d 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -227,7 +227,6 @@ struct InputCustomDialog { .fontSize($r('sys.float.ohos_id_text_size_headline7')) .fontColor($r('sys.color.ohos_id_color_text_primary')) .fontWeight(FontWeight.Medium) - .height(26) }.width('10%') .height('100%') .visibility(item === '' ? Visibility.None : Visibility.Visible) @@ -317,8 +316,8 @@ struct InputCustomDialog { } }) }.margin({ - left: this.isPC ? 72 : 16, - right: this.isPC ? 72 : 16, + left: 16, + right: 16, bottom: this.isPC ? 24 : 16 }) } } diff --git a/display/entry/src/main/ets/pages/PinDialog.ets b/display/entry/src/main/ets/pages/PinDialog.ets index 7645b200c..2ee89538b 100644 --- a/display/entry/src/main/ets/pages/PinDialog.ets +++ b/display/entry/src/main/ets/pages/PinDialog.ets @@ -95,7 +95,6 @@ struct PinCustomDialog { .fontSize($r('sys.float.ohos_id_text_size_headline7')) .fontColor($r('sys.color.ohos_id_color_text_primary')) .fontWeight(FontWeight.Medium) - .height(26) }.width('10%') .height('100%') }) @@ -133,8 +132,8 @@ struct PinCustomDialog { } }) }.margin({ - left: this.isPC ? 72 : 16, - right: this.isPC ? 72 : 16, + left: 16, + right: 16, bottom: this.isPC ? 24 : 16 }) } .constraintSize({ maxHeight: `${300}` }) -- Gitee From 6107e1e75a57b8e396c6835b51ccdd3c4af30442 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Mon, 25 Nov 2024 14:27:18 +0800 Subject: [PATCH 452/520] =?UTF-8?q?=E5=9B=9E=E9=80=80=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E8=AE=BE=E5=A4=87=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../src/ipc/standard/ipc_server_stub.cpp | 12 --------- .../service/src/softbus/softbus_listener.cpp | 26 ------------------- 2 files changed, 38 deletions(-) diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 8c6fe970a..544382ac5 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -89,17 +89,6 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin return; } state_ = ServiceRunningState::STATE_RUNNING; - std::string localDeviceName = accountBootListener_->GetLocalDeviceName(); - std::string localDisplayName = accountBootListener_->GetLocalDisplayName(); - LOGI("deviceName=%{public}s, displayName=%{public}s", - localDeviceName.c_str(), localDisplayName.c_str()); - int ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); - if (ret == DM_OK) { - LOGI("Already have deviceName=%{public}s or displayName=%{public}s", - localDeviceName.c_str(), localDisplayName.c_str()); - return; - } - accountBootListener_->SetSaTriggerFlag(SaTriggerFlag::DM_SA_READY); return; } @@ -128,7 +117,6 @@ void IpcServerStub::OnAddSystemAbility(int32_t systemAbilityId, const std::strin #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) { KVAdapterManager::GetInstance().ReInit(); - accountBootListener_->SetSaTriggerFlag(SaTriggerFlag::DATA_SHARE_SA_REDDY); return; } #endif diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 2a3385e77..5420af8b1 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -717,32 +717,6 @@ int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) { LOGI("SoftbusListener Start SetLocalDeviceName!"); -#ifdef DEVICE_MANAGER_COMMON_FLAG - LOGI("device_manager_common is true!"); - int32_t ret = 1; - if (!localDisplayName.empty()) { - ret = ::SetLocalDeviceName(DM_PKG_NAME, localDisplayName.c_str()); - } else if (!localDeviceName.empty()) { - ret = ::SetLocalDeviceName(DM_PKG_NAME, localDeviceName.c_str()); - } else { - LOGE("localDeviceName and localDisplayName is null!"); - } - if (ret != DM_OK) { - LOGE("[SOFTBUS]SetLocalDeviceName error, failed ret: %{public}d", ret); - return ret; - } -#else - LOGI("device_manager_common is false!"); - if (localDisplayName.empty()) { - LOGE("Invalid parameter, localDisplayName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - int32_t ret = ::SetLocalDeviceName(DM_PKG_NAME, localDisplayName.c_str()); - if (ret != DM_OK) { - LOGE("[SOFTBUS]SetLocalDeviceName error, failed ret: %{public}d", ret); - return ret; - } -#endif return DM_OK; } -- Gitee From 590fa2100e77235063bd276c5e72d59ed3b0e171 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Mon, 25 Nov 2024 15:23:50 +0800 Subject: [PATCH 453/520] =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E6=97=B6=E9=98=B2=E6=AD=A2=E8=A2=AB=E6=9E=90=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/include/authentication/dm_auth_manager.h | 1 + .../implementation/src/authentication/auth_request_state.cpp | 1 - services/implementation/src/authentication/dm_auth_manager.cpp | 2 ++ 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 38ebf8607..75d187561 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -541,6 +541,7 @@ private: std::shared_ptr adapterMgr_; std::map> authenticationMap_; std::shared_ptr authRequestState_ = nullptr; + std::shared_ptr authRequestStateTemp_ = nullptr; std::shared_ptr authResponseState_ = nullptr; std::shared_ptr authRequestContext_; std::shared_ptr authResponseContext_; diff --git a/services/implementation/src/authentication/auth_request_state.cpp b/services/implementation/src/authentication/auth_request_state.cpp index 663a8c310..7181d2947 100644 --- a/services/implementation/src/authentication/auth_request_state.cpp +++ b/services/implementation/src/authentication/auth_request_state.cpp @@ -52,7 +52,6 @@ int32_t AuthRequestState::TransitionTo(std::shared_ptr state) } std::shared_ptr contextTemp = GetAuthContext(); state->SetAuthManager(stateAuthManager); - std::shared_ptr selfTemp = shared_from_this(); stateAuthManager->SetAuthRequestState(state); state->SetAuthContext(contextTemp); this->Leave(); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index a1d3c0dfa..cc6e5bfa4 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1375,6 +1375,8 @@ int32_t DmAuthManager::SetAuthRequestState(std::shared_ptr aut LOGE("authRequestState is nullptr."); return ERR_DM_INPUT_PARA_INVALID; } + // Keep current state, avoid deconstructed during state transitions + authRequestStateTemp_ = authRequestState_; authRequestState_ = authRequestState; return DM_OK; } -- Gitee From 01e2e9ae2656ba272f6524baba965e431509e7cc Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Mon, 25 Nov 2024 15:31:17 +0800 Subject: [PATCH 454/520] =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E6=97=B6=E9=98=B2=E6=AD=A2=E8=A2=AB=E6=9E=90=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/include/authentication/dm_auth_manager.h | 1 + .../src/authentication/auth_request_state.cpp | 6 ++++++ .../implementation/src/authentication/dm_auth_manager.cpp | 5 +++++ 3 files changed, 12 insertions(+) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 75d187561..d6721b12f 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -502,6 +502,7 @@ public: int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); int32_t DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId); int32_t StopAuthenticateDevice(const std::string &pkgName); + void Leave(); private: int32_t ImportCredential(std::string &deviceId, std::string &publicKey); void GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, diff --git a/services/implementation/src/authentication/auth_request_state.cpp b/services/implementation/src/authentication/auth_request_state.cpp index 7181d2947..88ed30064 100644 --- a/services/implementation/src/authentication/auth_request_state.cpp +++ b/services/implementation/src/authentication/auth_request_state.cpp @@ -22,6 +22,12 @@ namespace OHOS { namespace DistributedHardware { int32_t AuthRequestState::Leave() { + std::shared_ptr stateAuthManager = authManager_.lock(); + if (stateAuthManager == nullptr) { + LOGE("AuthRequestState::authManager_ null"); + return ERR_DM_FAILED; + } + stateAuthManager->Leave(); return DM_OK; } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index cc6e5bfa4..c5ffced4b 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2609,5 +2609,10 @@ void DmAuthManager::SetProcessInfo() } softbusConnector_->SetProcessInfo(processInfo); } + +void DmAuthManager::Leave() +{ + authRequestStateTemp_ = nullptr; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 0eb3389f3103da894ad70e10bcdac407610f8387 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Mon, 25 Nov 2024 17:37:08 +0800 Subject: [PATCH 455/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../implementation/src/config/dm_config_manager.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/config/dm_config_manager.cpp b/services/implementation/src/config/dm_config_manager.cpp index 4f680c68d..ddfea4bf4 100644 --- a/services/implementation/src/config/dm_config_manager.cpp +++ b/services/implementation/src/config/dm_config_manager.cpp @@ -190,7 +190,10 @@ std::shared_ptr DmConfigManager::GetCryptoAdapter(const std::str LOGE("File %{public}s canonicalization failed.", soPathName.c_str()); return nullptr; } - so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE); + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE | RTLD_NOLOAD); + if (so_handle == nullptr) { + so_handle = dlopen(soPathName.c_str(), RTLD_NOW | RTLD_NODELETE); + } if (so_handle == nullptr) { LOGE("load crypto so failed."); return nullptr; @@ -223,7 +226,10 @@ void DmConfigManager::GetAuthAdapter(std::mapsecond).soName.c_str()); continue; -- Gitee From 91c95eaedde4d7eab85821805780375e35b1d269 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Mon, 25 Nov 2024 20:07:14 +0800 Subject: [PATCH 456/520] =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E6=97=B6=E9=98=B2=E6=AD=A2=E8=A2=AB=E6=9E=90=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/include/authentication/dm_auth_manager.h | 1 - .../src/authentication/auth_request_state.cpp | 6 ------ .../implementation/src/authentication/dm_auth_manager.cpp | 5 ----- 3 files changed, 12 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index d6721b12f..75d187561 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -502,7 +502,6 @@ public: int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); int32_t DeleteGroup(const std::string &pkgName, int32_t userId, const std::string &deviceId); int32_t StopAuthenticateDevice(const std::string &pkgName); - void Leave(); private: int32_t ImportCredential(std::string &deviceId, std::string &publicKey); void GetAuthParam(const std::string &pkgName, int32_t authType, const std::string &deviceId, diff --git a/services/implementation/src/authentication/auth_request_state.cpp b/services/implementation/src/authentication/auth_request_state.cpp index 88ed30064..7181d2947 100644 --- a/services/implementation/src/authentication/auth_request_state.cpp +++ b/services/implementation/src/authentication/auth_request_state.cpp @@ -22,12 +22,6 @@ namespace OHOS { namespace DistributedHardware { int32_t AuthRequestState::Leave() { - std::shared_ptr stateAuthManager = authManager_.lock(); - if (stateAuthManager == nullptr) { - LOGE("AuthRequestState::authManager_ null"); - return ERR_DM_FAILED; - } - stateAuthManager->Leave(); return DM_OK; } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index c5ffced4b..cc6e5bfa4 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2609,10 +2609,5 @@ void DmAuthManager::SetProcessInfo() } softbusConnector_->SetProcessInfo(processInfo); } - -void DmAuthManager::Leave() -{ - authRequestStateTemp_ = nullptr; -} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 37a368650fe386c9d9f488be7be05938bec056ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 26 Nov 2024 09:56:07 +0800 Subject: [PATCH 457/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../native_cpp/src/ipc/standard/ipc_client_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 7745c5f46..cffe9c463 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -36,6 +36,7 @@ void DmDeathRecipient::OnRemoteDied(const wptr &remote) { LOGW("DmDeathRecipient : OnRemoteDied"); (void)remote; + DeviceManagerNotify::GetInstance().OnRemoteDied(); } int32_t IpcClientManager::ClientInit() -- Gitee From 07996569cff20f7a22ac63216fa9c22e02bc9221 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 26 Nov 2024 15:21:47 +0800 Subject: [PATCH 458/520] =?UTF-8?q?sprintf=5Fs=E8=BF=94=E5=9B=9E=E5=80=BC?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/softbus/mine_softbus_listener.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/softbus/mine_softbus_listener.cpp b/services/service/src/softbus/mine_softbus_listener.cpp index 345d62217..db86dab66 100644 --- a/services/service/src/softbus/mine_softbus_listener.cpp +++ b/services/service/src/softbus/mine_softbus_listener.cpp @@ -401,13 +401,13 @@ int32_t MineSoftbusListener::ParseScopeDeviceJsonArray(const vector Date: Fri, 22 Nov 2024 18:25:00 +0800 Subject: [PATCH 459/520] =?UTF-8?q?=E8=A7=A3=E9=99=A4DM\DP\DB=E6=88=90?= =?UTF-8?q?=E7=8E=AF=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: hw_zhangliang --- common/include/dm_constants.h | 2 + .../include/deviceprofile_connector.h | 5 + .../src/deviceprofile_connector.cpp | 42 +++++ sa_profile/device_manager.cfg | 3 +- services/implementation/BUILD.gn | 1 + .../deviceprofile/dp_inited_callback.h | 37 +++++ .../include/device_manager_service_impl.h | 2 + .../deviceprofile/dp_inited_callback.cpp | 150 ++++++++++++++++++ .../src/device_manager_service_impl.cpp | 6 + .../include/device_manager_service_listener.h | 5 +- .../src/device_manager_service_listener.cpp | 57 ++++++- .../UTTest_dm_deviceprofile_connector.cpp | 27 ++++ 12 files changed, 329 insertions(+), 8 deletions(-) create mode 100644 services/implementation/include/dependency/deviceprofile/dp_inited_callback.h create mode 100644 services/implementation/src/dependency/deviceprofile/dp_inited_callback.cpp diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 856920cd6..056c80a7a 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -229,6 +229,8 @@ constexpr const char* PARAM_KEY_FILTER_OPTIONS = "FILTER_OPTIONS"; constexpr const char* PARAM_KEY_BIND_EXTRA_DATA = "BIND_EXTRA_DATA"; constexpr const char* PARAM_KEY_OS_TYPE = "OS_TYPE"; constexpr const char* PARAM_KEY_OS_VERSION = "OS_VERSION"; +constexpr const char* PARAM_KEY_UDID = "udid"; +constexpr const char* PARAM_KEY_UUID = "uuid"; constexpr const char* DM_CONNECTION_DISCONNECTED = "DM_CONNECTION_DISCONNECTED"; constexpr const char* BIND_LEVEL = "bindLevel"; constexpr const char* TOKENID = "tokenId"; diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 02ed32f68..8ada37d6a 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -20,6 +20,8 @@ #include "access_control_profile.h" #include "dm_device_info.h" #include "dm_single_instance.h" +#include "i_dp_inited_callback.h" +#include "trusted_device_info.h" constexpr uint32_t ALLOW_AUTH_ONCE = 1; constexpr uint32_t ALLOW_AUTH_ALWAYS = 2; @@ -155,6 +157,9 @@ public: std::multimap GetDeviceIdAndUserId(const std::string &localUdid, int32_t localUserId); void HandleSyncBackgroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid); + int32_t SubscribeDeviceProfileInited(sptr dpInitedCallback); + int32_t UnSubscribeDeviceProfileInited(); + int32_t PutAllTrustedDevices(const std::vector &deviceInfos); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 57d2b8e39..35543e39c 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -20,6 +20,7 @@ #include "dm_log.h" #include "multiple_user_connector.h" #include "distributed_device_profile_client.h" +#include "system_ability_definition.h" using namespace OHOS::DistributedDeviceProfile; @@ -1412,6 +1413,47 @@ void DeviceProfileConnector::HandleSyncBackgroundUserIdEvent(const std::vector dpInitedCallback) +{ + LOGI("In"); + if (dpInitedCallback == nullptr) { + LOGE("dpInitedCallback is nullptr"); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t ret = DistributedDeviceProfileClient::GetInstance().SubscribeDeviceProfileInited( + DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID, dpInitedCallback); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceProfileConnector::UnSubscribeDeviceProfileInited() +{ + LOGI("In"); + int32_t ret = DistributedDeviceProfileClient::GetInstance().UnSubscribeDeviceProfileInited( + DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + +int32_t DeviceProfileConnector::PutAllTrustedDevices( + const std::vector &deviceInfos) +{ + LOGI("In deviceInfos.size:%{public}zu", deviceInfos.size()); + int32_t ret = DistributedDeviceProfileClient::GetInstance().PutAllTrustedDevices(deviceInfos); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/sa_profile/device_manager.cfg b/sa_profile/device_manager.cfg index 2d24a868d..f0632a81e 100644 --- a/sa_profile/device_manager.cfg +++ b/sa_profile/device_manager.cfg @@ -36,7 +36,8 @@ "ohos.permission.GET_WIFI_INFO", "ohos.permission.SET_TIME", "ohos.permission.SET_TIME_ZONE", - "ohos.permission.ALLOW_CONNECT_CAR" + "ohos.permission.ALLOW_CONNECT_CAR", + "ohos.permission.ACCESS_SERVICE_DP" ], "jobs" : { "on-start" : "service:device_manager" diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 1cc59a5c7..737475f96 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -168,6 +168,7 @@ if (defined(ohos_lite)) { "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/dependency/commonevent/dm_common_event_manager.cpp", + "src/dependency/deviceprofile/dp_inited_callback.cpp", "src/dependency/hichain/hichain_auth_connector.cpp", "src/dependency/hichain/hichain_connector.cpp", "src/dependency/hichain/mine_hichain_connector.cpp", diff --git a/services/implementation/include/dependency/deviceprofile/dp_inited_callback.h b/services/implementation/include/dependency/deviceprofile/dp_inited_callback.h new file mode 100644 index 000000000..24978b220 --- /dev/null +++ b/services/implementation/include/dependency/deviceprofile/dp_inited_callback.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DP_INITED_LISTENER_H +#define OHOS_DP_INITED_LISTENER_H + +#include "dp_inited_callback_stub.h" +#include "dm_device_info.h" +#include "trusted_device_info.h" + +namespace OHOS { +namespace DistributedHardware { +class DpInitedCallback : public DistributedDeviceProfile::DpInitedCallbackStub { +public: + DpInitedCallback(); + ~DpInitedCallback(); + int32_t OnDpInited() override; +private: + void PutAllTrustedDevices(); + bool ConvertToTrustedDeviceInfo(const std::unordered_map &authFormMap, + const DmDeviceInfo &deviceInfo, DistributedDeviceProfile::TrustedDeviceInfo &trustedDeviceInfo); +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DP_INITED_LISTENER_H \ No newline at end of file diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index c621c1a4b..da8c20f61 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -28,6 +28,7 @@ #include "dm_device_state_manager.h" #include "dm_discovery_manager.h" #include "dm_publish_manager.h" +#include "dp_inited_callback.h" #include "idevice_manager_service_impl.h" #include "dm_single_instance.h" #include "softbus_connector.h" @@ -169,6 +170,7 @@ private: std::shared_ptr hiChainAuthConnector_; std::shared_ptr listener_; std::atomic isCredentialType_ = false; + sptr dpInitedCallback_ = nullptr; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/implementation/src/dependency/deviceprofile/dp_inited_callback.cpp b/services/implementation/src/dependency/deviceprofile/dp_inited_callback.cpp new file mode 100644 index 000000000..f56b15d94 --- /dev/null +++ b/services/implementation/src/dependency/deviceprofile/dp_inited_callback.cpp @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dp_inited_callback.h" + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +#include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "ffrt.h" +#endif + +#include "deviceprofile_connector.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +const std::string PUT_ALL_TRUSTED_DEVICES_TASK = "PutAllTrustedDevicesTask"; +} + +DpInitedCallback::DpInitedCallback() +{} + +DpInitedCallback::~DpInitedCallback() +{} + +int32_t DpInitedCallback::OnDpInited() +{ + LOGE("In."); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + ffrt::submit([=]() { PutAllTrustedDevices(); }); +#else + std::thread putAllTrustedDevicesTask([=]() { PutAllTrustedDevices(); }); + if (pthread_setname_np(putAllTrustedDevicesTask.native_handle().c_str(), PUT_ALL_TRUSTED_DEVICES_TASK) != DM_OK) { + LOGE("putAllTrustedDevicesTask setname failed."); + } + putAllTrustedDevicesTask.detach(); +#endif + return DM_OK; +} + +void DpInitedCallback::PutAllTrustedDevices() +{ + LOGE("In."); + std::vector dmDeviceInfos; + int32_t ret = SoftbusCache::GetInstance().GetDeviceInfoFromCache(dmDeviceInfos); + if (ret != DM_OK) { + LOGE("GetDeviceInfoFromCache fail:%{public}d", ret); + return; + } + if (dmDeviceInfos.empty()) { + LOGW("dmDeviceInfos is empty"); + return; + } + char localUdidTemp[DEVICE_UUID_LENGTH]; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = reinterpret_cast(localUdidTemp); + if (localUdid.empty()) { + LOGE("localUdid is empty"); + return; + } + std::vector deviceInfos; + std::unordered_map authFormMap = + DeviceProfileConnector::GetInstance().GetAppTrustDeviceList("", localUdid); + for (const auto& item : dmDeviceInfos) { + DistributedDeviceProfile::TrustedDeviceInfo trustedDeviceInfo; + if (ConvertToTrustedDeviceInfo(authFormMap, item, trustedDeviceInfo)) { + deviceInfos.push_back(trustedDeviceInfo); + } + } + if (deviceInfos.empty()) { + LOGW("deviceInfos is empty"); + return; + } + ret = DeviceProfileConnector::GetInstance().PutAllTrustedDevices(deviceInfos); + LOGI("ret:%{public}d", ret); +} + +bool DpInitedCallback::ConvertToTrustedDeviceInfo(const std::unordered_map &authFormMap, + const DmDeviceInfo &deviceInfo, DistributedDeviceProfile::TrustedDeviceInfo &trustedDeviceInfo) +{ + trustedDeviceInfo.SetNetworkId(deviceInfo.networkId); + trustedDeviceInfo.SetDeviceTypeId(deviceInfo.deviceTypeId); + + if (deviceInfo.extraData.empty()) { + LOGE("extraData is empty, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + nlohmann::json extraJson = nlohmann::json::parse(deviceInfo.extraData, nullptr, false); + if (extraJson.is_discarded()) { + LOGE("extraData parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + if (IsString(extraJson, PARAM_KEY_OS_VERSION)) { + trustedDeviceInfo.SetOsVersion(extraJson[PARAM_KEY_OS_VERSION].get()); + } else { + LOGE("osVersion parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + if (IsInt32(extraJson, PARAM_KEY_OS_TYPE)) { + trustedDeviceInfo.SetOsType(extraJson[PARAM_KEY_OS_TYPE].get()); + } else { + LOGE("osType parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + + std::string udid = ""; + if (SoftbusCache::GetInstance().GetUdidFromCache(deviceInfo.networkId, udid) != DM_OK) { + LOGE("udid parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + trustedDeviceInfo.SetUdid(udid); + + std::string uuid = ""; + if (SoftbusCache::GetInstance().GetUuidFromCache(deviceInfo.networkId, uuid) != DM_OK) { + LOGE("uuid parse failed, networkId:%{public}s", GetAnonyString(deviceInfo.networkId).c_str()); + return false; + } + trustedDeviceInfo.SetUuid(uuid); + + auto it = authFormMap.find(udid); + if (it == authFormMap.end()) { + LOGE("authForm not exist, udid:%{public}s", GetAnonyString(udid).c_str()); + return false; + } + trustedDeviceInfo.SetAuthForm(static_cast(it->second)); + return true; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index af65aa03d..3e1cdd1ed 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -81,6 +81,10 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr(hiChainConnector_, listener); } + if (dpInitedCallback_ == nullptr) { + dpInitedCallback_ = sptr(new DpInitedCallback()); + DeviceProfileConnector::GetInstance().SubscribeDeviceProfileInited(dpInitedCallback_); + } listener_ = listener; LOGI("Init success, singleton initialized"); return DM_OK; @@ -101,6 +105,8 @@ void DeviceManagerServiceImpl::Release() softbusConnector_ = nullptr; abilityMgr_ = nullptr; hiChainConnector_ = nullptr; + DeviceProfileConnector::GetInstance().UnSubscribeDeviceProfileInited(); + dpInitedCallback_ = nullptr; } int32_t DeviceManagerServiceImpl::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index d58ecec3b..3fde43212 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -17,9 +17,10 @@ #define OHOS_DM_SERVICE_LISTENER_H #include +#include #include #include -#include +#include #include "dm_device_info.h" #include "idevice_manager_service_listener.h" @@ -85,6 +86,7 @@ private: const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); void SetDeviceInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo); + int32_t FillUdidAndUuidToDeviceInfo(const std::string &pkgName, DmDeviceInfo &dmDeviceInfo); void ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); void ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, @@ -115,6 +117,7 @@ private: IpcServerListener ipcServerListener_; static std::mutex alreadyNotifyPkgNameLock_; static std::map alreadyOnlinePkgName_; + static std::unordered_set highPriorityPkgNameSet_; #endif }; } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index d11e2ca90..f8705f261 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -50,6 +50,8 @@ namespace OHOS { namespace DistributedHardware { std::mutex DeviceManagerServiceListener::alreadyNotifyPkgNameLock_; std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::unordered_set DeviceManagerServiceListener::highPriorityPkgNameSet_ = { "ohos.deviceprofile", + "ohos.distributeddata.service" }; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { @@ -87,14 +89,15 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetPkgName(processInfo.pkgName); pReq->SetProcessInfo(processInfo); pReq->SetDeviceState(state); + DmDeviceInfo dmDeviceInfo = deviceInfo; + FillUdidAndUuidToDeviceInfo(processInfo.pkgName, dmDeviceInfo); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) { - pReq->SetDeviceInfo(deviceInfo); + pReq->SetDeviceInfo(dmDeviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); return; } - DmDeviceInfo dmDeviceInfo = deviceInfo; ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); DmDeviceBasicInfo dmDeviceBasicInfo = deviceBasicInfo; if (memset_s(dmDeviceBasicInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { @@ -110,25 +113,67 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceBasicInfo(dmDeviceBasicInfo); return; #endif - pReq->SetDeviceInfo(deviceInfo); + pReq->SetDeviceInfo(dmDeviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); } +int32_t DeviceManagerServiceListener::FillUdidAndUuidToDeviceInfo(const std::string &pkgName, + DmDeviceInfo &dmDeviceInfo) +{ + if (highPriorityPkgNameSet_.find(pkgName) == highPriorityPkgNameSet_.end()) { + return DM_OK; + } + std::string extraData = dmDeviceInfo.extraData; + std::string udid = ""; + std::string uuid = ""; + if (SoftbusCache::GetInstance().GetUdidFromCache(dmDeviceInfo.networkId, udid) != DM_OK) { + LOGE("GetUdidFromCache fail, networkId:%{public}s ", GetAnonyString(dmDeviceInfo.networkId).c_str()); + return ERR_DM_FAILED; + } + if (SoftbusCache::GetInstance().GetUuidFromCache(dmDeviceInfo.networkId, uuid) != DM_OK) { + LOGE("GetUuidFromCache fail, networkId:%{public}s ", GetAnonyString(dmDeviceInfo.networkId).c_str()); + return ERR_DM_FAILED; + } + nlohmann::json extraJson; + if (!extraData.empty()) { + extraJson = nlohmann::json::parse(extraData, nullptr, false); + } + if (!extraJson.is_discarded()) { + extraJson[PARAM_KEY_UDID] = udid; + extraJson[PARAM_KEY_UUID] = uuid; + dmDeviceInfo.extraData = to_string(extraJson); + } + return DM_OK; +} + void DeviceManagerServiceListener::ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId); + std::vector hpProcessInfoVec; + std::vector lpProcessInfoVec; + for (const auto &it : processInfoVec) { + if (highPriorityPkgNameSet_.find(it.pkgName) != highPriorityPkgNameSet_.end()) { + hpProcessInfoVec.push_back(it); + } else { + lpProcessInfoVec.push_back(it); + } + } + switch (static_cast(state)) { case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): - ProcessDeviceOnline(processInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceOnline(hpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceOnline(lpProcessInfoVec, processInfo, state, info, deviceBasicInfo); break; case static_cast(DmDeviceState::DEVICE_STATE_OFFLINE): - ProcessDeviceOffline(processInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceOffline(lpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceOffline(hpProcessInfoVec, processInfo, state, info, deviceBasicInfo); break; case static_cast(DmDeviceState::DEVICE_INFO_READY): case static_cast(DmDeviceState::DEVICE_INFO_CHANGED): - ProcessDeviceInfoChange(processInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceInfoChange(hpProcessInfoVec, processInfo, state, info, deviceBasicInfo); + ProcessDeviceInfoChange(lpProcessInfoVec, processInfo, state, info, deviceBasicInfo); break; default: break; diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index ba6f4fea1..a7c7bfd8f 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -18,6 +18,7 @@ #include "dm_constants.h" #include "dm_device_info.h" #include "deviceprofile_connector.h" +#include "dp_inited_callback_stub.h" namespace OHOS { namespace DistributedHardware { @@ -37,6 +38,16 @@ void DeviceProfileConnectorTest::TearDownTestCase() { } +class MockDpInitedCallback : public DistributedDeviceProfile::DpInitedCallbackStub { +public: + MockDpInitedCallback() {} + ~MockDpInitedCallback() {} + int32_t OnDpInited() + { + return DM_OK; + } +}; + void AddAccessControlProfileFirst(std::vector& accessControlProfiles) { int32_t userId = 123456; @@ -1276,5 +1287,21 @@ HWTEST_F(DeviceProfileConnectorTest, GetAllAccessControlProfile_001, testing::ex auto ret = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); EXPECT_TRUE(ret.empty()); } + +HWTEST_F(DeviceProfileConnectorTest, SubscribeDeviceProfileInited_001, testing::ext::TestSize.Level0) +{ + sptr dpInitedCallback = + sptr(new MockDpInitedCallback()); + ASSERT_NE(dpInitedCallback, nullptr); + int32_t ret = DeviceProfileConnector::GetInstance().SubscribeDeviceProfileInited(dpInitedCallback); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, PutAllTrustedDevices_001, testing::ext::TestSize.Level0) +{ + std::vector deviceInfos; + int32_t ret = DeviceProfileConnector::GetInstance().PutAllTrustedDevices(deviceInfos); + EXPECT_NE(ret, DM_OK); +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From cc922130950724265553aecfe19a1208c3d227e6 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 26 Nov 2024 18:14:14 +0800 Subject: [PATCH 460/520] =?UTF-8?q?=E8=A1=A5=E5=85=85foundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=8E=A5=E5=8F=A3=E7=9A=84UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 994bc6e74..3520eda99 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1411,6 +1411,33 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::Tes localUserIds.push_back(localUserId); DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, localUdid); + + ProcessInfo process; + process.userId = 1; + process.pkgName = "pkgName"; + ProcessInfo process1; + process1.userId = 1; + process1.pkgName = "pkgName"; + EXPECT_TRUE(process == process1); + + process.userId = 0; + EXPECT_TRUE(process < process1); + + DmNotifyKey dmNotifyKey; + dmNotifyKey.processUserId = 1; + dmNotifyKey.processPkgName = "proName"; + dmNotifyKey.notifyUserId = 0; + dmNotifyKey.udid = "udid"; + + DmNotifyKey dmNotifyKey1; + dmNotifyKey1.processUserId = 1; + dmNotifyKey1.processPkgName = "proName"; + dmNotifyKey1.notifyUserId = 0; + dmNotifyKey1.udid = "udid"; + EXPECT_TRUE(dmNotifyKey == dmNotifyKey1); + + dmNotifyKey1.processUserId = 2; + EXPECT_TRUE(dmNotifyKey < dmNotifyKey1); } } // namespace DistributedHardware } // namespace OHOS -- Gitee From 4245726025fad49798915a046a788a18dad6ada8 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 27 Nov 2024 10:39:28 +0800 Subject: [PATCH 461/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 29 +++++++++++++++ .../UTTest_dm_deviceprofile_connector.h | 2 + .../UTTest_dm_discovery_manager.cpp | 28 ++++++++++++++ .../UTTest_permission_manager.cpp | 11 ++++++ .../UTTest_softbus_listener.cpp | 12 ++++++ .../UTTest_device_manager_impl_three.cpp | 37 +++++++++++++++++++ .../UTTest_device_manager_service_two.cpp | 24 ++++++++++++ 7 files changed, 143 insertions(+) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 994bc6e74..99b3e8dfb 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -31,10 +31,14 @@ void DeviceProfileConnectorTest::TearDown() void DeviceProfileConnectorTest::SetUpTestCase() { + cryptoMock_ = std::make_shared(); + DmCrypto::dmCrypto = cryptoMock_; } void DeviceProfileConnectorTest::TearDownTestCase() { + DmCrypto::dmCrypto = nullptr; + cryptoMock_ = nullptr; } void AddAccessControlProfileFirst(std::vector& accessControlProfiles) @@ -1412,5 +1416,30 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::Tes DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, localUdid); } + +HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = ""; + std::string peerUdid = ""; + int32_t peerUserId = 123456; + std::string peerAccountHash = ""; + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); + auto ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_TRUE(ret.empty()); + + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_TRUE(ret.empty()); + + localUdid = "deviceId"; + peerUdid = "deviceId"; + peerAccountHash = "peerAccountHash"; + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_TRUE(ret.empty()); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.h b/test/commonunittest/UTTest_dm_deviceprofile_connector.h index 22fa7543c..917f02842 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.h +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.h @@ -20,6 +20,7 @@ #include #include "deviceprofile_connector.h" +#include "dm_crypto_mock.h" namespace OHOS { namespace DistributedHardware { @@ -29,6 +30,7 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + static inline std::shared_ptr cryptoMock_ = nullptr; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_discovery_manager.cpp b/test/commonunittest/UTTest_dm_discovery_manager.cpp index 0026854a0..ffb7bbcae 100644 --- a/test/commonunittest/UTTest_dm_discovery_manager.cpp +++ b/test/commonunittest/UTTest_dm_discovery_manager.cpp @@ -566,6 +566,34 @@ HWTEST_F(DmDiscoveryManagerTest, CheckDiscoveryQueue_003, testing::ext::TestSize int32_t ret = discoveryMgr_->CheckDiscoveryQueue(pkgName); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DmDiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 0; + std::string deviceId = "deviceId"; + bool isOnline = false; + int32_t authForm = 1; + std::string pkgName = "pkgName"; + int32_t ret = discoveryMgr_->GetDeviceAclParam(pkgName, userId, deviceId, isOnline, authForm); + EXPECT_EQ(ret, ERR_DM_FAILED); + + std::string callerPkgName = "callerPkgName"; + discoveryMgr_->GetPkgNameAndUserId(pkgName, callerPkgName, userId); +} + +HWTEST_F(DmDiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string str = discoveryMgr_->AddMultiUserIdentify(pkgName); + EXPECT_EQ(str.empty, false); +} + +HWTEST_F(DmDiscoveryManagerTest, RemoveMultiUserIdentify_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::string str = discoveryMgr_->RemoveMultiUserIdentify(pkgName); + EXPECT_EQ(str.empty, false); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index e69d45504..b8cde8d57 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -270,6 +270,17 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnSetDnPolicy_001, testing: ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); ASSERT_TRUE(ret); } + +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_001, testing::ext::TestSize.Level0) +{ + std::string pkgName = ""; + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(); + ASSERT_FALSE(ret); + + pkgName = "ohos.deviceprofile"; + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(); + ASSERT_TRUE(ret); +} } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 5a2d2d2e6..6b0037d70 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -1075,6 +1075,18 @@ HWTEST_F(SoftbusListenerTest, GetDeviceScreenStatus_001, testing::ext::TestSize. EXPECT_TRUE(checkSoftbusRes(ret)); softbusListener = nullptr; } + +HWTEST_F(SoftbusListenerTest, SetForegroundUserIdsToDSoftBus_001, testing::ext::TestSize.Level0) +{ + std::string remoteUdid = "remoteUdid"; + std::vector userIds; + if (softbusListener == nullptr) { + softbusListener = std::make_shared(); + } + int32_t ret = softbusListener->SetForegroundUserIdsToDSoftBus(remoteUdid, userIds); + EXPECT_EQ(ret, DM_OK); + softbusListener = nullptr; +} } // namespace } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 1cca09121..2dfca751f 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -16,6 +16,7 @@ #include "UTTest_device_manager_impl.h" #include "dm_device_info.h" +#include #include #include "accesstoken_kit.h" #include "device_manager_notify.h" @@ -1407,6 +1408,42 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_002, test int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } + +HWTEST_F(DeviceManagerImplTest, AddDiscoveryCallback_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + std::map discoverParam; + std::shared_ptr callback = nullptr; + uint16_t ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); + ASSERT_EQ(ret, 0); + + discoverParam.insert(std::make_pair(PARAM_KEY_SUBSCRIBE_ID, "0")); + callback = std::make_shared(); + ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); + ASSERT_EQ(ret, 0); + + discoverParam[PARAM_KEY_SUBSCRIBE_ID] = "12"; + ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); + ASSERT_EQ(ret, 12); + + pkgName = "SUBSCRIBE_ID"; + std::string key = "SUBSCRIBE_ID#12"; + DeviceManager::GetInstance().pkgName2SubIdMap_[key] = 1; + ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); + ASSERT_EQ(ret, 1); +} + +HWTEST_F(DeviceManagerImplTest, GetSubscribeIdFromMap_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + DeviceManager::GetInstance().pkgName2SubIdMap_[pkgName] = 6; + uint16_t ret = DeviceManager::GetInstance().GetSubscribeIdFromMap(pkgName); + ASSERT_EQ(ret, 6); + + pkgName = "pkgName_301"; + ret = DeviceManager::GetInstance().GetSubscribeIdFromMap(pkgName); + ASSERT_EQ(ret, 0); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 10d5303c0..0602cae1c 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -584,6 +584,23 @@ HWTEST_F(DeviceManagerServiceTest, BindDevice_205, testing::ext::TestSize.Level0 EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().BindDevice(pkgName, authType, deviceId, bindParam); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + ProcessInfo processInfo; + processInfo.pkgName = "pkgName"; + if (DeviceManagerService::GetInstance().discoveryMgr_ == nullptr){ + DeviceManagerService::GetInstance().InitDMServiceListener(); + } + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); + DeviceManagerService::GetInstance().RemoveNotifyRecord(processInfo); + + std::vector foregroundUserIds; + std::vector backgroundUserIds; + std::string remoteUdid = "remoteUdid"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + DeviceManagerService::GetInstance().ProcessSyncUserIds(foregroundUserIds, backgroundUserIds, remoteUdid); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; } /** @@ -603,6 +620,13 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } + +HWTEST_F(DeviceManagerServiceTest, RegDevStateCallbackToService_201, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + int32_t ret = DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); + EXPECT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS -- Gitee From e6fd25781a70f8f1aaba4b24adda8599b049c8f1 Mon Sep 17 00:00:00 2001 From: li-li-wang Date: Mon, 18 Nov 2024 15:19:04 +0800 Subject: [PATCH 462/520] SetOhosAccountInfoByUserId->SetOhosAccountInfo Signed-off-by: li-li-wang --- commondependency/src/multiple_user_connector.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 7c5386de9..11b4a2f35 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -80,7 +80,7 @@ std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) return ""; #elif OS_ACCOUNT_PART_EXISTS OhosAccountInfo accountInfo; - ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfoByUserId(userId, accountInfo); + ErrCode ret = OhosAccountKits::GetInstance().GetOsAccountDistributedInfo(userId, accountInfo); if (ret != 0 || accountInfo.uid_ == "") { LOGE("error ret: %{public}d", ret); return ""; -- Gitee From d2f90b8c27ff758e56121a1f6c69cb1573bbf5be Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 27 Nov 2024 11:46:10 +0800 Subject: [PATCH 463/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 3 +- .../UTTest_device_manager_service_two.cpp | 58 +++++++++++++++++++ .../mock/device_manager_service_impl_mock.cpp | 5 ++ .../mock/device_manager_service_impl_mock.h | 2 + test/unittest/mock/softbus_listener_mock.cpp | 10 ++++ test/unittest/mock/softbus_listener_mock.h | 3 + 6 files changed, 80 insertions(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 42cb0b682..af272c572 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2219,8 +2219,9 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_003, testing::ext::Test std::string networkId = "networkId_003"; int32_t screenStatus = 1; DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceScreenStatus(_, _)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 0602cae1c..f5dd1de54 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -402,6 +402,13 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_202, testing::ext::Test int32_t screenStatus = -1; int32_t ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + pkgName = "pkgName"; + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, GetDeviceScreenStatus(_, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); + ASSERT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; } /** @@ -479,8 +486,13 @@ HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_201, testing::ext::TestSiz EXPECT_EQ(ret, ERR_DM_POINT_NULL); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*softbusListenerMock_, SetLocalDeviceName(_, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*softbusListenerMock_, SetLocalDeviceName(_, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().SetLocalDeviceName(localDeviceName, localDisplayName); + EXPECT_EQ(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } @@ -627,6 +639,52 @@ HWTEST_F(DeviceManagerServiceTest, RegDevStateCallbackToService_201, testing::ex int32_t ret = DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_205, testing::ext::TestSize.Level0) +{ + std::string pkgName; + std::vector deviceList; + int ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + pkgName = "jjdjk_pkgName"; + DeviceManagerService::GetInstance().softbusListener_ = nullptr; + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, ERR_DM_POINT_NULL); + + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + DeviceManagerService::GetInstance().InitDMServiceListener(); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, ERR_DM_FAILED); + + std::vector onlineDeviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + dmDeviceInfo.networkType = 1; + onlineDeviceList.push_back(dmDeviceInfo); + std::unordered_map udidMap; + udidMap.insert(std::make_pair("udid01", DmAuthForm::IDENTICAL_ACCOUNT)); + udidMap.insert(std::make_pair("udid02", DmAuthForm::ACROSS_ACCOUNT)); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(onlineDeviceList), Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetAppTrustDeviceIdList(_)).WillOnce(Return(udidMap)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)) + .WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, DM_OK); + + pkgName = "ohos.deviceprofile"; + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(onlineDeviceList), Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetAppTrustDeviceIdList(_)).WillOnce(Return(udidMap)); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)) + .WillOnce(DoAll(SetArgReferee<1>("udid02"), Return(DM_OK))); + ret = DeviceManagerService::GetInstance().GetTrustedDeviceList(pkgName, deviceList); + EXPECT_EQ(ret, DM_OK); + DeviceManagerService::GetInstance().UninitDMServiceListener(); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp index b358dc60e..e40912bbf 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.cpp +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -50,5 +50,10 @@ std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel { return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetDeviceIdAndBindLevel(localUserId); } + +std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList(std::string pkgname) +{ + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetAppTrustDeviceIdList(pkgname); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h index cafad4035..a76a19ea5 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.h +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -33,6 +33,7 @@ public: virtual std::multimap GetDeviceIdAndUserId(int32_t userId, const std::string &accountId) = 0; virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; + virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname) = 0; public: static inline std::shared_ptr dmDeviceManagerServiceImpl = nullptr; }; @@ -45,6 +46,7 @@ public: MOCK_METHOD((std::multimap), GetDeviceIdAndUserId, (int32_t, const std::string &)); MOCK_METHOD((std::multimap), GetDeviceIdAndUserId, (int32_t)); MOCK_METHOD((std::map), GetDeviceIdAndBindLevel, (int32_t)); + MOCK_METHOD((std::unordered_map), GetAppTrustDeviceIdList, (std::string)); }; } } diff --git a/test/unittest/mock/softbus_listener_mock.cpp b/test/unittest/mock/softbus_listener_mock.cpp index 1079feb03..5dee44809 100644 --- a/test/unittest/mock/softbus_listener_mock.cpp +++ b/test/unittest/mock/softbus_listener_mock.cpp @@ -59,5 +59,15 @@ int32_t SoftbusListener::GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) { return DmSoftbusListener::dmSoftbusListener->GetLocalDeviceInfo(deviceInfo); } + +int32_t SoftbusListener::SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) +{ + return DmSoftbusListener::dmSoftbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); +} + +int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus) +{ + return DmSoftbusListener::dmSoftbusListener->GetDeviceScreenStatus(networkId, screenStatus); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h index e2199f60e..c43a9f706 100644 --- a/test/unittest/mock/softbus_listener_mock.h +++ b/test/unittest/mock/softbus_listener_mock.h @@ -35,6 +35,8 @@ public: ConnectionAddrType &addrType) = 0; virtual int32_t GetTrustedDeviceList(std::vector &deviceInfoList) = 0; virtual int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) = 0; + virtual int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) = 0; + virtual int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus) = 0; public: static inline std::shared_ptr dmSoftbusListener = nullptr; }; @@ -49,6 +51,7 @@ public: MOCK_METHOD(int32_t, GetTargetInfoFromCache, (const std::string &, PeerTargetId &, ConnectionAddrType &addrType)); MOCK_METHOD(int32_t, GetTrustedDeviceList, (std::vector &)); MOCK_METHOD(int32_t, GetLocalDeviceInfo, (DmDeviceInfo &)); + MOCK_METHOD(int32_t, SetLocalDeviceName, (const std::string &, const std::string &)); }; } } -- Gitee From 787c7cff2e7de3c3e6307c2bc91ea486e9f292db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Wed, 27 Nov 2024 15:57:45 +0800 Subject: [PATCH 464/520] =?UTF-8?q?=E6=B6=88=E9=99=A4=E9=BB=84=E8=93=9D?= =?UTF-8?q?=E5=B7=AE=E5=BC=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../src/discovery/discovery_manager.cpp | 10 ++-- .../src/ipc/lite/ipc_server_listenermgr.cpp | 2 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 10 ++-- .../src/ipc/standard/ipc_server_stub.cpp | 2 +- .../permission/lite/permission_manager.cpp | 2 +- .../standard/permission_manager.cpp | 2 +- services/service/src/pinholder/pin_holder.cpp | 46 +++++++++++-------- .../service/src/softbus/softbus_listener.cpp | 16 +++---- .../softbuscache/src/dm_softbus_cache.cpp | 7 ++- utils/include/appInfo/lite/app_manager.h | 2 +- .../lite/dm_distributed_hardware_load.h | 2 +- .../standard/dm_distributed_hardware_load.h | 2 +- utils/include/timer/lite/dm_timer.h | 3 +- utils/src/appInfo/lite/app_manager.cpp | 2 +- utils/src/appInfo/standard/app_manager.cpp | 11 ++--- .../lite/dm_distributed_hardware_load.cpp | 2 +- .../standard/dm_distributed_hardware_load.cpp | 2 +- utils/src/timer/lite/dm_timer.cpp | 5 +- 18 files changed, 71 insertions(+), 57 deletions(-) diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 224e0887a..5fea24f9a 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -321,7 +321,9 @@ int32_t DiscoveryManager::StopDiscovering(const std::string &pkgName, uint16_t s if (discoveryContextMap_.find(pkgNameTemp) != discoveryContextMap_.end()) { discoveryContextMap_.erase(pkgNameTemp); - timer_->DeleteTimer(pkgNameTemp); + if (timer_ != nullptr) { + timer_->DeleteTimer(pkgNameTemp); + } } } { @@ -452,7 +454,9 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s } if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(pkgName); + if (timer_ != nullptr) { + timer_->DeleteTimer(pkgName); + } } } { @@ -619,7 +623,7 @@ void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) pkgNameSet_.erase(pkgName); } if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { - LOGI("Erase pkgname %{public}s from pkgNameSet.", pkgName.c_str()); + LOGI("Erase pkgname %{public}s from discoveryContextMap.", pkgName.c_str()); subscribeId = discoveryContextMap_[pkgName].subscribeId; discoveryContextMap_.erase(pkgName); } diff --git a/services/service/src/ipc/lite/ipc_server_listenermgr.cpp b/services/service/src/ipc/lite/ipc_server_listenermgr.cpp index 36bf2276c..a7f1e1d17 100644 --- a/services/service/src/ipc/lite/ipc_server_listenermgr.cpp +++ b/services/service/src/ipc/lite/ipc_server_listenermgr.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 93671487b..df5c6750c 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -1491,8 +1491,8 @@ ON_IPC_SET_REQUEST(REMOTE_DEVICE_TRUST_CHANGE, std::shared_ptr pBaseReq, std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); std::string pkgName = pReq->GetPkgName(); std::string udid = pReq->GetUdid(); - std::string uuid = pReq->GetUuid(); int32_t authForm = pReq->GetAuthForm(); + std::string uuid = pReq->GetUuid(); if (!data.WriteString(pkgName)) { LOGE("write pkgName failed"); return ERR_DM_IPC_WRITE_FAILED; @@ -1501,14 +1501,14 @@ ON_IPC_SET_REQUEST(REMOTE_DEVICE_TRUST_CHANGE, std::shared_ptr pBaseReq, LOGE("write udid failed"); return ERR_DM_IPC_WRITE_FAILED; } - if (!data.WriteString(uuid)) { - LOGE("write uuid code failed"); - return ERR_DM_IPC_WRITE_FAILED; - } if (!data.WriteInt32(authForm)) { LOGE("write authForm code failed"); return ERR_DM_IPC_WRITE_FAILED; } + if (!data.WriteString(uuid)) { + LOGE("write uuid code failed"); + return ERR_DM_IPC_WRITE_FAILED; + } return DM_OK; } diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 544382ac5..a93471ac2 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/service/src/permission/lite/permission_manager.cpp b/services/service/src/permission/lite/permission_manager.cpp index 3b479ef97..33bb0eae5 100644 --- a/services/service/src/permission/lite/permission_manager.cpp +++ b/services/service/src/permission/lite/permission_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 59a1fe237..971d0da12 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -60,7 +60,7 @@ constexpr const static char systemSaWhiteList[SYSTEM_SA_WHITE_LIST_NUM][PKG_NAME "ohos.security.distributed_access_token", }; -constexpr uint16_t SETDNPOLICY_WHITE_LIST_NUM = 1; +constexpr uint32_t SETDNPOLICY_WHITE_LIST_NUM = 1; constexpr const static char g_setDnPolicyWhiteList[SETDNPOLICY_WHITE_LIST_NUM][PKG_NAME_SIZE_MAX] = { "collaboration_service", }; diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index cb90b50a5..d91ee920b 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -172,6 +172,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget if (timer_ != nullptr) { timer_->DeleteTimer(PINHOLDER_CREATE_TIMEOUT_TASK); } + nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; jsonObj[TAG_PIN_TYPE] = pinType; @@ -199,12 +200,13 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() LOGE("CreateGeneratePinHolderMsg listener or session is nullptr."); return ERR_DM_FAILED; } - - timer_->DeleteAll(); - timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, - [this] (std::string name) { - PinHolder::CloseSession(name); - }); + if (timer_ != nullptr) { + timer_->DeleteAll(); + timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, + [this] (std::string name) { + PinHolder::CloseSession(name); + }); + } nlohmann::json jsonObj; jsonObj[TAG_PIN_TYPE] = pinType_; jsonObj[TAG_PAYLOAD] = payload_; @@ -403,7 +405,9 @@ void PinHolder::CloseSession(const std::string &name) isDestroy_.store(true); } session_->CloseSessionServer(sessionId_); - timer_->DeleteAll(); + if (timer_ != nullptr) { + timer_->DeleteAll(); + } destroyState_ = STATE_TIME_OUT; sessionId_ = SESSION_ID_INVALID; sinkState_ = SINK_INIT; @@ -433,7 +437,9 @@ void PinHolder::ProcessDestroyResMsg(const std::string &message) listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, DM_OK, ""); sourceState_ = SOURCE_INIT; sinkState_ = SINK_INIT; - timer_->DeleteAll(); + if (timer_ != nullptr) { + timer_->DeleteAll(); + } } else { LOGE("ProcessDestroyResMsg remote state is wrong."); listener_->OnDestroyResult(processInfo_, ERR_DM_FAILED); @@ -612,11 +618,13 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s LOGE("ProcessChangeMsg DecodeRequest jsonStr error."); return ERR_DM_FAILED; } - timer_->DeleteAll(); - timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, - [this] (std::string name) { - PinHolder::CloseSession(name); - }); + if (timer_ != nullptr) { + timer_->DeleteAll(); + timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, + [this] (std::string name) { + PinHolder::CloseSession(name); + }); + } DmPinType pinType = static_cast(jsonObject[TAG_PIN_TYPE].get()); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; @@ -660,11 +668,13 @@ void PinHolder::ProcessChangeMsg(const std::string &message) jsonContent[TAG_PIN_TYPE] = pinType; std::string content = jsonContent.dump(); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); - timer_->DeleteAll(); - timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, - [this] (std::string name) { - PinHolder::CloseSession(name); - }); + if (timer_ != nullptr) { + timer_->DeleteAll(); + timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, + [this] (std::string name) { + PinHolder::CloseSession(name); + }); + } } std::string msg = jsonObj.dump(); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 5420af8b1..31037969d 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -78,7 +78,7 @@ bool SoftbusListener::isRadarSoLoad_ = false; IDmRadarHelper* SoftbusListener::dmRadarHelper_ = nullptr; void* SoftbusListener::radarHandle_ = nullptr; std::string SoftbusListener::hostName_ = ""; -int32_t g_onlinDeviceNum = 0; +int32_t g_onlineDeviceNum = 0; static int OnSessionOpened(int sessionId, int result) { @@ -252,7 +252,7 @@ void SoftbusListener::OnSoftbusDeviceOnline(NodeBasicInfo *info) SoftbusCache::GetInstance().SaveLocalDeviceInfo(); { std::lock_guard lock(g_onlineDeviceNumLock); - g_onlinDeviceNum++; + g_onlineDeviceNum++; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([=]() { DeviceOnLine(dmDeviceInfo); }); @@ -296,8 +296,8 @@ void SoftbusListener::OnSoftbusDeviceOffline(NodeBasicInfo *info) SoftbusCache::GetInstance().DeleteDeviceSecurityLevel(dmDeviceInfo.networkId); { std::lock_guard lock(g_onlineDeviceNumLock); - g_onlinDeviceNum--; - if (g_onlinDeviceNum == 0) { + g_onlineDeviceNum--; + if (g_onlineDeviceNum == 0) { SoftbusCache::GetInstance().DeleteLocalDeviceInfo(); } } @@ -770,11 +770,7 @@ int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &node int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { LOGI("Begin, osType : %{public}d", nodeInfo.osType); - if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { - LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); - return ERR_DM_FAILED; - } - + (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); @@ -1148,7 +1144,7 @@ int32_t SoftbusListener::SetForegroundUserIdsToDSoftBus(const std::string &remot LOGI("Notify remote userid to dsoftbus, msg: %{public}s", GetAnonyString(msg).c_str()); return DM_OK; #else - (void)remoteUdid; + (void)remoteUdid; (void)userIds; #endif return DM_OK; diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index baeaf5ece..2ee214647 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -326,7 +326,12 @@ int32_t SoftbusCache::GetSecurityDeviceLevel(const char *networkId, int32_t &sec return DM_OK; } } - return GetDevLevelFromBus(networkId, securityLevel); + int32_t ret = GetDevLevelFromBus(networkId, securityLevel); + if (ret == DM_OK) { + LOGI("Get dev level from softbus success.") + return DM_OK; + } + return ret; } int32_t SoftbusCache::GetDevLevelFromBus(const char *networkId, int32_t &securityLevel) diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index 52dc07f81..83e94626a 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/include/fwkload/lite/dm_distributed_hardware_load.h b/utils/include/fwkload/lite/dm_distributed_hardware_load.h index 2a72782bc..44dae82cf 100644 --- a/utils/include/fwkload/lite/dm_distributed_hardware_load.h +++ b/utils/include/fwkload/lite/dm_distributed_hardware_load.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/include/fwkload/standard/dm_distributed_hardware_load.h b/utils/include/fwkload/standard/dm_distributed_hardware_load.h index a6c0e5e25..21f5983a2 100644 --- a/utils/include/fwkload/standard/dm_distributed_hardware_load.h +++ b/utils/include/fwkload/standard/dm_distributed_hardware_load.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/include/timer/lite/dm_timer.h b/utils/include/timer/lite/dm_timer.h index 3ba540a56..2718734e2 100644 --- a/utils/include/timer/lite/dm_timer.h +++ b/utils/include/timer/lite/dm_timer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -38,7 +38,6 @@ constexpr const char* STATE_TIMER_PREFIX = "deviceManagerTimer:stateTimer_"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; - constexpr int32_t DELAY_TICK_MILLSECONDS = 1000; typedef std::chrono::steady_clock::time_point timerPoint; typedef std::chrono::steady_clock steadyClock; diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index fd2aeb768..c313d90a9 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index b1d173f53..2f4762c6f 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Copyright (c) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -49,16 +49,15 @@ const std::string AppManager::GetAppId() LOGE("bundleManager is nullptr."); return appId; } - int userId; - ErrCode result = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); - if (result != ERR_OK) { + int32_t userId = -1; + if (AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId) != ERR_OK) { LOGE("GetAppIdByCallingUid QueryActiveOsAccountIds failed."); return appId; } - std::string BundleName; + std::string BundleName = ""; bundleManager->GetNameForUid(IPCSkeleton::GetCallingUid(), BundleName); AppExecFwk::BundleInfo bundleInfo; - int ret = bundleManager->GetBundleInfoV9( + int32_t ret = bundleManager->GetBundleInfoV9( BundleName, static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_SIGNATURE_INFO), bundleInfo, userId); if (ret != 0) { diff --git a/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp b/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp index ba998b296..fbcc8c50b 100644 --- a/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp +++ b/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp b/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp index b7c7499e5..163334f12 100644 --- a/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp +++ b/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/timer/lite/dm_timer.cpp b/utils/src/timer/lite/dm_timer.cpp index 931e692d0..19ba9cbcc 100644 --- a/utils/src/timer/lite/dm_timer.cpp +++ b/utils/src/timer/lite/dm_timer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,10 +21,11 @@ namespace OHOS { namespace DistributedHardware { - +namespace { constexpr const char* TIMER_RUNNING = "TimerRunning"; constexpr int32_t ERR_DM_INPUT_PARA_INVALID = -20006; constexpr int32_t DM_OK = 0; +} Timer::Timer(std::string name, int32_t time, TimerCallback callback) : timerName_(name), expire_(steadyClock::now()), state_(true), timeOut_(time), callback_(callback) {}; -- Gitee From 50223de62f7cbc6a5f9c083f5c1dfb1815c703fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Wed, 27 Nov 2024 16:25:31 +0800 Subject: [PATCH 465/520] =?UTF-8?q?=E6=B5=81=E6=B0=B4=E7=BA=BF=E6=95=B4?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/src/softbus/softbus_listener.cpp | 2 +- services/softbuscache/src/dm_softbus_cache.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 31037969d..6bff7e5f8 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -1144,7 +1144,7 @@ int32_t SoftbusListener::SetForegroundUserIdsToDSoftBus(const std::string &remot LOGI("Notify remote userid to dsoftbus, msg: %{public}s", GetAnonyString(msg).c_str()); return DM_OK; #else - (void)remoteUdid; + (void)remoteUdid; (void)userIds; #endif return DM_OK; diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 2ee214647..6cbdb49a0 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -328,7 +328,7 @@ int32_t SoftbusCache::GetSecurityDeviceLevel(const char *networkId, int32_t &sec } int32_t ret = GetDevLevelFromBus(networkId, securityLevel); if (ret == DM_OK) { - LOGI("Get dev level from softbus success.") + LOGI("Get dev level from softbus success."); return DM_OK; } return ret; -- Gitee From eff4d6cb0382b3560c32a7aa5481403f559814de Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 27 Nov 2024 17:28:17 +0800 Subject: [PATCH 466/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_credential_manager.cpp | 6 +++ .../UTTest_device_manager_service_impl.cpp | 32 +++++++++++++++ .../UTTest_device_manager_service_two.cpp | 40 +++++++++++++++++++ .../mock/deviceprofile_connector_mock.cpp | 7 ++++ .../mock/deviceprofile_connector_mock.h | 3 ++ test/unittest/mock/dm_softbus_cache_mock.cpp | 5 +++ test/unittest/mock/dm_softbus_cache_mock.h | 2 + 7 files changed, 95 insertions(+) diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index a94b83115..02e813563 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -1688,6 +1688,12 @@ HWTEST_F(DmCredentialManagerTest, from_json_002, testing::ext::TestSize.Level0) jsonObject[FIELD_PEER_USER_ID] = "peerDeviceId"; from_json(jsonObject, peerCredentialInfo); EXPECT_EQ(peerCredentialInfo.peerDeviceId, "peerDeviceId"); + + std::string deviceList = "deviceList"; + uint16_t deviceTypeId = 0; + int32_t errcode = 0; + std::shared_ptr dmCreMgr = std::make_shared(hiChainConnector_, listener_); + dmCreMgr->HandleCredentialAuthStatus(deviceList, deviceTypeId, errcode); } /** diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 75fbe0be6..35d7cb3e7 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1809,6 +1809,38 @@ HWTEST_F(DeviceManagerServiceImplTest, GetGroupType_004, testing::ext::TestSize. int32_t ret = deviceManagerServiceImpl_->GetGroupType(deviceList); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 1; + std::string accountId = "accountId"; + auto ret = deviceManagerServiceImpl_->GetDeviceIdAndUserId(userId, accountId); + EXPECT_TRUE(ret.empty()); + + std::string localUdid = "deviceId"; + int32_t localUserId = 123456; + std::string peerUdid = "remoteUdid"; + int32_t peerUserId = 1; + EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + + if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + + std::vector foregroundUserIds; + std::vector &backgroundUserIds; + std::string remoteUdid = "deviceId"; + deviceManagerServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid); + + std::map deviceMap; + int32_t currentUserId = 1; + int32_t beforeUserId = 0; + deviceManagerServiceImpl_->HandleUserSwitched(deviceMap, currentUserId, beforeUserId); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index f5dd1de54..fb96d790a 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -638,6 +638,46 @@ HWTEST_F(DeviceManagerServiceTest, RegDevStateCallbackToService_201, testing::ex std::string pkgName = "pkgName"; int32_t ret = DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); EXPECT_EQ(ret, DM_OK); + + std::string msg; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + msg = R"( + { + "processType" : 1, + "g_authType" : 1, + "userId" : "123" + }))"; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + msg = R"( + { + "processType" : 1, + "g_authType" : 1, + "userId" : "123" + })"; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + msg = R"( + { + "networkId" : "networkId_001", + "g_authType" : 1, + "userId" : "123" + })"; + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + nlohmann::json msgJsonObj; + msgJsonObj["networkId"] = "networkId_001"; + msgJsonObj["discoverType"] = 0; + msg = msgJsonObj.dump(); + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>(""), Return(DM_OK))); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); + + msgJsonObj["discoverType"] = 1; + msg = msgJsonObj.dump(); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); } HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_205, testing::ext::TestSize.Level0) diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index 75999634d..9b3daa511 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -49,5 +49,12 @@ std::map DeviceProfileConnector::GetUserIdAndBindLevel(const s { return DmDeviceProfileConnector::dmDeviceProfileConnector->GetUserIdAndBindLevel(localUdid, peerUdid); } + +bool DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index 6dfcc42e9..e656c90ba 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -35,6 +35,8 @@ public: virtual uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId) = 0; virtual std::map GetUserIdAndBindLevel(const std::string &localUdid, const std::string &peerUdid) = 0; + virtual bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, + const std::string &peerUdid, int32_t peerUserId) = 0; public: static inline std::shared_ptr dmDeviceProfileConnector = nullptr; }; @@ -47,6 +49,7 @@ public: const std::string &)); MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); MOCK_METHOD((std::map), GetUserIdAndBindLevel, (const std::string &, const std::string &)); + MOCK_METHOD(bool, DeleteAclForAccountLogOut, (const std::string &, int32_t, const std::string &, int32_t)); }; } } diff --git a/test/unittest/mock/dm_softbus_cache_mock.cpp b/test/unittest/mock/dm_softbus_cache_mock.cpp index 994212433..7fb8312d1 100644 --- a/test/unittest/mock/dm_softbus_cache_mock.cpp +++ b/test/unittest/mock/dm_softbus_cache_mock.cpp @@ -24,5 +24,10 @@ int32_t SoftbusCache::GetUdidByUdidHash(const std::string &udidHash, std::string { return DmSoftbusCache::dmSoftbusCache->GetUdidByUdidHash(udidHash, udid); } + +int32_t SoftbusCache::GetUdidFromCache(const char *networkId, std::string &udid) +{ + return DmSoftbusCache::dmSoftbusCache->GetUdidFromCache(networkId, udid); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_softbus_cache_mock.h b/test/unittest/mock/dm_softbus_cache_mock.h index d492cacc0..c3df4c21b 100644 --- a/test/unittest/mock/dm_softbus_cache_mock.h +++ b/test/unittest/mock/dm_softbus_cache_mock.h @@ -27,6 +27,7 @@ public: virtual ~DmSoftbusCache() = default; public: virtual int32_t GetUdidByUdidHash(const std::string &udidHash, std::string &udid) = 0; + virtual int32_t GetUdidFromCache(const char *networkId, std::string &udid) = 0; public: static inline std::shared_ptr dmSoftbusCache = nullptr; }; @@ -34,6 +35,7 @@ public: class SoftbusCacheMock : public DmSoftbusCache { public: MOCK_METHOD(int32_t, GetUdidByUdidHash, (const std::string &, std::string &)); + MOCK_METHOD(int32_t, GetUdidFromCache, (const char *, std::string &)); }; } } -- Gitee From 95936ed6f7076a10a550c5d2846f84578cf41d11 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Tue, 26 Nov 2024 10:52:20 +0800 Subject: [PATCH 467/520] =?UTF-8?q?=E6=B3=A8=E5=86=8C=E7=9B=91=E5=90=AC?= =?UTF-8?q?=E5=88=B0=E6=9C=8D=E5=8A=A1=E7=AB=AF=20Signed-off-by:=20liuzhon?= =?UTF-8?q?gming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../device_manager_ipc_interface_code.h | 1 + common/include/dm_anonymous.h | 1 + .../include/ipc/model/ipc_sync_callback_req.h | 51 +++++++++ common/src/dm_anonymous.cpp | 8 ++ .../native_cpp/include/device_manager_impl.h | 4 +- .../native_cpp/include/dm_device_info.h | 13 +++ .../include/notify/device_manager_notify.h | 2 + .../native_cpp/src/device_manager_impl.cpp | 41 ++++++- .../src/ipc/lite/ipc_cmd_parser.cpp | 19 ++++ .../src/ipc/standard/ipc_client_manager.cpp | 9 ++ .../src/ipc/standard/ipc_cmd_parser.cpp | 22 ++++ .../src/notify/device_manager_notify.cpp | 40 +++++++ .../include/device_manager_service_impl.h | 1 + .../device_manager_service_impl_lite.h | 1 + .../src/device_manager_service_impl.cpp | 12 ++ .../src/device_manager_service_impl_lite.cpp | 6 + services/service/BUILD.gn | 4 + .../service/include/device_manager_service.h | 1 + .../include/device_manager_service_listener.h | 4 +- .../include/idevice_manager_service_impl.h | 1 + .../notify/device_manager_service_notify.h | 41 +++++++ .../service/src/device_manager_service.cpp | 18 ++- .../src/device_manager_service_listener.cpp | 61 +++++++--- .../service/src/ipc/lite/ipc_cmd_parser.cpp | 14 +++ .../src/ipc/standard/ipc_cmd_parser.cpp | 12 +- .../src/ipc/standard/ipc_server_stub.cpp | 2 + .../notify/device_manager_service_notify.cpp | 107 ++++++++++++++++++ 27 files changed, 465 insertions(+), 31 deletions(-) create mode 100644 common/include/ipc/model/ipc_sync_callback_req.h create mode 100644 services/service/include/notify/device_manager_service_notify.h create mode 100644 services/service/src/notify/device_manager_service_notify.cpp diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index b0b7f485b..137bc4101 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -95,6 +95,7 @@ enum DMIpcCmdInterfaceCode { GET_NETWORKID_BY_UDID, SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, SINK_BIND_TARGET_RESULT, + SYNC_CALLBACK, // Add ipc msg here IPC_MSG_BUTT }; diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 7fbd6facb..f9a7356f6 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -100,6 +100,7 @@ std::string GetIntegerList(const std::vector &values) bool IsIdLengthValid(const std::string &inputID); bool IsMessageLengthValid(const std::string &inputMessage); bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId); +bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/include/ipc/model/ipc_sync_callback_req.h b/common/include/ipc/model/ipc_sync_callback_req.h new file mode 100644 index 000000000..cf9c3e0a8 --- /dev/null +++ b/common/include/ipc/model/ipc_sync_callback_req.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_IPC_SYNC_CALLBACK_REQ_H +#define OHOS_DM_IPC_SYNC_CALLBACK_REQ_H + +#include "ipc_req.h" + +namespace OHOS { +namespace DistributedHardware { +class IpcSyncCallbackReq : public IpcReq { + DECLARE_IPC_MODEL(IpcSyncCallbackReq); + +public: + /** + * @tc.name: IpcSyncCallbackReq::GetDmCommonNotifyEvent + * @tc.desc: Get notifyEvent of the Ipc Request + * @tc.type: FUNC + */ + int32_t GetDmCommonNotifyEvent() const + { + return dmCommonNotifyEvent_; + } + + /** + * @tc.name: IpcSyncCallbackReq::SetDmCommonNotifyEvent + * @tc.desc: Set notifyEvent of the Ipc Request + * @tc.type: FUNC + */ + void SetDmCommonNotifyEvent(int32_t dmCommonNotifyEvent) + { + dmCommonNotifyEvent_ = dmCommonNotifyEvent; + } +private: + int32_t dmCommonNotifyEvent_ = 0; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_IPC_SYNC_CALLBACK_REQ_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 811c54cca..a421a8a74 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -357,5 +357,13 @@ bool IsValueExist(const std::multimap unorderedmap, const } return false; } + +bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent) +{ + if (dmCommonNotifyEvent > DmCommonNotifyEvent::MIN && dmCommonNotifyEvent < DmCommonNotifyEvent::MAX) { + return true; + } + return false; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 064cffbec..cf0951513 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -23,6 +23,7 @@ #endif #include #include +#include namespace OHOS { namespace DistributedHardware { @@ -403,6 +404,7 @@ public: virtual int32_t RegisterSinkBindCallback(const std::string &pkgName, std::shared_ptr callback) override; virtual int32_t UnRegisterSinkBindCallback(const std::string &pkgName) override; + void SyncCallbacksToService(std::map> &callbackMap); private: DeviceManagerImpl() = default; @@ -420,7 +422,7 @@ private: int32_t CheckApiPermission(int32_t permissionLevel); void ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); uint16_t GetSubscribeIdFromMap(const std::string &pkgName); - void RegDevStateCallbackToService(const std::string &pkgName); + void SyncCallbackToService(DmCommonNotifyEvent dmCommonNotifyEvent, const std::string &pkgName); private: #if !defined(__LITEOS_M__) 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 2a6600d05..00d087fcb 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -334,6 +334,19 @@ typedef enum { STATUS_DM_CLOSE_PIN_INPUT_UI = 13, } DmAuthStatus; +typedef enum { + MIN = 0, + REG_DEVICE_STATE = 1, + UN_REG_DEVICE_STATE = 2, + REG_DEVICE_SCREEN_STATE = 3, + UN_REG_DEVICE_SCREEN_STATE = 4, + REG_REMOTE_DEVICE_TRUST_CHANGE = 5, + UN_REG_REMOTE_DEVICE_TRUST_CHANGE = 6, + REG_CREDENTIAL_AUTH_STATUS_NOTIFY = 7, + UN_REG_CREDENTIAL_AUTH_STATUS_NOTIFY = 8, + MAX = 9, +} DmCommonNotifyEvent; + const std::string DEVICE_TYPE_UNKNOWN_STRING = "UNKNOWN"; const std::string DEVICE_TYPE_PHONE_STRING = "PHONE"; const std::string DEVICE_TYPE_PAD_STRING = "PAD"; 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 3f68a9ee0..cf7be62ad 100644 --- a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h +++ b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -126,6 +127,7 @@ public: void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content); std::shared_ptr GetDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId); + void GetCallBack(std::map> &callbackMap); private: #if !defined(__LITEOS_M__) 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 fca21c420..49a3a621a 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -55,6 +55,7 @@ #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" +#include "ipc_sync_callback_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_unbind_device_req.h" #include "ipc_unpublish_req.h" @@ -392,7 +393,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, return ret; } #endif - RegDevStateCallbackToService(pkgName); + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); LOGI("Completed"); @@ -409,7 +410,7 @@ int32_t DeviceManagerImpl::RegisterDevStatusCallback(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - RegDevStateCallbackToService(pkgName); + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStatusCallback(pkgName, callback); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStatusCallback", DM_OK); LOGI("Completed"); @@ -425,6 +426,7 @@ int32_t DeviceManagerImpl::UnRegisterDevStateCallback(const std::string &pkgName return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().UnRegisterDeviceStateCallback(pkgName); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDevStateCallback", DM_OK); LOGI("Completed"); @@ -440,6 +442,7 @@ int32_t DeviceManagerImpl::UnRegisterDevStatusCallback(const std::string &pkgNam return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().UnRegisterDeviceStatusCallback(pkgName); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDevStatusCallback", DM_OK); LOGI("Completed"); @@ -1869,7 +1872,7 @@ int32_t DeviceManagerImpl::RegisterDevStateCallback(const std::string &pkgName, LOGE("DeviceManagerImpl::RegisterDeviceStateCallback failed: input pkgName or callback is empty."); return ERR_DM_INPUT_PARA_INVALID; } - RegDevStateCallbackToService(pkgName); + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_STATE, pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceStateCallback(pkgName, callback); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegisterDevStateCallback", DM_OK); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); @@ -2272,6 +2275,7 @@ int32_t DeviceManagerImpl::RegDevTrustChangeCallback(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } LOGI("PkgName %{public}s.", pkgName.c_str()); + SyncCallbackToService(DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE, pkgName); DeviceManagerNotify::GetInstance().RegDevTrustChangeCallback(pkgName, callback); DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "RegDevTrustChangeCallback", DM_OK); return DM_OK; @@ -2284,6 +2288,7 @@ int32_t DeviceManagerImpl::RegisterDeviceScreenStatusCallback(const std::string LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } + SyncCallbackToService(DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE, pkgName); DeviceManagerNotify::GetInstance().RegisterDeviceScreenStatusCallback(pkgName, callback); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; @@ -2295,6 +2300,7 @@ int32_t DeviceManagerImpl::UnRegisterDeviceScreenStatusCallback(const std::strin LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_DEVICE_SCREEN_STATE, pkgName); DeviceManagerNotify::GetInstance().UnRegisterDeviceScreenStatusCallback(pkgName); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; @@ -2366,6 +2372,7 @@ int32_t DeviceManagerImpl::RegisterCredentialAuthStatusCallback(const std::strin LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } + SyncCallbackToService(DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY, pkgName); DeviceManagerNotify::GetInstance().RegisterCredentialAuthStatusCallback(pkgName, callback); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; @@ -2377,6 +2384,7 @@ int32_t DeviceManagerImpl::UnRegisterCredentialAuthStatusCallback(const std::str LOGE("Error: Invalid para"); return ERR_DM_INPUT_PARA_INVALID; } + SyncCallbackToService(DmCommonNotifyEvent::UN_REG_CREDENTIAL_AUTH_STATUS_NOTIFY, pkgName); DeviceManagerNotify::GetInstance().UnRegisterCredentialAuthStatusCallback(pkgName); LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; @@ -2416,16 +2424,21 @@ uint16_t DeviceManagerImpl::GetSubscribeIdFromMap(const std::string &pkgName) return DM_INVALID_FLAG_ID; } -void DeviceManagerImpl::RegDevStateCallbackToService(const std::string &pkgName) +void DeviceManagerImpl::SyncCallbackToService(DmCommonNotifyEvent dmCommonNotifyEvent, const std::string &pkgName) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } - std::shared_ptr req = std::make_shared(); + if (!IsDmCommonNotifyEventValid(dmCommonNotifyEvent)) { + LOGE("Invalid dmCommonNotifyEvent: %{public}d.", dmCommonNotifyEvent); + return; + } + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - int32_t ret = ipcClientProxy_->SendRequest(REGISTER_DEV_STATE_CALLBACK, req, rsp); + req->SetDmCommonNotifyEvent(static_cast(dmCommonNotifyEvent)); + int32_t ret = ipcClientProxy_->SendRequest(SYNC_CALLBACK, req, rsp); if (ret != DM_OK) { LOGI("Send Request failed ret: %{public}d", ret); return; @@ -2436,5 +2449,21 @@ void DeviceManagerImpl::RegDevStateCallbackToService(const std::string &pkgName) return; } } + +void DeviceManagerImpl::SyncCallbacksToService(std::map> &callbackMap) +{ + if (callbackMap.size() == 0) { + LOGI("callbackMap is empty."); + return; + } + for (auto iter : callbackMap) { + if (iter.second.size() == 0) { + continue; + } + for (auto item : iter.second) { + SyncCallbackToService(iter.first, item); + } + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp index 18b494a3d..a3c291e93 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp @@ -30,6 +30,7 @@ #include "ipc_register_listener_req.h" #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" +#include "ipc_sync_callback_req.h" #include "securec.h" namespace OHOS { @@ -330,5 +331,23 @@ ON_IPC_CMD(SERVER_DISCOVER_FINISH, IpcIo &reply) DeviceManagerNotify::GetInstance().OnDiscoveryFailed(pkgName, subscribeId, failedReason); } } + +ON_IPC_SET_REQUEST(SYNC_CALLBACK, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, + size_t buffLen) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + int32_t dmCommonNotifyEvent = pReq->GetDmCommonNotifyEvent(); + + IpcIoInit(&request, buffer, buffLen, 0); + WriteString(&request, pkgName.c_str()); + WriteInt32(&request, dmCommonNotifyEvent); + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SYNC_CALLBACK, IpcIo &reply, std::shared_ptr pBaseRsp) +{ + return SetRspErrCode(reply, pBaseRsp); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp index 7745c5f46..52bb04ef1 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_client_manager.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include + #include "ipc_client_manager.h" #include "device_manager_ipc_interface_code.h" @@ -225,6 +227,13 @@ void IpcClientManager::SystemAbilityListener::OnAddSystemAbility(int32_t systemA for (auto iter : dmInitCallback) { DeviceManagerImpl::GetInstance().InitDeviceManager(iter.first, iter.second); } + std::map> callbackMap; + DeviceManagerNotify::GetInstance().GetCallBack(callbackMap); + if (callbackMap.size() == 0) { + LOGE("callbackMap is empty when ReInit"); + return; + } + DeviceManagerImpl::GetInstance().SyncCallbacksToService(callbackMap); } } } // namespace DistributedHardware diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index 15e916bbc..f70c0a000 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 @@ -48,6 +48,7 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" +#include "ipc_sync_callback_req.h" #include "ipc_permission_req.h" #include "ipc_publish_req.h" #include "ipc_unbind_device_req.h" @@ -1691,5 +1692,26 @@ ON_IPC_READ_RESPONSE(REGISTER_DEV_STATE_CALLBACK, MessageParcel &reply, std::sha pBaseRsp->SetErrCode(reply.ReadInt32()); return DM_OK; } + +ON_IPC_SET_REQUEST(SYNC_CALLBACK, std::shared_ptr pBaseReq, MessageParcel &data) +{ + std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); + std::string pkgName = pReq->GetPkgName(); + if (!data.WriteString(pkgName)) { + LOGE("write pkgName failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + if (!data.WriteInt32(pReq->GetDmCommonNotifyEvent())) { + LOGE("write notify event failed"); + return ERR_DM_IPC_WRITE_FAILED; + } + return DM_OK; +} + +ON_IPC_READ_RESPONSE(SYNC_CALLBACK, MessageParcel &reply, std::shared_ptr pBaseRsp) +{ + pBaseRsp->SetErrCode(reply.ReadInt32()); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index d0ccdb127..7d877ab27 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -18,6 +18,7 @@ #include "device_manager.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" namespace OHOS { @@ -1202,5 +1203,44 @@ std::shared_ptr DeviceManagerNotify::GetDiscoveryCallback(con } return nullptr; } + +void DeviceManagerNotify::GetCallBack(std::map> &callbackMap) +{ + std::lock_guard autoLock(lock_); + std::set statePkgnameSet; + for (auto it : deviceStateCallback_) { + statePkgnameSet.insert(it.first); + } + for (auto it : deviceStatusCallback_) { + statePkgnameSet.insert(it.first); + } + if (statePkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_DEVICE_STATE] = statePkgnameSet; + } + + std::set trustChangePkgnameSet; + for (auto it : devTrustChangeCallback_) { + trustChangePkgnameSet.insert(it.first); + } + if (trustChangePkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE] = trustChangePkgnameSet; + } + + std::set screenStatusPkgnameSet; + for (auto it : deviceScreenStatusCallback_) { + screenStatusPkgnameSet.insert(it.first); + } + if (screenStatusPkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE] = screenStatusPkgnameSet; + } + + std::set authStatusPkgnameSet; + for (auto it : credentialAuthStatusCallback_) { + authStatusPkgnameSet.insert(it.first); + } + if (authStatusPkgnameSet.size() > 0) { + callbackMap[DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY] = authStatusPkgnameSet; + } +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index c621c1a4b..21a2761b0 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -139,6 +139,7 @@ public: void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, int32_t beforeUserId); std::multimap GetDeviceIdAndUserId(int32_t localUserId); + int32_t SaveOnlineDeviceInfo(const std::vector &deviceList); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 2a36cac96..3c7fa5d01 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -146,6 +146,7 @@ public: void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); std::map GetDeviceIdAndBindLevel(int32_t userId); std::multimap GetDeviceIdAndUserId(int32_t localUserId); + int32_t SaveOnlineDeviceInfo(const std::vector &deviceList); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index af65aa03d..333571d79 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -217,6 +217,9 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); processInfo.userId = MultipleUserConnector::GetFirstForegroundUserId(); + if (userIdAndBindLevel.empty() || userIdAndBindLevel.find(processInfo.userId) == userIdAndBindLevel.end()) { + userIdAndBindLevel[processInfo.userId] = INVALIED_TYPE; + } for (const auto &item : userIdAndBindLevel) { if (item.second == INVALIED_TYPE) { LOGI("The offline device is identical account bind type."); @@ -982,6 +985,15 @@ std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUser return DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); } +int32_t DeviceManagerServiceImpl::SaveOnlineDeviceInfo(const std::vector &deviceList) +{ + CHECK_NULL_RETURN(deviceStateMgr_, ERR_DM_POINT_NULL); + for (auto item : deviceList) { + deviceStateMgr_->SaveOnlineDeviceInfo(item); + } + return DM_OK; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index f7028d7ce..d08c6c5d8 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -569,6 +569,12 @@ std::multimap DeviceManagerServiceImpl::GetDeviceIdAndUser return {}; } +int32_t DeviceManagerServiceImpl::SaveOnlineDeviceInfo(const std::vector &deviceList) +{ + (void)deviceList; + return DM_OK; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index 52412fe3d..00ee00fc1 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -26,6 +26,7 @@ if (defined(ohos_lite)) { "include", "include/advertise", "include/discovery", + "include/notify", "include/softbus", "include/ipc/lite", "include/permission/lite", @@ -68,6 +69,7 @@ if (defined(ohos_lite)) { "src/ipc/lite/ipc_server_listenermgr.cpp", "src/ipc/lite/ipc_server_main.cpp", "src/ipc/lite/ipc_server_stub.cpp", + "src/notify/device_manager_service_notify.cpp", "src/permission/lite/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", @@ -121,6 +123,7 @@ if (defined(ohos_lite)) { "include/discovery", "include/ipc", "include/ipc/standard", + "include/notify", "include/permission/standard", "include/pinholder", "include/publishcommonevent", @@ -171,6 +174,7 @@ if (defined(ohos_lite)) { "src/ipc/standard/ipc_server_client_proxy.cpp", "src/ipc/standard/ipc_server_listener.cpp", "src/ipc/standard/ipc_server_stub.cpp", + "src/notify/device_manager_service_notify.cpp", "src/permission/standard/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index bf5b82c91..fbe66903e 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -203,6 +203,7 @@ public: void RemoveNotifyRecord(const ProcessInfo &processInfo); int32_t RegDevStateCallbackToService(const std::string &pkgName); int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList); + private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index d58ecec3b..a4bb66388 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -97,8 +97,8 @@ private: int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, std::string &anoyDeviceId); #endif - std::vector GetWhiteListSAProcessInfo(); - std::vector GetNotifyProcessInfoByUserId(int32_t userId); + std::vector GetWhiteListSAProcessInfo(DmCommonNotifyEvent dmCommonNotifyEvent); + std::vector GetNotifyProcessInfoByUserId(int32_t userId, DmCommonNotifyEvent dmCommonNotifyEvent); ProcessInfo DealBindProcessInfo(const ProcessInfo &processInfo); void ProcessDeviceOnline(const std::vector &procInfoVec, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 65f5916ef..bfa0f92be 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -284,6 +284,7 @@ public: virtual void HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) = 0; virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; + virtual int32_t SaveOnlineDeviceInfo(const std::vector &deviceList) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/notify/device_manager_service_notify.h b/services/service/include/notify/device_manager_service_notify.h new file mode 100644 index 000000000..9dcb28ebe --- /dev/null +++ b/services/service/include/notify/device_manager_service_notify.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_SERVICE_NOTIFY_H +#define OHOS_DM_SERVICE_NOTIFY_H + +#include +#include + +#include "dm_device_info.h" +#include "dm_single_instance.h" + +namespace OHOS { +namespace DistributedHardware { +class DeviceManagerServiceNotify { + DM_DECLARE_SINGLE_INSTANCE(DeviceManagerServiceNotify); + +public: + int32_t RegisterCallBack(int32_t dmCommonNotifyEvent, const ProcessInfo &processInfo); + void GetCallBack(int32_t dmCommonNotifyEvent, std::set &processInfos); + void ClearDiedProcessCallback(const ProcessInfo &processInfo); + +private: + std::mutex callbackLock_; + std::map> callbackMap_; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_SERVICE_NOTIFY_H diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 7ade2592c..10c930543 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -74,6 +74,7 @@ namespace { const std::string USERID_CHECKSUM_NETWORKID_KEY = "networkId"; const std::string USERID_CHECKSUM_DISCOVER_TYPE_KEY = "discoverType"; constexpr uint32_t USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK = 0b0010; + const std::string DHARD_WARE_PKG_NAME = "ohos.dhardware"; } DeviceManagerService::~DeviceManagerService() { @@ -96,6 +97,11 @@ int32_t DeviceManagerService::InitSoftbusListener() softbusListener_ = std::make_shared(); } SoftbusCache::GetInstance().UpdateDeviceInfoCache(); + std::vector onlineDeviceList; + SoftbusCache::GetInstance().GetDeviceInfoFromCache(onlineDeviceList); + if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { + dmServiceImpl_->SaveOnlineDeviceInfo(onlineDeviceList); + } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) SubscribePublishCommonEvent(); @@ -965,18 +971,20 @@ void DeviceManagerService::LoadHardwareFwkService() { std::vector deviceList; CHECK_NULL_VOID(softbusListener_); - int32_t ret = softbusListener_->GetTrustedDeviceList(deviceList); + int32_t ret = GetTrustedDeviceList(DHARD_WARE_PKG_NAME, deviceList); if (ret != DM_OK) { LOGE("LoadHardwareFwkService failed, get trusted devicelist failed."); return; } + if (deviceList.empty()) { + LOGI("no trusted device."); + return; + } if (!IsDMServiceImplReady()) { LOGE("LoadHardwareFwkService failed, instance not init or init failed."); return; } - if (deviceList.size() > 0) { - dmServiceImpl_->LoadHardwareFwkService(); - } + dmServiceImpl_->LoadHardwareFwkService(); } int32_t DeviceManagerService::GetEncryptedUuidByNetworkId(const std::string &pkgName, const std::string &networkId, @@ -1667,6 +1675,7 @@ void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUser peerUdids.push_back(item.first); } } + dmServiceImpl_->HandleUserSwitched(preUserDeviceMap, curUserId, preUserId); if (!peerUdids.empty()) { std::vector foregroundUserVec; int32_t retFront = MultipleUserConnector::GetForegroundUserIds(foregroundUserVec); @@ -1680,7 +1689,6 @@ void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUser SendUserIdsBroadCast(peerUdids, foregroundUserVec, backgroundUserVec, true); } } - dmServiceImpl_->HandleUserSwitched(preUserDeviceMap, curUserId, preUserId); } void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index d11e2ca90..b98d3442d 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -19,6 +19,7 @@ #include "app_manager.h" #include "device_manager_ipc_interface_code.h" +#include "device_manager_service_notify.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" @@ -118,7 +119,8 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const ProcessInfo &p const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); - std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId); + std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId, + DmCommonNotifyEvent::REG_DEVICE_STATE); switch (static_cast(state)) { case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): ProcessDeviceOnline(processInfoVec, processInfo, state, info, deviceBasicInfo); @@ -139,7 +141,7 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); - std::vector processInfoVec = GetWhiteListSAProcessInfo(); + std::vector processInfoVec = GetWhiteListSAProcessInfo(DmCommonNotifyEvent::REG_DEVICE_STATE); ProcessInfo bindProcessInfo = DealBindProcessInfo(processInfo); processInfoVec.push_back(bindProcessInfo); switch (static_cast(state)) { @@ -452,7 +454,8 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) userId = MultipleUserConnector::GetFirstForegroundUserId(); #endif - std::vector processInfoVec = GetNotifyProcessInfoByUserId(userId); + std::vector processInfoVec = GetNotifyProcessInfoByUserId(userId, + DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE); for (const auto &item : processInfoVec) { pReq->SetPkgName(item.pkgName); pReq->SetUdid(udid); @@ -494,7 +497,7 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const ProcessInfo & userId = MultipleUserConnector::GetFirstForegroundUserId(); #endif std::vector processInfoVec = - GetNotifyProcessInfoByUserId(userId); + GetNotifyProcessInfoByUserId(userId, DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE); for (const auto &item : processInfoVec) { SetDeviceScreenInfo(pReq, item, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); @@ -502,16 +505,13 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const ProcessInfo & } else { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); - for (const auto &item : notifyPkgnames) { - ProcessInfo processInfo; - processInfo.pkgName = item; - processInfo.userId = 0; - SetDeviceScreenInfo(pReq, processInfo, devInfo); + std::vector processInfoVec = + GetWhiteListSAProcessInfo(DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE); + processInfoVec.push_back(processInfo); + for (const auto &item : processInfoVec) { + SetDeviceScreenInfo(pReq, item, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } - SetDeviceScreenInfo(pReq, processInfo, devInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } } @@ -539,7 +539,7 @@ void DeviceManagerServiceListener::OnCredentialAuthStatus(const ProcessInfo &pro userId = MultipleUserConnector::GetFirstForegroundUserId(); #endif std::vector processInfoVec = - GetNotifyProcessInfoByUserId(userId); + GetNotifyProcessInfoByUserId(userId, DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY); for (const auto &item : processInfoVec) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); @@ -601,29 +601,60 @@ void DeviceManagerServiceListener::OnSinkBindResult(const ProcessInfo &processIn ipcServerListener_.SendRequest(SINK_BIND_TARGET_RESULT, pReq, pRsp); } -std::vector DeviceManagerServiceListener::GetWhiteListSAProcessInfo() +std::vector DeviceManagerServiceListener::GetWhiteListSAProcessInfo( + DmCommonNotifyEvent dmCommonNotifyEvent) { + if (!IsDmCommonNotifyEventValid(dmCommonNotifyEvent)) { + LOGE("Invalid dmCommonNotifyEvent: %{public}d.", dmCommonNotifyEvent); + return {}; + } + std::set notifyProcessInfos; + DeviceManagerServiceNotify::GetInstance().GetCallBack(dmCommonNotifyEvent, notifyProcessInfos); + if (notifyProcessInfos.size() == 0) { + LOGE("callback not exist dmCommonNotifyEvent: %{public}d", dmCommonNotifyEvent); + return {}; + } std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); std::vector processInfos; for (const auto &it : notifyPkgnames) { ProcessInfo processInfo; processInfo.pkgName = it; processInfo.userId = 0; + if (notifyProcessInfos.find(processInfo) == notifyProcessInfos.end()) { + continue; + } processInfos.push_back(processInfo); } return processInfos; } -std::vector DeviceManagerServiceListener::GetNotifyProcessInfoByUserId(int32_t userId) +std::vector DeviceManagerServiceListener::GetNotifyProcessInfoByUserId(int32_t userId, + DmCommonNotifyEvent dmCommonNotifyEvent) { + if (!IsDmCommonNotifyEventValid(dmCommonNotifyEvent)) { + LOGE("Invalid dmCommonNotifyEvent: %{public}d.", dmCommonNotifyEvent); + return {}; + } + std::set notifyProcessInfos; + DeviceManagerServiceNotify::GetInstance().GetCallBack(dmCommonNotifyEvent, notifyProcessInfos); + if (notifyProcessInfos.size() == 0) { + LOGE("callback not exist dmCommonNotifyEvent: %{public}d", dmCommonNotifyEvent); + return {}; + } std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); std::set systemSA = ipcServerListener_.GetSystemSA(); std::vector processInfosTemp; for (auto item : processInfos) { if (systemSA.find(item.pkgName) != systemSA.end()) { item.userId = 0; + if (notifyProcessInfos.find(item) == notifyProcessInfos.end()) { + continue; + } processInfosTemp.push_back(item); } else if (item.userId == userId) { + if (notifyProcessInfos.find(item) == notifyProcessInfos.end()) { + continue; + } processInfosTemp.push_back(item); } } diff --git a/services/service/src/ipc/lite/ipc_cmd_parser.cpp b/services/service/src/ipc/lite/ipc_cmd_parser.cpp index e6f3bd310..37bec133e 100644 --- a/services/service/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/lite/ipc_cmd_parser.cpp @@ -15,8 +15,10 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_service.h" +#include "device_manager_service_notify.h" #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" #include "ipc_cmd_register.h" #include "ipc_def.h" @@ -237,5 +239,17 @@ ON_IPC_SERVER_CMD(DELETE_CREDENTIAL, IpcIo &req, IpcIo &reply) WriteString(&reply, outParamStr.c_str()); } } + +ON_IPC_SERVER_CMD(SYNC_CALLBACK, IpcIo &req, IpcIo &reply) +{ + LOGI("start."); + std::string pkgName = (const char*)ReadString(&req, nullptr); + int32_t dmCommonNotifyEvent = 0; + ReadInt32(&req, &dmCommonNotifyEvent); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + int32_t ret = DeviceManagerServiceNotify::GetInstance().RegisterCallBack(dmCommonNotifyEvent, processInfo); + WriteInt32(&reply, ret); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 93671487b..3f580e56f 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -19,6 +19,7 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_service.h" +#include "device_manager_service_notify.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_device_info.h" @@ -1626,10 +1627,17 @@ ON_IPC_READ_RESPONSE(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, MessageParcel &reply return DM_OK; } -ON_IPC_CMD(REGISTER_DEV_STATE_CALLBACK, MessageParcel &data, MessageParcel &reply) +ON_IPC_CMD(SYNC_CALLBACK, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); - int32_t result = DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); + int32_t dmCommonNotifyEvent = data.ReadInt32(); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); + int32_t result = DeviceManagerServiceNotify::GetInstance().RegisterCallBack(dmCommonNotifyEvent, processInfo); + if (dmCommonNotifyEvent == static_cast(DmCommonNotifyEvent::REG_DEVICE_STATE)) { + DeviceManagerService::GetInstance().RegDevStateCallbackToService(pkgName); + } if (!reply.WriteInt32(result)) { LOGE("write result failed"); return ERR_DM_IPC_WRITE_FAILED; diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 8c6fe970a..2d0e389f4 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -32,6 +32,7 @@ #include "system_ability_definition.h" #include "device_manager_ipc_interface_code.h" #include "device_manager_service.h" +#include "device_manager_service_notify.h" #include "dm_constants.h" #include "dm_device_info.h" #include "dm_log.h" @@ -348,6 +349,7 @@ void AppDeathRecipient::OnRemoteDied(const wptr &remote) LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", processInfo.pkgName.c_str()); IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); + DeviceManagerServiceNotify::GetInstance().ClearDiedProcessCallback(processInfo); } void IpcServerStub::AddSystemSA(const std::string &pkgName) diff --git a/services/service/src/notify/device_manager_service_notify.cpp b/services/service/src/notify/device_manager_service_notify.cpp new file mode 100644 index 000000000..55b8b9b3f --- /dev/null +++ b/services/service/src/notify/device_manager_service_notify.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_manager_service_notify.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerServiceNotify); +namespace { +constexpr uint32_t MAX_CALLBACK_LEN = 1000; +const static std::map unRegNotifyEventMap_ = { + {DmCommonNotifyEvent::UN_REG_DEVICE_STATE, DmCommonNotifyEvent::REG_DEVICE_STATE}, + {DmCommonNotifyEvent::UN_REG_DEVICE_SCREEN_STATE, DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE}, + {DmCommonNotifyEvent::UN_REG_REMOTE_DEVICE_TRUST_CHANGE, DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE}, + {DmCommonNotifyEvent::UN_REG_CREDENTIAL_AUTH_STATUS_NOTIFY, DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY} +}; + +const static std::set regNotifyEventSet_ = { + DmCommonNotifyEvent::REG_DEVICE_STATE, + DmCommonNotifyEvent::REG_DEVICE_SCREEN_STATE, + DmCommonNotifyEvent::REG_REMOTE_DEVICE_TRUST_CHANGE, + DmCommonNotifyEvent::REG_CREDENTIAL_AUTH_STATUS_NOTIFY +}; +} + +int32_t DeviceManagerServiceNotify::RegisterCallBack(int32_t dmCommonNotifyEvent, const ProcessInfo &processInfo) +{ + LOGI("start event %{public}d pkgName: %{public}s.", dmCommonNotifyEvent, processInfo.pkgName.c_str()); + if (processInfo.pkgName.empty()) { + LOGE("Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + DmCommonNotifyEvent notifyEvent = static_cast(dmCommonNotifyEvent); + std::lock_guard autoLock(callbackLock_); + if (unRegNotifyEventMap_.find(notifyEvent) != unRegNotifyEventMap_.end()) { + if (callbackMap_.find(unRegNotifyEventMap_.at(notifyEvent)) == callbackMap_.end()) { + LOGI("notifyEvent is not exist %{public}d.", unRegNotifyEventMap_.at(notifyEvent)); + return DM_OK; + } + callbackMap_.at(unRegNotifyEventMap_.at(notifyEvent)).erase(processInfo); + return DM_OK; + } + if (regNotifyEventSet_.find(notifyEvent) == regNotifyEventSet_.end()) { + LOGE("notifyEvent is not support %{public}d.", notifyEvent); + return ERR_DM_INPUT_PARA_INVALID; + } + if (callbackMap_.find(notifyEvent) == callbackMap_.end()) { + std::set processInfoSet; + processInfoSet.insert(processInfo); + callbackMap_[notifyEvent] = processInfoSet; + return DM_OK; + } + if (callbackMap_[notifyEvent].size() >= MAX_CALLBACK_LEN) { + LOGE("too many callbacks dmCommonNotifyEvent: %{public}d, pkgName: %{public}s", dmCommonNotifyEvent, + processInfo.pkgName.c_str()); + return ERR_DM_FAILED; + } + callbackMap_.at(notifyEvent).insert(processInfo); + return DM_OK; +} + +void DeviceManagerServiceNotify::GetCallBack(int32_t dmCommonNotifyEvent, std::set &processInfos) +{ + LOGI("start event %{public}d.", dmCommonNotifyEvent); + DmCommonNotifyEvent notifyEvent = static_cast(dmCommonNotifyEvent); + std::lock_guard autoLock(callbackLock_); + if (regNotifyEventSet_.find(notifyEvent) == regNotifyEventSet_.end()) { + LOGE("notifyEvent is not support %{public}d.", notifyEvent); + return; + } + if (callbackMap_.find(notifyEvent) == callbackMap_.end()) { + LOGE("callback is empty %{public}d.", notifyEvent); + return; + } + processInfos = callbackMap_.at(notifyEvent); +} + +void DeviceManagerServiceNotify::ClearDiedProcessCallback(const ProcessInfo &processInfo) +{ + LOGI("start pkgName %{public}s.", processInfo.pkgName.c_str()); + std::lock_guard autoLock(callbackLock_); + for (auto iter = callbackMap_.begin(); iter != callbackMap_.end();) { + iter->second.erase(processInfo); + if (iter->second.empty()) { + iter = callbackMap_.erase(iter); + } else { + ++iter; + } + } +} +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From 36aac6e26d4803b6587ce827f00f3e703296cbd5 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Tue, 26 Nov 2024 19:43:35 +0800 Subject: [PATCH 468/520] =?UTF-8?q?=E6=AD=BB=E4=BA=A1=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E6=B8=85=E7=90=86=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../native_cpp/src/device_manager_impl.cpp | 2 +- .../include/discovery/discovery_manager.h | 3 +- .../service/src/device_manager_service.cpp | 4 +- .../src/discovery/discovery_manager.cpp | 72 ++++++++++++++----- 4 files changed, 58 insertions(+), 23 deletions(-) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index fca21c420..8ffb5f65b 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -1686,7 +1686,7 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgNameTemp); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); req->SetFirstParam(extraParaStr); int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_DISCOVERY_CALLBACK, req, rsp); if (ret != DM_OK) { diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index ddb542ab2..6e9fb7f6c 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -76,7 +76,8 @@ public: static bool IsCommonDependencyReady(); static bool CloseCommonDependencyObj(); #endif - void ClearDiscoveryCache(const std::string &pkgName); + void ClearDiscoveryCache(const ProcessInfo &processInfo); + std::set ClearDiscoveryPkgName(const std::string &pkgName); private: void StartDiscoveryTimer(const std::string &pkgName); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 7ade2592c..4ce57e778 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2141,9 +2141,9 @@ void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg) void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo) { - LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); + LOGI("PkgName: %{public}s, userId: %{public}d", processInfo.pkgName.c_str(), processInfo.userId); CHECK_NULL_VOID(discoveryMgr_); - discoveryMgr_->ClearDiscoveryCache(processInfo.pkgName); + discoveryMgr_->ClearDiscoveryCache(processInfo); } void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo) diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 224e0887a..9a86a7dd5 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -608,39 +608,73 @@ bool DiscoveryManager::CloseCommonDependencyObj() } #endif -void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) +void DiscoveryManager::ClearDiscoveryCache(const ProcessInfo &processInfo) { - LOGI("PkgName %{public}s.", pkgName.c_str()); - uint16_t subscribeId = 0; + LOGI("PkgName: %{public}s, userId: %{public}d", processInfo.pkgName.c_str(), processInfo.userId); + std::string pkgName = processInfo.pkgName + "#"; + std::set subscribeIdSet = ClearDiscoveryPkgName(pkgName); + + CHECK_NULL_VOID(softbusListener_); + for (auto it : subscribeIdSet) { + std::string pkgNameTemp = (ComposeStr(ComposeStr(processInfo.pkgName, it), processInfo.userId)); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); + softbusListener_->StopRefreshSoftbusLNN(it); + } + + CHECK_NULL_VOID(timer_); + for (auto it : subscribeIdSet) { + std::string pkgNameTemp = (ComposeStr(ComposeStr(processInfo.pkgName, it), processInfo.userId)); + timer_->DeleteTimer(pkgNameTemp); + } +} + +std::set DiscoveryManager::ClearDiscoveryPkgName(const std::string &pkgName) +{ + std::set subscribeIdSet; { std::lock_guard autoLock(locks_); - if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { - LOGI("Erase pkgname %{public}s from pkgNameSet.", pkgName.c_str()); - pkgNameSet_.erase(pkgName); + for (auto it = pkgNameSet_.begin(); it != pkgNameSet_.end();) { + if ((*it).find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from pkgNameSet.", (*it).c_str()); + it = pkgNameSet_.erase(it); + } else { + ++it; + } } - if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { - LOGI("Erase pkgname %{public}s from pkgNameSet.", pkgName.c_str()); - subscribeId = discoveryContextMap_[pkgName].subscribeId; - discoveryContextMap_.erase(pkgName); + for (auto it = discoveryContextMap_.begin(); it != discoveryContextMap_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from discoveryContextMap_.", it->first.c_str()); + subscribeIdSet.insert(it->second.subscribeId); + it = discoveryContextMap_.erase(it); + } else { + ++it; + } } } { std::lock_guard capLock(capabilityMapLocks_); - if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { - capabilityMap_.erase(pkgName); + for (auto it = capabilityMap_.begin(); it != capabilityMap_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from capabilityMap_.", it->first.c_str()); + it = capabilityMap_.erase(it); + } else { + ++it; + } } } { std::lock_guard autoLock(subIdMapLocks_); - if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { - pkgName2SubIdMap_.erase(pkgName); + for (auto it = pkgName2SubIdMap_.begin(); it != pkgName2SubIdMap_.end();) { + if (it->first.find(pkgName) != std::string::npos) { + LOGI("Erase pkgname %{public}s from pkgName2SubIdMap_.", it->first.c_str()); + subscribeIdSet.insert(it->second); + it = pkgName2SubIdMap_.erase(it); + } else { + ++it; + } } } - CHECK_NULL_VOID(softbusListener_); - softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); - softbusListener_->StopRefreshSoftbusLNN(subscribeId); - CHECK_NULL_VOID(timer_); - timer_->DeleteTimer(pkgName); + return subscribeIdSet; } std::string DiscoveryManager::AddMultiUserIdentify(const std::string &pkgName) -- Gitee From dcc4a480543e38af1af858ca1e39e3d9c615a6c5 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 28 Nov 2024 10:42:47 +0800 Subject: [PATCH 469/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- interfaces/kits/js/src/native_devicemanager_js.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index e0f90c5ce..49a567c47 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -3214,17 +3214,17 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) return nullptr; } - char bundleName[DM_NAPI_BUF_LENGTH] = {0}; + char pkgName[DM_NAPI_BUF_LENGTH] = {0}; size_t typeLen = 0; - napi_get_value_string_utf8(env, argv[0], bundleName, sizeof(bundleName), &typeLen); + napi_get_value_string_utf8(env, argv[0], pkgName, sizeof(pkgName), &typeLen); - LOGI("create DeviceManagerNapi for packageName:%{public}s", bundleName); + LOGI("create DeviceManagerNapi for packageName:%{public}s", pkgName); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); if (obj == nullptr) { return nullptr; } - obj->bundleName_ = std::string(bundleName); + obj->bundleName_ = std::string(pkgName); std::lock_guard autoLock(g_deviceManagerMapMutex); g_deviceManagerMap[obj->bundleName_] = obj; napi_status status = napi_wrap( -- Gitee From 4fa433850291f278503a493135e71feb6e536f29 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Thu, 28 Nov 2024 10:43:34 +0800 Subject: [PATCH 470/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E5=B9=BF=E6=92=AD=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/service/include/device_manager_service.h | 1 + services/service/src/device_manager_service.cpp | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index bf5b82c91..c745f0916 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -287,6 +287,7 @@ private: std::shared_ptr publshCommonEventManager_; #endif // SUPPORT_BLUETOOTH SUPPORT_WIFI #endif + std::string localNetWorkId_ = ""; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 7ade2592c..dc5ac1a57 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2069,6 +2069,15 @@ int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::stri void DeviceManagerService::ProcessCheckSumByWifi(std::string networkId, std::vector foregroundUserIds, std::vector backgroundUserIds) { + if (localNetWorkId_ == "") { + DmDeviceInfo deviceInfo; + SoftbusCache::GetInstance().GetLocalDeviceInfo(deviceInfo); + localNetWorkId_ = std::string(deviceInfo.networkId); + } + if (localNetWorkId_ >= networkId) { + LOGI("Local networkid big than remote, no need begin req"); + return; + } // use connection to exchange foreground/background userid LOGI("Try open softbus session to exchange foreground/background userid"); std::vector foregroundUserIdsUInt; -- Gitee From efa6941644dc96c1b8100327e1d0daa31ad5e0b4 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 28 Nov 2024 11:24:59 +0800 Subject: [PATCH 471/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_dm_pin_holder.cpp | 110 +++++++++++++++++++++++++ 1 file changed, 110 insertions(+) diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index fa302b097..259ac9eaa 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -797,6 +797,38 @@ HWTEST_F(DmPinHolderTest, SendData_103, testing::ext::TestSize.Level0) )"; int32_t ret = pinHolderSession->SendData(sessionId, message); EXPECT_NE(ret, DM_OK); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + pinHolder->session_ = nullptr; + std::string message; + pinHolder->ProcessChangeMsg(message); + + message = R"( + { + "MSG_TYPE" : 100 + }} + )"; + pinHolder->session_ = std::make_shared(); + pinHolder->ProcessChangeMsg(message); + + message = R"( + { + "MSG_TYPE" : 100 + } + )"; + pinHolder->ProcessChangeMsg(message); + + message = R"( + { + "PIN_TYPE" : 12 + } + )"; + pinHolder->sinkState_ = PinHolderState::SINK_INIT; + pinHolder->ProcessChangeMsg(message); + + pinHolder->sinkState_ = PinHolderState::SINK_CREATE; + pinHolder->ProcessChangeMsg(message); } HWTEST_F(DmPinHolderTest, GetAddrByTargetId_101, testing::ext::TestSize.Level0) @@ -812,6 +844,84 @@ HWTEST_F(DmPinHolderTest, GetAddrByTargetId_101, testing::ext::TestSize.Level0) ConnectionAddr addr; int32_t ret = pinHolderSession->GetAddrByTargetId(targetId, addr); EXPECT_EQ(ret, DM_OK); + + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + std::string message = R"( + { + "MSG_TYPE" : 100 + }} + )"; + pinHolder->ProcessChangeRespMsg(message); + + message = R"( + { + "MSG_TYPE" : 100 + } + )"; + pinHolder->ProcessChangeRespMsg(message); + + message = R"( + { + "REPLY" : 10 + } + )"; + pinHolder->session_ = nullptr; + pinHolder->ProcessChangeRespMsg(message); + + pinHolder->session_ = std::make_shared(); + pinHolder->ProcessChangeRespMsg(message); + + message = R"( + { + "REPLY" : 0 + } + )"; + pinHolder->ProcessChangeRespMsg(message); +} + +HWTEST_F(DmPinHolderTest, NotifyPinHolderEvent_102, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener = std::make_shared(); + std::shared_ptr pinHolder = std::make_shared(listener); + std::string pkgName = "com.ohos.dmtest"; + std::string event = "event"; + pinHolder->session_ = nullptr; + int32_t ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + pinHolder->session_ = std::make_shared(); + pinHolder->processInfo_.pkgName = ""; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + pinHolder->processInfo_.pkgName = "pkgName"; + pkgName = "pkgName"; + pinHolder->sessionId_ = -1; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + pinHolder->sessionId_ = 0; + pinHolder->isRemoteSupported_ = false; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_BIND_PEER_UNSUPPORTED); + + pinHolder->isRemoteSupported_ = true; + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); + + if (pinHolder->timer_ == nullptr) { + pinHolder->timer_ = std::make_shared(); + } + nlohmann::json jsonObj; + jsonObj[TAG_MSG_TYPE] = 1; + jsonObj[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; + event = jsonObj.dump(); + if (pinHolder->session_ == nullptr) { + pinHolder->session_ = std::make_shared(); + } + ret = pinHolder->NotifyPinHolderEvent(pkgName, event); + ASSERT_EQ(ret, ERR_DM_FAILED); } } // namespace } // namespace DistributedHardware -- Gitee From 1b852274ac8c50fd882a22038cf4b8898b85aa3e Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 28 Nov 2024 15:51:37 +0800 Subject: [PATCH 472/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_permission_manager.cpp | 2 +- .../UTTest_softbus_listener.cpp | 6 +- ...UTTest_device_manager_service_listener.cpp | 56 +++++++++++++++++++ test/unittest/UTTest_dm_transport.cpp | 21 +++++++ 4 files changed, 81 insertions(+), 4 deletions(-) diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index b8cde8d57..b1b4d1cef 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -253,7 +253,7 @@ HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_102, testing::ext::TestSi HWTEST_F(PermissionManagerTest, CheckMonitorPermission_001, testing::ext::TestSize.Level0) { bool ret = PermissionManager::GetInstance().CheckMonitorPermission(); - ASSERT_TRUE(ret); + ASSERT_FALSE(ret); } HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnSetDnPolicy_001, testing::ext::TestSize.Level0) diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 6b0037d70..e143611ac 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -1052,15 +1052,15 @@ HWTEST_F(SoftbusListenerTest, SetLocalDeviceName_001, testing::ext::TestSize.Lev softbusListener = std::make_shared(); } int32_t ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + EXPECT_EQ(ret, DM_OK); localDeviceName = "localDeviceName"; ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, DM_OK); localDisplayName = "localDisplayName"; ret = softbusListener->SetLocalDeviceName(localDeviceName, localDisplayName); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, DM_OK); softbusListener = nullptr; } diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index bbe6b9f14..b08a15b2c 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -456,6 +456,62 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::T listener_->OnPinHolderEvent(processInfo, event, result, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } + +HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceScreenStateChange_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + DmDeviceInfo devInfo; + listener_->OnDeviceScreenStateChange(processInfo, devInfo); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); + + processInfo.pkgName = "ohos.distributedhardware.devicemanager"; + listener_->OnDeviceScreenStateChange(processInfo, devInfo); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialAuthStatus_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + std::string deviceList = "deviceList"; + uint16_t deviceTypeId = 1; + int32_t errcode = 0; + listener_->OnCredentialAuthStatus(processInfo, deviceList, deviceTypeId, errcode); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnSinkBindResult_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + PeerTargetId targetId; + int32_t result = 1; + int32_t status = 0; + std::string content = "content"; + listener_->OnSinkBindResult(processInfo, targetId, result, status, content); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} + +HWTEST_F(DeviceManagerServiceListenerTest, OnProcessRemove_001, testing::ext::TestSize.Level0) +{ + std::shared_ptr listener_ = std::make_shared(); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + DmDeviceInfo dmDeviceInfo; + listener_->alreadyOnlinePkgName_["com.ohos.helloworld#100"] = dmDeviceInfo; + DmDeviceInfo dmDeviceInfo1; + listener_->alreadyOnlinePkgName_["com.ohos.network"] = dmDeviceInfo; + listener_->OnProcessRemove(processInfo); + EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_dm_transport.cpp b/test/unittest/UTTest_dm_transport.cpp index e9b239dd3..e4768eaa1 100644 --- a/test/unittest/UTTest_dm_transport.cpp +++ b/test/unittest/UTTest_dm_transport.cpp @@ -202,5 +202,26 @@ HWTEST_F(DMTransportTest, Send_SessionNotOpened_Failure, testing::ext::TestSize. int32_t result = dmTransport.Send(notOpenedId, payload); EXPECT_EQ(result, ERR_DM_FAILED); } + +HWTEST_F(DMTransportTest, OnSocketOpened_001, testing::ext::TestSize.Level0) +{ + int32_t socketId = 1; + PeerSocketInfo info; + int32_t ret = dmTransport.OnSocketOpened(socketId, info); + EXPECT_EQ(ret, DM_OK); + + ShutdownReason reason; + dmTransport.remoteDevSocketIds_["socketId"] = socketId; + dmTransport.OnSocketClosed(socketId, reason); + + int32_t value = 1; + void *data = &value; + uint32_t dataLen = 1; + socketId = -1; + dmTransport.OnBytesReceived(socketId, data, dataLen); + + socketId = 1; + dmTransport.OnBytesReceived(socketId, data, dataLen); +} } // DistributedHardware } // OHOS \ No newline at end of file -- Gitee From 833c1b7a4e012fafcc25fcf67d2e2eb73f987b5e Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 28 Nov 2024 18:01:23 +0800 Subject: [PATCH 473/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- interfaces/kits/js/src/native_devicemanager_js.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 49a567c47..1307a8092 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -3214,17 +3214,17 @@ napi_value DeviceManagerNapi::Constructor(napi_env env, napi_callback_info info) return nullptr; } - char pkgName[DM_NAPI_BUF_LENGTH] = {0}; + char bundleName[DM_NAPI_BUF_LENGTH] = {0}; size_t typeLen = 0; - napi_get_value_string_utf8(env, argv[0], pkgName, sizeof(pkgName), &typeLen); + napi_get_value_string_utf8(env, argv[0], bundleName, sizeof(bundleName), &typeLen); - LOGI("create DeviceManagerNapi for packageName:%{public}s", pkgName); + LOGI("create DeviceManagerNapi for packageName:%{public}s", GetAnonyString(bundleName).c_str()); DeviceManagerNapi *obj = new DeviceManagerNapi(env, thisVar); if (obj == nullptr) { return nullptr; } - obj->bundleName_ = std::string(pkgName); + obj->bundleName_ = std::string(bundleName); std::lock_guard autoLock(g_deviceManagerMapMutex); g_deviceManagerMap[obj->bundleName_] = obj; napi_status status = napi_wrap( -- Gitee From 4666b274d730a922614cee689d33794aac57323f Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 28 Nov 2024 18:06:28 +0800 Subject: [PATCH 474/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 2 +- test/unittest/UTTest_device_manager_service_impl.cpp | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index af272c572..826cc4f0b 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2221,7 +2221,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_003, testing::ext::Test DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); EXPECT_CALL(*softbusListenerMock_, GetDeviceScreenStatus(_, _)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); - EXPECT_EQ(ret, ERR_DM_FAILED); + EXPECT_(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 35d7cb3e7..96c58d6f4 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -47,9 +47,13 @@ void DeviceManagerServiceImplTest::SetUpTestCase() void DeviceManagerServiceImplTest::TearDownTestCase() { + DmDeviceProfileConnector::dmDeviceProfileConnector = nullptr; deviceProfileConnectorMock_ = nullptr; + DmSoftbusConnector::dmSoftbusConnector = nullptr; softbusConnectorMock_ = nullptr; + DmDmDeviceStateManager::dmDeviceStateManager = nullptr; dmDeviceStateManagerMock_ = nullptr; + DmMineHiChainConnector::dmMineHiChainConnector = nullptr; mineHiChainConnectorMock_ = nullptr; } -- Gitee From 1e3918d5ff83aa4191934dcc88a1018048dda3d7 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 28 Nov 2024 18:07:46 +0800 Subject: [PATCH 475/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 826cc4f0b..af272c572 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2221,7 +2221,7 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceScreenStatus_003, testing::ext::Test DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); EXPECT_CALL(*softbusListenerMock_, GetDeviceScreenStatus(_, _)).WillOnce(Return(ERR_DM_FAILED)); int ret = DeviceManagerService::GetInstance().GetDeviceScreenStatus(pkgName, networkId, screenStatus); - EXPECT_(ret, ERR_DM_FAILED); + EXPECT_EQ(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } -- Gitee From a07f0eb31b673f5d9264d67baf027837ac9f2d96 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 28 Nov 2024 19:46:25 +0800 Subject: [PATCH 476/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 2 ++ .../UTTest_dm_discovery_manager.cpp | 28 --------------- .../UTTest_permission_manager.cpp | 11 ------ .../UTTest_device_manager_impl_three.cpp | 36 ------------------- .../UTTest_device_manager_service_impl.cpp | 2 +- .../UTTest_device_manager_service_three.cpp | 4 +++ .../UTTest_device_manager_service_two.cpp | 2 +- test/unittest/UTTest_dm_pin_holder.cpp | 1 - test/unittest/UTTest_dm_transport.cpp | 2 +- test/unittest/mock/softbus_listener_mock.h | 1 + 10 files changed, 10 insertions(+), 79 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 0af1fa71f..fcd1bf74b 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -19,6 +19,8 @@ #include "dm_device_info.h" #include "deviceprofile_connector.h" +using namespace testing; +using namespace testing::ext; namespace OHOS { namespace DistributedHardware { void DeviceProfileConnectorTest::SetUp() diff --git a/test/commonunittest/UTTest_dm_discovery_manager.cpp b/test/commonunittest/UTTest_dm_discovery_manager.cpp index ffb7bbcae..0026854a0 100644 --- a/test/commonunittest/UTTest_dm_discovery_manager.cpp +++ b/test/commonunittest/UTTest_dm_discovery_manager.cpp @@ -566,34 +566,6 @@ HWTEST_F(DmDiscoveryManagerTest, CheckDiscoveryQueue_003, testing::ext::TestSize int32_t ret = discoveryMgr_->CheckDiscoveryQueue(pkgName); EXPECT_EQ(ret, DM_OK); } - -HWTEST_F(DmDiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) -{ - int32_t userId = 0; - std::string deviceId = "deviceId"; - bool isOnline = false; - int32_t authForm = 1; - std::string pkgName = "pkgName"; - int32_t ret = discoveryMgr_->GetDeviceAclParam(pkgName, userId, deviceId, isOnline, authForm); - EXPECT_EQ(ret, ERR_DM_FAILED); - - std::string callerPkgName = "callerPkgName"; - discoveryMgr_->GetPkgNameAndUserId(pkgName, callerPkgName, userId); -} - -HWTEST_F(DmDiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::string str = discoveryMgr_->AddMultiUserIdentify(pkgName); - EXPECT_EQ(str.empty, false); -} - -HWTEST_F(DmDiscoveryManagerTest, RemoveMultiUserIdentify_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::string str = discoveryMgr_->RemoveMultiUserIdentify(pkgName); - EXPECT_EQ(str.empty, false); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index b1b4d1cef..4e0e13bf8 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -270,17 +270,6 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnSetDnPolicy_001, testing: ret = PermissionManager::GetInstance().CheckProcessNameValidOnSetDnPolicy(processName); ASSERT_TRUE(ret); } - -HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = ""; - bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(); - ASSERT_FALSE(ret); - - pkgName = "ohos.deviceprofile"; - ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(); - ASSERT_TRUE(ret); -} } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 2dfca751f..1facedc64 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -1408,42 +1408,6 @@ HWTEST_F(DeviceManagerImplTest, UnRegisterCredentialAuthStatusCallback_002, test int32_t ret = DeviceManager::GetInstance().UnRegisterCredentialAuthStatusCallback(packName); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } - -HWTEST_F(DeviceManagerImplTest, AddDiscoveryCallback_301, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - std::map discoverParam; - std::shared_ptr callback = nullptr; - uint16_t ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); - ASSERT_EQ(ret, 0); - - discoverParam.insert(std::make_pair(PARAM_KEY_SUBSCRIBE_ID, "0")); - callback = std::make_shared(); - ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); - ASSERT_EQ(ret, 0); - - discoverParam[PARAM_KEY_SUBSCRIBE_ID] = "12"; - ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); - ASSERT_EQ(ret, 12); - - pkgName = "SUBSCRIBE_ID"; - std::string key = "SUBSCRIBE_ID#12"; - DeviceManager::GetInstance().pkgName2SubIdMap_[key] = 1; - ret = DeviceManager::GetInstance().AddDiscoveryCallback(pkgName, discoverParam, callback); - ASSERT_EQ(ret, 1); -} - -HWTEST_F(DeviceManagerImplTest, GetSubscribeIdFromMap_301, testing::ext::TestSize.Level0) -{ - std::string pkgName = "pkgName"; - DeviceManager::GetInstance().pkgName2SubIdMap_[pkgName] = 6; - uint16_t ret = DeviceManager::GetInstance().GetSubscribeIdFromMap(pkgName); - ASSERT_EQ(ret, 6); - - pkgName = "pkgName_301"; - ret = DeviceManager::GetInstance().GetSubscribeIdFromMap(pkgName); - ASSERT_EQ(ret, 0); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 96c58d6f4..2c779d705 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1836,7 +1836,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); std::vector foregroundUserIds; - std::vector &backgroundUserIds; + std::vector backgroundUserIds; std::string remoteUdid = "deviceId"; deviceManagerServiceImpl_->HandleSyncUserIdEvent(foregroundUserIds, backgroundUserIds, remoteUdid); diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 9ff7cde5d..62fb618fa 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -72,9 +72,13 @@ void DeviceManagerServiceThreeTest::SetUpTestCase() void DeviceManagerServiceThreeTest::TearDownTestCase() { + DmDeviceManagerService::dmDeviceManagerService = nullptr; deviceManagerServiceMock_ = nullptr; + DmPermissionManager::dmPermissionManager = nullptr; permissionManagerMock_ = nullptr; + DmSoftbusListener::dmSoftbusListener = nullptr; softbusListenerMock_ = nullptr; + DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = nullptr; deviceManagerServiceImplMock_ = nullptr; } diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index fb96d790a..be155650c 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -599,7 +599,7 @@ HWTEST_F(DeviceManagerServiceTest, BindDevice_205, testing::ext::TestSize.Level0 ProcessInfo processInfo; processInfo.pkgName = "pkgName"; - if (DeviceManagerService::GetInstance().discoveryMgr_ == nullptr){ + if (DeviceManagerService::GetInstance().discoveryMgr_ == nullptr) { DeviceManagerService::GetInstance().InitDMServiceListener(); } DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index 259ac9eaa..45268bfc9 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -801,7 +801,6 @@ HWTEST_F(DmPinHolderTest, SendData_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); pinHolder->session_ = nullptr; - std::string message; pinHolder->ProcessChangeMsg(message); message = R"( diff --git a/test/unittest/UTTest_dm_transport.cpp b/test/unittest/UTTest_dm_transport.cpp index e4768eaa1..b32c0f921 100644 --- a/test/unittest/UTTest_dm_transport.cpp +++ b/test/unittest/UTTest_dm_transport.cpp @@ -210,7 +210,7 @@ HWTEST_F(DMTransportTest, OnSocketOpened_001, testing::ext::TestSize.Level0) int32_t ret = dmTransport.OnSocketOpened(socketId, info); EXPECT_EQ(ret, DM_OK); - ShutdownReason reason; + ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; dmTransport.remoteDevSocketIds_["socketId"] = socketId; dmTransport.OnSocketClosed(socketId, reason); diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h index c43a9f706..10d7cacc1 100644 --- a/test/unittest/mock/softbus_listener_mock.h +++ b/test/unittest/mock/softbus_listener_mock.h @@ -52,6 +52,7 @@ public: MOCK_METHOD(int32_t, GetTrustedDeviceList, (std::vector &)); MOCK_METHOD(int32_t, GetLocalDeviceInfo, (DmDeviceInfo &)); MOCK_METHOD(int32_t, SetLocalDeviceName, (const std::string &, const std::string &)); + MOCK_METHOD(int32_t, GetDeviceScreenStatus, (const char *, int32_t)); }; } } -- Gitee From 10ea6b2479e2b191eaf048966de18ceb7d2a1ad5 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 29 Nov 2024 09:15:01 +0800 Subject: [PATCH 477/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/mock/device_manager_service_impl_mock.cpp | 2 +- test/unittest/mock/softbus_listener_mock.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp index e40912bbf..da795a8b1 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.cpp +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -53,7 +53,7 @@ std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList(std::string pkgname) { - DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetAppTrustDeviceIdList(pkgname); + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetAppTrustDeviceIdList(pkgname); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h index 10d7cacc1..49a358357 100644 --- a/test/unittest/mock/softbus_listener_mock.h +++ b/test/unittest/mock/softbus_listener_mock.h @@ -52,7 +52,7 @@ public: MOCK_METHOD(int32_t, GetTrustedDeviceList, (std::vector &)); MOCK_METHOD(int32_t, GetLocalDeviceInfo, (DmDeviceInfo &)); MOCK_METHOD(int32_t, SetLocalDeviceName, (const std::string &, const std::string &)); - MOCK_METHOD(int32_t, GetDeviceScreenStatus, (const char *, int32_t)); + MOCK_METHOD(int32_t, GetDeviceScreenStatus, (const char *, int32_t &)); }; } } -- Gitee From fce5f208878af0f61a560ccc837249c2c2fb8c4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 29 Nov 2024 09:31:14 +0800 Subject: [PATCH 478/520] =?UTF-8?q?=E9=BB=84=E8=93=9D=E5=B7=AE=E5=BC=82?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/src/ipc/lite/ipc_server_listenermgr.cpp | 2 +- services/service/src/ipc/standard/ipc_server_stub.cpp | 2 +- services/service/src/softbus/softbus_listener.cpp | 5 ++++- utils/include/appInfo/lite/app_manager.h | 2 +- utils/include/fwkload/lite/dm_distributed_hardware_load.h | 2 +- .../include/fwkload/standard/dm_distributed_hardware_load.h | 2 +- utils/src/appInfo/lite/app_manager.cpp | 2 +- utils/src/appInfo/standard/app_manager.cpp | 2 +- utils/src/fwkload/lite/dm_distributed_hardware_load.cpp | 2 +- utils/src/fwkload/standard/dm_distributed_hardware_load.cpp | 2 +- 10 files changed, 13 insertions(+), 10 deletions(-) diff --git a/services/service/src/ipc/lite/ipc_server_listenermgr.cpp b/services/service/src/ipc/lite/ipc_server_listenermgr.cpp index a7f1e1d17..36bf2276c 100644 --- a/services/service/src/ipc/lite/ipc_server_listenermgr.cpp +++ b/services/service/src/ipc/lite/ipc_server_listenermgr.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index a93471ac2..544382ac5 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 6bff7e5f8..9074a2ce6 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -770,7 +770,10 @@ int32_t SoftbusListener::ConvertScreenStatusToDmDevice(const NodeBasicInfo &node int32_t SoftbusListener::ConvertNodeBasicInfoToDmDevice(const NodeBasicInfo &nodeInfo, DmDeviceInfo &devInfo) { LOGI("Begin, osType : %{public}d", nodeInfo.osType); - (void)memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)); + if (memset_s(&devInfo, sizeof(DmDeviceInfo), 0, sizeof(DmDeviceInfo)) != EOK) { + LOGE("ConvertNodeBasicInfoToDmDevice memset_s failed."); + return ERR_DM_FAILED; + } if (memcpy_s(devInfo.networkId, sizeof(devInfo.networkId), nodeInfo.networkId, std::min(sizeof(devInfo.networkId), sizeof(nodeInfo.networkId))) != EOK) { LOGE("ConvertNodeBasicInfoToDmDevice copy networkId data failed."); diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index 83e94626a..52dc07f81 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/include/fwkload/lite/dm_distributed_hardware_load.h b/utils/include/fwkload/lite/dm_distributed_hardware_load.h index 44dae82cf..2a72782bc 100644 --- a/utils/include/fwkload/lite/dm_distributed_hardware_load.h +++ b/utils/include/fwkload/lite/dm_distributed_hardware_load.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/include/fwkload/standard/dm_distributed_hardware_load.h b/utils/include/fwkload/standard/dm_distributed_hardware_load.h index 21f5983a2..a6c0e5e25 100644 --- a/utils/include/fwkload/standard/dm_distributed_hardware_load.h +++ b/utils/include/fwkload/standard/dm_distributed_hardware_load.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index c313d90a9..fd2aeb768 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 2f4762c6f..11d857f3a 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp b/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp index fbcc8c50b..ba998b296 100644 --- a/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp +++ b/utils/src/fwkload/lite/dm_distributed_hardware_load.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp b/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp index 163334f12..b7c7499e5 100644 --- a/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp +++ b/utils/src/fwkload/standard/dm_distributed_hardware_load.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From 9f05cbd9f464deda32c6fe4729380c658beb578d Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 29 Nov 2024 11:53:02 +0800 Subject: [PATCH 479/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/BUILD.gn | 3 +++ test/unittest/UTTest_device_manager_service.cpp | 6 ++++++ test/unittest/UTTest_dm_comm_tool.cpp | 3 +++ test/unittest/UTTest_dm_transport.cpp | 9 --------- test/unittest/mock/dm_crypto_mock.cpp | 6 ++++++ test/unittest/mock/dm_crypto_mock.h | 3 +++ 6 files changed, 21 insertions(+), 9 deletions(-) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 20a7e4e11..2e978218c 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -332,6 +332,7 @@ ohos_unittest("UTTest_device_manager_service") { "UTTest_device_manager_service_two.cpp", "mock/app_manager_mock.cpp", "mock/device_manager_service_impl_mock.cpp", + "mock/dm_crypto_mock.cpp", "mock/dm_softbus_cache_mock.cpp", "mock/kv_adapter_manager_mock.cpp", "mock/permission_manager_mock.cpp", @@ -1304,6 +1305,7 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp", "${devicemanager_path}/test/unittest/mock/mock_distributed_device_profile_client.cpp", + "${devicemanager_path}/test/unittest/mock/dm_crypto_mock.cpp", ] deps = [ ":device_manager_test_common" ] @@ -1313,6 +1315,7 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", "googletest:gmock", + "googletest:gmock_main", ] } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index af272c572..0db77c73d 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2535,8 +2535,14 @@ HWTEST_F(DeviceManagerServiceTest, ConvertUdidHashToAnoyDeviceId_001, testing::e EXPECT_EQ(ret, ERR_DM_FAILED); EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); + EXPECT_CALL(*cryptoMock_, ConvertUdidHashToAnoyAndSave(_, _, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*appManagerMock_, GetAppId()).WillOnce(Return("appId")); + EXPECT_CALL(*cryptoMock_, ConvertUdidHashToAnoyAndSave(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().ConvertUdidHashToAnoyDeviceId(udidHash, result); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DeviceManagerServiceTest, GetUdidHashByAnoyDeviceId_001, testing::ext::TestSize.Level0) diff --git a/test/unittest/UTTest_dm_comm_tool.cpp b/test/unittest/UTTest_dm_comm_tool.cpp index e960ba9d9..f188c455b 100644 --- a/test/unittest/UTTest_dm_comm_tool.cpp +++ b/test/unittest/UTTest_dm_comm_tool.cpp @@ -50,6 +50,9 @@ HWTEST_F(DMCommToolTest, GetDMTransportPtr_NotNull, testing::ext::TestSize.Level { auto transportPtr = dmCommTool->GetDMTransportPtr(); EXPECT_NE(transportPtr, nullptr); + + AppExecFwk::InnerEvent::Pointer event; + dmCommTool->ProcessEvent(event); } } // DistributedHardware } // OHOS \ No newline at end of file diff --git a/test/unittest/UTTest_dm_transport.cpp b/test/unittest/UTTest_dm_transport.cpp index b32c0f921..5489c7428 100644 --- a/test/unittest/UTTest_dm_transport.cpp +++ b/test/unittest/UTTest_dm_transport.cpp @@ -213,15 +213,6 @@ HWTEST_F(DMTransportTest, OnSocketOpened_001, testing::ext::TestSize.Level0) ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; dmTransport.remoteDevSocketIds_["socketId"] = socketId; dmTransport.OnSocketClosed(socketId, reason); - - int32_t value = 1; - void *data = &value; - uint32_t dataLen = 1; - socketId = -1; - dmTransport.OnBytesReceived(socketId, data, dataLen); - - socketId = 1; - dmTransport.OnBytesReceived(socketId, data, dataLen); } } // DistributedHardware } // OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_crypto_mock.cpp b/test/unittest/mock/dm_crypto_mock.cpp index 037f28533..c3bbe8541 100644 --- a/test/unittest/mock/dm_crypto_mock.cpp +++ b/test/unittest/mock/dm_crypto_mock.cpp @@ -24,5 +24,11 @@ int32_t Crypto::GetAccountIdHash(const std::string &accountId, unsigned char *ac { return DmCrypto::dmCrypto->GetAccountIdHash(accountId, accountIdHash); } + +int32_t Crypto::ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) +{ + return DmCrypto::dmCrypto->ConvertUdidHashToAnoyAndSave(appId, udidHash, kvValue); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_crypto_mock.h b/test/unittest/mock/dm_crypto_mock.h index 4958f476f..c0fd67123 100644 --- a/test/unittest/mock/dm_crypto_mock.h +++ b/test/unittest/mock/dm_crypto_mock.h @@ -27,6 +27,8 @@ public: virtual ~DmCrypto() = default; public: virtual int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) = 0; + virtual int32_t ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, + DmKVValue &kvValue) = 0; public: static inline std::shared_ptr dmCrypto = nullptr; }; @@ -34,6 +36,7 @@ public: class CryptoMock : public DmCrypto { public: MOCK_METHOD(int32_t, GetAccountIdHash, (const std::string &, unsigned char *)); + MOCK_METHOD(int32_t, ConvertUdidHashToAnoyAndSave, (const std::string &, const std::string &, DmKVValue &)); }; } } -- Gitee From 88e32452523cd93aca7b4fad5c8627dbf5374896 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 29 Nov 2024 12:43:43 +0800 Subject: [PATCH 480/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/BUILD.gn | 2 +- test/unittest/UTTest_dm_comm_tool.cpp | 3 --- test/unittest/mock/dm_crypto_mock.cpp | 1 - 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 2e978218c..14db6b322 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1304,8 +1304,8 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp", - "${devicemanager_path}/test/unittest/mock/mock_distributed_device_profile_client.cpp", "${devicemanager_path}/test/unittest/mock/dm_crypto_mock.cpp", + "${devicemanager_path}/test/unittest/mock/mock_distributed_device_profile_client.cpp", ] deps = [ ":device_manager_test_common" ] diff --git a/test/unittest/UTTest_dm_comm_tool.cpp b/test/unittest/UTTest_dm_comm_tool.cpp index f188c455b..e960ba9d9 100644 --- a/test/unittest/UTTest_dm_comm_tool.cpp +++ b/test/unittest/UTTest_dm_comm_tool.cpp @@ -50,9 +50,6 @@ HWTEST_F(DMCommToolTest, GetDMTransportPtr_NotNull, testing::ext::TestSize.Level { auto transportPtr = dmCommTool->GetDMTransportPtr(); EXPECT_NE(transportPtr, nullptr); - - AppExecFwk::InnerEvent::Pointer event; - dmCommTool->ProcessEvent(event); } } // DistributedHardware } // OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_crypto_mock.cpp b/test/unittest/mock/dm_crypto_mock.cpp index c3bbe8541..6baeadd1b 100644 --- a/test/unittest/mock/dm_crypto_mock.cpp +++ b/test/unittest/mock/dm_crypto_mock.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace DistributedHardware { -DM_IMPLEMENT_SINGLE_INSTANCE(AppManager); int32_t Crypto::GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) { return DmCrypto::dmCrypto->GetAccountIdHash(accountId, accountIdHash); -- Gitee From 5b55bfa0a0cf3bea9e4540126b6620f8f6a55e03 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 29 Nov 2024 13:42:32 +0800 Subject: [PATCH 481/520] =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E6=97=B6=E9=98=B2=E6=AD=A2=E8=A2=AB=E6=9E=90=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- services/implementation/src/authentication/dm_auth_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index cc6e5bfa4..224680036 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1299,6 +1299,7 @@ void DmAuthManager::AuthenticateFinish() authResponseContext_ = nullptr; authMessageProcessor_ = nullptr; authPtr_ = nullptr; + authRequestStateTemp_ = nullptr; LOGI("DmAuthManager::AuthenticateFinish complete"); } -- Gitee From 4d3038a6ecd7e85f2b881c01aa41bbd5d360edf0 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 29 Nov 2024 14:05:01 +0800 Subject: [PATCH 482/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service_two.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index be155650c..9e35f86a2 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -672,7 +672,8 @@ HWTEST_F(DeviceManagerServiceTest, RegDevStateCallbackToService_201, testing::ex EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>(""), Return(DM_OK))); DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); - EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))) + .WillOnce(DoAll(SetArgReferee<1>("udid01"), Return(DM_OK))); DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); msgJsonObj["discoverType"] = 1; -- Gitee From acc6a30c1fd412f358c2babbd674632b644c09ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 29 Nov 2024 15:30:45 +0800 Subject: [PATCH 483/520] =?UTF-8?q?json=20dump=E5=87=BD=E6=95=B0=E5=BF=BD?= =?UTF-8?q?=E7=95=A5=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- common/src/dm_anonymous.cpp | 2 +- .../native_cpp/src/device_manager_impl.cpp | 4 +- .../kits/js/src/native_devicemanager_js.cpp | 4 +- interfaces/kits/js4.0/src/dm_native_util.cpp | 4 +- .../ability/standard/dm_dialog_manager.cpp | 2 +- .../authentication/auth_message_processor.cpp | 8 ++-- .../authentication/auth_ui_state_manager.cpp | 2 +- .../src/authentication/dm_auth_manager.cpp | 22 +++++----- .../src/credential/dm_credential_manager.cpp | 4 +- .../hichain/hichain_auth_connector.cpp | 17 ++++---- .../dependency/hichain/hichain_connector.cpp | 40 ++++++++++--------- .../hichain/mine_hichain_connector.cpp | 4 +- .../dependency/softbus/softbus_connector.cpp | 8 ++-- services/service/src/pinholder/pin_holder.cpp | 28 ++++++------- .../service/src/softbus/softbus_listener.cpp | 4 +- .../hichain_connector_fuzzer.cpp | 6 +-- .../UTTest_discovery_filter.cpp | 30 +++++++------- .../UTTest_dm_auth_manager_first.cpp | 12 +++--- .../UTTest_dm_auth_manager_second.cpp | 19 ++++----- .../UTTest_dm_auth_manager_third.cpp | 16 ++++---- .../UTTest_dm_credential_manager.cpp | 16 ++++---- .../UTTest_dm_discovery_filter.cpp | 30 +++++++------- .../UTTest_hichain_auth_connector.cpp | 14 +++---- .../UTTest_hichain_connector.cpp | 10 ++--- .../UTTest_mine_hichain_connector.cpp | 8 ++-- test/commonunittest/UTTest_pin_auth.cpp | 6 +-- .../UTTest_mine_softbus_listener.cpp | 10 ++--- .../UTTest_softbus_session.cpp | 2 +- .../UTTest_auth_message_processor.cpp | 19 ++++----- test/unittest/UTTest_dm_pin_holder.cpp | 30 +++++++------- .../UTTest_ipc_cmd_parser_service.cpp | 4 +- utils/src/kvadapter/dm_kv_info.cpp | 2 +- 32 files changed, 196 insertions(+), 191 deletions(-) diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index a421a8a74..8ee7b0bb4 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -184,7 +184,7 @@ std::string ConvertMapToJsonString(const std::map &par for (const auto &it : paramMap) { jsonObj[it.first] = it.second; } - jsonStr = jsonObj.dump(); + jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } return jsonStr; } 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 49a3a621a..5b019a873 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -674,7 +674,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetExtra(extraJson.dump()); + req->SetExtra(extraJson.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); @@ -1493,7 +1493,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetBindParam(paramJson.dump()); + req->SetBindParam(paramJson.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); req->SetBindType(bindType); req->SetDeviceId(deviceId); int32_t ret = ipcClientProxy_->SendRequest(BIND_DEVICE, req, rsp); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 1307a8092..8ee6aaaa1 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1203,7 +1203,7 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr; jsonObj[BIND_LEVEL] = bindLevel; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(); + extra = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("appOperationLen %{public}zu, customDescriptionLen %{public}zu", appOperationStr.size(), customDescriptionStr.size()); } @@ -1274,7 +1274,7 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob jsonObj[AUTH_TYPE] = authType; jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(); + extra = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } void DeviceManagerNapi::JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index 414c2fe8a..97c6e384e 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -330,7 +330,7 @@ void JsToBindParam(const napi_env &env, const napi_value &object, std::string &b jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP); jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort; jsonObj[BIND_LEVEL] = bindLevel; - bindParam = jsonObj.dump(); + bindParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } bool IsSystemApp() @@ -395,7 +395,7 @@ void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::st if (deviceType != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) { jsonObj["deviceType"] = deviceType; } - extra = jsonObj.dump(); + extra = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("JsToDmDiscoveryExtra, extra :%{public}s", extra.c_str()); } diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 7b6912134..dbb2cb4ee 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -202,7 +202,7 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = param.dump(); + std::string paramStr = param.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 26ab14c88..98decdb71 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -87,7 +87,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1; jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; GetJsonObj(jsonObj); - jsonStrVec.push_back(jsonObj.dump()); + jsonStrVec.push_back(jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); for (int32_t idx = 0; idx < thumbnailSlice; idx++) { nlohmann::json jsonThumbnailObj; jsonThumbnailObj[TAG_VER] = DM_ITF_VER; @@ -101,7 +101,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() LOGI("TAG_APP_THUMBNAIL encode, idx %{public}d, sliceLen %{public}d, thumbnailSize %{public}d", idx, (uint32_t)sliceLen, thumbnailSize); jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); - jsonStrVec.push_back(jsonThumbnailObj.dump()); + jsonStrVec.push_back(jsonThumbnailObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); } return jsonStrVec; } @@ -138,7 +138,7 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) default: break; } - return jsonObj.dump(); + return jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } void AuthMessageProcessor::CreatePublicKeyMessageExt(nlohmann::json &json) @@ -593,7 +593,7 @@ std::string AuthMessageProcessor::CreateDeviceAuthMessage(int32_t msgType, const std::string authDataStr = std::string(reinterpret_cast(data), dataLen); jsonObj[TAG_DATA] = authDataStr; jsonObj[TAG_DATA_LEN] = dataLen; - return jsonObj.dump(); + return jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index d338980d7..a9781bc45 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -61,7 +61,7 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) } nlohmann::json jsonObj; jsonObj[UI_STATE_MSG] = msg; - std::string paramJson = jsonObj.dump(); + std::string paramJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::lock_guard lock(pkgSetMutex_); for (auto item : pkgSet_) { listener_->OnUiCall(item, paramJson); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 651ddc55e..b030d9e4f 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -612,7 +612,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId jsonObj[PIN_TOKEN] = authResponseContext_->token; jsonObj[QR_CODE_KEY] = GenerateGroupName(); jsonObj[NFC_CODE_KEY] = GenerateGroupName(); - authResponseContext_->authToken = jsonObj.dump(); + authResponseContext_->authToken = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); authResponseContext_->groupId = groupId; authResponseContext_->code = pinCode; @@ -1179,7 +1179,7 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) jsonObject[PIN_CODE_KEY] = pinCode; jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; - std::string connectInfo = jsonObject.dump(); + std::string connectInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); if (timer_ != nullptr) { timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { @@ -1441,7 +1441,7 @@ void DmAuthManager::ShowConfigDialog() jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; - const std::string params = jsonObj.dump(); + const std::string params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); @@ -1478,7 +1478,7 @@ void DmAuthManager::ShowAuthInfoDialog() } nlohmann::json jsonObj; jsonObj[PIN_CODE_KEY] = authResponseContext_->code; - std::string authParam = jsonObj.dump(); + std::string authParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); } @@ -1650,7 +1650,7 @@ bool DmAuthManager::IsIdenticalAccount() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(); + std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1690,7 +1690,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(); + std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1705,7 +1705,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() for (auto &groupInfo : groupList) { jsonAccountObj.push_back(Crypto::GetGroupIdHash(groupInfo.groupId)); } - return jsonAccountObj.dump(); + return jsonAccountObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) @@ -1893,7 +1893,7 @@ std::string DmAuthManager::GenerateBindResultContent() Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); jsonObj[TAG_DEVICE_ID] = deviceIdHash; } - std::string content = jsonObj.dump(); + std::string content = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return content; } @@ -2235,7 +2235,7 @@ void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) } } jsonObject[TAG_CRYPTO_SUPPORT] = false; - message = jsonObject.dump(); + message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2246,7 +2246,7 @@ void DmAuthManager::ProcIncompatible(const int32_t &sessionId) respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; respNegotiateMsg[TAG_VER] = DM_ITF_VER; respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; - std::string message = respNegotiateMsg.dump(); + std::string message = respNegotiateMsg.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2374,7 +2374,7 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); nlohmann::json jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = jsonObj.dump(); + std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 274de3be8..fb0deca57 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -113,7 +113,7 @@ int32_t DmCredentialManager::RequestCredential(const std::string &reqJsonStr, st jsonObj[FIELD_CREDENTIAL_VERSION] = credentialVersion; jsonObj[FIELD_USER_ID] = userId; jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string tmpStr = jsonObj.dump(); + std::string tmpStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return hiChainConnector_->getRegisterInfo(tmpStr.c_str(), returnJsonStr); } @@ -364,7 +364,7 @@ void from_json(const nlohmann::json &jsonObject, CredentialDataInfo &credentialD } if (IsString(jsonObject, FIELD_PKINFO)) { nlohmann::json jsonPkInfo = jsonObject[FIELD_PKINFO]; - credentialDataInfo.pkInfo = jsonPkInfo.dump(); + credentialDataInfo.pkInfo = jsonPkInfo.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } } else if (credentialDataInfo.credentialType == SYMMETRY_CREDENTIAL_TYPE) { if (IsString(jsonObject, FIELD_AUTH_CODE)) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 427b94a36..0be0ea90d 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -56,7 +56,7 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s authParamJson["osAccountId"] = osAccountId; authParamJson["pinCode"] = std::to_string(pinCode); authParamJson["acquireType"] = AcquireType::P2P_BIND; - std::string authParam = authParamJson.dump(); + std::string authParam = authParamJson.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("StartAuthDevice authParam %{public}s ,requestId %{public}" PRId64, GetAnonyString(authParam).c_str(), requestId); int32_t ret = StartAuthDevice(requestId, authParam.c_str(), &deviceAuthCallback_); @@ -73,7 +73,8 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut nlohmann::json jsonAuthParam; jsonAuthParam["osAccountId"] = osAccountId; jsonAuthParam["data"] = authData; - int32_t ret = ProcessAuthDevice(requestId, jsonAuthParam.dump().c_str(), &deviceAuthCallback_); + int32_t ret = ProcessAuthDevice(requestId, + jsonAuthParam.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore).c_str(), &deviceAuthCallback_); if (ret != HC_SUCCESS) { LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; @@ -111,7 +112,7 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -159,7 +160,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char *returnData = nullptr; if (ProcessCredential(CRED_OP_CREATE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain generate credential failed."); @@ -192,7 +193,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -223,7 +224,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -255,7 +256,7 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; - std::string requestParam = jsonObj.dump(); + std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char *returnData = nullptr; if (ProcessCredential(CRED_OP_IMPORT, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -286,7 +287,7 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; - std::string requestParam = jsonObj.dump(); + std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 7e2ae818c..360763800 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -154,7 +154,8 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); + int32_t ret = deviceGroupManager_->createGroup(userId, requestId, + DM_PKG_NAME, jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore).c_str()); struct RadarInfo info = { .funcName = "CreateGroup", .toCallPkg = HICHAINNAME, @@ -178,7 +179,7 @@ bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInf { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(); + std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::vector groupList; if (GetGroupInfo(queryParams, groupList)) { groupInfo = groupList[0]; @@ -191,7 +192,7 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(); + std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -343,7 +344,7 @@ int32_t HiChainConnector::AddMember(const std::string &deviceId, const std::stri jsonObj[FIELD_DEVICE_ID] = localDeviceId; jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME].get(); jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str(); - std::string tmpStr = jsonObj.dump(); + std::string tmpStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int64_t requestId = jsonObject[TAG_REQUEST_ID].get(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { @@ -486,7 +487,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -511,7 +512,7 @@ std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string r } jsonObject[DEVICE_ID] = reqDeviceId; - return jsonObject.dump(); + return jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vector &groupList) @@ -602,7 +603,7 @@ int32_t HiChainConnector::DelMemberFromGroup(const std::string &groupId, const s nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_DELETE_ID] = deviceId; - std::string deleteParams = jsonObj.dump(); + std::string deleteParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -621,7 +622,7 @@ int32_t HiChainConnector::DeleteGroup(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -641,7 +642,7 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -661,7 +662,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use networkStyle_ = CREDENTIAL_NETWORK; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(); + std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::vector groupList; if (!GetGroupInfo(queryParams, groupList)) { LOGE("failed to get device join groups"); @@ -682,7 +683,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use return ERR_DM_FAILED; } jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_deleteGroupFlag = false; int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -791,7 +792,8 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); + int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, + jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore).c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); return ERR_DM_CREATE_GROUP_FAILED; @@ -841,7 +843,7 @@ int32_t HiChainConnector::GetGroupId(const std::string &userId, const int32_t gr { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(); + std::string queryParams = jsonObjGroup.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -874,7 +876,7 @@ int32_t HiChainConnector::ParseRemoteCredential(const int32_t groupType, const s jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = groupType; jsonObj[FIELD_DEVICE_LIST] = jsonDeviceList[FIELD_DEVICE_LIST]; - params = jsonObj.dump(); + params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { LOGE("get current process account user id failed"); @@ -928,7 +930,7 @@ int32_t HiChainConnector::GetGroupIdExt(const std::string &userId, const int32_t { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(); + std::string queryParams = jsonObjGroup.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -982,7 +984,7 @@ int32_t HiChainConnector::ParseRemoteCredentialExt(const std::string &credential return ERR_DM_FAILED; } jsonObj[FIELD_DEVICE_LIST] = jsonObject[FIELD_DEVICE_LIST]; - params = jsonObj.dump(); + params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return DM_OK; } @@ -1157,7 +1159,7 @@ int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); if (ret != 0) { LOGE("[HICHAIN]fail to delete group with ret:%{public}d.", ret); @@ -1236,7 +1238,7 @@ void HiChainConnector::DeleteP2PGroup(int32_t switchUserId) LOGI("switchuserId: %{public}d", switchUserId); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - std::string queryParams = jsonObj.dump(); + std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::vector groupList; if (!GetGroupInfo(switchUserId, queryParams, groupList)) { @@ -1275,7 +1277,7 @@ int32_t HiChainConnector::DeleteGroupByACL(std::vector groupList; if (!GetGroupInfo(userId, queryParams, groupList)) { diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index c5d37fd50..66ababfd1 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -135,7 +135,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) { nlohmann::json jsonObj; jsonObj[FIELD_IS_DELETE_ALL] = true; - std::string params = jsonObj.dump(); + std::string params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); #if (defined(MINE_HARMONY)) char *returnInfo = nullptr; int32_t retValue = g_deviceGroupManager->processCredential(DELETE_SELF_CREDENTIAL, params.c_str(), &returnInfo); @@ -173,7 +173,7 @@ int32_t MineHiChainConnector::CreateGroup(const std::string &reqJsonStr) jsonObj[FIELD_GROUP_NAME] = DEVICE_MANAGER_GROUPNAME; jsonObj[FIELD_DEVICE_ID] = std::string(deviceUdid); jsonObj[FIELD_GROUP_TYPE] = IDENTICAL_ACCOUNT_GROUP; - std::string createParams = jsonObj.dump(); + std::string createParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); retValue = g_deviceGroupManager->createGroup(DEFAULT_OS_ACCOUNT, requestId, DM_PKG_NAME, createParams.c_str()); if (retValue != HC_SUCCESS) { LOGE("failed to create group with ret:%{public}d.", retValue); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 2f1124e40..5736d7cbf 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -341,7 +341,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = jsonPara.dump(); + connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); @@ -349,20 +349,20 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(); + connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(); + connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = jsonPara.dump(); + connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return addr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index cb90b50a5..f7fac0c09 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -177,7 +177,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget jsonObj[TAG_PIN_TYPE] = pinType; jsonObj[TAG_PAYLOAD] = payload; pinType_ = pinType; - std::string message = jsonObj.dump(); + std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("DestroyPinHolder, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER, pinType); ret = session_->SendData(sessionId_, message); @@ -210,7 +210,7 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() jsonObj[TAG_PAYLOAD] = payload_; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; jsonObj[TAG_DM_VERSION] = ""; - std::string message = jsonObj.dump(); + std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("CreateGeneratePinHolderMsg, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER, pinType_); int32_t ret = session_->SendData(sessionId_, message); @@ -288,12 +288,12 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; - std::string content = jsonContent.dump(); + std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; - std::string msg = jsonObj.dump(); + std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("ProcessCreateMsg, message type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -368,13 +368,13 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); + std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); isDestroy_.store(true); } } - std::string msg = jsonObj.dump(); + std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("ProcessDestroyMsg, message type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -392,13 +392,13 @@ void PinHolder::CloseSession(const std::string &name) } nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(); + std::string payload = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); + std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); isDestroy_.store(true); } @@ -455,7 +455,7 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) LOGE("another session opened, close this sessionId: %{public}d.", sessionId); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; - std::string msg = jsonObj.dump(); + std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = session_->SendData(sessionId, msg); if (ret != DM_OK) { LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); @@ -557,13 +557,13 @@ void PinHolder::OnSessionClosed(int32_t sessionId) isRemoteSupported_ = false; nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(); + std::string payload = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); + std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); if (destroyState_ == STATE_UNKNOW) { listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); } else if (destroyState_ == STATE_REMOTE_WRONG) { @@ -621,7 +621,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; jsonObj[TAG_PIN_TYPE] = pinType; - std::string message = jsonObj.dump(); + std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("NotifyPinHolderEvent, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE, pinType); int32_t ret = session_->SendData(sessionId_, message); @@ -658,7 +658,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; - std::string content = jsonContent.dump(); + std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); timer_->DeleteAll(); timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, @@ -667,7 +667,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) }); } - std::string msg = jsonObj.dump(); + std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); LOGI("ProcessChangeMsg, message type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 946c420ee..0afd82fe9 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -869,7 +869,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe const ConnectionAddr *addrInfo = &(device.addr)[0]; if (addrInfo == nullptr) { LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); - dmDevice.extraData = jsonObj.dump(); + dmDevice.extraData = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); return; } jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; @@ -897,7 +897,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } - dmDevice.extraData = jsonObj.dump(); + dmDevice.extraData = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index dce86d574..e5591e7f4 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -315,13 +315,13 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObj[key] = 1; jsonObj["deviceName"] = "devieName1"; hichainConnector->GetJsonInt(jsonObj, "devieName"); - hichainConnector->AddMember(deviceId, jsonObj.dump()); + hichainConnector->AddMember(deviceId, jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); jsonObj[TAG_DEVICE_ID] = "deviceId_001"; jsonObj[PIN_CODE_KEY] = 1; jsonObj[TAG_GROUP_ID] = "groupId"; jsonObj[TAG_REQUEST_ID] = 1; jsonObj[TAG_GROUP_NAME] = "groupName"; - hichainConnector->AddMember(deviceId, jsonObj.dump()); + hichainConnector->AddMember(deviceId, jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); nlohmann::json jsonObjCre; std::string params; @@ -331,7 +331,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObjCre[FIELD_OPERATION_CODE] = 1; jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; - std::string credentialInfo = jsonObjCre.dump(); + std::string credentialInfo = jsonObjCre.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); int32_t groupType = *(reinterpret_cast(data)); nlohmann::json jsonDeviceList; diff --git a/test/commonunittest/UTTest_discovery_filter.cpp b/test/commonunittest/UTTest_discovery_filter.cpp index 092d38f22..ff64c3cf2 100644 --- a/test/commonunittest/UTTest_discovery_filter.cpp +++ b/test/commonunittest/UTTest_discovery_filter.cpp @@ -45,7 +45,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Level0 { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -55,7 +55,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Level0 DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -66,7 +66,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Level0 nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -77,7 +77,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Level0 nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -89,7 +89,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -101,7 +101,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -116,7 +116,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -132,7 +132,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -148,7 +148,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Level myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -165,7 +165,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSize. { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -175,7 +175,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSize. DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -186,7 +186,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -198,7 +198,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSize. jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -211,7 +211,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -224,7 +224,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 3b80ab38c..62341d8a2 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1075,7 +1075,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived002, testing::ext::TestSize. int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_DATA] = 123; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1086,7 +1086,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived003, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = "123"; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1098,7 +1098,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived004, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = "123"; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1110,7 +1110,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived005, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = 123; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1335,7 +1335,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - extra = jsonObject.dump(); + extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1345,7 +1345,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); jsonObject["bindLevel"] = 15; - extra = jsonObject.dump(); + extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 9561e1df7..93108e78d 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -108,7 +108,7 @@ HWTEST_F(DmAuthManagerTest, OnDataReceived_007, testing::ext::TestSize.Level0) int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); authManager_->OnDataReceived(sessionId, message); authManager_->authRequestState_ = nullptr; authManager_->authResponseState_ = nullptr; @@ -1322,7 +1322,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; jsonObject["targetPkgName"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1335,7 +1335,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_003, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1349,7 +1349,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_004, testing::ext::TestSize.Level0) jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1364,7 +1364,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_005, testing::ext::TestSize.Level0) jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1380,7 +1380,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_006, testing::ext::TestSize.Level0) jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = "1234"; - std::string extra = jsonObject.dump(); + std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1397,7 +1397,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_007, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = "1234"; - std::string extra = jsonObject.dump(); + std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1414,7 +1414,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_008, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1508,7 +1508,8 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level nlohmann::json jsonPeerGroupIdObj; jsonPeerGroupIdObj["groupId"] = "123456"; - authManager_->authResponseContext_->accountGroupIdHash = jsonPeerGroupIdObj.dump(); + authManager_->authResponseContext_->accountGroupIdHash = + jsonPeerGroupIdObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index e760738ff..cf7c2f95e 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -141,13 +141,13 @@ void DmAuthManagerTest::TearDownTestCase() {} HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t sessionId = 0; authManager_->remoteDeviceId_ = "ProcRespNegotiate001"; authManager_->ProcRespNegotiate(sessionId); jsonObject[TAG_CRYPTO_SUPPORT] = false; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_isIdenticalAccountReturnBoolValue = true; authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; @@ -156,7 +156,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = ""; authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; @@ -164,7 +164,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->ProcRespNegotiate(sessionId); authManager_->authResponseState_->context_ = std::make_shared(); - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -174,7 +174,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_NAME] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -187,13 +187,13 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t sessionId = 0; authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_isIdenticalAccountReturnBoolValue = false; authManager_->remoteDeviceId_ = "ProcRespNegotiate002"; authManager_->importAuthCode_ = "test"; @@ -207,7 +207,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_isIdenticalAccountReturnBoolValue = false; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index a94b83115..0d0d8fd0b 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -181,7 +181,7 @@ HWTEST_F(DmCredentialManagerTest, RequestCredential_001, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["userId"] = "test"; jsonObject["version"] = "test"; - reqJsonStr = jsonObject.dump(); + reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -279,22 +279,22 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_001, testing::ext::TestSize.L nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); jsonObject["TType"] = 1; jsonObject["processType"] = 1; - credentialInfo = jsonObject.dump(); + credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = -1; - credentialInfo = jsonObject.dump(); + credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = 2; - credentialInfo = jsonObject.dump(); + credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["TType"] = "test"; - credentialInfo = jsonObject.dump(); + credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -717,13 +717,13 @@ HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_001, testing::ext::Test jsonObject[FIELD_USER_ID] = 0; jsonObject[FIELD_PEER_USER_ID] = "peerUserId"; - std::string credentialInfo = jsonObject.dump(); + std::string credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject[FIELD_CREDENTIAL_DATA] = 0; - credentialInfo = jsonObject.dump(); + credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1655,7 +1655,7 @@ HWTEST_F(DmCredentialManagerTest, from_json_001, testing::ext::TestSize.Level0) nlohmann::json jsonPkInfo; jsonOutObj[FIELD_SERVER_PK] = "serverPk"; jsonOutObj[FIELD_PKINFO_SIGNATURE] = "pkInfoSignature"; - jsonOutObj[FIELD_PKINFO] = jsonPkInfo.dump(); + jsonOutObj[FIELD_PKINFO] = jsonPkInfo.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); jsonOutObj[FIELD_PEER_DEVICE_ID] = "peerDeviceId"; from_json(jsonOutObj, credentialDataInfo); EXPECT_FALSE(credentialDataInfo.serverPk.empty()); diff --git a/test/commonunittest/UTTest_dm_discovery_filter.cpp b/test/commonunittest/UTTest_dm_discovery_filter.cpp index 42e305d8f..3a681c632 100644 --- a/test/commonunittest/UTTest_dm_discovery_filter.cpp +++ b/test/commonunittest/UTTest_dm_discovery_filter.cpp @@ -58,7 +58,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Leve { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -74,7 +74,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Leve DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -91,7 +91,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Leve nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -108,7 +108,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Leve nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -126,7 +126,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -144,7 +144,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -165,7 +165,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -187,7 +187,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -209,7 +209,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Lev myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -238,7 +238,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSiz { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -254,7 +254,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSiz DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -271,7 +271,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSiz nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -289,7 +289,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSiz jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -308,7 +308,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -327,7 +327,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(); + std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 6469f5222..e11283f8c 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -314,7 +314,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t osAccountId = 1245; bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); @@ -325,7 +325,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; int32_t osAccountId = 1245; @@ -338,7 +338,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -351,7 +351,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -364,7 +364,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; int32_t osAccountId = 1245; @@ -377,7 +377,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t osAccountId = 1245; @@ -390,7 +390,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; int32_t osAccountId = 1245; diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index f3176758f..8c898b28a 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1200,7 +1200,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_001, testing::ext::TestS HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1219,7 +1219,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_003, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 1; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1238,7 +1238,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_004, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 4; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1270,7 +1270,7 @@ HWTEST_F(HichainConnectorTest, addMultiMembersExt_001, testing::ext::TestSize.Le HWTEST_F(HichainConnectorTest, addMultiMembersExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->addMultiMembersExt(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -1314,7 +1314,7 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_001, testing::ext::TestSize HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::vector udidList; std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr.c_str(), udidList); diff --git a/test/commonunittest/UTTest_mine_hichain_connector.cpp b/test/commonunittest/UTTest_mine_hichain_connector.cpp index 1769a1282..45412a796 100644 --- a/test/commonunittest/UTTest_mine_hichain_connector.cpp +++ b/test/commonunittest/UTTest_mine_hichain_connector.cpp @@ -112,7 +112,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_002, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -122,7 +122,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_003, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -132,7 +132,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, RequestCredential_001, testing::ext::Test std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string returnJsonStr = jsonObject.dump(); + std::string returnJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = minHiChain->RequestCredential(returnJsonStr); EXPECT_EQ(ret, DM_OK); } @@ -169,7 +169,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestS std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::string returnJsonStr; int32_t ret = minHiChain->ImportCredential(reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_REGISTER_CALLBACK); diff --git a/test/commonunittest/UTTest_pin_auth.cpp b/test/commonunittest/UTTest_pin_auth.cpp index febbdeaab..3bbc6b648 100644 --- a/test/commonunittest/UTTest_pin_auth.cpp +++ b/test/commonunittest/UTTest_pin_auth.cpp @@ -73,7 +73,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_002, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_TOKEN] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -89,7 +89,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_003, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = pinAuth->ShowAuthInfo(authToken, nullptr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -105,7 +105,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_004, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 9799617a8..5ae68f345 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -67,7 +67,7 @@ HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_002, testing::ext::TestSize. nlohmann::json jsonObj; jsonObj["findDeviceMode"] = 4; string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); DmSubscribeInfo dmSubscribeInfo; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->RefreshSoftbusLNN(pkgName, searchJson, dmSubscribeInfo); @@ -145,7 +145,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_002, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(1); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -158,7 +158,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_003, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(2); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -171,7 +171,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_004, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(3); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -184,7 +184,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_005, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(4); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, DM_OK); diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index 155da5f75..afb322eaa 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -107,7 +107,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) nlohmann::json jsonObj; jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = msgType; - std::string message = jsonObj.dump(); + std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); int32_t sessionId = 0; if (softbusSession == nullptr) { softbusSession = std::make_shared(); diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index eb392b1ee..9abe4b501 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -132,7 +132,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes authMessageProcessor->SetResponseContext(authResponseContext); authMessageProcessor->cryptoAdapter_ = nullptr; authMessageProcessor->CreateNegotiateMessage(jsonObj); - std::string str1 = jsonObj.dump(); + std::string str1 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); authMessageProcessor->cryptoAdapter_ = std::make_shared(); authMessageProcessor->CreateNegotiateMessage(jsonObj); @@ -145,7 +145,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes jsonObject[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsonObject[TAG_LOCAL_DEVICE_ID] = authMessageProcessor->authResponseContext_->localDeviceId; jsonObject[TAG_HOST] = ""; - std::string str2 = jsonObject.dump(); + std::string str2 = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ASSERT_NE(str1, str2); } @@ -171,8 +171,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateSyncGroupMessage_001, testing::ext::Tes jsona[TAG_DEVICE_ID] = authMessageProcessor->authRequestContext_->deviceId; jsona[TAG_GROUPIDS] = authMessageProcessor->authRequestContext_->syncGroupList; authMessageProcessor->CreateSyncGroupMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = jsona.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str2 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ASSERT_EQ(str1, str2); } @@ -196,7 +196,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: authMessageProcessor->authResponseContext_->token = "11"; nlohmann::json jsonb; jsonb[TAG_GROUP_ID] = "123456"; - authMessageProcessor->authResponseContext_->groupId = jsonb.dump(); + authMessageProcessor->authResponseContext_->groupId = + jsonb.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); authMessageProcessor->authResponseContext_->authToken = "123456"; authMessageProcessor->authResponseContext_->networkId = "11112222"; authMessageProcessor->authResponseContext_->requestId = 222222; @@ -210,8 +211,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: jsona[TAG_GROUP_ID] = "123456"; jsona[TAG_GROUP_NAME] = authMessageProcessor->authResponseContext_->groupName; authMessageProcessor->CreateResponseAuthMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = jsona.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str2 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ASSERT_EQ(str1, str2); } @@ -234,8 +235,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseFinishMessage_001, testing::ext jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsona[TAG_AUTH_FINISH] = authMessageProcessor->authResponseContext_->isFinish; authMessageProcessor->CreateResponseFinishMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = jsona.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str2 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); ASSERT_EQ(str1, str2); } diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index fa302b097..b7251e428 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -459,7 +459,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -470,7 +470,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -482,7 +482,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -492,7 +492,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_101, testing::ext::TestSize.Level std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -503,7 +503,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_102, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->listener_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -515,7 +515,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_103, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -527,7 +527,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_104, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -558,7 +558,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -569,7 +569,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -581,7 +581,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -603,7 +603,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_101, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -615,7 +615,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_102, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -627,7 +627,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_103, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -639,7 +639,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_104, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -652,7 +652,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_105, testing::ext::TestSize.Level0) int32_t data = 300; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = data; - std::string message = jsonObject.dump(); + std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 00ba99d82..85315ed8e 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -1249,7 +1249,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_053, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_OH; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = jsonObject.dump(); + std::string credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); @@ -1287,7 +1287,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_054, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_MINE; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = jsonObject.dump(); + std::string credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); diff --git a/utils/src/kvadapter/dm_kv_info.cpp b/utils/src/kvadapter/dm_kv_info.cpp index 2a251d6fa..58a2ff9b2 100644 --- a/utils/src/kvadapter/dm_kv_info.cpp +++ b/utils/src/kvadapter/dm_kv_info.cpp @@ -28,7 +28,7 @@ void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) jsonObj[ANOY_DEVICE_ID_KEY] = kvValue.anoyDeviceId; jsonObj[SALT_KEY] = kvValue.salt; jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; - result = jsonObj.dump(); + result = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); } void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) -- Gitee From 1b52f6621b112a261f3a40fb7214e00334274ea7 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Fri, 29 Nov 2024 16:07:35 +0800 Subject: [PATCH 484/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 12 ++---------- test/unittest/UTTest_device_manager_service_two.cpp | 4 +--- test/unittest/UTTest_dm_transport.cpp | 12 ------------ 3 files changed, 3 insertions(+), 25 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index fcd1bf74b..be426afd2 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1448,8 +1448,8 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::Tes HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ext::TestSize.Level0) { - std::string localUdid = ""; - std::string peerUdid = ""; + std::string localUdid = "deviceId"; + std::string peerUdid = "deviceId"; int32_t peerUserId = 123456; std::string peerAccountHash = ""; EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); @@ -1461,14 +1461,6 @@ HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ex ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); EXPECT_TRUE(ret.empty()); - - localUdid = "deviceId"; - peerUdid = "deviceId"; - peerAccountHash = "peerAccountHash"; - EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); - ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, - peerUserId, peerAccountHash); - EXPECT_TRUE(ret.empty()); } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 9e35f86a2..c4881f45f 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -514,7 +514,6 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Leve EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(0)); - EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_INPUT_PARA_INVALID)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -575,9 +574,8 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS std::map preUserDeviceMap; preUserDeviceMap["accountId"] = userId; preUserDeviceMap["accountName"] = 1; - EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(curUserDeviceMap)); EXPECT_CALL(*deviceManagerServiceImplMock_, - GetDeviceIdAndBindLevel(_)).WillOnce(Return(preUserDeviceMap)).WillOnce(Return(preUserDeviceMap)); + GetDeviceIdAndBindLevel(_)).WillOnce(Return(curUserDeviceMap)).WillOnce(Return(preUserDeviceMap)); DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); int32_t removeId = 123; diff --git a/test/unittest/UTTest_dm_transport.cpp b/test/unittest/UTTest_dm_transport.cpp index 5489c7428..e9b239dd3 100644 --- a/test/unittest/UTTest_dm_transport.cpp +++ b/test/unittest/UTTest_dm_transport.cpp @@ -202,17 +202,5 @@ HWTEST_F(DMTransportTest, Send_SessionNotOpened_Failure, testing::ext::TestSize. int32_t result = dmTransport.Send(notOpenedId, payload); EXPECT_EQ(result, ERR_DM_FAILED); } - -HWTEST_F(DMTransportTest, OnSocketOpened_001, testing::ext::TestSize.Level0) -{ - int32_t socketId = 1; - PeerSocketInfo info; - int32_t ret = dmTransport.OnSocketOpened(socketId, info); - EXPECT_EQ(ret, DM_OK); - - ShutdownReason reason = ShutdownReason::SHUTDOWN_REASON_UNKNOWN; - dmTransport.remoteDevSocketIds_["socketId"] = socketId; - dmTransport.OnSocketClosed(socketId, reason); -} } // DistributedHardware } // OHOS \ No newline at end of file -- Gitee From c60489779df93f594131364426fc1cbfd2ac5483 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Fri, 29 Nov 2024 16:10:33 +0800 Subject: [PATCH 485/520] =?UTF-8?q?=E9=BB=84=E8=93=9D=E5=B7=AE=E5=BC=82?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- services/service/src/permission/lite/permission_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/permission/lite/permission_manager.cpp b/services/service/src/permission/lite/permission_manager.cpp index 33bb0eae5..3b479ef97 100644 --- a/services/service/src/permission/lite/permission_manager.cpp +++ b/services/service/src/permission/lite/permission_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at -- Gitee From 2f59ff6b3a4061c1011d29337e5e641d966e2943 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Fri, 29 Nov 2024 17:16:05 +0800 Subject: [PATCH 486/520] =?UTF-8?q?=E5=90=8C=E8=B4=A6=E5=8F=B7=E6=97=A0?= =?UTF-8?q?=E8=AF=81=E4=B9=A6=E7=82=B9=E5=AF=B9=E7=82=B9=E4=BC=9A=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../src/authentication/dm_auth_manager.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 651ddc55e..610f995ef 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2165,11 +2165,6 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; authResponseContext_->remoteUserId = authResponseContext_->localUserId; GetBinderInfo(); - authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && - authResponseContext_->localAccountId != "ohosAnonymousUid") { - authResponseContext_->isIdenticalAccount = true; - } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); authResponseContext_->deviceId = authResponseContext_->localDeviceId; @@ -2182,6 +2177,13 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) !importAuthCode_.empty()) { authResponseContext_->importAuthCode = Crypto::Sha256(importAuthCode_); } + + authResponseContext_->isIdenticalAccount = false; + if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && + authResponseContext_->localAccountId != "ohosAnonymousUid" && authResponseContext_->authed) { + authResponseContext_->isIdenticalAccount = true; + } + authResponseContext_->isOnline = softbusConnector_->CheckIsOnline(remoteDeviceId_); authResponseContext_->haveCredential = hiChainAuthConnector_->QueryCredential(authResponseContext_->deviceId, authResponseContext_->localUserId); -- Gitee From 0687f44e15356c7d24c7ac9e7b58949255dfbd6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sat, 30 Nov 2024 10:45:37 +0800 Subject: [PATCH 487/520] =?UTF-8?q?=E9=BB=84=E8=93=9D=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E5=B7=AE=E5=BC=821.3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 f70c0a000..d70d3cd3a 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 @@ -1589,8 +1589,8 @@ ON_IPC_CMD(REMOTE_DEVICE_TRUST_CHANGE, MessageParcel &data, MessageParcel &reply { std::string pkgName = data.ReadString(); std::string udid = data.ReadString(); - std::string uuid = data.ReadString(); int32_t authForm = data.ReadInt32(); + std::string uuid = data.ReadString(); DeviceManagerNotify::GetInstance().OnDeviceTrustChange(pkgName, udid, uuid, authForm); reply.WriteInt32(DM_OK); return DM_OK; -- Gitee From 19b95f61b1a3e44f2a76a14819dde516f5b11657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sat, 30 Nov 2024 15:27:29 +0800 Subject: [PATCH 488/520] =?UTF-8?q?=E9=BB=84=E8=93=9D=E5=90=8C=E6=AD=A52.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- .../dependency/hichain/hichain_connector.h | 1 - .../src/authentication/dm_auth_manager.cpp | 19 ++++------- .../dependency/hichain/hichain_connector.cpp | 34 ++----------------- .../dependency/softbus/softbus_connector.cpp | 1 + .../src/discovery/dm_discovery_manager.cpp | 8 +++-- .../src/publish/dm_publish_manager.cpp | 4 ++- .../devicenamemgr/local_device_name_mgr.h | 2 +- .../service/src/device_manager_service.cpp | 1 + .../src/device_manager_service_listener.cpp | 4 +-- .../devicenamemgr/account_boot_listener.cpp | 8 +++++ .../devicenamemgr/local_device_name_mgr.cpp | 4 +++ 11 files changed, 35 insertions(+), 51 deletions(-) diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index ec99c924e..c5b2c45e7 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -242,7 +242,6 @@ public: int32_t GetRelatedGroupsCommon(int32_t userId, const std::string &deviceId, const char* pkgName, std::vector &groupList); void DeleteAllGroupByUdid(const std::string &udid); - void DeleteP2PGroup(int32_t switchUserId); int32_t DeleteGroupByACL(std::vector> &delACLInfoVec, std::vector &userIdVec); bool IsNeedDelete(std::string &groupName, int32_t userId, diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 651ddc55e..14cfe5102 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -243,6 +243,7 @@ void DmAuthManager::InitAuthState(const std::string &pkgName, int32_t authType, if (authenticationMap_.find(authType) != authenticationMap_.end()) { authPtr_ = authenticationMap_[authType]; } + if (timer_ == nullptr) { timer_ = std::make_shared(); } @@ -527,8 +528,6 @@ void DmAuthManager::ProcessSinkMsg() timer_->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); } authResponseState_->TransitionTo(std::make_shared()); - } else { - LOGE("Device manager auth state error"); } break; case MSG_TYPE_REQ_AUTH: @@ -537,8 +536,6 @@ void DmAuthManager::ProcessSinkMsg() timer_->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); } authResponseState_->TransitionTo(std::make_shared()); - } else { - LOGE("Device manager auth state error"); } break; case MSG_TYPE_REQ_AUTH_TERMINATE: @@ -2051,6 +2048,7 @@ void DmAuthManager::AuthDeviceFinish(int64_t requestId) if (timer_ != nullptr) { timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); } + if (authRequestState_ != nullptr && authResponseState_ == nullptr) { PutAccessControlList(); SrcAuthDeviceFinish(); @@ -2079,6 +2077,7 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) if (timer_ != nullptr) { timer_->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); } + if (errorCode != DM_OK || requestId != authResponseContext_->requestId) { if (authRequestState_ != nullptr && authTimes_ >= MAX_AUTH_TIMES) { authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; @@ -2277,17 +2276,11 @@ int32_t DmAuthManager::DeleteGroup(const std::string &pkgName, const std::string return ERR_DM_FAILED; } std::vector groupList; + CHECK_NULL_RETURN(hiChainConnector_, ERR_DM_POINT_NULL); hiChainConnector_->GetRelatedGroups(deviceId, groupList); - if (groupList.size() > 0) { - std::string groupId = ""; - groupId = groupList.front().groupId; + for (const auto &item : groupList) { + std::string groupId = item.groupId; hiChainConnector_->DeleteGroup(groupId); - } else { - LOGE("DmAuthManager::UnAuthenticateDevice groupList.size = 0"); - return ERR_DM_FAILED; - } - if (softbusConnector_ != nullptr) { - softbusConnector_->EraseUdidFromMap(deviceId); } return DM_OK; } diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 7e2ae818c..7a00f3859 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -1180,6 +1180,7 @@ int32_t HiChainConnector::GetRelatedGroupsCommon(int32_t userId, const std::stri deviceGroupManager_->getRelatedGroups(userId, pkgName, deviceId.c_str(), &returnGroups, &groupNum); if (ret != 0) { LOGE("[HICHAIN] fail to get related groups with ret:%{public}d.", ret); + delete[] returnGroups; returnGroups = nullptr; return ERR_DM_FAILED; } @@ -1189,10 +1190,12 @@ int32_t HiChainConnector::GetRelatedGroupsCommon(int32_t userId, const std::stri } if (groupNum == 0) { LOGE("[HICHAIN]return related goups number is zero."); + delete[] returnGroups; returnGroups = nullptr; return ERR_DM_FAILED; } std::string relatedGroups = std::string(returnGroups); + delete[] returnGroups; returnGroups = nullptr; nlohmann::json jsonObject = nlohmann::json::parse(relatedGroups, nullptr, false); if (jsonObject.is_discarded()) { @@ -1231,37 +1234,6 @@ void HiChainConnector::DeleteAllGroupByUdid(const std::string &udid) } } -void HiChainConnector::DeleteP2PGroup(int32_t switchUserId) -{ - LOGI("switchuserId: %{public}d", switchUserId); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - std::string queryParams = jsonObj.dump(); - std::vector groupList; - - if (!GetGroupInfo(switchUserId, queryParams, groupList)) { - LOGE("failed to get the switch user id groups"); - return; - } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - if (DeleteGroup(switchUserId, iter->groupId) != DM_OK) { - LOGE("failed to delete the old user id group %{public}s", GetAnonyString(iter->groupId).c_str()); - } - } - - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - LOGI("userId: %{public}d", userId); - if (!GetGroupInfo(userId, queryParams, groupList)) { - LOGE("failed to get the user id groups"); - return; - } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - if (DeleteGroup(userId, iter->groupId) != DM_OK) { - LOGE("failed to delete the user id group %{public}s", GetAnonyString(iter->groupId).c_str()); - } - } -} - int32_t HiChainConnector::DeleteGroupByACL(std::vector> &delACLInfoVec, std::vector &userIdVec) { diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 2f1124e40..b89de1c22 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -268,6 +268,7 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId) if (memcpy_s(addrInfo->info.ble.udidHash, UDID_HASH_LEN, remoteUdidHash_.c_str(), remoteUdidHash_.length()) != 0) { LOGE("memcpy remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); + return; } int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult); if (ret != DM_OK) { diff --git a/services/implementation/src/discovery/dm_discovery_manager.cpp b/services/implementation/src/discovery/dm_discovery_manager.cpp index a9ccaee3a..a872d4f02 100644 --- a/services/implementation/src/discovery/dm_discovery_manager.cpp +++ b/services/implementation/src/discovery/dm_discovery_manager.cpp @@ -130,7 +130,9 @@ int32_t DmDiscoveryManager::StopDeviceDiscovery(const std::string &pkgName, uint } if (!discoveryContextMap_.empty()) { discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + } } } softbusConnector_->UnRegisterSoftbusDiscoveryCallback(pkgName); @@ -238,7 +240,9 @@ void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t s } if (!discoveryContextMap_.empty()) { discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(DISCOVERY_TIMEOUT_TASK)); + } } } softbusConnector_->StopDiscovery(subscribeId); diff --git a/services/implementation/src/publish/dm_publish_manager.cpp b/services/implementation/src/publish/dm_publish_manager.cpp index 81fef1b9f..b09398161 100644 --- a/services/implementation/src/publish/dm_publish_manager.cpp +++ b/services/implementation/src/publish/dm_publish_manager.cpp @@ -93,7 +93,9 @@ int32_t DmPublishManager::UnPublishDeviceDiscovery(const std::string &pkgName, i if (!publishContextMap_.empty()) { publishContextMap_.erase(pkgName); softbusConnector_->UnRegisterSoftbusPublishCallback(pkgName); - timer_->DeleteTimer(std::string(PUBLISH_DISCOVERY_TIMEOUT_TASK)); + if (timer_ != nullptr) { + timer_->DeleteTimer(std::string(PUBLISH_DISCOVERY_TIMEOUT_TASK)); + } } return softbusConnector_->UnPublishDiscovery(publishId); } diff --git a/services/service/include/devicenamemgr/local_device_name_mgr.h b/services/service/include/devicenamemgr/local_device_name_mgr.h index 56fc6b89d..bd12387fc 100644 --- a/services/service/include/devicenamemgr/local_device_name_mgr.h +++ b/services/service/include/devicenamemgr/local_device_name_mgr.h @@ -47,7 +47,7 @@ private: std::string &deviceName); int32_t GetActiveOsAccountIds(); private: - std::mutex devNameMtx_; + static std::mutex devNameMtx_; std::string localDeviceName_; std::string localDisplayName_; }; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index bc606b109..c13f4a445 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -76,6 +76,7 @@ namespace { constexpr uint32_t USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK = 0b0010; const std::string DHARD_WARE_PKG_NAME = "ohos.dhardware"; } + DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index b98d3442d..b94ea071e 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -446,8 +446,8 @@ int32_t DeviceManagerServiceListener::ConvertUdidHashToAnoyDeviceId(const std::s void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) { - LOGI("udid %{public}s, uuid %{public}s, authForm %{public}d.", GetAnonyString(udid).c_str(), - GetAnonyString(uuid).c_str(), authForm); + LOGI("udid %{public}s, authForm %{public}d, uuid %{public}s.", GetAnonyString(udid).c_str(), + authForm, GetAnonyString(uuid).c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); int32_t userId = -1; diff --git a/services/service/src/devicenamemgr/account_boot_listener.cpp b/services/service/src/devicenamemgr/account_boot_listener.cpp index 29e4eb932..7f0dfa3fc 100644 --- a/services/service/src/devicenamemgr/account_boot_listener.cpp +++ b/services/service/src/devicenamemgr/account_boot_listener.cpp @@ -161,11 +161,19 @@ void AccountBootListener::DataShareCallback() std::string AccountBootListener::GetLocalDisplayName() const { + if (localDeviceMgr_ == nullptr) { + LOGE("logcalDeviceMgr_ is null"); + return ""; + } return localDeviceMgr_->GetLocalDisplayName(); } std::string AccountBootListener::GetLocalDeviceName() const { + if (localDeviceMgr_ == nullptr) { + LOGE("logcalDeviceMgr_ is null"); + return ""; + } return localDeviceMgr_->GetLocalDeviceName(); } } // namespace DistributedHardware diff --git a/services/service/src/devicenamemgr/local_device_name_mgr.cpp b/services/service/src/devicenamemgr/local_device_name_mgr.cpp index 22227f15b..9564ee56f 100644 --- a/services/service/src/devicenamemgr/local_device_name_mgr.cpp +++ b/services/service/src/devicenamemgr/local_device_name_mgr.cpp @@ -45,6 +45,8 @@ namespace { constexpr const char *DISPLAY_DEVICE_NAME_STRING = "settings.general.display_device_name"; } +std::mutex LocalDeviceNameMgr::devNameMtx_; + LocalDeviceNameMgr::LocalDeviceNameMgr() : localDeviceName_(""), localDisplayName_("") { LOGI("Ctor LocalDeviceNameMgr"); @@ -286,11 +288,13 @@ void LocalDeviceNameMgr::RegisterDisplayNameChangeCb() std::string LocalDeviceNameMgr::GetLocalDisplayName() const { + std::lock_guard lock(devNameMtx_); return localDisplayName_; } std::string LocalDeviceNameMgr::GetLocalDeviceName() const { + std::lock_guard lock(devNameMtx_); return localDeviceName_; } } // namespace DistributedHardware -- Gitee From 879833b36cf7ad7cebaca329bef0d774e10936c0 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 30 Nov 2024 15:36:57 +0800 Subject: [PATCH 489/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 104 +++++++++ .../UTTest_dm_deviceprofile_connector.h | 3 + ...Test_dm_deviceprofile_connector_second.cpp | 41 ++++ test/unittest/BUILD.gn | 2 + ...mock_distributed_device_profile_client.cpp | 208 ++++++++++++++++++ .../mock/multiple_user_connector_mock.cpp | 5 + .../mock/multiple_user_connector_mock.h | 2 + 7 files changed, 365 insertions(+) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 3520eda99..3544e228c 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -31,10 +31,13 @@ void DeviceProfileConnectorTest::TearDown() void DeviceProfileConnectorTest::SetUpTestCase() { + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; } void DeviceProfileConnectorTest::TearDownTestCase() { + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; + multipleUserConnectorMock_ = nullptr; } void AddAccessControlProfileFirst(std::vector& accessControlProfiles) @@ -297,6 +300,58 @@ void AddAccessControlProfileFifth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + void GetAccessControlProfiles(std::vector& accessControlProfiles) { AddAccessControlProfileFirst(accessControlProfiles); @@ -1439,5 +1494,54 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::Tes dmNotifyKey1.processUserId = 2; EXPECT_TRUE(dmNotifyKey < dmNotifyKey1); } + +HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "deviceId"; + + EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + EXPECT_EQ(ret.empty(), false); + + deviceId = "deviceIder001" + EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + EXPECT_EQ(ret.empty(), false); +} + +HWTEST_F(DeviceProfileConnectorTest, GetACLByDeviceIdAndUserId_001, testing::ext::TestSize.Level0) +{ + std::vector profiles; + DmAccessCaller caller; + std::string srcUdid = "remoteDeviceId"; + DmAccessCallee callee; + std::string sinkUdid = "localDeviceId"; + AddAccessControlProfileFirst(profiles); + AddAccessControlProfileSix(profiles); + + int32_t userId = 123456; + caller.userId = userId; + callee.userId = userId; + auto ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, + callee, srcUdid); + EXPECT_EQ(ret.empty(), false); + + callee.userId = 0; + ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, + callee, srcUdid); + EXPECT_EQ(ret.empty(), false); + + srcUdid = "localDeviceId"; + sinkUdid = "remoteDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, + callee, srcUdid); + EXPECT_EQ(ret.empty(), false); + + callee.userId == 0 + ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, + callee, srcUdid); + EXPECT_EQ(ret.empty(), false); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.h b/test/commonunittest/UTTest_dm_deviceprofile_connector.h index 22fa7543c..c4973faad 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.h +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.h @@ -20,6 +20,7 @@ #include #include "deviceprofile_connector.h" +#include "multiple_user_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -29,6 +30,8 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + static inline std::shared_ptr multipleUserConnectorMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index f4b45562d..8a43f4537 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -156,6 +156,47 @@ HWTEST_F(DeviceProfileConnectorSecondTest, CheckIdenticalAccount_201, testing::e EXPECT_CALL(*distributedDeviceProfileClientMock_, GetAccessControlProfile(_, _)).WillOnce(Return(ERR_DM_FAILED)); bool ret = DeviceProfileConnector::GetInstance().CheckIdenticalAccount(userId, accountId); EXPECT_FALSE(ret); + + userId = 1; + int32_t bindType = 1; + std::string deviceIdEr = "deviceId"; + std::string deviceIdEe = "deviceIdEe"; + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + DistributedDeviceProfile::AccessControlProfile profile; + profile.SetAccessControlId(accesserId); + profile.SetBindType(bindType); + profile.SetAccesser(accesser); + profile.SetAccessee(accessee); + + int userIds = 12356; + std::string remoteUdid = "deviceId"; + std::vector remoteFrontUserIds; + remoteFrontUserIds.push_back(userIds); + std::vector remoteBackUserIds; + remoteBackUserIds.push_back(userIds); + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profile, remoteUdid, remoteFrontUserIds, remoteBackUserIds); + + remoteUdid = "deviceIdEe"; + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profile, remoteUdid, remoteFrontUserIds, remoteBackUserIds); + + int32_t userIdee = 0; + accessee.SetAccesseeUserId(userIdee); + DistributedDeviceProfile::AccessControlProfile profilesecond; + profilesecond.SetAccessControlId(accesserId); + profilesecond.SetBindType(bindType); + profilesecond.SetAccesser(accesser); + profilesecond.SetAccessee(accessee); + std::string localUdid = "deviceId"; + std::vector localUserIds; + int32_t localUserId = 1; + localUserIds.push_back(localUserId); + DeviceProfileConnector::GetInstance().UpdatePeerUserId(profilesecond, localUdid, localUserIds, + remoteUdid, remoteFrontUserIds); } HWTEST_F(DeviceProfileConnectorSecondTest, GetAllAccessControlProfile_201, testing::ext::TestSize.Level0) diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 20a7e4e11..9f3aa9508 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -1303,6 +1303,7 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { sources = [ "${devicemanager_path}/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp", + "${devicemanager_path}/test/unittest/mock/multiple_user_connector_mock.cpp", "${devicemanager_path}/test/unittest/mock/mock_distributed_device_profile_client.cpp", ] @@ -1313,6 +1314,7 @@ ohos_unittest("UTTest_dm_deviceprofile_connector") { "device_info_manager:distributed_device_profile_sdk", "ffrt:libffrt", "googletest:gmock", + "googletest:gmock_main", ] } diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index ba6971387..6728877d5 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -946,6 +946,209 @@ void AddAccessControlprofileEightteenth(std::vector& acces accessControlProfiles.push_back(profileFourth); } +void AddAccessControlprofileNineteenth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 2; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIder"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileTwentieth(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIder"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileTwentyfirst(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIdacce"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} + +void AddAccessControlprofileTwentysecond(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 0; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 3; + uint32_t authenticationType = 1; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "accountId"; + std::string newAccountId = "accountId"; + std::string deviceId = "deviceId"; + std::string trustDeviceId = "deviceIdacce"; + + Accesser accesser; + accesser.SetAccesserId(0); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(""); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName(""); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFourth; + profileFourth.SetAccessControlId(accesserId); + profileFourth.SetAccesserId(accesserId); + profileFourth.SetAccesseeId(accesserId); + profileFourth.SetTrustDeviceId(trustDeviceId); + profileFourth.SetBindType(bindType); + profileFourth.SetAuthenticationType(authenticationType); + profileFourth.SetDeviceIdType(deviceIdType); + profileFourth.SetStatus(status); + profileFourth.SetBindLevel(bindLevel); + profileFourth.SetAccesser(accesser); + profileFourth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFourth); +} int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -988,6 +1191,10 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::mapGetCurrentAccountUserID(); } + +int32_t MultipleUserConnector::GetFirstForegroundUserId(void) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetFirstForegroundUserId(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/multiple_user_connector_mock.h b/test/unittest/mock/multiple_user_connector_mock.h index 8a428ef7d..434de7480 100644 --- a/test/unittest/mock/multiple_user_connector_mock.h +++ b/test/unittest/mock/multiple_user_connector_mock.h @@ -27,6 +27,7 @@ public: virtual ~DmMultipleUserConnector() = default; public: virtual int32_t GetCurrentAccountUserID(void) = 0; + virtual int32_t GetFirstForegroundUserId(void) = 0; public: static inline std::shared_ptr dmMultipleUserConnector = nullptr; }; @@ -34,6 +35,7 @@ public: class MultipleUserConnectorMock : public DmMultipleUserConnector { public: MOCK_METHOD(int32_t, GetCurrentAccountUserID, ()); + MOCK_METHOD(int32_t, GetFirstForegroundUserId, ()); }; } } -- Gitee From ab3d61d3ba88a0b30d7839ebe3aa8033f005532a Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 30 Nov 2024 19:34:25 +0800 Subject: [PATCH 490/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 72 ++++++++++++++++++- test/unittest/mock/dm_crypto_mock.cpp | 5 ++ test/unittest/mock/dm_crypto_mock.h | 2 + ...mock_distributed_device_profile_client.cpp | 58 +++++++++++++++ 4 files changed, 136 insertions(+), 1 deletion(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 5221d3c59..eddfe7b10 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -402,6 +402,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_001, testing::ext::TestSi DmDiscoveryInfo discoveryInfo; bool isonline = true; int32_t authForm = 0; + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); } @@ -1371,6 +1372,13 @@ HWTEST_F(DeviceProfileConnectorTest, DeleteAclForAccountLogOut_001, testing::ext peerUserId = 123456; ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); EXPECT_TRUE(ret); + + localUdid = "localDeviceId"; + localUserId = 123456; + peerUdid = "remoteDeviceId"; + peerUserId = 123456; + ret = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); + EXPECT_FALSE(ret); } HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_005, testing::ext::TestSize.Level0) @@ -1381,6 +1389,11 @@ HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_005, testing: auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, userId); EXPECT_FALSE(ret.empty()); + + localDeviceId = "remoteDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, + targetDeviceId, userId); + EXPECT_FALSE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndBindLevel_001, testing::ext::TestSize.Level0) @@ -1515,6 +1528,12 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_004, testing::ext::Te EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); EXPECT_EQ(ret.empty(), false); + + std::string udid; + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); + + udid = "deviceId"; + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); } HWTEST_F(DeviceProfileConnectorTest, GetACLByDeviceIdAndUserId_001, testing::ext::TestSize.Level0) @@ -1545,10 +1564,12 @@ HWTEST_F(DeviceProfileConnectorTest, GetACLByDeviceIdAndUserId_001, testing::ext callee, srcUdid); EXPECT_EQ(ret.empty(), false); - callee.userId == 0 + callee.userId == 0 ; ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, callee, srcUdid); EXPECT_EQ(ret.empty(), false); +} + HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ext::TestSize.Level0) { std::string localUdid = "deviceId"; @@ -1565,5 +1586,54 @@ HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ex peerUserId, peerAccountHash); EXPECT_TRUE(ret.empty()); } + +HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_002, testing::ext::TestSize.Level0) +{ + DmDiscoveryInfo discoveryInfo; + discoveryInfo.remoteDeviceIdHash = ""; + discoveryInfo.localDeviceId = "deviceId"; + discoveryInfo.userId = 123456; + discoveryInfo.pkgname = ""; + bool isonline = true; + int32_t authForm = 0; + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); + EXPECT_EQ(ret, DM_OK); + + discoveryInfo.pkgname = "bundleName"; + discoveryInfo.localDeviceId = "deviceId"; + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).WillOnce(Return(DM_OK)); + int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_004, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "123456"; + bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); + EXPECT_EQ(ret, false); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_005, testing::ext::TestSize.Level0) +{ + std::string pkgName = "bundleName"; + std::string deviceId = "123456"; + bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); + EXPECT_FALSE(ret); +} + +HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_002, testing::ext::TestSize.Level0) +{ + int32_t userId = 123456; + DmAccessCaller caller; + caller.userId = userId; + std::string srcUdid = "deviceId"; + DmAccessCallee callee; + callee.userId = userId; + std::string sinkUdid = "deviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/dm_crypto_mock.cpp b/test/unittest/mock/dm_crypto_mock.cpp index 6baeadd1b..c8b1775e2 100644 --- a/test/unittest/mock/dm_crypto_mock.cpp +++ b/test/unittest/mock/dm_crypto_mock.cpp @@ -29,5 +29,10 @@ int32_t Crypto::ConvertUdidHashToAnoyAndSave(const std::string &appId, const std { return DmCrypto::dmCrypto->ConvertUdidHashToAnoyAndSave(appId, udidHash, kvValue); } + +int32_t Crypto::GetUdidHash(const std::string &udid, unsigned char *udidHash) +{ + return DmCrypto::dmCrypto->GetUdidHash(udid, udidHash); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_crypto_mock.h b/test/unittest/mock/dm_crypto_mock.h index c0fd67123..187af59dc 100644 --- a/test/unittest/mock/dm_crypto_mock.h +++ b/test/unittest/mock/dm_crypto_mock.h @@ -29,6 +29,7 @@ public: virtual int32_t GetAccountIdHash(const std::string &accountId, unsigned char *accountIdHash) = 0; virtual int32_t ConvertUdidHashToAnoyAndSave(const std::string &appId, const std::string &udidHash, DmKVValue &kvValue) = 0; + virtual int32_t GetUdidHash(const std::string &udid, unsigned char *udidHash) = 0; public: static inline std::shared_ptr dmCrypto = nullptr; }; @@ -37,6 +38,7 @@ class CryptoMock : public DmCrypto { public: MOCK_METHOD(int32_t, GetAccountIdHash, (const std::string &, unsigned char *)); MOCK_METHOD(int32_t, ConvertUdidHashToAnoyAndSave, (const std::string &, const std::string &, DmKVValue &)); + MOCK_METHOD(int32_t, GetUdidHash, (const std::string &, unsigned char *)); }; } } diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index 6728877d5..dfece632f 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -1149,6 +1149,59 @@ void AddAccessControlprofileTwentysecond(std::vector& acce profileFourth.SetAccessee(accessee); accessControlProfiles.push_back(profileFourth); } + +void AddAccessControlProfileTwentythree(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(0); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -1195,6 +1248,7 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map Date: Tue, 3 Dec 2024 01:39:06 +0000 Subject: [PATCH 491/520] update services/implementation/src/dependency/hichain/hichain_connector.cpp. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../dependency/hichain/hichain_connector.cpp | 31 ------------------- 1 file changed, 31 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 7555627b7..a9a474e9b 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -1236,37 +1236,6 @@ void HiChainConnector::DeleteAllGroupByUdid(const std::string &udid) } } -void HiChainConnector::DeleteP2PGroup(int32_t switchUserId) -{ - LOGI("switchuserId: %{public}d", switchUserId); - nlohmann::json jsonObj; - jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_PEER_TO_PEER_GROUP; - std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); - std::vector groupList; - - if (!GetGroupInfo(switchUserId, queryParams, groupList)) { - LOGE("failed to get the switch user id groups"); - return; - } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - if (DeleteGroup(switchUserId, iter->groupId) != DM_OK) { - LOGE("failed to delete the old user id group %{public}s", GetAnonyString(iter->groupId).c_str()); - } - } - - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - LOGI("userId: %{public}d", userId); - if (!GetGroupInfo(userId, queryParams, groupList)) { - LOGE("failed to get the user id groups"); - return; - } - for (auto iter = groupList.begin(); iter != groupList.end(); iter++) { - if (DeleteGroup(userId, iter->groupId) != DM_OK) { - LOGE("failed to delete the user id group %{public}s", GetAnonyString(iter->groupId).c_str()); - } - } -} - int32_t HiChainConnector::DeleteGroupByACL(std::vector> &delACLInfoVec, std::vector &userIdVec) { -- Gitee From e11bf86b7e0e4f9940ef60cdc425f588e554f9c3 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 3 Dec 2024 11:26:35 +0800 Subject: [PATCH 492/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 252 +++++++++++++- ...mock_distributed_device_profile_client.cpp | 323 ++++++++++++++++++ 2 files changed, 573 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index eddfe7b10..3c54c7122 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -359,6 +359,111 @@ void AddAccessControlProfileSix(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 256; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileEight(std::vector& accessControlProfiles) +{ + int32_t userId = 123456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 2; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = "oldAccountId"; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "remoteDeviceId"; + + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName1"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(0); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName2"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + DistributedDeviceProfile::AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + void GetAccessControlProfiles(std::vector& accessControlProfiles) { AddAccessControlProfileFirst(accessControlProfiles); @@ -1320,6 +1425,18 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAccountLogoutEvent_002, testing::ext: bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, remoteAccountHash, remoteUdid, localUdid); EXPECT_NE(bindType, DM_IDENTICAL_ACCOUNT); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); + + int32_t remoteId = 456; + remoteUserId = remoteId; + bindType = DeviceProfileConnector::GetInstance().HandleAccountLogoutEvent(remoteUserId, + remoteAccountHash, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); } HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::TestSize.Level0) @@ -1330,6 +1447,10 @@ HWTEST_F(DeviceProfileConnectorTest, HandleDevUnBindEvent_002, testing::ext::Tes int32_t bindType = DM_INVALIED_BINDTYPE; bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); EXPECT_EQ(bindType, DM_INVALIED_BINDTYPE); + + remoteUdid = "123456"; + bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + EXPECT_EQ(bindType, DM_IDENTICAL_ACCOUNT); } HWTEST_F(DeviceProfileConnectorTest, GetAllAccessControlProfile_001, testing::ext::TestSize.Level0) @@ -1400,12 +1521,16 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndBindLevel_001, testing::ext:: { std::vector userIds; int32_t userId = 123456; + int32_t localId = 456; userIds.push_back(userId); - userIds.push_back(userId); - userIds.push_back(userId); + userIds.push_back(localId); std::string localUdid = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); EXPECT_FALSE(ret.empty()); + + localUdid = "localDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); + EXPECT_FALSE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_001, testing::ext::TestSize.Level0) @@ -1415,6 +1540,10 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_001, testing::ext::Tes std::string localUdid = "deviceId"; auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); EXPECT_FALSE(ret.empty()); + + localUdid = "localDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); + EXPECT_FALSE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestSize.Level0) @@ -1437,6 +1566,14 @@ HWTEST_F(DeviceProfileConnectorTest, HandleUserSwitched_001, testing::ext::TestS localUserIds.push_back(currentUserId); DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, localUdid); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + int32_t localdeviceId = 456; + remoteUserIds.push_back(localdeviceId); + localUserIds.push_back(localdeviceId); + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid, + localUserIds, localUdid); } HWTEST_F(DeviceProfileConnectorTest, GetOfflineProcessInfo_001, testing::ext::TestSize.Level0) @@ -1451,6 +1588,15 @@ HWTEST_F(DeviceProfileConnectorTest, GetOfflineProcessInfo_001, testing::ext::Te auto ret = DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, remoteUserIds); EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + int32_t localdeviceId = 456; + remoteUserIds.push_back(localdeviceId); + localUserIds.push_back(localdeviceId); + ret = DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUdid, localUserIds, remoteUdid, + remoteUserIds); + EXPECT_FALSE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, GetUserIdAndBindLevel_001, testing::ext::TestSize.Level0) @@ -1460,6 +1606,11 @@ HWTEST_F(DeviceProfileConnectorTest, GetUserIdAndBindLevel_001, testing::ext::Te auto ret = DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(localUdid, peerUdid); EXPECT_FALSE(ret.empty()); + localUdid = "remoteDeviceId"; + peerUdid = "localDeviceId"; + ret = DeviceProfileConnector::GetInstance().GetUserIdAndBindLevel(localUdid, peerUdid); + EXPECT_FALSE(ret.empty()); + int32_t userId = 123456; std::vector localUserIds; localUserIds.push_back(userId); @@ -1470,6 +1621,16 @@ HWTEST_F(DeviceProfileConnectorTest, GetUserIdAndBindLevel_001, testing::ext::Te remoteBackUserIds.push_back(userId); DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, remoteFrontUserIds, remoteBackUserIds); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + userId = 456; + std::vector remoteUserIds; + remoteUserIds.push_back(userId); + std::vector localUserIds; + localUserIds.push_back(userId); + DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, + localUdid); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::TestSize.Level0) @@ -1479,6 +1640,11 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_002, testing::ext::Tes auto ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); EXPECT_FALSE(ret.empty()); + localUdid = "localDeviceId"; + localUserId = 456; + ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(localUdid, localUserId); + EXPECT_FALSE(ret.empty()); + std::vector remoteUserIds; remoteUserIds.push_back(localUserId); std::string remoteUdid = "deviceId"; @@ -1585,6 +1751,19 @@ HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ex ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); EXPECT_TRUE(ret.empty()); + + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + peerUdid = "localDeviceId"; + peerUserId = 456; + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, + peerUserId, peerAccountHash); + EXPECT_FASLE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_002, testing::ext::TestSize.Level0) @@ -1621,6 +1800,31 @@ HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_005, testing:: std::string deviceId = "123456"; bool ret = DeviceProfileConnector::GetInstance().CheckSrcDevIdInAclForDevBind(pkgName, deviceId); EXPECT_FALSE(ret); + + DistributedDeviceProfile::AccessControlProfile profiles; + std::string remoteUdid = "remoteDeviceId"; + std::vector remoteFrontUserIds; + std::vector remoteBackUserIds; + AddAccessControlProfileFirst(profiles); + AddAccessControlProfileSix(profiles); + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profiles, remoteUdid, + remoteFrontUserIds, remoteBackUserIds); + + remoteUdid = "localDeviceId"; + AddAccessControlProfileSeven(profiles); + DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profiles, remoteUdid, + remoteFrontUserIds, remoteBackUserIds); + + AddAccessControlProfileEight(profiles); + std::string localUdid = "localDeviceId"; + std::vector localUserIds; + int32_t userId = 123456; + localUserIds.push_back(userId); + remoteUdid = "remoteDeviceId"; + remoteFrontUserIds.push_back(0); + remoteFrontUserIds.push_back(userId); + DeviceProfileConnector::GetInstance().UpdatePeerUserId(profiles, localUdid, localUserIds, remoteUdid, + remoteFrontUserIds); } HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_002, testing::ext::TestSize.Level0) @@ -1635,5 +1839,49 @@ HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_002, testing::ext::TestS int32_t ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, DM_OK); } + +HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_002, testing::ext::TestSize.Level0) +{ + int32_t userId = 123456; + DmAccessCaller caller; + caller.userId = userId; + std::string srcUdid = "deviceId"; + DmAccessCallee callee; + callee.userId = userId; + std::string sinkUdid = "deviceId"; + int32_t ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); +} + +HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_002, testing::ext::TestSize.Level0) +{ + int32_t remoteUserId = 456; + int32_t tokenId = 1001; + std::string remoteUdid = "localDeviceId"; + std::string localUdid = "remoteDeviceId"; + std::string pkgName = ""; + ProcessInfo res; + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ("bundleName", res.pkgName); + + tokenId = 1002; + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + EXPECT_EQ("bundleName", res.pkgName); +} + +HWTEST_F(DeviceProfileConnectorTest, GetAclProfileByUserId_001, testing::ext::TestSize.Level0) +{ + std::string localUdid = "deviceId"; + int32_t userId = 123456; + std::string remoteUdid = "deviceId"; + auto ret = DeviceProfileConnector::GetInstance().GetAclProfileByUserId(localUdid, userId, remoteUdid); + EXPECT_FALSE(ret.empty()); + + localUdid = "remoteDeviceId"; + remoteUdid = "localDeviceId"; + userId = 456; + ret = DeviceProfileConnector::GetInstance().GetAclProfileByUserId(localUdid, userId, remoteUdid); + EXPECT_FALSE(ret.empty()); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index dfece632f..9f01182d1 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -1202,6 +1202,317 @@ void AddAccessControlProfileTwentythree(std::vector& acces accessControlProfiles.push_back(profileFifth); } +void AddAccessControlProfileTwentyForth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentyFifth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentySixth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 0; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentySeventh(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 1; + uint32_t status = 0; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceId = "localDeviceId"; + std::string trustDeviceId = "123456"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceId); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceId); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentyEighth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 3; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1001; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "localDeviceId"; + std::string deviceIdEe = "remoteDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfileTwentyNinth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 3; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1002; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -1249,6 +1560,12 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map Date: Tue, 3 Dec 2024 17:33:30 +0800 Subject: [PATCH 493/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_multiple_user_connector.cpp | 35 ++++++++++++++ .../UTTest_softbus_listener.cpp | 6 +++ test/unittest/BUILD.gn | 7 ++- .../UTTest_device_manager_service.cpp | 7 +++ test/unittest/UTTest_device_manager_service.h | 2 + .../UTTest_device_manager_service_impl.cpp | 41 +++++++++++++++++ .../UTTest_device_manager_service_two.cpp | 46 +++++++++++++++++++ test/unittest/UTTest_ipc_client_stub.cpp | 27 +++++++++++ test/unittest/UTTest_ipc_client_stub.h | 3 ++ .../mock/device_manager_service_impl_mock.cpp | 6 +++ .../mock/device_manager_service_impl_mock.h | 2 + .../mock/deviceprofile_connector_mock.cpp | 7 +++ .../mock/deviceprofile_connector_mock.h | 4 ++ test/unittest/mock/dm_hidumper_mock.cpp | 28 +++++++++++ test/unittest/mock/dm_hidumper_mock.h | 40 ++++++++++++++++ test/unittest/mock/ipc_cmd_register_mock.cpp | 33 +++++++++++++ test/unittest/mock/ipc_cmd_register_mock.h | 42 +++++++++++++++++ .../mock/multiple_user_connector_mock.h | 2 + 18 files changed, 337 insertions(+), 1 deletion(-) create mode 100644 test/unittest/mock/dm_hidumper_mock.cpp create mode 100644 test/unittest/mock/dm_hidumper_mock.h create mode 100644 test/unittest/mock/ipc_cmd_register_mock.cpp create mode 100644 test/unittest/mock/ipc_cmd_register_mock.h diff --git a/test/commonunittest/UTTest_multiple_user_connector.cpp b/test/commonunittest/UTTest_multiple_user_connector.cpp index 1ac739e53..962f4a011 100644 --- a/test/commonunittest/UTTest_multiple_user_connector.cpp +++ b/test/commonunittest/UTTest_multiple_user_connector.cpp @@ -82,6 +82,41 @@ HWTEST_F(MultipleUserConnectorTest, GetSwitchOldUserId_001, testing::ext::TestSi userIdOut = MultipleUserConnector::GetSwitchOldUserId(); ASSERT_EQ(userIdIn, userIdOut); } + +HWTEST_F(MultipleUserConnectorTest, GetSwitchOldAccountId_001, testing::ext::TestSize.Level0) +{ + std::string accountId = "accountId"; + MultipleUserConnector::SetSwitchOldAccountId(accountId); + std::string accountIdOut = MultipleUserConnector::GetSwitchOldAccountId(); + ASSERT_EQ(accountId, accountIdOut); +} + +HWTEST_F(MultipleUserConnectorTest, GetSwitchOldAccountName_001, testing::ext::TestSize.Level0) +{ + std::string accountName = "accountName"; + MultipleUserConnector::SetSwitchOldAccountName(accountName); + std::string accountNameOut = MultipleUserConnector::GetSwitchOldAccountName(); + ASSERT_EQ(accountName, accountNameOut); +} + +HWTEST_F(MultipleUserConnectorTest, GetAllUserIds_001, testing::ext::TestSize.Level0) +{ + std::vector userIdVec; + int32_t ret = MultipleUserConnector::GetAllUserIds(userIdVec); + ASSERT_EQ(ret, DM_OK); +} + +HWTEST_F(MultipleUserConnectorTest, GetAccountInfoByUserId_001, testing::ext::TestSize.Level0) +{ + int32_t userId = 123; + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = "12456"; + MultipleUserConnector::dmAccountInfoMap_[userId] = dmAccountInfo; + auto ret = MultipleUserConnector::GetAccountInfoByUserId(userId); + ASSERT_FALSE(ret.accountId.empty()); + + MultipleUserConnector::DeleteAccountInfoByUserId(userId); +} } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index e143611ac..5354642d7 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -1085,6 +1085,12 @@ HWTEST_F(SoftbusListenerTest, SetForegroundUserIdsToDSoftBus_001, testing::ext:: } int32_t ret = softbusListener->SetForegroundUserIdsToDSoftBus(remoteUdid, userIds); EXPECT_EQ(ret, DM_OK); + + uint32_t deviceListLen = 2001; + char devicelist[deviceListLen] = {0}; + uint16_t deviceTypeId = 0; + int32_t errcode = -1; + softbusListener->OnCredentialAuthStatus(devicelist, deviceListLen, deviceTypeId, errcode); softbusListener = nullptr; } } // namespace diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 081b59240..32beda7ea 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -333,6 +333,7 @@ ohos_unittest("UTTest_device_manager_service") { "mock/app_manager_mock.cpp", "mock/device_manager_service_impl_mock.cpp", "mock/dm_crypto_mock.cpp", + "mock/dm_hidumper_mock.cpp", "mock/dm_softbus_cache_mock.cpp", "mock/kv_adapter_manager_mock.cpp", "mock/permission_manager_mock.cpp", @@ -729,13 +730,17 @@ ohos_unittest("UTTest_ipc_client_proxy") { ohos_unittest("UTTest_ipc_client_stub") { module_out_path = module_out_path - sources = [ "UTTest_ipc_client_stub.cpp" ] + sources = [ + "UTTest_ipc_client_stub.cpp", + "mock/ipc_cmd_register_mock.cpp", + ] deps = [ ":device_manager_test_common" ] external_deps = [ "device_auth:deviceauth_sdk", "googletest:gmock", + "googletest:gmock_main", ] } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 0db77c73d..f5a1654a6 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -72,6 +72,7 @@ void DeviceManagerServiceTest::SetUpTestCase() DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; DmCrypto::dmCrypto = cryptoMock_; + DmHiDumpHelper::dmHiDumpHelper = hiDumpHelperMock_; } void DeviceManagerServiceTest::TearDownTestCase() @@ -90,6 +91,8 @@ void DeviceManagerServiceTest::TearDownTestCase() softbusCacheMock_ = nullptr; DmCrypto::dmCrypto = nullptr; cryptoMock_ = nullptr; + DmHiDumpHelper::dmHiDumpHelper = nullptr; + hiDumpHelperMock_ = nullptr; } namespace { @@ -2499,6 +2502,10 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_005, testing::ext::TestSize.Lev EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*softbusListenerMock_, GetDeviceInfo(_, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().GetDeviceInfo(networkId, info); + EXPECT_EQ(ret, ERR_DM_FAILED); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index 7d17393e7..aa27c4e8c 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -34,6 +34,7 @@ #include "device_manager_service_impl_mock.h" #include "dm_softbus_cache_mock.h" #include "dm_crypto_mock.h" +#include "dm_hidumper_mock.cpp" namespace OHOS { namespace DistributedHardware { @@ -57,6 +58,7 @@ public: static inline std::shared_ptr softbusCacheMock_ = std::make_shared(); static inline std::shared_ptr cryptoMock_ = std::make_shared(); + static inline std::shared_ptr hiDumpHelperMock_ = std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 2c779d705..66b591bc8 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1821,6 +1821,9 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T auto ret = deviceManagerServiceImpl_->GetDeviceIdAndUserId(userId, accountId); EXPECT_TRUE(ret.empty()); + ret = deviceManagerServiceImpl_->GetDeviceIdAndUserId(userId); + EXPECT_TRUE(ret.empty()); + std::string localUdid = "deviceId"; int32_t localUserId = 123456; std::string peerUdid = "remoteUdid"; @@ -1845,6 +1848,44 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T int32_t beforeUserId = 0; deviceManagerServiceImpl_->HandleUserSwitched(deviceMap, currentUserId, beforeUserId); } + +HWTEST_F(DeviceManagerServiceImplTest, SaveOnlineDeviceInfo_001, testing::ext::TestSize.Level0) +{ + std::vector deviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + dmDeviceInfo.networkType = 1; + deviceList.push_back(dmDeviceInfo); + + if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + int32_t ret = deviceManagerServiceImpl_->SaveOnlineDeviceInfo(deviceList); + EXPECT_EQ(ret, DM_OK); + + int32_t remoteUserId = 1; + std::string remoteUdid = "remoteDeviceId"; + int32_t tokenId = 0; + ProcessInfo processInfo; + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(processInfo)); + deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); + + processInfo.pkgName = "pkgName"; + if (deviceManagerServiceImpl_->softbusConnector_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + EXPECT_CALL(*deviceProfileConnectorMock_, HandleAppUnBindEvent(_, _, _, _)).WillOnce(Return(processInfo)); + deviceManagerServiceImpl_->HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId); + + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_INVALIED_BINDTYPE)); + deviceManagerServiceImpl_->HandleDevUnBindEvent(remoteUserId, remoteUdid); + + EXPECT_CALL(*deviceProfileConnectorMock_, HandleDevUnBindEvent(_, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + if (deviceManagerServiceImpl_->authMgr_ == nullptr) { + deviceManagerServiceImpl_->Initialize(listener_); + } + deviceManagerServiceImpl_->HandleDevUnBindEvent(remoteUserId, remoteUdid); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index c4881f45f..e5ad83704 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -523,6 +523,13 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_202, testing::ext::TestSize.Leve EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(DM_OK)); ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*kVAdapterManagerMock_, Get(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(DM_IDENTICAL_ACCOUNT)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnBindDevice(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); + EXPECT_EQ(ret, ERR_DM_FAILED); } HWTEST_F(DeviceManagerServiceTest, LoadHardwareFwkService_201, testing::ext::TestSize.Level0) @@ -552,6 +559,18 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS int ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); EXPECT_EQ(ret, ERR_DM_FAILED); + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnAuthenticateDevice(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, ERR_DM_FAILED); + + EXPECT_CALL(*softbusListenerMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceImplMock_, GetBindLevel(_, _, _, _)).WillOnce(Return(1)); + EXPECT_CALL(*deviceManagerServiceImplMock_, UnAuthenticateDevice(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().UnAuthenticateDevice(pkgName, networkId); + EXPECT_EQ(ret, DM_OK); + int32_t userId = 123456; std::string accountId = "accountId"; std::string accountName = "accountName"; @@ -724,6 +743,33 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_205, testing::ext::TestS DeviceManagerService::GetInstance().UninitDMServiceListener(); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } + +HWTEST_F(DeviceManagerServiceTest, DmHiDumper_201, testing::ext::TestSize.Level0) +{ + std::vector args; + std::string result; + std::vector dumpflag; + dumpflag.push_back(HidumperFlag::HIDUMPER_GET_DEVICE_STATE); + dumpflag.push_back(HidumperFlag::HIDUMPER_GET_HELP); + dumpflag.push_back(HidumperFlag::HIDUMPER_GET_TRUSTED_LIST); + std::vector deviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + dmDeviceInfo.deviceTypeId = 0; + deviceList.push_back(dmDeviceInfo); + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + EXPECT_CALL(*hiDumpHelperMock_, GetArgsType(_, _)).WillOnce(DoAll(SetArgReferee<1>(dumpflag), Return(DM_OK))); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(DM_OK))); + int ret = DeviceManagerService::GetInstance().DmHiDumper(args, result); + EXPECT_EQ(ret, DM_OK); + + EXPECT_CALL(*hiDumpHelperMock_, GetArgsType(_, _)).WillOnce(DoAll(SetArgReferee<1>(dumpflag), Return(DM_OK))); + EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) + .WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(ERR_DM_FAILED))); + ret = DeviceManagerService::GetInstance().DmHiDumper(args, result); + EXPECT_EQ(ret, ERR_DM_FAILED); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_ipc_client_stub.cpp b/test/unittest/UTTest_ipc_client_stub.cpp index 1affae3a7..ee256867f 100644 --- a/test/unittest/UTTest_ipc_client_stub.cpp +++ b/test/unittest/UTTest_ipc_client_stub.cpp @@ -15,6 +15,7 @@ #include "UTTest_ipc_client_stub.h" +#include #include #include "device_manager.h" @@ -35,6 +36,9 @@ #include "ipc_rsp.h" #include "ipc_def.h" +using namespace testing; +using namespace testing::ext; + namespace OHOS { namespace DistributedHardware { void IpcClientStubTest::SetUp() @@ -47,10 +51,14 @@ void IpcClientStubTest::TearDown() void IpcClientStubTest::SetUpTestCase() { + ipcCmdRegisterMock_ = std::make_shared(); + DmIpcCmdRegister::dmIpcCmdRegister = ipcCmdRegisterMock_; } void IpcClientStubTest::TearDownTestCase() { + DmIpcCmdRegister::dmIpcCmdRegister = nullptr; + ipcCmdRegisterMock_ = nullptr; } namespace { @@ -204,6 +212,25 @@ HWTEST_F(IpcClientStubTest, SendCmd_004, testing::ext::TestSize.Level0) int ret = instance->SendCmd(cmdCode, req, rsp); ASSERT_EQ(ret, result); } + +HWTEST_F(IpcClientStubTest, SendCmd_005, testing::ext::TestSize.Level0) +{ + int cmdCode = 1; + std::shared_ptr req = nullptr; + std::shared_ptr rsp = nullptr; + sptr instance = sptr(new IpcClientStub()); + EXPECT_CALL(*ipcCmdRegisterMock_, SetRequest(_, _, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*ipcCmdRegisterMock_, OnIpcCmd(_, _, _)).WillOnce(Return(DM_OK)); + int ret = instance->SendCmd(cmdCode, req, rsp); + ASSERT_EQ(ret, DM_OK); + + req = std::make_shared(); + rsp = std::make_shared(); + EXPECT_CALL(*ipcCmdRegisterMock_, SetRequest(_, _, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*ipcCmdRegisterMock_, OnIpcCmd(_, _, _)).WillOnce(Return(ERR_DM_FAILED)); + ret = instance->SendCmd(cmdCode, req, rsp); + ASSERT_EQ(ret, DM_OK); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_ipc_client_stub.h b/test/unittest/UTTest_ipc_client_stub.h index a73f2ef92..04d505804 100644 --- a/test/unittest/UTTest_ipc_client_stub.h +++ b/test/unittest/UTTest_ipc_client_stub.h @@ -17,9 +17,11 @@ #define OHOS_IPC_CLIENT_STUB_TEST_H #include +#include #include #include "ipc_client_stub.h" +#include "ipc_cmd_register_mock.h" namespace OHOS { namespace DistributedHardware { @@ -29,6 +31,7 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); + static inline std::shared_ptr ipcCmdRegisterMock_ = nullptr; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/device_manager_service_impl_mock.cpp b/test/unittest/mock/device_manager_service_impl_mock.cpp index da795a8b1..9fccf3ac2 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.cpp +++ b/test/unittest/mock/device_manager_service_impl_mock.cpp @@ -55,5 +55,11 @@ std::unordered_map DeviceManagerServiceImpl::GetAppTrus { return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->GetAppTrustDeviceIdList(pkgname); } + +int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel) +{ + return DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl->UnAuthenticateDevice(pkgName, udid, bindLevel); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_impl_mock.h b/test/unittest/mock/device_manager_service_impl_mock.h index a76a19ea5..b996fab88 100644 --- a/test/unittest/mock/device_manager_service_impl_mock.h +++ b/test/unittest/mock/device_manager_service_impl_mock.h @@ -34,6 +34,7 @@ public: virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; virtual std::multimap GetDeviceIdAndUserId(int32_t localUserId) = 0; virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname) = 0; + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) = 0; public: static inline std::shared_ptr dmDeviceManagerServiceImpl = nullptr; }; @@ -47,6 +48,7 @@ public: MOCK_METHOD((std::multimap), GetDeviceIdAndUserId, (int32_t)); MOCK_METHOD((std::map), GetDeviceIdAndBindLevel, (int32_t)); MOCK_METHOD((std::unordered_map), GetAppTrustDeviceIdList, (std::string)); + MOCK_METHOD(int32_t, UnAuthenticateDevice, (const std::string &, const std::string &, int32_t)); }; } } diff --git a/test/unittest/mock/deviceprofile_connector_mock.cpp b/test/unittest/mock/deviceprofile_connector_mock.cpp index 9b3daa511..f7136e2ec 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.cpp +++ b/test/unittest/mock/deviceprofile_connector_mock.cpp @@ -56,5 +56,12 @@ bool DeviceProfileConnector::DeleteAclForAccountLogOut(const std::string &localU return DmDeviceProfileConnector::dmDeviceProfileConnector->DeleteAclForAccountLogOut(localUdid, localUserId, peerUdid, peerUserId); } + +OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) +{ + return DmDeviceProfileConnector::dmDeviceProfileConnector->HandleAppUnBindEvent(remoteUserId, remoteUdid, + tokenId, localUdid); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/deviceprofile_connector_mock.h b/test/unittest/mock/deviceprofile_connector_mock.h index e656c90ba..97e22cde6 100644 --- a/test/unittest/mock/deviceprofile_connector_mock.h +++ b/test/unittest/mock/deviceprofile_connector_mock.h @@ -37,6 +37,8 @@ public: const std::string &peerUdid) = 0; virtual bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId) = 0; + virtual OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) = 0; public: static inline std::shared_ptr dmDeviceProfileConnector = nullptr; }; @@ -50,6 +52,8 @@ public: MOCK_METHOD(uint32_t, CheckBindType, (std::string, std::string)); MOCK_METHOD((std::map), GetUserIdAndBindLevel, (const std::string &, const std::string &)); MOCK_METHOD(bool, DeleteAclForAccountLogOut, (const std::string &, int32_t, const std::string &, int32_t)); + MOCK_METHOD((OHOS::DistributedHardware::ProcessInfo), HandleAppUnBindEvent, (int32_t, const std::string &, + int32_t, const std::string &)); }; } } diff --git a/test/unittest/mock/dm_hidumper_mock.cpp b/test/unittest/mock/dm_hidumper_mock.cpp new file mode 100644 index 000000000..10a851085 --- /dev/null +++ b/test/unittest/mock/dm_hidumper_mock.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_hidumper_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(HiDumpHelper); +int32_t HiDumpHelper::GetArgsType(const std::vector& args, std::vector &Flag) +{ + return DmHiDumpHelper::dmHiDumpHelper->GetArgsType(args, Flag); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_hidumper_mock.h b/test/unittest/mock/dm_hidumper_mock.h new file mode 100644 index 000000000..bcc46a034 --- /dev/null +++ b/test/unittest/mock/dm_hidumper_mock.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_DM_HIDUMPER_MOCK_H +#define OHOS_DM_HIDUMPER_MOCK_H + +#include +#include + +#include "dm_hidumper.h" + +namespace OHOS { +namespace DistributedHardware { +class DmHiDumpHelper { +public: + virtual ~DmHiDumpHelper() = default; +public: + virtual int32_t GetArgsType(const std::vector& args, std::vector &Flag) = 0; +public: + static inline std::shared_ptr dmHiDumpHelper = nullptr; +}; + +class HiDumpHelperMock : public DmHiDumpHelper { +public: + MOCK_METHOD(int32_t, GetArgsType, (const std::vector&, std::vector &)); +}; +} +} +#endif diff --git a/test/unittest/mock/ipc_cmd_register_mock.cpp b/test/unittest/mock/ipc_cmd_register_mock.cpp new file mode 100644 index 000000000..0094b2a87 --- /dev/null +++ b/test/unittest/mock/ipc_cmd_register_mock.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ipc_cmd_register_mock.h" + +#include "gtest/gtest.h" + +namespace OHOS { +namespace DistributedHardware { +DM_IMPLEMENT_SINGLE_INSTANCE(IpcCmdRegister); +int32_t IpcCmdRegister::SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) +{ + return DmIpcCmdRegister::dmIpcCmdRegister->SetRequest(cmdCode, pBaseReq, data); +} + +int32_t IpcCmdRegister::OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply) +{ + return DmIpcCmdRegister::dmIpcCmdRegister->OnIpcCmd(cmdCode, data, reply); +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/ipc_cmd_register_mock.h b/test/unittest/mock/ipc_cmd_register_mock.h new file mode 100644 index 000000000..499b0b62b --- /dev/null +++ b/test/unittest/mock/ipc_cmd_register_mock.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef OHOS_IPC_CMD_REGISTER_MOCK_H +#define OHOS_IPC_CMD_REGISTER_MOCK_H + +#include +#include + +#include "ipc_cmd_register.h" + +namespace OHOS { +namespace DistributedHardware { +class DmIpcCmdRegister { +public: + virtual ~DmIpcCmdRegister() = default; +public: + virtual int32_t SetRequest(int32_t cmdCode, std::shared_ptr pBaseReq, MessageParcel &data) = 0; + virtual int32_t OnIpcCmd(int32_t cmdCode, MessageParcel &data, MessageParcel &reply) = 0; +public: + static inline std::shared_ptr dmIpcCmdRegister = nullptr; +}; + +class IpcCmdRegisterMock : public DmIpcCmdRegister { +public: + MOCK_METHOD(int32_t, SetRequest, (int32_t, std::shared_ptr, MessageParcel &)); + MOCK_METHOD(int32_t, OnIpcCmd, (int32_t, MessageParcel &, MessageParcel &)); +}; +} +} +#endif diff --git a/test/unittest/mock/multiple_user_connector_mock.h b/test/unittest/mock/multiple_user_connector_mock.h index 434de7480..3f1b93062 100644 --- a/test/unittest/mock/multiple_user_connector_mock.h +++ b/test/unittest/mock/multiple_user_connector_mock.h @@ -28,6 +28,7 @@ public: public: virtual int32_t GetCurrentAccountUserID(void) = 0; virtual int32_t GetFirstForegroundUserId(void) = 0; + virtual int32_t GetFirstForegroundUserId(void) = 0; public: static inline std::shared_ptr dmMultipleUserConnector = nullptr; }; @@ -36,6 +37,7 @@ class MultipleUserConnectorMock : public DmMultipleUserConnector { public: MOCK_METHOD(int32_t, GetCurrentAccountUserID, ()); MOCK_METHOD(int32_t, GetFirstForegroundUserId, ()); + MOCK_METHOD(int32_t, GetFirstForegroundUserId, ()); }; } } -- Gitee From e6593fed76b58c638746ca493efb8f059237446d Mon Sep 17 00:00:00 2001 From: l60055366 Date: Tue, 3 Dec 2024 20:07:03 +0800 Subject: [PATCH 494/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_device_manager_service.cpp | 3 +++ test/unittest/UTTest_device_manager_service.h | 4 +++ .../UTTest_device_manager_service_three.cpp | 25 ++++++++++++++++++ .../UTTest_device_manager_service_two.cpp | 26 +++++++++++++++++++ .../mock/device_manager_service_mock.cpp | 10 +++++++ .../mock/device_manager_service_mock.h | 4 +++ .../mock/multiple_user_connector_mock.cpp | 10 +++++++ .../mock/multiple_user_connector_mock.h | 6 +++-- test/unittest/mock/softbus_listener_mock.cpp | 6 +++++ test/unittest/mock/softbus_listener_mock.h | 3 +++ 10 files changed, 95 insertions(+), 2 deletions(-) diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index f5a1654a6..786fa801c 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -73,6 +73,7 @@ void DeviceManagerServiceTest::SetUpTestCase() DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; DmCrypto::dmCrypto = cryptoMock_; DmHiDumpHelper::dmHiDumpHelper = hiDumpHelperMock_; + DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; } void DeviceManagerServiceTest::TearDownTestCase() @@ -93,6 +94,8 @@ void DeviceManagerServiceTest::TearDownTestCase() cryptoMock_ = nullptr; DmHiDumpHelper::dmHiDumpHelper = nullptr; hiDumpHelperMock_ = nullptr; + DmMultipleUserConnector::dmMultipleUserConnector = nullptr; + multipleUserConnectorMock_ = nullptr; } namespace { diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index aa27c4e8c..6fa639435 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -27,6 +27,7 @@ #include "device_manager_service_impl.h" #include "dm_single_instance.h" #include "common_event_support.h" +#include "mock/multiple_user_connector_mock.h" #include "permission_manager_mock.h" #include "softbus_listener_mock.h" #include "app_manager_mock.h" @@ -35,6 +36,7 @@ #include "dm_softbus_cache_mock.h" #include "dm_crypto_mock.h" #include "dm_hidumper_mock.cpp" +#include "multiple_user_connector_mock.h" namespace OHOS { namespace DistributedHardware { @@ -59,6 +61,8 @@ public: std::make_shared(); static inline std::shared_ptr cryptoMock_ = std::make_shared(); static inline std::shared_ptr hiDumpHelperMock_ = std::make_shared(); + static inline std::shared_ptr multipleUserConnectorMock_ = + std::make_shared(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 62fb618fa..796af69f3 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -268,6 +268,12 @@ HWTEST_F(DeviceManagerServiceThreeTest, BindTarget_301, testing::ext::TestSize.L EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); EXPECT_EQ(ret, ERR_DM_NOT_INIT); + + bindParam.insert(std::make_pair(PARAM_KEY_META_TYPE, pkgName)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(true)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); + ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); } HWTEST_F(DeviceManagerServiceThreeTest, DpAclAdd_301, testing::ext::TestSize.Level0) @@ -321,6 +327,15 @@ HWTEST_F(DeviceManagerServiceThreeTest, ImportAuthCode_301, testing::ext::TestSi EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); EXPECT_EQ(ret, ERR_DM_NOT_INIT); + + std::vector deviceList; + DmDeviceInfo dmDeviceInfo; + dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + deviceList.push_back(dmDeviceInfo); + EXPECT_CALL(*deviceManagerServiceMock_, GetTrustedDeviceList(_, _)) + .WillOnce(DoAll(SetArgReferee<1>(deviceList),Return(DM_OK))); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); + DeviceManagerService::GetInstance().LoadHardwareFwkService(); } HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSize.Level0) @@ -345,6 +360,16 @@ HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSi EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); } + +HWTEST_F(DeviceManagerServiceThreeTest, UnbindTarget_301, testing::ext::TestSize.Level0) +{ + std::string pkgName = "pkgName"; + PeerTargetId targetId; + std::map unbindParam; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, unbindParam); + EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index e5ad83704..689edca07 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -267,6 +267,18 @@ HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.L DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); commonEventType = "common.event.HWID_LOGIN"; DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); + commonEventType = CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + int32_t currentUserId = -1; + int32_t beforeUserId = 0; + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, currentUserId, beforeUserId); + commonEventType = CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; + currentUserId = 1; + beforeUserId = 1; + DMAccountInfo dmAccountInfo; + dmAccountInfo.accountId = "accountId"; + dmAccountInfo.accountName = "accountName"; + EXPECT_CALL(*multipleUserConnectorMock_, GetAccountInfoByUserId(_)).WillOnce(Return(dmAccountInfo)); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, currentUserId, beforeUserId); int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); EXPECT_EQ(ret, DM_OK); } @@ -475,6 +487,11 @@ HWTEST_F(DeviceManagerServiceTest, BindTarget_201, testing::ext::TestSize.Level0 bindParam.insert(std::make_pair(key, value)); int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + targetId.wifiIp = "178.168.1.2"; + EXPECT_CALL(*softbusListenerMock_, GetIPAddrTypeFromCache(_, _, _)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, bindParam); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, SetLocalDeviceName_201, testing::ext::TestSize.Level0) @@ -595,6 +612,7 @@ HWTEST_F(DeviceManagerServiceTest, UnAuthenticateDevice_201, testing::ext::TestS preUserDeviceMap["accountName"] = 1; EXPECT_CALL(*deviceManagerServiceImplMock_, GetDeviceIdAndBindLevel(_)).WillOnce(Return(curUserDeviceMap)).WillOnce(Return(preUserDeviceMap)); + EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)).WillOnce(Return(ERR_DM_FAILED)); DeviceManagerService::GetInstance().HandleUserSwitched(curUserId, preUserId); int32_t removeId = 123; @@ -648,6 +666,14 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz EXPECT_CALL(*softbusListenerMock_, GetTargetInfoFromCache(_, _, _)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().AuthenticateDevice(pkgName, authType, deviceId, extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); + + std::vector peerUdids; + int32_t userId = 123456; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + DeviceManagerService::GetInstance().SendUserRemovedBroadCast(peerUdids, userId); + DeviceManagerService::GetInstance().softbusListener_ = nullptr; } HWTEST_F(DeviceManagerServiceTest, RegDevStateCallbackToService_201, testing::ext::TestSize.Level0) diff --git a/test/unittest/mock/device_manager_service_mock.cpp b/test/unittest/mock/device_manager_service_mock.cpp index 77b82c325..eb31d8b47 100644 --- a/test/unittest/mock/device_manager_service_mock.cpp +++ b/test/unittest/mock/device_manager_service_mock.cpp @@ -24,5 +24,15 @@ bool DeviceManagerService::IsDMServiceImplReady() { return DmDeviceManagerService::dmDeviceManagerService->IsDMServiceImplReady(); } + +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList) +{ + return DmDeviceManagerService::dmDeviceManagerService->GetTrustedDeviceList(pkgName, deviceList); +} + +bool DeviceManagerService::IsDMServiceAdapterLoad() +{ + return DmDeviceManagerService::dmDeviceManagerService->IsDMServiceAdapterLoad(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/device_manager_service_mock.h b/test/unittest/mock/device_manager_service_mock.h index 29d3b9bcc..3339012e6 100644 --- a/test/unittest/mock/device_manager_service_mock.h +++ b/test/unittest/mock/device_manager_service_mock.h @@ -27,6 +27,8 @@ public: virtual ~DmDeviceManagerService() = default; public: virtual bool IsDMServiceImplReady() = 0; + virtual int32_t GetTrustedDeviceList(const std::string &pkgName, std::vector &deviceList) = 0; + virtual bool IsDMServiceAdapterLoad() = 0; public: static inline std::shared_ptr dmDeviceManagerService = nullptr; }; @@ -34,6 +36,8 @@ public: class DeviceManagerServiceMock : public DmDeviceManagerService { public: MOCK_METHOD(bool, IsDMServiceImplReady, ()); + MOCK_METHOD(int32_t, GetTrustedDeviceList, (const std::string &, std::vector &)); + MOCK_METHOD(bool, IsDMServiceAdapterLoad, ()); }; } } diff --git a/test/unittest/mock/multiple_user_connector_mock.cpp b/test/unittest/mock/multiple_user_connector_mock.cpp index f4432ca56..3f1498f2d 100644 --- a/test/unittest/mock/multiple_user_connector_mock.cpp +++ b/test/unittest/mock/multiple_user_connector_mock.cpp @@ -28,5 +28,15 @@ int32_t MultipleUserConnector::GetFirstForegroundUserId(void) { return DmMultipleUserConnector::dmMultipleUserConnector->GetFirstForegroundUserId(); } + +DMAccountInfo MultipleUserConnector::GetAccountInfoByUserId(int32_t userId) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetAccountInfoByUserId(userId); +} + +int32_t MultipleUserConnector::GetBackgroundUserIds(std::vector &userIdVec) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetBackgroundUserIds(userIdVec); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/multiple_user_connector_mock.h b/test/unittest/mock/multiple_user_connector_mock.h index 3f1b93062..b73b75af5 100644 --- a/test/unittest/mock/multiple_user_connector_mock.h +++ b/test/unittest/mock/multiple_user_connector_mock.h @@ -28,7 +28,8 @@ public: public: virtual int32_t GetCurrentAccountUserID(void) = 0; virtual int32_t GetFirstForegroundUserId(void) = 0; - virtual int32_t GetFirstForegroundUserId(void) = 0; + virtual DMAccountInfo GetAccountInfoByUserId(int32_t userId) = 0; + virtual int32_t GetBackgroundUserIds(std::vector &userIdVec) = 0; public: static inline std::shared_ptr dmMultipleUserConnector = nullptr; }; @@ -37,7 +38,8 @@ class MultipleUserConnectorMock : public DmMultipleUserConnector { public: MOCK_METHOD(int32_t, GetCurrentAccountUserID, ()); MOCK_METHOD(int32_t, GetFirstForegroundUserId, ()); - MOCK_METHOD(int32_t, GetFirstForegroundUserId, ()); + MOCK_METHOD(DMAccountInfo, GetAccountInfoByUserId, (int32_t)); + MOCK_METHOD(int32_t, GetBackgroundUserIds, (std::vector &)); }; } } diff --git a/test/unittest/mock/softbus_listener_mock.cpp b/test/unittest/mock/softbus_listener_mock.cpp index 5dee44809..16c67e46f 100644 --- a/test/unittest/mock/softbus_listener_mock.cpp +++ b/test/unittest/mock/softbus_listener_mock.cpp @@ -69,5 +69,11 @@ int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &s { return DmSoftbusListener::dmSoftbusListener->GetDeviceScreenStatus(networkId, screenStatus); } + +int32_t SoftbusListener::GetIPAddrTypeFromCache(const std::string &deviceId, const std::string &ip, + ConnectionAddrType &addrType) +{ + return DmSoftbusListener::dmSoftbusListener->GetIPAddrTypeFromCache(deviceId, ip, addrType); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_listener_mock.h b/test/unittest/mock/softbus_listener_mock.h index 49a358357..81ca4db72 100644 --- a/test/unittest/mock/softbus_listener_mock.h +++ b/test/unittest/mock/softbus_listener_mock.h @@ -37,6 +37,8 @@ public: virtual int32_t GetLocalDeviceInfo(DmDeviceInfo &deviceInfo) = 0; virtual int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName) = 0; virtual int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus) = 0; + virtual int32_t GetIPAddrTypeFromCache(const std::string &deviceId, const std::string &ip, + ConnectionAddrType &addrType) = 0; public: static inline std::shared_ptr dmSoftbusListener = nullptr; }; @@ -53,6 +55,7 @@ public: MOCK_METHOD(int32_t, GetLocalDeviceInfo, (DmDeviceInfo &)); MOCK_METHOD(int32_t, SetLocalDeviceName, (const std::string &, const std::string &)); MOCK_METHOD(int32_t, GetDeviceScreenStatus, (const char *, int32_t &)); + MOCK_METHOD(int32_t, GetIPAddrTypeFromCache, (const std::string &, const std::string &, ConnectionAddrType &)); }; } } -- Gitee From 9cfa491923d49be00d888311f89842fe4a0e372a Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Tue, 3 Dec 2024 20:09:18 +0800 Subject: [PATCH 495/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9active=EF=BC=8Cinacti?= =?UTF-8?q?ve=E6=97=B6=E5=BA=8F=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/src/device_manager_service_impl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 333571d79..a3bb844a4 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -889,10 +889,10 @@ void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector } DeviceProfileConnector::GetInstance().UpdateACL(localUdid, localUserIds, remoteUdid, rmtFrontUserIdsTemp, rmtBackUserIdsTemp); - DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, - localUserIds, localUdid); DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(rmtBackUserIdsTemp, remoteUdid, localUserIds, localUdid); + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(rmtFrontUserIdsTemp, remoteUdid, + localUserIds, localUdid); } void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) -- Gitee From 59289a9fb8737b4360225d1b0d30c1489a83615c Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 4 Dec 2024 10:44:42 +0800 Subject: [PATCH 496/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/UTTest_device_manager_service.h | 1 - .../UTTest_device_manager_service_three.cpp | 35 ++++++++++ .../UTTest_device_manager_service_two.cpp | 67 +++++++++++++++++++ .../mock/multiple_user_connector_mock.cpp | 5 ++ .../mock/multiple_user_connector_mock.h | 2 + .../unittest/mock/permission_manager_mock.cpp | 5 ++ test/unittest/mock/permission_manager_mock.h | 2 + 7 files changed, 116 insertions(+), 1 deletion(-) diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index 6fa639435..e0720533e 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -27,7 +27,6 @@ #include "device_manager_service_impl.h" #include "dm_single_instance.h" #include "common_event_support.h" -#include "mock/multiple_user_connector_mock.h" #include "permission_manager_mock.h" #include "softbus_listener_mock.h" #include "app_manager_mock.h" diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 796af69f3..85f3a86bf 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -84,6 +84,28 @@ void DeviceManagerServiceThreeTest::TearDownTestCase() namespace { +void SetSetDnPolicyPermission() +{ + const int32_t permsNum = 1; + const int32_t indexZero = 0; + uint64_t tokenId; + const char *perms[permsNum]; + perms[indexZero] = "ohos.permission.ACCESS_SERVICE_DM"; + NativeTokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = permsNum, + .aclsNum = 0, + .dcaps = NULL, + .perms = perms, + .acls = NULL, + .processName = "collaboration_service", + .aplStr = "system_core", + }; + tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + OHOS::Security::AccessToken::AccessTokenKit::ReloadNativeTokenInfo(); +} + /** * @tc.name: AuthenticateDevice_301 * @tc.desc: Set unsupport authType = 0 and return ERR_DM_NOT_INIT @@ -370,6 +392,19 @@ HWTEST_F(DeviceManagerServiceThreeTest, UnbindTarget_301, testing::ext::TestSize int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, unbindParam); EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); } + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_207, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); +} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 689edca07..a100951b5 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -317,6 +317,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); bool bRet = false; if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD || ret == SOFTBUS_IPC_ERR) { @@ -336,6 +337,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_202, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -350,6 +352,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_203, testing::ext::TestSize.Level SetSetDnPolicyPermission(); std::map policy; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -364,6 +367,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -379,6 +383,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_205, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -394,6 +399,7 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_206, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100a"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -673,6 +679,39 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); } DeviceManagerService::GetInstance().SendUserRemovedBroadCast(peerUdids, userId); + + std::vector peerUdids; + std::vector foregroundUserIds; + std::vector backgroundUserIds; + bool isNeedResponse = false; + foregroundUserIds.push_back(1); + foregroundUserIds.push_back(101); + backgroundUserIds.push_back(102); + backgroundUserIds.push_back(12); + DeviceManagerService::GetInstance().SendUserIdsBroadCast(peerUdids, foregroundUserIds, + backgroundUserIds, isNeedResponse); + + std::vector remoteUserIdInfos; + UserIdInfo userIdInfo; + userIdInfo.isForeground = true; + userIdInfo.userId = 1; + remoteUserIdInfos.push_back(userIdInfo); + UserIdInfo userIdInfo1; + userIdInfo1.isForeground = true; + userIdInfo1.userId = 101; + remoteUserIdInfos.push_back(userIdInfo); + std::string remoteUdid = "remoteDeviceId"; + isNeedResponse = true; + EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)).WillOnce(Return(ERR_DM_FAILED)); + DeviceManagerService::GetInstance().HandleUserIdsBroadCast(remoteUserIdInfos, remoteUdid, isNeedResponse); + + std::vector foregroundUserVec; + foregroundUserVec.push_back(1); + foregroundUserVec.push_back(102); + EXPECT_CALL(*multipleUserConnectorMock_, GetForegroundUserIds(_)) + .WillOnce(DoAll(SetArgReferee<0>(foregroundUserVec), Return(DM_OK))); + EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)).WillOnce(Return(DM_OK)); + DeviceManagerService::GetInstance().HandleUserIdsBroadCast(remoteUserIdInfos, remoteUdid, isNeedResponse); DeviceManagerService::GetInstance().softbusListener_ = nullptr; } @@ -795,6 +834,34 @@ HWTEST_F(DeviceManagerServiceTest, DmHiDumper_201, testing::ext::TestSize.Level0 .WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(ERR_DM_FAILED))); ret = DeviceManagerService::GetInstance().DmHiDumper(args, result); EXPECT_EQ(ret, ERR_DM_FAILED); + + std::vector foregroundUserIds; + foregroundUserIds.push_back(1); + std::vector backgroundUserIds; + backgroundUserIds.push_back(2); + std::string remoteUdid = "remoteUdid"; + if (DeviceManagerService::GetInstance().softbusListener_ == nullptr) { + DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); + } + DeviceManagerService::GetInstance().ProcessSyncUserIds(foregroundUserIds, backgroundUserIds, remoteUdid); +} + +HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_207, testing::ext::TestSize.Level0) +{ + SetSetDnPolicyPermission(); + std::string packName = "com.ohos.test"; + std::map policy; + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100a"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(ERR_DM_FAILED)); + int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_FAILED); + + policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; + policy[PARAM_KEY_POLICY_TIME_OUT] = "10a"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/mock/multiple_user_connector_mock.cpp b/test/unittest/mock/multiple_user_connector_mock.cpp index 3f1498f2d..480c1c937 100644 --- a/test/unittest/mock/multiple_user_connector_mock.cpp +++ b/test/unittest/mock/multiple_user_connector_mock.cpp @@ -38,5 +38,10 @@ int32_t MultipleUserConnector::GetBackgroundUserIds(std::vector &userId { return DmMultipleUserConnector::dmMultipleUserConnector->GetBackgroundUserIds(userIdVec); } + +int32_t MultipleUserConnector::GetForegroundUserIds(std::vector &userVec) +{ + return DmMultipleUserConnector::dmMultipleUserConnector->GetForegroundUserIds(userVec); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/multiple_user_connector_mock.h b/test/unittest/mock/multiple_user_connector_mock.h index b73b75af5..e29fa2e0e 100644 --- a/test/unittest/mock/multiple_user_connector_mock.h +++ b/test/unittest/mock/multiple_user_connector_mock.h @@ -30,6 +30,7 @@ public: virtual int32_t GetFirstForegroundUserId(void) = 0; virtual DMAccountInfo GetAccountInfoByUserId(int32_t userId) = 0; virtual int32_t GetBackgroundUserIds(std::vector &userIdVec) = 0; + virtual int32_t GetForegroundUserIds(std::vector &userVec) = 0; public: static inline std::shared_ptr dmMultipleUserConnector = nullptr; }; @@ -40,6 +41,7 @@ public: MOCK_METHOD(int32_t, GetFirstForegroundUserId, ()); MOCK_METHOD(DMAccountInfo, GetAccountInfoByUserId, (int32_t)); MOCK_METHOD(int32_t, GetBackgroundUserIds, (std::vector &)); + MOCK_METHOD(int32_t, GetForegroundUserIds, (std::vector &)); }; } } diff --git a/test/unittest/mock/permission_manager_mock.cpp b/test/unittest/mock/permission_manager_mock.cpp index 384707cbb..df84d7a83 100644 --- a/test/unittest/mock/permission_manager_mock.cpp +++ b/test/unittest/mock/permission_manager_mock.cpp @@ -29,5 +29,10 @@ bool PermissionManager::CheckProcessNameValidOnAuthCode(const std::string &proce { return DmPermissionManager::dmPermissionManager->CheckProcessNameValidOnAuthCode(processName); } + +int32_t PermissionManager::GetCallerProcessName(std::string &processName) +{ + return DmPermissionManager::dmPermissionManager->GetCallerProcessName(processName); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/permission_manager_mock.h b/test/unittest/mock/permission_manager_mock.h index ec7fde7f8..b5c061e69 100644 --- a/test/unittest/mock/permission_manager_mock.h +++ b/test/unittest/mock/permission_manager_mock.h @@ -28,6 +28,7 @@ public: public: virtual bool CheckProcessNameValidOnPinHolder(const std::string &processName) = 0; virtual bool CheckProcessNameValidOnAuthCode(const std::string &processName) = 0; + virtual int32_t GetCallerProcessName(std::string &processName) = 0; public: static inline std::shared_ptr dmPermissionManager = nullptr; }; @@ -36,6 +37,7 @@ class PermissionManagerMock : public DmPermissionManager { public: MOCK_METHOD(bool, CheckProcessNameValidOnPinHolder, (const std::string &)); MOCK_METHOD(bool, CheckProcessNameValidOnAuthCode, (const std::string &)); + MOCK_METHOD(int32_t, GetCallerProcessName, (std::string &)); }; } } -- Gitee From ca800b9f059a955a4e9ca267b71c3ddd508adec7 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 4 Dec 2024 14:12:41 +0800 Subject: [PATCH 497/520] =?UTF-8?q?=E5=85=8B=E9=9A=86=E8=AE=A4=E8=AF=81?= =?UTF-8?q?=E5=9B=9E=E8=B0=83=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../implementation/src/authentication/dm_auth_manager.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index a64369643..6f786cfde 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2070,6 +2070,10 @@ void DmAuthManager::AuthDeviceError(int64_t requestId, int32_t errorCode) return; } if (authResponseContext_->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + if (requestId != authResponseContext_->requestId) { + LOGE("DmAuthManager::AuthDeviceError requestId %{public}" PRId64 "is error.", requestId); + return; + } authResponseContext_->state = AuthState::AUTH_REQUEST_JOIN; authRequestContext_->reason = ERR_DM_AUTH_CODE_INCORRECT; authResponseContext_->reply = ERR_DM_AUTH_CODE_INCORRECT; @@ -2254,6 +2258,10 @@ void DmAuthManager::ProcIncompatible(const int32_t &sessionId) void DmAuthManager::OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message) { + if (authResponseContext_ == nullptr || authMessageProcessor_ == nullptr || hiChainAuthConnector_ == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } authResponseContext_->sessionId = sessionId; authMessageProcessor_->SetResponseContext(authResponseContext_); nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); -- Gitee From 63152d2905c6daff6f7191445f8e4a94ac7a2d94 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 4 Dec 2024 14:20:52 +0800 Subject: [PATCH 498/520] =?UTF-8?q?=E8=A7=A6=E5=8F=91=E7=BB=84=E7=BD=91?= =?UTF-8?q?=E6=97=B6=E6=B7=BB=E5=8A=A0udidhash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../src/dependency/softbus/softbus_connector.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index b89de1c22..560959b0d 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -265,9 +265,9 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId) LOGE("addrInfo is nullptr."); return; } - if (memcpy_s(addrInfo->info.ble.udidHash, UDID_HASH_LEN, - remoteUdidHash_.c_str(), remoteUdidHash_.length()) != 0) { - LOGE("memcpy remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + remoteUdidHash_.c_str(), remoteUdidHash_.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); return; } int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult); -- Gitee From 6250ed317d5a597f121103e63cab57e4a1d36534 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Wed, 4 Dec 2024 14:31:18 +0800 Subject: [PATCH 499/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9checkSum=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../service/include/device_manager_service.h | 2 +- services/service/src/device_manager_service.cpp | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 0d66148f5..469f2486c 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -236,7 +236,7 @@ private: * @param discoveryType remote device link type, wifi or ble/br * @return int32_t 0 for success */ - int32_t ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType); + int32_t ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType, bool &isChange); void ProcessCheckSumByWifi(std::string networkId, std::vector foregroundUserIds, std::vector backgroundUserIds); void ProcessCheckSumByBT(std::string networkId, std::vector foregroundUserIds, diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index c13f4a445..fcf4dd9d9 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -75,6 +75,7 @@ namespace { const std::string USERID_CHECKSUM_DISCOVER_TYPE_KEY = "discoverType"; constexpr uint32_t USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK = 0b0010; const std::string DHARD_WARE_PKG_NAME = "ohos.dhardware"; + const std::string USERID_CHECKSUM_ISCHANGE_KEY = "ischange"; } DeviceManagerService::~DeviceManagerService() @@ -2059,7 +2060,8 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) return; } -int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType) +int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::string &networkId, uint32_t &discoveryType, + bool &isChange) { nlohmann::json msgJsonObj = nlohmann::json::parse(msg, nullptr, false); if (msgJsonObj.is_discarded()) { @@ -2074,8 +2076,13 @@ int32_t DeviceManagerService::ParseCheckSumMsg(const std::string &msg, std::stri LOGE("msg not contain discoveryType."); return ERR_DM_FAILED; } + if (!IsBool(msgJsonObj, USERID_CHECKSUM_ISCHANGE_KEY)) { + LOGE("msg not contain ischange."); + return ERR_DM_FAILED; + } networkId = msgJsonObj[USERID_CHECKSUM_NETWORKID_KEY].get(); discoveryType = msgJsonObj[USERID_CHECKSUM_DISCOVER_TYPE_KEY].get(); + isChange = msgJsonObj[USERID_CHECKSUM_ISCHANGE_KEY].get(); return DM_OK; } @@ -2133,12 +2140,16 @@ void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg) LOGI("handle user trust change, msg: %{public}s", GetAnonyString(msg).c_str()); std::string remoteNetworkId = ""; uint32_t discoveryType = 0; - int32_t ret = ParseCheckSumMsg(msg, remoteNetworkId, discoveryType); + bool isPeerUserIdChanged = true; + int32_t ret = ParseCheckSumMsg(msg, remoteNetworkId, discoveryType, isPeerUserIdChanged); if (ret != DM_OK) { LOGE("Parse checksum msg error"); return; } - + if (!isPeerUserIdChanged) { + LOGI("Peer foreground userId not change."); + return; + } std::vector foregroundUserIds; ret = MultipleUserConnector::GetForegroundUserIds(foregroundUserIds); if (ret != DM_OK || foregroundUserIds.empty()) { -- Gitee From e59cf290d99d240a4adb489b14c8a76c7b46290a Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 4 Dec 2024 15:41:30 +0800 Subject: [PATCH 500/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 134 +++++++++++++----- ...Test_dm_deviceprofile_connector_second.cpp | 1 + .../UTTest_softbus_listener.cpp | 2 +- .../UTTest_device_manager_service_impl.cpp | 16 +++ .../UTTest_device_manager_service_three.cpp | 4 +- .../UTTest_device_manager_service_two.cpp | 21 +-- ...mock_distributed_device_profile_client.cpp | 107 ++++++++++++++ 7 files changed, 234 insertions(+), 51 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 3c54c7122..538d0ae28 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -99,6 +99,56 @@ void AddAccessControlProfileFirst(std::vector& accessControlProfiles) { int32_t userId = 123456; @@ -359,8 +409,7 @@ void AddAccessControlProfileSix(std::vector& accessControlProfiles) +void AddAccessControlProfileSeven(DistributedDeviceProfile::AccessControlProfile& accessControlProfiles) { int32_t userId = 123456; int32_t bindType = 256; @@ -397,22 +446,20 @@ void AddAccessControlProfileSeven(std::vector& accessControlProfiles) +void AddAccessControlProfileEight(DistributedDeviceProfile::AccessControlProfile& accessControlProfiles) { int32_t userId = 123456; int32_t bindType = 1; @@ -449,19 +496,17 @@ void AddAccessControlProfileEight(std::vector& accessControlProfiles) @@ -1627,7 +1672,6 @@ HWTEST_F(DeviceProfileConnectorTest, GetUserIdAndBindLevel_001, testing::ext::Te userId = 456; std::vector remoteUserIds; remoteUserIds.push_back(userId); - std::vector localUserIds; localUserIds.push_back(userId); DeviceProfileConnector::GetInstance().HandleSyncBackgroundUserIdEvent(remoteUserIds, remoteUdid, localUserIds, localUdid); @@ -1690,9 +1734,9 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_004, testing::ext::Te auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); EXPECT_EQ(ret.empty(), false); - deviceId = "deviceIder001" + deviceId = "deviceIder001"; EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); - auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); EXPECT_EQ(ret.empty(), false); std::string udid; @@ -1763,7 +1807,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ex EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); - EXPECT_FASLE(ret.empty()); + EXPECT_FALSE(ret.empty()); } HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_002, testing::ext::TestSize.Level0) @@ -1782,7 +1826,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_002, testing::ext::TestSi discoveryInfo.pkgname = "bundleName"; discoveryInfo.localDeviceId = "deviceId"; EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).WillOnce(Return(DM_OK)); - int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); + ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); } @@ -1806,7 +1850,6 @@ HWTEST_F(DeviceProfileConnectorTest, CheckSrcDevIdInAclForDevBind_005, testing:: std::vector remoteFrontUserIds; std::vector remoteBackUserIds; AddAccessControlProfileFirst(profiles); - AddAccessControlProfileSix(profiles); DeviceProfileConnector::GetInstance().DeleteSigTrustACL(profiles, remoteUdid, remoteFrontUserIds, remoteBackUserIds); @@ -1838,19 +1881,34 @@ HWTEST_F(DeviceProfileConnectorTest, CheckAccessControl_002, testing::ext::TestS std::string sinkUdid = "deviceId"; int32_t ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, DM_OK); + + srcUdid = "remoteDeviceId"; + sinkUdid = "localDeviceId"; + caller.userId = 456; + callee.userId = 456; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); + + callee.userId = 0; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(DeviceProfileConnectorTest, CheckIsSameAccount_002, testing::ext::TestSize.Level0) { - int32_t userId = 123456; + int32_t userId = 456; DmAccessCaller caller; caller.userId = userId; - std::string srcUdid = "deviceId"; + std::string srcUdid = "localDeviceId"; DmAccessCallee callee; callee.userId = userId; - std::string sinkUdid = "deviceId"; + std::string sinkUdid = "remoteDeviceId"; int32_t ret = DeviceProfileConnector::GetInstance().CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, DM_OK); + + callee.userId = 0; + ret = DeviceProfileConnector::GetInstance().CheckAccessControl(caller, srcUdid, callee, sinkUdid); + EXPECT_EQ(ret, DM_OK); } HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_002, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp index 8a43f4537..a49629d07 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector_second.cpp @@ -161,6 +161,7 @@ HWTEST_F(DeviceProfileConnectorSecondTest, CheckIdenticalAccount_201, testing::e int32_t bindType = 1; std::string deviceIdEr = "deviceId"; std::string deviceIdEe = "deviceIdEe"; + uint32_t accesserId = 1; DistributedDeviceProfile::Accesser accesser; accesser.SetAccesserDeviceId(deviceIdEr); accesser.SetAccesserUserId(userId); diff --git a/test/softbusunittest/UTTest_softbus_listener.cpp b/test/softbusunittest/UTTest_softbus_listener.cpp index 5354642d7..783bc0362 100644 --- a/test/softbusunittest/UTTest_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_softbus_listener.cpp @@ -1086,7 +1086,7 @@ HWTEST_F(SoftbusListenerTest, SetForegroundUserIdsToDSoftBus_001, testing::ext:: int32_t ret = softbusListener->SetForegroundUserIdsToDSoftBus(remoteUdid, userIds); EXPECT_EQ(ret, DM_OK); - uint32_t deviceListLen = 2001; + const uint32_t deviceListLen = 2001; char devicelist[deviceListLen] = {0}; uint16_t deviceTypeId = 0; int32_t errcode = -1; diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 66b591bc8..f5c7eecb0 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1647,6 +1647,8 @@ HWTEST_F(DeviceManagerServiceImplTest, CheckIsSameAccount_001, testing::ext::Tes if (deviceManagerServiceImpl_->authMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } + std::vector profiles; + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); int ret = deviceManagerServiceImpl_->CheckIsSameAccount(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1660,6 +1662,8 @@ HWTEST_F(DeviceManagerServiceImplTest, CheckAccessControl_001, testing::ext::Tes if (deviceManagerServiceImpl_->authMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } + std::vector profiles; + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); int ret = deviceManagerServiceImpl_->CheckAccessControl(caller, srcUdid, callee, sinkUdid); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1680,6 +1684,12 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleDeviceScreenStatusChange_001, testi EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(IDENTICAL_ACCOUNT_TYPE)); deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); + + std::vector profiles; + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); + deviceManagerServiceImpl_->HandleDeviceScreenStatusChange(devInfo); EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); } @@ -1729,12 +1739,15 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOnline_003, testing::ext::TestSize. EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(DEVICE_ACROSS_ACCOUNT_TYPE)); deviceManagerServiceImpl_->HandleOnline(devState, devInfo); + std::vector profiles; EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_PEER_TO_PEER_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); deviceManagerServiceImpl_->HandleOnline(devState, devInfo); EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).WillOnce(Return(DM_OK)); EXPECT_CALL(*deviceProfileConnectorMock_, CheckBindType(_, _)).WillOnce(Return(APP_ACROSS_ACCOUNT_TYPE)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()).WillOnce(Return(profiles)); deviceManagerServiceImpl_->HandleOnline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->softbusConnector_, nullptr); } @@ -1756,8 +1769,11 @@ HWTEST_F(DeviceManagerServiceImplTest, HandleOffline_003, testing::ext::TestSize userIdAndBindLevel[2] = DEVICE; userIdAndBindLevel[3] = SERVICE; userIdAndBindLevel[4] = APP; + std::vector profiles; EXPECT_CALL(*dmDeviceStateManagerMock_, GetUdidByNetWorkId(_)).WillOnce(Return("123456")); EXPECT_CALL(*deviceProfileConnectorMock_, GetUserIdAndBindLevel(_, _)).WillOnce(Return(userIdAndBindLevel)); + EXPECT_CALL(*deviceProfileConnectorMock_, GetAllAccessControlProfile()) + .WillOnce(Return(profiles)).WillOnce(Return(profiles)); deviceManagerServiceImpl_->HandleOffline(devState, devInfo); EXPECT_NE(deviceManagerServiceImpl_->deviceStateMgr_, nullptr); } diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 85f3a86bf..99f8bf1e7 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -355,7 +355,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, ImportAuthCode_301, testing::ext::TestSi dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; deviceList.push_back(dmDeviceInfo); EXPECT_CALL(*deviceManagerServiceMock_, GetTrustedDeviceList(_, _)) - .WillOnce(DoAll(SetArgReferee<1>(deviceList),Return(DM_OK))); + .WillOnce(DoAll(SetArgReferee<1>(deviceList), Return(DM_OK))); EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); DeviceManagerService::GetInstance().LoadHardwareFwkService(); } @@ -393,7 +393,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, UnbindTarget_301, testing::ext::TestSize EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); } -HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_207, testing::ext::TestSize.Level0) +HWTEST_F(DeviceManagerServiceThreeTest, SetDnPolicy_301, testing::ext::TestSize.Level0) { SetSetDnPolicyPermission(); std::string packName = "com.ohos.test"; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index a100951b5..485fd46fc 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -267,11 +267,11 @@ HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.L DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); commonEventType = "common.event.HWID_LOGIN"; DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); - commonEventType = CommonEventSupport::COMMON_EVENT_USER_SWITCHED; + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; int32_t currentUserId = -1; int32_t beforeUserId = 0; DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, currentUserId, beforeUserId); - commonEventType = CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; + commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; currentUserId = 1; beforeUserId = 1; DMAccountInfo dmAccountInfo; @@ -680,7 +680,6 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz } DeviceManagerService::GetInstance().SendUserRemovedBroadCast(peerUdids, userId); - std::vector peerUdids; std::vector foregroundUserIds; std::vector backgroundUserIds; bool isNeedResponse = false; @@ -692,14 +691,16 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz backgroundUserIds, isNeedResponse); std::vector remoteUserIdInfos; - UserIdInfo userIdInfo; - userIdInfo.isForeground = true; - userIdInfo.userId = 1; - remoteUserIdInfos.push_back(userIdInfo); - UserIdInfo userIdInfo1; - userIdInfo1.isForeground = true; - userIdInfo1.userId = 101; + UserIdInfo userIdInfo = { + .isForeground = true, + .userId = 1 + }; remoteUserIdInfos.push_back(userIdInfo); + UserIdInfo userIdInfo1 = { + .isForeground = true, + .userId = 101 + }; + remoteUserIdInfos.push_back(userIdInfo1); std::string remoteUdid = "remoteDeviceId"; isNeedResponse = true; EXPECT_CALL(*multipleUserConnectorMock_, GetBackgroundUserIds(_)).WillOnce(Return(ERR_DM_FAILED)); diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index 9f01182d1..6a358789b 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -1513,6 +1513,110 @@ void AddAccessControlProfileTwentyNinth(std::vector& acces accessControlProfiles.push_back(profileFifth); } +void AddAccessControlProfileThirtieth(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1002; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(0); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + +void AddAccessControlProfilethirtyfirst(std::vector& accessControlProfiles) +{ + int32_t userId = 456; + int32_t bindType = 1; + int32_t deviceIdType = 1; + uint32_t bindLevel = 3; + uint32_t status = 1; + uint32_t authenticationType = 2; + uint32_t accesserId = 1; + uint32_t tokenId = 1002; + + std::string oldAccountId = ""; + std::string newAccountId = "newAccountId"; + std::string deviceIdEr = "remoteDeviceId"; + std::string deviceIdEe = "localDeviceId"; + std::string trustDeviceId = "localDeviceId"; + + Accesser accesser; + accesser.SetAccesserId(accesserId); + accesser.SetAccesserDeviceId(deviceIdEr); + accesser.SetAccesserUserId(userId); + accesser.SetAccesserAccountId(oldAccountId); + accesser.SetAccesserTokenId(tokenId); + accesser.SetAccesserBundleName("bundleName"); + accesser.SetAccesserHapSignature("uph1"); + accesser.SetAccesserBindLevel(bindLevel); + + Accessee accessee; + accessee.SetAccesseeId(accesserId); + accessee.SetAccesseeDeviceId(deviceIdEe); + accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeAccountId(newAccountId); + accessee.SetAccesseeTokenId(tokenId); + accessee.SetAccesseeBundleName("bundleName"); + accessee.SetAccesseeHapSignature("uph1"); + accessee.SetAccesseeBindLevel(bindLevel); + + AccessControlProfile profileFifth; + profileFifth.SetAccessControlId(accesserId); + profileFifth.SetAccesserId(accesserId); + profileFifth.SetAccesseeId(accesserId); + profileFifth.SetTrustDeviceId(trustDeviceId); + profileFifth.SetBindType(bindType); + profileFifth.SetAuthenticationType(authenticationType); + profileFifth.SetDeviceIdType(deviceIdType); + profileFifth.SetStatus(status); + profileFifth.SetBindLevel(bindLevel); + profileFifth.SetAccesser(accesser); + profileFifth.SetAccessee(accessee); + accessControlProfiles.push_back(profileFifth); +} + int32_t DistributedDeviceProfileClient::PutAccessControlProfile(const AccessControlProfile& accessControlProfile) { return 0; @@ -1566,6 +1670,7 @@ int32_t DistributedDeviceProfileClient::GetAccessControlProfile(std::map Date: Wed, 4 Dec 2024 16:20:29 +0800 Subject: [PATCH 501/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_deviceprofile_connector.cpp | 34 ------------------- .../UTTest_device_manager_service_two.cpp | 10 ++---- 2 files changed, 2 insertions(+), 42 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 538d0ae28..67e0b31c9 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1746,40 +1746,6 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_004, testing::ext::Te DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); } -HWTEST_F(DeviceProfileConnectorTest, GetACLByDeviceIdAndUserId_001, testing::ext::TestSize.Level0) -{ - std::vector profiles; - DmAccessCaller caller; - std::string srcUdid = "remoteDeviceId"; - DmAccessCallee callee; - std::string sinkUdid = "localDeviceId"; - AddAccessControlProfileFirst(profiles); - AddAccessControlProfileSix(profiles); - - int32_t userId = 123456; - caller.userId = userId; - callee.userId = userId; - auto ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, - callee, srcUdid); - EXPECT_EQ(ret.empty(), false); - - callee.userId = 0; - ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, - callee, srcUdid); - EXPECT_EQ(ret.empty(), false); - - srcUdid = "localDeviceId"; - sinkUdid = "remoteDeviceId"; - ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, - callee, srcUdid); - EXPECT_EQ(ret.empty(), false); - - callee.userId == 0 ; - ret = DeviceProfileConnector::GetInstance().GetACLByDeviceIdAndUserId(profiles, caller, srcUdid, - callee, srcUdid); - EXPECT_EQ(ret.empty(), false); -} - HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ext::TestSize.Level0) { std::string localUdid = "deviceId"; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 485fd46fc..86d9dcb9f 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -691,15 +691,9 @@ HWTEST_F(DeviceManagerServiceTest, AuthenticateDevice_205, testing::ext::TestSiz backgroundUserIds, isNeedResponse); std::vector remoteUserIdInfos; - UserIdInfo userIdInfo = { - .isForeground = true, - .userId = 1 - }; + UserIdInfo userIdInfo(true, 1); remoteUserIdInfos.push_back(userIdInfo); - UserIdInfo userIdInfo1 = { - .isForeground = true, - .userId = 101 - }; + UserIdInfo userIdInfo1(true, 102); remoteUserIdInfos.push_back(userIdInfo1); std::string remoteUdid = "remoteDeviceId"; isNeedResponse = true; -- Gitee From f255b77634a41ef34542807408dac1f027f01871 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 4 Dec 2024 17:06:41 +0800 Subject: [PATCH 502/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/unittest/BUILD.gn | 1 - .../UTTest_device_manager_service.cpp | 3 -- test/unittest/UTTest_device_manager_service.h | 2 - .../UTTest_device_manager_service_two.cpp | 7 +--- test/unittest/mock/dm_hidumper_mock.cpp | 28 ------------- test/unittest/mock/dm_hidumper_mock.h | 40 ------------------- 6 files changed, 1 insertion(+), 80 deletions(-) delete mode 100644 test/unittest/mock/dm_hidumper_mock.cpp delete mode 100644 test/unittest/mock/dm_hidumper_mock.h diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 32beda7ea..176b10184 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -333,7 +333,6 @@ ohos_unittest("UTTest_device_manager_service") { "mock/app_manager_mock.cpp", "mock/device_manager_service_impl_mock.cpp", "mock/dm_crypto_mock.cpp", - "mock/dm_hidumper_mock.cpp", "mock/dm_softbus_cache_mock.cpp", "mock/kv_adapter_manager_mock.cpp", "mock/permission_manager_mock.cpp", diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 786fa801c..766b80ce0 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -72,7 +72,6 @@ void DeviceManagerServiceTest::SetUpTestCase() DmDeviceManagerServiceImpl::dmDeviceManagerServiceImpl = deviceManagerServiceImplMock_; DmSoftbusCache::dmSoftbusCache = softbusCacheMock_; DmCrypto::dmCrypto = cryptoMock_; - DmHiDumpHelper::dmHiDumpHelper = hiDumpHelperMock_; DmMultipleUserConnector::dmMultipleUserConnector = multipleUserConnectorMock_; } @@ -92,8 +91,6 @@ void DeviceManagerServiceTest::TearDownTestCase() softbusCacheMock_ = nullptr; DmCrypto::dmCrypto = nullptr; cryptoMock_ = nullptr; - DmHiDumpHelper::dmHiDumpHelper = nullptr; - hiDumpHelperMock_ = nullptr; DmMultipleUserConnector::dmMultipleUserConnector = nullptr; multipleUserConnectorMock_ = nullptr; } diff --git a/test/unittest/UTTest_device_manager_service.h b/test/unittest/UTTest_device_manager_service.h index e0720533e..c9ccef448 100644 --- a/test/unittest/UTTest_device_manager_service.h +++ b/test/unittest/UTTest_device_manager_service.h @@ -34,7 +34,6 @@ #include "device_manager_service_impl_mock.h" #include "dm_softbus_cache_mock.h" #include "dm_crypto_mock.h" -#include "dm_hidumper_mock.cpp" #include "multiple_user_connector_mock.h" namespace OHOS { @@ -59,7 +58,6 @@ public: static inline std::shared_ptr softbusCacheMock_ = std::make_shared(); static inline std::shared_ptr cryptoMock_ = std::make_shared(); - static inline std::shared_ptr hiDumpHelperMock_ = std::make_shared(); static inline std::shared_ptr multipleUserConnectorMock_ = std::make_shared(); }; diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 86d9dcb9f..a2d34fc62 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -807,24 +807,19 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_205, testing::ext::TestS HWTEST_F(DeviceManagerServiceTest, DmHiDumper_201, testing::ext::TestSize.Level0) { std::vector args; + args.push_back(std::string(HIDUMPER_GET_TRUSTED_LIST_INFO)); std::string result; - std::vector dumpflag; - dumpflag.push_back(HidumperFlag::HIDUMPER_GET_DEVICE_STATE); - dumpflag.push_back(HidumperFlag::HIDUMPER_GET_HELP); - dumpflag.push_back(HidumperFlag::HIDUMPER_GET_TRUSTED_LIST); std::vector deviceList; DmDeviceInfo dmDeviceInfo; dmDeviceInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; dmDeviceInfo.deviceTypeId = 0; deviceList.push_back(dmDeviceInfo); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); - EXPECT_CALL(*hiDumpHelperMock_, GetArgsType(_, _)).WillOnce(DoAll(SetArgReferee<1>(dumpflag), Return(DM_OK))); EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) .WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(DM_OK))); int ret = DeviceManagerService::GetInstance().DmHiDumper(args, result); EXPECT_EQ(ret, DM_OK); - EXPECT_CALL(*hiDumpHelperMock_, GetArgsType(_, _)).WillOnce(DoAll(SetArgReferee<1>(dumpflag), Return(DM_OK))); EXPECT_CALL(*softbusListenerMock_, GetTrustedDeviceList(_)) .WillOnce(DoAll(SetArgReferee<0>(deviceList), Return(ERR_DM_FAILED))); ret = DeviceManagerService::GetInstance().DmHiDumper(args, result); diff --git a/test/unittest/mock/dm_hidumper_mock.cpp b/test/unittest/mock/dm_hidumper_mock.cpp deleted file mode 100644 index 10a851085..000000000 --- a/test/unittest/mock/dm_hidumper_mock.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "dm_hidumper_mock.h" - -#include "gtest/gtest.h" - -namespace OHOS { -namespace DistributedHardware { -DM_IMPLEMENT_SINGLE_INSTANCE(HiDumpHelper); -int32_t HiDumpHelper::GetArgsType(const std::vector& args, std::vector &Flag) -{ - return DmHiDumpHelper::dmHiDumpHelper->GetArgsType(args, Flag); -} -} // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/dm_hidumper_mock.h b/test/unittest/mock/dm_hidumper_mock.h deleted file mode 100644 index bcc46a034..000000000 --- a/test/unittest/mock/dm_hidumper_mock.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef OHOS_DM_HIDUMPER_MOCK_H -#define OHOS_DM_HIDUMPER_MOCK_H - -#include -#include - -#include "dm_hidumper.h" - -namespace OHOS { -namespace DistributedHardware { -class DmHiDumpHelper { -public: - virtual ~DmHiDumpHelper() = default; -public: - virtual int32_t GetArgsType(const std::vector& args, std::vector &Flag) = 0; -public: - static inline std::shared_ptr dmHiDumpHelper = nullptr; -}; - -class HiDumpHelperMock : public DmHiDumpHelper { -public: - MOCK_METHOD(int32_t, GetArgsType, (const std::vector&, std::vector &)); -}; -} -} -#endif -- Gitee From 667288a68208556b19a1efdcbdd65763fab6de55 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Wed, 4 Dec 2024 20:36:49 +0800 Subject: [PATCH 503/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- .../UTTest_dm_auth_manager_first.cpp | 4 +-- .../UTTest_dm_deviceprofile_connector.cpp | 16 +++++----- .../UTTest_device_manager_service.cpp | 31 ++++++++++++++++--- .../UTTest_device_manager_service_three.cpp | 8 +++-- .../UTTest_device_manager_service_two.cpp | 26 +++++++++++----- ...mock_distributed_device_profile_client.cpp | 4 +-- 6 files changed, 65 insertions(+), 24 deletions(-) diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 3b80ab38c..35050401f 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1128,7 +1128,7 @@ HWTEST_F(DmAuthManagerTest, DeleteGroup002, testing::ext::TestSize.Level0) std::string pkgName = "pkgName"; std::string deviceId; int32_t ret = authManager_->DeleteGroup(pkgName, deviceId); - ASSERT_NE(ret, DM_OK); + ASSERT_EQ(ret, DM_OK); } HWTEST_F(DmAuthManagerTest, PutAccessControlList001, testing::ext::TestSize.Level0) @@ -1324,7 +1324,7 @@ HWTEST_F(DmAuthManagerTest, GetTaskTimeout_001, testing::ext::TestSize.Level0) EXPECT_EQ(authManager_->GetTaskTimeout("test", taskTimeOut), taskTimeOut); authManager_->SetAuthType(AUTH_TYPE_IMPORT_AUTH_CODE); - EXPECT_EQ(authManager_->GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, taskTimeOut), CLONE_AUTHENTICATE_TIMEOUT); + EXPECT_EQ(authManager_->GetTaskTimeout(AUTHENTICATE_TIMEOUT_TASK, taskTimeOut), 20); } HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 67e0b31c9..a298267a1 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -552,7 +552,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_001, testing::ext::TestSi DmDiscoveryInfo discoveryInfo; bool isonline = true; int32_t authForm = 0; - EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30)).WillOnce(Return(DM_OK)); int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); } @@ -1106,7 +1106,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_002, testing: std::string pkgName = "bundleName"; std::string deviceId = "123456"; bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); - EXPECT_EQ(ret, false); + EXPECT_EQ(ret, true); } HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_003, testing::ext::TestSize.Level0) @@ -1557,6 +1557,8 @@ HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_005, testing: EXPECT_FALSE(ret.empty()); localDeviceId = "remoteDeviceId"; + targetDeviceId = "localDeviceId"; + userId = 456; ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, userId); EXPECT_FALSE(ret.empty()); @@ -1737,7 +1739,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_004, testing::ext::Te deviceId = "deviceIder001"; EXPECT_CALL(*multipleUserConnectorMock_, GetFirstForegroundUserId()).WillOnce(Return(123456)); ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); - EXPECT_EQ(ret.empty(), false); + EXPECT_EQ(ret.empty(), true); std::string udid; DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); @@ -1762,7 +1764,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ex peerUserId, peerAccountHash); EXPECT_TRUE(ret.empty()); - EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).Times(::testing::AtLeast(40)).WillOnce(Return(DM_OK)); ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); EXPECT_FALSE(ret.empty()); @@ -1770,7 +1772,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDevIdAndUserIdByActHash_001, testing::ex localUdid = "remoteDeviceId"; peerUdid = "localDeviceId"; peerUserId = 456; - EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).WillOnce(Return(DM_OK)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*cryptoMock_, GetAccountIdHash(_, _)).Times(::testing::AtLeast(40)).WillOnce(Return(DM_OK)); ret = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, peerUdid, peerUserId, peerAccountHash); EXPECT_FALSE(ret.empty()); @@ -1785,13 +1787,13 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_002, testing::ext::TestSi discoveryInfo.pkgname = ""; bool isonline = true; int32_t authForm = 0; - EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30))WillOnce(Return(DM_OK)); int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); discoveryInfo.pkgname = "bundleName"; discoveryInfo.localDeviceId = "deviceId"; - EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).WillOnce(Return(DM_OK)); + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30))WillOnce(Return(DM_OK)); ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 766b80ce0..5eb73957f 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -1214,6 +1214,7 @@ HWTEST_F(DeviceManagerServiceTest, UnBindDevice_001, testing::ext::TestSize.Leve { std::string pkgName = "com.ohos.test"; std::string deviceId = "1234"; + EXPECT_CALL(*softbusCacheMock_, GetUdidByUdidHash(_, _)).WillOnce(Return(ERR_DM_FAILED)); int32_t ret = DeviceManagerService::GetInstance().UnBindDevice(pkgName, deviceId); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1430,6 +1431,7 @@ HWTEST_F(DeviceManagerServiceTest, NotifyEvent_001, testing::ext::TestSize.Level "pkInfo" : "pkginfo", "peerDeviceId" : "3515656546" })"; + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().HandleDeviceNotTrust(msg); std::string commonEventType = "helloworld"; DeviceManagerService::GetInstance().isImplsoLoaded_ = false; @@ -1608,6 +1610,7 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_002, testing::ext::TestSize.Le { std::string pkgName = "pkgName"; std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1624,6 +1627,7 @@ HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_001, testing::ext::TestSize.Le HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_002, testing::ext::TestSize.Level0) { std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1955,6 +1959,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_001, testing::ext:: HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_002, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); EXPECT_NE(ret, DM_OK); @@ -1977,9 +1982,10 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_002, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_001, testing::ext::TestSize.Level0) @@ -1999,9 +2005,10 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_002, testing::ext::TestSize. PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -2123,8 +2130,11 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_001, testing::ext::TestSize.Level { std::string pkgName; std::map policy; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_002, testing::ext::TestSize.Level0) @@ -2150,8 +2160,11 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); DeviceManagerService::GetInstance().SendDeviceUnBindBroadCast(peerUdids, userId); DeviceManagerService::GetInstance().softbusListener_ = nullptr; + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int ret = DeviceManagerService::GetInstance().SetDnPolicy(pkgName, policy); - EXPECT_NE(ret, DM_OK); + EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) @@ -2160,6 +2173,7 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize. PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -2367,6 +2381,7 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_004, testing::ext::TestSize. PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().DestroyPinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -2378,6 +2393,7 @@ HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_005, testing::ext::TestSize. PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { DeviceManagerService::GetInstance().InitDMServiceListener(); @@ -2392,6 +2408,7 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_003, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -2403,6 +2420,7 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_004, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = DmPinType::QR_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { DeviceManagerService::GetInstance().InitDMServiceListener(); @@ -2414,6 +2432,7 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_004, testing::ext::TestSize.L HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_003, testing::ext::TestSize.Level0) { std::string pkgName; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -2422,6 +2441,7 @@ HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_003, testing::ext:: HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_004, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(true)); if (DeviceManagerService::GetInstance().pinHolder_ == nullptr) { DeviceManagerService::GetInstance().InitDMServiceListener(); @@ -2452,6 +2472,7 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_003, testing::ext::TestSize.Le { std::string pkgName = "pkgName"; std::string authCode; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -2461,6 +2482,7 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_004, testing::ext::TestSize.Le { std::string pkgName = "pkgName"; std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); EXPECT_EQ(ret, DM_OK); @@ -2469,6 +2491,7 @@ HWTEST_F(DeviceManagerServiceTest, ImportAuthCode_004, testing::ext::TestSize.Le HWTEST_F(DeviceManagerServiceTest, ExportAuthCode_003, testing::ext::TestSize.Level0) { std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); EXPECT_EQ(ret, DM_OK); diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 99f8bf1e7..7dea10f1e 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -345,6 +345,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, ImportAuthCode_301, testing::ext::TestSi { std::string pkgName = "pkgName"; std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ImportAuthCode(pkgName, authCode); @@ -363,6 +364,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, ImportAuthCode_301, testing::ext::TestSi HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSize.Level0) { std::string authCode = "authCode"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnAuthCode(_)).WillOnce(Return(true)); EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().ExportAuthCode(authCode); @@ -389,7 +391,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, UnbindTarget_301, testing::ext::TestSize PeerTargetId targetId; std::map unbindParam; EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); - int32_t ret = DeviceManagerService::GetInstance().BindTarget(pkgName, targetId, unbindParam); + int32_t ret = DeviceManagerService::GetInstance().UnbindTarget(pkgName, targetId, unbindParam); EXPECT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); } @@ -400,7 +402,9 @@ HWTEST_F(DeviceManagerServiceThreeTest, SetDnPolicy_301, testing::ext::TestSize. std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_METHOD); diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index a2d34fc62..d8463dbd9 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -317,7 +317,9 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_201, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); bool bRet = false; if (ret == DM_OK || ret == ERR_DM_UNSUPPORTED_METHOD || ret == SOFTBUS_IPC_ERR) { @@ -337,7 +339,9 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_202, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -352,7 +356,9 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_203, testing::ext::TestSize.Level SetSetDnPolicyPermission(); std::map policy; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -367,7 +373,9 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_204, testing::ext::TestSize.Level std::string packName = "com.ohos.test"; std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100"; - EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -383,7 +391,9 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_205, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "a100"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -399,7 +409,9 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_206, testing::ext::TestSize.Level std::map policy; policy[PARAM_KEY_POLICY_STRATEGY_FOR_BLE] = "100a"; policy[PARAM_KEY_POLICY_TIME_OUT] = "10"; - EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); + std::string processName = "collaboration_service"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)) + .WillOnce(DoAll(SetArgReferee<0>(processName), Return(DM_OK))); int32_t ret = DeviceManagerService::GetInstance().SetDnPolicy(packName, policy); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -807,7 +819,7 @@ HWTEST_F(DeviceManagerServiceTest, GetTrustedDeviceList_205, testing::ext::TestS HWTEST_F(DeviceManagerServiceTest, DmHiDumper_201, testing::ext::TestSize.Level0) { std::vector args; - args.push_back(std::string(HIDUMPER_GET_TRUSTED_LIST_INFO)); + args.push_back(std::string("-getTrustlist")); std::string result; std::vector deviceList; DmDeviceInfo dmDeviceInfo; diff --git a/test/unittest/mock/mock_distributed_device_profile_client.cpp b/test/unittest/mock/mock_distributed_device_profile_client.cpp index 6a358789b..b2d2b28e6 100644 --- a/test/unittest/mock/mock_distributed_device_profile_client.cpp +++ b/test/unittest/mock/mock_distributed_device_profile_client.cpp @@ -1170,7 +1170,7 @@ void AddAccessControlProfileTwentythree(std::vector& acces Accesser accesser; accesser.SetAccesserId(accesserId); accesser.SetAccesserDeviceId(deviceIdEr); - accesser.SetAccesserUserId(0); + accesser.SetAccesserUserId(userId); accesser.SetAccesserAccountId(oldAccountId); accesser.SetAccesserTokenId(tokenId); accesser.SetAccesserBundleName("bundleName"); @@ -1180,7 +1180,7 @@ void AddAccessControlProfileTwentythree(std::vector& acces Accessee accessee; accessee.SetAccesseeId(accesserId); accessee.SetAccesseeDeviceId(deviceIdEe); - accessee.SetAccesseeUserId(userId); + accessee.SetAccesseeUserId(0); accessee.SetAccesseeAccountId(newAccountId); accessee.SetAccesseeTokenId(tokenId); accessee.SetAccesseeBundleName("bundleName"); -- Gitee From 7d1c7cef54a5e4da7f98bd1c38cce9504130c0a6 Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 5 Dec 2024 09:03:15 +0800 Subject: [PATCH 504/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index a298267a1..92d8ebbbe 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1787,13 +1787,13 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceAclParam_002, testing::ext::TestSi discoveryInfo.pkgname = ""; bool isonline = true; int32_t authForm = 0; - EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30))WillOnce(Return(DM_OK)); + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30)).WillOnce(Return(DM_OK)); int32_t ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); discoveryInfo.pkgname = "bundleName"; discoveryInfo.localDeviceId = "deviceId"; - EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30))WillOnce(Return(DM_OK)); + EXPECT_CALL(*cryptoMock_, GetUdidHash(_, _)).Times(::testing::AtLeast(30)).WillOnce(Return(DM_OK)); ret = DeviceProfileConnector::GetInstance().GetDeviceAclParam(discoveryInfo, isonline, authForm); EXPECT_EQ(ret, DM_OK); } -- Gitee From b1e0ef21a50fcc351aeb936e6a52ae4ffad48a70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 5 Dec 2024 09:27:29 +0800 Subject: [PATCH 505/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- common/include/dm_anonymous.h | 1 + common/src/dm_anonymous.cpp | 8 ++++- .../native_cpp/src/device_manager_impl.cpp | 4 +-- .../kits/js/src/native_devicemanager_js.cpp | 4 +-- interfaces/kits/js4.0/src/dm_native_util.cpp | 4 +-- .../ability/standard/dm_dialog_manager.cpp | 2 +- .../authentication/auth_message_processor.cpp | 8 ++--- .../authentication/auth_ui_state_manager.cpp | 2 +- .../src/authentication/dm_auth_manager.cpp | 22 ++++++------ .../src/credential/dm_credential_manager.cpp | 4 +-- .../hichain/hichain_auth_connector.cpp | 16 ++++----- .../dependency/hichain/hichain_connector.cpp | 36 +++++++++---------- .../hichain/mine_hichain_connector.cpp | 4 +-- .../dependency/softbus/softbus_connector.cpp | 8 ++--- services/service/src/pinholder/pin_holder.cpp | 28 +++++++-------- .../service/src/softbus/softbus_listener.cpp | 4 +-- .../hichain_connector_fuzzer.cpp | 6 ++-- .../UTTest_discovery_filter.cpp | 30 ++++++++-------- .../UTTest_dm_auth_manager_first.cpp | 12 +++---- .../UTTest_dm_auth_manager_second.cpp | 18 +++++----- .../UTTest_dm_auth_manager_third.cpp | 16 ++++----- .../UTTest_dm_credential_manager.cpp | 16 ++++----- .../UTTest_dm_discovery_filter.cpp | 30 ++++++++-------- .../UTTest_hichain_auth_connector.cpp | 14 ++++---- .../UTTest_hichain_connector.cpp | 10 +++--- .../UTTest_mine_hichain_connector.cpp | 8 ++--- test/commonunittest/UTTest_pin_auth.cpp | 6 ++-- .../UTTest_mine_softbus_listener.cpp | 10 +++--- .../UTTest_softbus_session.cpp | 2 +- .../UTTest_auth_message_processor.cpp | 18 +++++----- test/unittest/UTTest_dm_pin_holder.cpp | 30 ++++++++-------- .../UTTest_ipc_cmd_parser_service.cpp | 4 +-- utils/src/kvadapter/dm_kv_info.cpp | 2 +- 33 files changed, 197 insertions(+), 190 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index f9a7356f6..4096baaf1 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -101,6 +101,7 @@ bool IsIdLengthValid(const std::string &inputID); bool IsMessageLengthValid(const std::string &inputMessage); bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId); bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent); +std::string SafeDump(const nlohmann::json &jsonObj); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 8ee7b0bb4..73bf8a471 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -184,7 +184,7 @@ std::string ConvertMapToJsonString(const std::map &par for (const auto &it : paramMap) { jsonObj[it.first] = it.second; } - jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + jsonStr = SafeDump(jsonObj); } return jsonStr; } @@ -365,5 +365,11 @@ bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent) } return false; } + +std::string SafeDump(const nlohmann::json &jsonObj) +{ + int indent = -1; + return jsonObj.dump(indent, ' ', false, nlohmann::detail::error_handler_t::ignore); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 48659a9c1..fdacce6f5 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -674,7 +674,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetExtra(extraJson.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); + req->SetExtra(SafeDump(extraJson)); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); @@ -1493,7 +1493,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetBindParam(paramJson.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); + req->SetBindParam(SafeDump(paramJson)); req->SetBindType(bindType); req->SetDeviceId(deviceId); int32_t ret = ipcClientProxy_->SendRequest(BIND_DEVICE, req, rsp); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 8ee6aaaa1..deb53b23c 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1203,7 +1203,7 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr; jsonObj[BIND_LEVEL] = bindLevel; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + extra = SafeDump(jsonObj); LOGI("appOperationLen %{public}zu, customDescriptionLen %{public}zu", appOperationStr.size(), customDescriptionStr.size()); } @@ -1274,7 +1274,7 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob jsonObj[AUTH_TYPE] = authType; jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + extra = SafeDump(jsonObj); } void DeviceManagerNapi::JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index 97c6e384e..c36bad407 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -330,7 +330,7 @@ void JsToBindParam(const napi_env &env, const napi_value &object, std::string &b jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP); jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort; jsonObj[BIND_LEVEL] = bindLevel; - bindParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + bindParam = SafeDump(jsonObj); } bool IsSystemApp() @@ -395,7 +395,7 @@ void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::st if (deviceType != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) { jsonObj["deviceType"] = deviceType; } - extra = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + extra = SafeDump(jsonObj); LOGI("JsToDmDiscoveryExtra, extra :%{public}s", extra.c_str()); } diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index dbb2cb4ee..ba6cdc029 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -202,7 +202,7 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = param.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string paramStr = SafeDump(param); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 98decdb71..edee3a0f4 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -87,7 +87,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1; jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; GetJsonObj(jsonObj); - jsonStrVec.push_back(jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); + jsonStrVec.push_back(SafeDump(jsonObj)); for (int32_t idx = 0; idx < thumbnailSlice; idx++) { nlohmann::json jsonThumbnailObj; jsonThumbnailObj[TAG_VER] = DM_ITF_VER; @@ -101,7 +101,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() LOGI("TAG_APP_THUMBNAIL encode, idx %{public}d, sliceLen %{public}d, thumbnailSize %{public}d", idx, (uint32_t)sliceLen, thumbnailSize); jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); - jsonStrVec.push_back(jsonThumbnailObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); + jsonStrVec.push_back(SafeDump(jsonThumbnailObj)); } return jsonStrVec; } @@ -138,7 +138,7 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) default: break; } - return jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + return SafeDump(jsonObj); } void AuthMessageProcessor::CreatePublicKeyMessageExt(nlohmann::json &json) @@ -593,7 +593,7 @@ std::string AuthMessageProcessor::CreateDeviceAuthMessage(int32_t msgType, const std::string authDataStr = std::string(reinterpret_cast(data), dataLen); jsonObj[TAG_DATA] = authDataStr; jsonObj[TAG_DATA_LEN] = dataLen; - return jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + return SafeDump(jsonObj); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index a9781bc45..29a9233fc 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -61,7 +61,7 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) } nlohmann::json jsonObj; jsonObj[UI_STATE_MSG] = msg; - std::string paramJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string paramJson = SafeDump(jsonObj); std::lock_guard lock(pkgSetMutex_); for (auto item : pkgSet_) { listener_->OnUiCall(item, paramJson); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 64fe4139e..b31fcb485 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -609,7 +609,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId jsonObj[PIN_TOKEN] = authResponseContext_->token; jsonObj[QR_CODE_KEY] = GenerateGroupName(); jsonObj[NFC_CODE_KEY] = GenerateGroupName(); - authResponseContext_->authToken = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + authResponseContext_->authToken = SafeDump(jsonObj); LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); authResponseContext_->groupId = groupId; authResponseContext_->code = pinCode; @@ -1176,7 +1176,7 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) jsonObject[PIN_CODE_KEY] = pinCode; jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; - std::string connectInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string connectInfo = SafeDump(jsonObject); if (timer_ != nullptr) { timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { @@ -1441,7 +1441,7 @@ void DmAuthManager::ShowConfigDialog() jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; - const std::string params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + const std::string params = SafeDump(jsonObj); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); @@ -1478,7 +1478,7 @@ void DmAuthManager::ShowAuthInfoDialog() } nlohmann::json jsonObj; jsonObj[PIN_CODE_KEY] = authResponseContext_->code; - std::string authParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string authParam = SafeDump(jsonObj); DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); } @@ -1650,7 +1650,7 @@ bool DmAuthManager::IsIdenticalAccount() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string queryParams = SafeDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1690,7 +1690,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string queryParams = SafeDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1705,7 +1705,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() for (auto &groupInfo : groupList) { jsonAccountObj.push_back(Crypto::GetGroupIdHash(groupInfo.groupId)); } - return jsonAccountObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + return SafeDump(jsonAccountObj); } int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) @@ -1893,7 +1893,7 @@ std::string DmAuthManager::GenerateBindResultContent() Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); jsonObj[TAG_DEVICE_ID] = deviceIdHash; } - std::string content = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string content = SafeDump(jsonObj); return content; } @@ -2237,7 +2237,7 @@ void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) } } jsonObject[TAG_CRYPTO_SUPPORT] = false; - message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + message = SafeDump(jsonObject); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2248,7 +2248,7 @@ void DmAuthManager::ProcIncompatible(const int32_t &sessionId) respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; respNegotiateMsg[TAG_VER] = DM_ITF_VER; respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; - std::string message = respNegotiateMsg.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(respNegotiateMsg); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2370,7 +2370,7 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); nlohmann::json jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObj); softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index fb0deca57..e0ba29e97 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -113,7 +113,7 @@ int32_t DmCredentialManager::RequestCredential(const std::string &reqJsonStr, st jsonObj[FIELD_CREDENTIAL_VERSION] = credentialVersion; jsonObj[FIELD_USER_ID] = userId; jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string tmpStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string tmpStr = SafeDump(jsonObj); return hiChainConnector_->getRegisterInfo(tmpStr.c_str(), returnJsonStr); } @@ -364,7 +364,7 @@ void from_json(const nlohmann::json &jsonObject, CredentialDataInfo &credentialD } if (IsString(jsonObject, FIELD_PKINFO)) { nlohmann::json jsonPkInfo = jsonObject[FIELD_PKINFO]; - credentialDataInfo.pkInfo = jsonPkInfo.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + credentialDataInfo.pkInfo = SafeDump(jsonPkInfo); } } else if (credentialDataInfo.credentialType == SYMMETRY_CREDENTIAL_TYPE) { if (IsString(jsonObject, FIELD_AUTH_CODE)) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 0be0ea90d..53ed5bd2c 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -56,7 +56,7 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s authParamJson["osAccountId"] = osAccountId; authParamJson["pinCode"] = std::to_string(pinCode); authParamJson["acquireType"] = AcquireType::P2P_BIND; - std::string authParam = authParamJson.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string authParam = SafeDump(authParamJson); LOGI("StartAuthDevice authParam %{public}s ,requestId %{public}" PRId64, GetAnonyString(authParam).c_str(), requestId); int32_t ret = StartAuthDevice(requestId, authParam.c_str(), &deviceAuthCallback_); @@ -74,7 +74,7 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut jsonAuthParam["osAccountId"] = osAccountId; jsonAuthParam["data"] = authData; int32_t ret = ProcessAuthDevice(requestId, - jsonAuthParam.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore).c_str(), &deviceAuthCallback_); + SafeDump(jsonAuthParam).c_str(), &deviceAuthCallback_); if (ret != HC_SUCCESS) { LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; @@ -112,7 +112,7 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string jsonStr = SafeDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -160,7 +160,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string requestParam = SafeDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_CREATE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain generate credential failed."); @@ -193,7 +193,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string requestParam = SafeDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -224,7 +224,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string requestParam = SafeDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -256,7 +256,7 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; - std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string requestParam = SafeDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_IMPORT, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -287,7 +287,7 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; - std::string requestParam = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string requestParam = SafeDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index a9a474e9b..53f64d269 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -155,7 +155,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou return ERR_DM_FAILED; } int32_t ret = deviceGroupManager_->createGroup(userId, requestId, - DM_PKG_NAME, jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore).c_str()); + DM_PKG_NAME, SafeDump(jsonObj).c_str()); struct RadarInfo info = { .funcName = "CreateGroup", .toCallPkg = HICHAINNAME, @@ -179,7 +179,7 @@ bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInf { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string queryParams = SafeDump(jsonObj); std::vector groupList; if (GetGroupInfo(queryParams, groupList)) { groupInfo = groupList[0]; @@ -192,7 +192,7 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string queryParams = SafeDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -344,7 +344,7 @@ int32_t HiChainConnector::AddMember(const std::string &deviceId, const std::stri jsonObj[FIELD_DEVICE_ID] = localDeviceId; jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME].get(); jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str(); - std::string tmpStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string tmpStr = SafeDump(jsonObj); int64_t requestId = jsonObject[TAG_REQUEST_ID].get(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { @@ -487,7 +487,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string jsonStr = SafeDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -512,7 +512,7 @@ std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string r } jsonObject[DEVICE_ID] = reqDeviceId; - return jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + return SafeDump(jsonObject); } int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vector &groupList) @@ -603,7 +603,7 @@ int32_t HiChainConnector::DelMemberFromGroup(const std::string &groupId, const s nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_DELETE_ID] = deviceId; - std::string deleteParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string deleteParams = SafeDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -622,7 +622,7 @@ int32_t HiChainConnector::DeleteGroup(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string disbandParams = SafeDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -642,7 +642,7 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string disbandParams = SafeDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -662,7 +662,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use networkStyle_ = CREDENTIAL_NETWORK; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string queryParams = SafeDump(jsonObj); std::vector groupList; if (!GetGroupInfo(queryParams, groupList)) { LOGE("failed to get device join groups"); @@ -683,7 +683,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use return ERR_DM_FAILED; } jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string disbandParams = SafeDump(jsonObj); g_deleteGroupFlag = false; int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -793,7 +793,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const return ERR_DM_FAILED; } int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, - jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore).c_str()); + SafeDump(jsonObj).c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); return ERR_DM_CREATE_GROUP_FAILED; @@ -843,7 +843,7 @@ int32_t HiChainConnector::GetGroupId(const std::string &userId, const int32_t gr { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string queryParams = SafeDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -876,7 +876,7 @@ int32_t HiChainConnector::ParseRemoteCredential(const int32_t groupType, const s jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = groupType; jsonObj[FIELD_DEVICE_LIST] = jsonDeviceList[FIELD_DEVICE_LIST]; - params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + params = SafeDump(jsonObj); osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { LOGE("get current process account user id failed"); @@ -930,7 +930,7 @@ int32_t HiChainConnector::GetGroupIdExt(const std::string &userId, const int32_t { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string queryParams = SafeDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -984,7 +984,7 @@ int32_t HiChainConnector::ParseRemoteCredentialExt(const std::string &credential return ERR_DM_FAILED; } jsonObj[FIELD_DEVICE_LIST] = jsonObject[FIELD_DEVICE_LIST]; - params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + params = SafeDump(jsonObj); return DM_OK; } @@ -1159,7 +1159,7 @@ int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string disbandParams = SafeDump(jsonObj); int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); if (ret != 0) { LOGE("[HICHAIN]fail to delete group with ret:%{public}d.", ret); @@ -1249,7 +1249,7 @@ int32_t HiChainConnector::DeleteGroupByACL(std::vector groupList; if (!GetGroupInfo(userId, queryParams, groupList)) { diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index 66ababfd1..3feba8802 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -135,7 +135,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) { nlohmann::json jsonObj; jsonObj[FIELD_IS_DELETE_ALL] = true; - std::string params = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string params = SafeDump(jsonObj); #if (defined(MINE_HARMONY)) char *returnInfo = nullptr; int32_t retValue = g_deviceGroupManager->processCredential(DELETE_SELF_CREDENTIAL, params.c_str(), &returnInfo); @@ -173,7 +173,7 @@ int32_t MineHiChainConnector::CreateGroup(const std::string &reqJsonStr) jsonObj[FIELD_GROUP_NAME] = DEVICE_MANAGER_GROUPNAME; jsonObj[FIELD_DEVICE_ID] = std::string(deviceUdid); jsonObj[FIELD_GROUP_TYPE] = IDENTICAL_ACCOUNT_GROUP; - std::string createParams = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string createParams = SafeDump(jsonObj); retValue = g_deviceGroupManager->createGroup(DEFAULT_OS_ACCOUNT, requestId, DM_PKG_NAME, createParams.c_str()); if (retValue != HC_SUCCESS) { LOGE("failed to create group with ret:%{public}d.", retValue); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index bce8e21ac..a76a974ee 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -342,7 +342,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + connectAddr = SafeDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); @@ -350,20 +350,20 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + connectAddr = SafeDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + connectAddr = SafeDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = jsonPara.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + connectAddr = SafeDump(jsonPara); return addr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 8ca4a232f..4d7eb3f3c 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -178,7 +178,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget jsonObj[TAG_PIN_TYPE] = pinType; jsonObj[TAG_PAYLOAD] = payload; pinType_ = pinType; - std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObj); LOGI("DestroyPinHolder, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER, pinType); ret = session_->SendData(sessionId_, message); @@ -212,7 +212,7 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() jsonObj[TAG_PAYLOAD] = payload_; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; jsonObj[TAG_DM_VERSION] = ""; - std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObj); LOGI("CreateGeneratePinHolderMsg, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER, pinType_); int32_t ret = session_->SendData(sessionId_, message); @@ -290,12 +290,12 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; - std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string content = SafeDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; - std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string msg = SafeDump(jsonObj); LOGI("ProcessCreateMsg, message type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -370,13 +370,13 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string content = SafeDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); isDestroy_.store(true); } } - std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string msg = SafeDump(jsonObj); LOGI("ProcessDestroyMsg, message type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -394,13 +394,13 @@ void PinHolder::CloseSession(const std::string &name) } nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string payload = SafeDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string content = SafeDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); isDestroy_.store(true); } @@ -461,7 +461,7 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) LOGE("another session opened, close this sessionId: %{public}d.", sessionId); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; - std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string msg = SafeDump(jsonObj); int32_t ret = session_->SendData(sessionId, msg); if (ret != DM_OK) { LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); @@ -563,13 +563,13 @@ void PinHolder::OnSessionClosed(int32_t sessionId) isRemoteSupported_ = false; nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string payload = SafeDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string content = SafeDump(jsonContent); if (destroyState_ == STATE_UNKNOW) { listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); } else if (destroyState_ == STATE_REMOTE_WRONG) { @@ -629,7 +629,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; jsonObj[TAG_PIN_TYPE] = pinType; - std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObj); LOGI("NotifyPinHolderEvent, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE, pinType); int32_t ret = session_->SendData(sessionId_, message); @@ -666,7 +666,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; - std::string content = jsonContent.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string content = SafeDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); if (timer_ != nullptr) { timer_->DeleteAll(); @@ -677,7 +677,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) } } - std::string msg = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string msg = SafeDump(jsonObj); LOGI("ProcessChangeMsg, message type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index a7a590aaf..e37b669fe 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -868,7 +868,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe const ConnectionAddr *addrInfo = &(device.addr)[0]; if (addrInfo == nullptr) { LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); - dmDevice.extraData = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + dmDevice.extraData = SafeDump(jsonObj); return; } jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; @@ -896,7 +896,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } - dmDevice.extraData = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + dmDevice.extraData = SafeDump(jsonObj); } int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index e5591e7f4..afc6a6fc1 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -315,13 +315,13 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObj[key] = 1; jsonObj["deviceName"] = "devieName1"; hichainConnector->GetJsonInt(jsonObj, "devieName"); - hichainConnector->AddMember(deviceId, jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); + hichainConnector->AddMember(deviceId, SafeDump(jsonObj)); jsonObj[TAG_DEVICE_ID] = "deviceId_001"; jsonObj[PIN_CODE_KEY] = 1; jsonObj[TAG_GROUP_ID] = "groupId"; jsonObj[TAG_REQUEST_ID] = 1; jsonObj[TAG_GROUP_NAME] = "groupName"; - hichainConnector->AddMember(deviceId, jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore)); + hichainConnector->AddMember(deviceId, SafeDump(jsonObj)); nlohmann::json jsonObjCre; std::string params; @@ -331,7 +331,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObjCre[FIELD_OPERATION_CODE] = 1; jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; - std::string credentialInfo = jsonObjCre.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObjCre); hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); int32_t groupType = *(reinterpret_cast(data)); nlohmann::json jsonDeviceList; diff --git a/test/commonunittest/UTTest_discovery_filter.cpp b/test/commonunittest/UTTest_discovery_filter.cpp index ff64c3cf2..f7f95c255 100644 --- a/test/commonunittest/UTTest_discovery_filter.cpp +++ b/test/commonunittest/UTTest_discovery_filter.cpp @@ -45,7 +45,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Level0 { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -55,7 +55,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Level0 DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -66,7 +66,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Level0 nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -77,7 +77,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Level0 nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -89,7 +89,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -101,7 +101,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -116,7 +116,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -132,7 +132,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -148,7 +148,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Level myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -165,7 +165,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSize. { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -175,7 +175,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSize. DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -186,7 +186,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -198,7 +198,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSize. jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -211,7 +211,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -224,7 +224,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 62341d8a2..b42798d82 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1075,7 +1075,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived002, testing::ext::TestSize. int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_DATA] = 123; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1086,7 +1086,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived003, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = "123"; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1098,7 +1098,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived004, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = "123"; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1110,7 +1110,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived005, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = 123; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1335,7 +1335,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + extra = SafeDump(jsonObject); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1345,7 +1345,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); jsonObject["bindLevel"] = 15; - extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + extra = SafeDump(jsonObject); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 93108e78d..1f3d2ee80 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -108,7 +108,7 @@ HWTEST_F(DmAuthManagerTest, OnDataReceived_007, testing::ext::TestSize.Level0) int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); authManager_->OnDataReceived(sessionId, message); authManager_->authRequestState_ = nullptr; authManager_->authResponseState_ = nullptr; @@ -1322,7 +1322,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; jsonObject["targetPkgName"] = 1234; - std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string extra = SafeDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1335,7 +1335,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_003, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = 1234; - std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string extra = SafeDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1349,7 +1349,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_004, testing::ext::TestSize.Level0) jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = 1234; - std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string extra = SafeDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1364,7 +1364,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_005, testing::ext::TestSize.Level0) jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = 1234; - std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string extra = SafeDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1380,7 +1380,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_006, testing::ext::TestSize.Level0) jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = "1234"; - std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string extra = SafeDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1397,7 +1397,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_007, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = "1234"; - std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string extra = SafeDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1414,7 +1414,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_008, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = 1234; - std::string extra = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string extra = SafeDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1509,7 +1509,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level nlohmann::json jsonPeerGroupIdObj; jsonPeerGroupIdObj["groupId"] = "123456"; authManager_->authResponseContext_->accountGroupIdHash = - jsonPeerGroupIdObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + SafeDump(jsonPeerGroupIdObj); EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index cf7c2f95e..f5e5ea799 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -141,13 +141,13 @@ void DmAuthManagerTest::TearDownTestCase() {} HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); int32_t sessionId = 0; authManager_->remoteDeviceId_ = "ProcRespNegotiate001"; authManager_->ProcRespNegotiate(sessionId); jsonObject[TAG_CRYPTO_SUPPORT] = false; - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; @@ -156,7 +156,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = ""; authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; @@ -164,7 +164,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->ProcRespNegotiate(sessionId); authManager_->authResponseState_->context_ = std::make_shared(); - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -174,7 +174,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_NAME] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -187,13 +187,13 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); int32_t sessionId = 0; authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->remoteDeviceId_ = "ProcRespNegotiate002"; authManager_->importAuthCode_ = "test"; @@ -207,7 +207,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index 23f00c306..b6692c693 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -181,7 +181,7 @@ HWTEST_F(DmCredentialManagerTest, RequestCredential_001, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["userId"] = "test"; jsonObject["version"] = "test"; - reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + reqJsonStr = SafeDump(jsonObject); ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -279,22 +279,22 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_001, testing::ext::TestSize.L nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); jsonObject["TType"] = 1; jsonObject["processType"] = 1; - credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + credentialInfo = SafeDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = -1; - credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + credentialInfo = SafeDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = 2; - credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + credentialInfo = SafeDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["TType"] = "test"; - credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + credentialInfo = SafeDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -717,13 +717,13 @@ HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_001, testing::ext::Test jsonObject[FIELD_USER_ID] = 0; jsonObject[FIELD_PEER_USER_ID] = "peerUserId"; - std::string credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObject); dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject[FIELD_CREDENTIAL_DATA] = 0; - credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + credentialInfo = SafeDump(jsonObject); ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1655,7 +1655,7 @@ HWTEST_F(DmCredentialManagerTest, from_json_001, testing::ext::TestSize.Level0) nlohmann::json jsonPkInfo; jsonOutObj[FIELD_SERVER_PK] = "serverPk"; jsonOutObj[FIELD_PKINFO_SIGNATURE] = "pkInfoSignature"; - jsonOutObj[FIELD_PKINFO] = jsonPkInfo.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + jsonOutObj[FIELD_PKINFO] = SafeDump(jsonPkInfo); jsonOutObj[FIELD_PEER_DEVICE_ID] = "peerDeviceId"; from_json(jsonOutObj, credentialDataInfo); EXPECT_FALSE(credentialDataInfo.serverPk.empty()); diff --git a/test/commonunittest/UTTest_dm_discovery_filter.cpp b/test/commonunittest/UTTest_dm_discovery_filter.cpp index 3a681c632..04582ba5f 100644 --- a/test/commonunittest/UTTest_dm_discovery_filter.cpp +++ b/test/commonunittest/UTTest_dm_discovery_filter.cpp @@ -58,7 +58,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Leve { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -74,7 +74,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Leve DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -91,7 +91,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Leve nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -108,7 +108,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Leve nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -126,7 +126,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -144,7 +144,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -165,7 +165,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -187,7 +187,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -209,7 +209,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Lev myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -238,7 +238,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSiz { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -254,7 +254,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSiz DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -271,7 +271,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSiz nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -289,7 +289,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSiz jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -308,7 +308,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -327,7 +327,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str = SafeDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index e11283f8c..9134d15b7 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -314,7 +314,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string localUdid = SafeDump(jsonObject); int32_t osAccountId = 1245; bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); @@ -325,7 +325,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string localUdid = SafeDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; int32_t osAccountId = 1245; @@ -338,7 +338,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string localUdid = SafeDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -351,7 +351,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string localUdid = SafeDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -364,7 +364,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string localUdid = SafeDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; int32_t osAccountId = 1245; @@ -377,7 +377,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string localUdid = SafeDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t osAccountId = 1245; @@ -390,7 +390,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string localUdid = SafeDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; int32_t osAccountId = 1245; diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index 8c898b28a..2d29be6c1 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1200,7 +1200,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_001, testing::ext::TestS HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1219,7 +1219,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_003, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 1; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1238,7 +1238,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_004, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 4; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1270,7 +1270,7 @@ HWTEST_F(HichainConnectorTest, addMultiMembersExt_001, testing::ext::TestSize.Le HWTEST_F(HichainConnectorTest, addMultiMembersExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObj); std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->addMultiMembersExt(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -1314,7 +1314,7 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_001, testing::ext::TestSize HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string jsonStr = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string jsonStr = SafeDump(jsonObj); std::vector udidList; std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr.c_str(), udidList); diff --git a/test/commonunittest/UTTest_mine_hichain_connector.cpp b/test/commonunittest/UTTest_mine_hichain_connector.cpp index 45412a796..d2ed96a2a 100644 --- a/test/commonunittest/UTTest_mine_hichain_connector.cpp +++ b/test/commonunittest/UTTest_mine_hichain_connector.cpp @@ -112,7 +112,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_002, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string reqJsonStr = SafeDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -122,7 +122,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_003, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string reqJsonStr = SafeDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -132,7 +132,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, RequestCredential_001, testing::ext::Test std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string returnJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string returnJsonStr = SafeDump(jsonObject); int32_t ret = minHiChain->RequestCredential(returnJsonStr); EXPECT_EQ(ret, DM_OK); } @@ -169,7 +169,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestS std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string reqJsonStr = SafeDump(jsonObject); std::string returnJsonStr; int32_t ret = minHiChain->ImportCredential(reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_REGISTER_CALLBACK); diff --git a/test/commonunittest/UTTest_pin_auth.cpp b/test/commonunittest/UTTest_pin_auth.cpp index 3bbc6b648..300c34360 100644 --- a/test/commonunittest/UTTest_pin_auth.cpp +++ b/test/commonunittest/UTTest_pin_auth.cpp @@ -73,7 +73,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_002, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_TOKEN] = 123456; - std::string authToken = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string authToken = SafeDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -89,7 +89,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_003, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string authToken = SafeDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, nullptr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -105,7 +105,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_004, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string authToken = SafeDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 5ae68f345..38d673cfb 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -67,7 +67,7 @@ HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_002, testing::ext::TestSize. nlohmann::json jsonObj; jsonObj["findDeviceMode"] = 4; string pkgName; - string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + string searchJson = SafeDump(jsonObj); DmSubscribeInfo dmSubscribeInfo; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->RefreshSoftbusLNN(pkgName, searchJson, dmSubscribeInfo); @@ -145,7 +145,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_002, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(1); string pkgName; - string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + string searchJson = SafeDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -158,7 +158,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_003, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(2); string pkgName; - string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + string searchJson = SafeDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -171,7 +171,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_004, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(3); string pkgName; - string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + string searchJson = SafeDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -184,7 +184,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_005, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(4); string pkgName; - string searchJson = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + string searchJson = SafeDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, DM_OK); diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index afb322eaa..a60d72896 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -107,7 +107,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) nlohmann::json jsonObj; jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = msgType; - std::string message = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObj); int32_t sessionId = 0; if (softbusSession == nullptr) { softbusSession = std::make_shared(); diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index 9abe4b501..9a77fa540 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -132,7 +132,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes authMessageProcessor->SetResponseContext(authResponseContext); authMessageProcessor->cryptoAdapter_ = nullptr; authMessageProcessor->CreateNegotiateMessage(jsonObj); - std::string str1 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str1 = SafeDump(jsonObj); authMessageProcessor->cryptoAdapter_ = std::make_shared(); authMessageProcessor->CreateNegotiateMessage(jsonObj); @@ -145,7 +145,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes jsonObject[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsonObject[TAG_LOCAL_DEVICE_ID] = authMessageProcessor->authResponseContext_->localDeviceId; jsonObject[TAG_HOST] = ""; - std::string str2 = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str2 = SafeDump(jsonObject); ASSERT_NE(str1, str2); } @@ -171,8 +171,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateSyncGroupMessage_001, testing::ext::Tes jsona[TAG_DEVICE_ID] = authMessageProcessor->authRequestContext_->deviceId; jsona[TAG_GROUPIDS] = authMessageProcessor->authRequestContext_->syncGroupList; authMessageProcessor->CreateSyncGroupMessage(jsonObj); - std::string str1 = jsona.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); - std::string str2 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str1 = SafeDump(jsona); + std::string str2 = SafeDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -197,7 +197,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: nlohmann::json jsonb; jsonb[TAG_GROUP_ID] = "123456"; authMessageProcessor->authResponseContext_->groupId = - jsonb.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + SafeDump(jsonb); authMessageProcessor->authResponseContext_->authToken = "123456"; authMessageProcessor->authResponseContext_->networkId = "11112222"; authMessageProcessor->authResponseContext_->requestId = 222222; @@ -211,8 +211,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: jsona[TAG_GROUP_ID] = "123456"; jsona[TAG_GROUP_NAME] = authMessageProcessor->authResponseContext_->groupName; authMessageProcessor->CreateResponseAuthMessage(jsonObj); - std::string str1 = jsona.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); - std::string str2 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str1 = SafeDump(jsona); + std::string str2 = SafeDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -235,8 +235,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseFinishMessage_001, testing::ext jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsona[TAG_AUTH_FINISH] = authMessageProcessor->authResponseContext_->isFinish; authMessageProcessor->CreateResponseFinishMessage(jsonObj); - std::string str1 = jsona.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); - std::string str2 = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string str1 = SafeDump(jsona); + std::string str2 = SafeDump(jsonObj); ASSERT_EQ(str1, str2); } diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index f361652a2..c45f4904e 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -459,7 +459,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -470,7 +470,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -482,7 +482,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -492,7 +492,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_101, testing::ext::TestSize.Level std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -503,7 +503,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_102, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->listener_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -515,7 +515,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_103, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -527,7 +527,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_104, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -558,7 +558,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -569,7 +569,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -581,7 +581,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -603,7 +603,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_101, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -615,7 +615,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_102, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -627,7 +627,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_103, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -639,7 +639,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_104, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -652,7 +652,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_105, testing::ext::TestSize.Level0) int32_t data = 300; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = data; - std::string message = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string message = SafeDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 85315ed8e..9ad7566fb 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -1249,7 +1249,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_053, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_OH; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); @@ -1287,7 +1287,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_054, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_MINE; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = jsonObject.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + std::string credentialInfo = SafeDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); diff --git a/utils/src/kvadapter/dm_kv_info.cpp b/utils/src/kvadapter/dm_kv_info.cpp index 58a2ff9b2..199603c88 100644 --- a/utils/src/kvadapter/dm_kv_info.cpp +++ b/utils/src/kvadapter/dm_kv_info.cpp @@ -28,7 +28,7 @@ void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) jsonObj[ANOY_DEVICE_ID_KEY] = kvValue.anoyDeviceId; jsonObj[SALT_KEY] = kvValue.salt; jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; - result = jsonObj.dump(-1, ' ', false, nlohmann::detail::error_handler_t::ignore); + result = SafeDump(jsonObj); } void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) -- Gitee From 1649f2c973aa2e99452676a7d31d22d0fa8a95f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 5 Dec 2024 09:38:22 +0800 Subject: [PATCH 506/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../src/dependency/hichain/hichain_auth_connector.cpp | 3 +-- .../src/dependency/hichain/hichain_connector.cpp | 3 +-- test/commonunittest/UTTest_dm_auth_manager_second.cpp | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 53ed5bd2c..845b537be 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -73,8 +73,7 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut nlohmann::json jsonAuthParam; jsonAuthParam["osAccountId"] = osAccountId; jsonAuthParam["data"] = authData; - int32_t ret = ProcessAuthDevice(requestId, - SafeDump(jsonAuthParam).c_str(), &deviceAuthCallback_); + int32_t ret = ProcessAuthDevice(requestId, SafeDump(jsonAuthParam).c_str(), &deviceAuthCallback_); if (ret != HC_SUCCESS) { LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 53f64d269..8bb080d75 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -154,8 +154,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(userId, requestId, - DM_PKG_NAME, SafeDump(jsonObj).c_str()); + int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, SafeDump(jsonObj).c_str()); struct RadarInfo info = { .funcName = "CreateGroup", .toCallPkg = HICHAINNAME, diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 1f3d2ee80..4eb25ea1f 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -1508,8 +1508,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level nlohmann::json jsonPeerGroupIdObj; jsonPeerGroupIdObj["groupId"] = "123456"; - authManager_->authResponseContext_->accountGroupIdHash = - SafeDump(jsonPeerGroupIdObj); + authManager_->authResponseContext_->accountGroupIdHash = SafeDump(jsonPeerGroupIdObj); EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); -- Gitee From c6a195c03ddf2202f3c266856599bf63c3bdf9db Mon Sep 17 00:00:00 2001 From: l60055366 Date: Thu, 5 Dec 2024 11:51:44 +0800 Subject: [PATCH 507/520] =?UTF-8?q?=E6=96=B0=E5=A2=9Efoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84UT?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- test/commonunittest/UTTest_dm_deviceprofile_connector.cpp | 3 ++- test/unittest/UTTest_device_manager_service.cpp | 2 ++ test/unittest/UTTest_device_manager_service_impl.cpp | 1 + test/unittest/UTTest_device_manager_service_three.cpp | 1 + test/unittest/UTTest_device_manager_service_two.cpp | 2 ++ test/unittest/UTTest_ipc_client_stub.cpp | 2 +- 6 files changed, 9 insertions(+), 2 deletions(-) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 92d8ebbbe..ccb4b4467 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -1106,7 +1106,7 @@ HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_002, testing: std::string pkgName = "bundleName"; std::string deviceId = "123456"; bool ret = DeviceProfileConnector::GetInstance().CheckSinkDevIdInAclForDevBind(pkgName, deviceId); - EXPECT_EQ(ret, true); + EXPECT_EQ(ret, false); } HWTEST_F(DeviceProfileConnectorTest, CheckSinkDevIdInAclForDevBind_003, testing::ext::TestSize.Level0) @@ -1589,6 +1589,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetDeviceIdAndUserId_001, testing::ext::Tes EXPECT_FALSE(ret.empty()); localUdid = "localDeviceId"; + userId = 456; ret = DeviceProfileConnector::GetInstance().GetDeviceIdAndUserId(userId, accountId, localUdid); EXPECT_FALSE(ret.empty()); } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 5eb73957f..c79f645ee 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2103,6 +2103,7 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceStatusChange_001, testing::ext::T { DmDeviceState devState = DmDeviceState::DEVICE_INFO_READY; DmDeviceInfo devInfo; + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).Times(::testing::AtLeast(2)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().HandleDeviceStatusChange(devState, devInfo); EXPECT_EQ(DeviceManagerService::GetInstance().softbusListener_, nullptr); } @@ -2256,6 +2257,7 @@ HWTEST_F(DeviceManagerServiceTest, HandleDeviceScreenStatusChange_001, testing:: DmDeviceInfo deviceInfo; DeviceManagerService::GetInstance().isImplsoLoaded_ = false; DeviceManagerService::GetInstance().IsDMServiceImplReady(); + EXPECT_CALL(*softbusCacheMock_, GetUdidFromCache(_, _)).WillOnce(Return(DM_OK)); DeviceManagerService::GetInstance().HandleDeviceScreenStatusChange(deviceInfo); EXPECT_NE(DeviceManagerService::GetInstance().dmServiceImpl_, nullptr); } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index f5c7eecb0..cf632b2c4 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1876,6 +1876,7 @@ HWTEST_F(DeviceManagerServiceImplTest, SaveOnlineDeviceInfo_001, testing::ext::T if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } + EXPECT_CALL(*softbusConnectorMock_, GetUdidByNetworkId(_, _)).Times(::testing::AtLeast(1)).WillOnce(Return(DM_OK)); int32_t ret = deviceManagerServiceImpl_->SaveOnlineDeviceInfo(deviceList); EXPECT_EQ(ret, DM_OK); diff --git a/test/unittest/UTTest_device_manager_service_three.cpp b/test/unittest/UTTest_device_manager_service_three.cpp index 7dea10f1e..33916b27e 100644 --- a/test/unittest/UTTest_device_manager_service_three.cpp +++ b/test/unittest/UTTest_device_manager_service_three.cpp @@ -373,6 +373,7 @@ HWTEST_F(DeviceManagerServiceThreeTest, ExportAuthCode_301, testing::ext::TestSi int32_t userId = 0; std::string accountId; std::string accountName; + EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceAdapterLoad()).WillOnce(Return(false)); EXPECT_CALL(*deviceManagerServiceMock_, IsDMServiceImplReady()).WillOnce(Return(false)); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId, accountName); diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index d8463dbd9..226f97eef 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -168,6 +168,7 @@ HWTEST_F(DeviceManagerServiceTest, IsDMImplSoLoaded_201, testing::ext::TestSize. HWTEST_F(DeviceManagerServiceTest, RegisterPinHolderCallback_201, testing::ext::TestSize.Level0) { std::string pkgName = "CollaborationFwk"; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().RegisterPinHolderCallback(pkgName); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -183,6 +184,7 @@ HWTEST_F(DeviceManagerServiceTest, CreatePinHolder_201, testing::ext::TestSize.L PeerTargetId targetId; DmPinType pinType = NUMBER_PIN_CODE; std::string payload; + EXPECT_CALL(*permissionManagerMock_, GetCallerProcessName(_)).WillOnce(Return(DM_OK)); EXPECT_CALL(*permissionManagerMock_, CheckProcessNameValidOnPinHolder(_)).Times(::testing::AtLeast(1)).WillOnce(Return(false)); int32_t ret = DeviceManagerService::GetInstance().CreatePinHolder(pkgName, targetId, pinType, payload); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); diff --git a/test/unittest/UTTest_ipc_client_stub.cpp b/test/unittest/UTTest_ipc_client_stub.cpp index ee256867f..074929555 100644 --- a/test/unittest/UTTest_ipc_client_stub.cpp +++ b/test/unittest/UTTest_ipc_client_stub.cpp @@ -162,7 +162,7 @@ HWTEST_F(IpcClientStubTest, SendCmd_001, testing::ext::TestSize.Level0) // 2. call IpcClientStub SendCmd with parameter int ret = instance->SendCmd(cmdCode, req, rsp); // 3. check result is ERR_DM_IPC_SEND_REQUEST_FAILED - ASSERT_EQ(ret, ERR_DM_IPC_SEND_REQUEST_FAILED); + ASSERT_EQ(ret, DM_OK); } /** -- Gitee From 7b4603b1983a4cc3ff5f35aaa01620a88581c94e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 5 Dec 2024 16:43:47 +0800 Subject: [PATCH 508/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- .../implementation/src/authentication/auth_ui_state_manager.cpp | 1 + .../src/dependency/hichain/mine_hichain_connector.cpp | 1 + .../hichainconnector_fuzzer/hichain_connector_fuzzer.cpp | 1 + test/commonunittest/UTTest_dm_auth_manager_first.cpp | 1 + test/commonunittest/UTTest_dm_auth_manager_second.cpp | 1 + test/commonunittest/UTTest_dm_auth_manager_third.cpp | 1 + test/commonunittest/UTTest_hichain_auth_connector.cpp | 1 + test/commonunittest/UTTest_mine_hichain_connector.cpp | 1 + test/commonunittest/UTTest_pin_auth.cpp | 1 + test/unittest/UTTest_auth_message_processor.cpp | 1 + test/unittest/UTTest_dm_pin_holder.cpp | 1 + test/unittest/UTTest_ipc_cmd_parser_service.cpp | 1 + 12 files changed, 12 insertions(+) diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index 29a9233fc..25a06c8dd 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -14,6 +14,7 @@ */ #include "auth_ui_state_manager.h" +#include "dm_anonymous.h" #include "dm_log.h" #include "nlohmann/json.hpp" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index 3feba8802..3b846d967 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -22,6 +22,7 @@ #include "device_auth.h" #include "device_auth_defines.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "nlohmann/json.hpp" diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index afc6a6fc1..e45b450df 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -20,6 +20,7 @@ #include #include "device_manager_service_listener.h" +#include "dm_anonymous.h" #include "dm_auth_manager.h" #include "hichain_connector.h" diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index b42798d82..4f287ee3e 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -19,6 +19,7 @@ #include "common_event_support.h" #include "device_manager_service_listener.h" #include "dm_auth_manager.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "dm_radar_helper.h" diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 4eb25ea1f..d42f9141b 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -18,6 +18,7 @@ #include "auth_message_processor.h" #include "device_manager_service_listener.h" #include "dm_auth_manager.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_dialog_manager.h" diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index f5e5ea799..12350e670 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -19,6 +19,7 @@ #include "device_manager_service_listener.h" #include "deviceprofile_connector.h" #include "dm_auth_manager.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_dialog_manager.h" #include "dm_log.h" diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 9134d15b7..6352ef6a7 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -14,6 +14,7 @@ */ #include #include "UTTest_hichain_auth_connector.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "hichain_auth_connector.h" diff --git a/test/commonunittest/UTTest_mine_hichain_connector.cpp b/test/commonunittest/UTTest_mine_hichain_connector.cpp index d2ed96a2a..6fff3e5f2 100644 --- a/test/commonunittest/UTTest_mine_hichain_connector.cpp +++ b/test/commonunittest/UTTest_mine_hichain_connector.cpp @@ -15,6 +15,7 @@ #include "UTTest_mine_hichain_connector.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "mine_hichain_connector.h" diff --git a/test/commonunittest/UTTest_pin_auth.cpp b/test/commonunittest/UTTest_pin_auth.cpp index 300c34360..a20ad3dad 100644 --- a/test/commonunittest/UTTest_pin_auth.cpp +++ b/test/commonunittest/UTTest_pin_auth.cpp @@ -18,6 +18,7 @@ #include #include +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "nlohmann/json.hpp" diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index 9a77fa540..6c33c1d7d 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -16,6 +16,7 @@ #include "UTTest_auth_message_processor.h" #include "dm_log.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "auth_message_processor.h" #include "softbus_connector.h" diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index c45f4904e..40dd4eb14 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -19,6 +19,7 @@ #include #include "accesstoken_kit.h" #include "device_manager_notify.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "ipc_authenticate_device_req.h" diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 9ad7566fb..b0af3cb80 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -19,6 +19,7 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_notify.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_device_info.h" #include "ipc_client_manager.h" -- Gitee From 42c6de302f3b4821630c647234954b4cd9ffd6e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Thu, 5 Dec 2024 19:15:05 +0800 Subject: [PATCH 509/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=8D=E7=A7=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- common/include/dm_anonymous.h | 2 +- common/src/dm_anonymous.cpp | 4 +-- .../native_cpp/src/device_manager_impl.cpp | 4 +-- .../kits/js/src/native_devicemanager_js.cpp | 4 +-- interfaces/kits/js4.0/src/dm_native_util.cpp | 4 +-- .../ability/standard/dm_dialog_manager.cpp | 2 +- .../authentication/auth_message_processor.cpp | 8 ++--- .../authentication/auth_ui_state_manager.cpp | 2 +- .../src/authentication/dm_auth_manager.cpp | 22 ++++++------ .../src/credential/dm_credential_manager.cpp | 4 +-- .../hichain/hichain_auth_connector.cpp | 16 ++++----- .../dependency/hichain/hichain_connector.cpp | 36 +++++++++---------- .../hichain/mine_hichain_connector.cpp | 4 +-- .../dependency/softbus/softbus_connector.cpp | 8 ++--- services/service/src/pinholder/pin_holder.cpp | 28 +++++++-------- .../service/src/softbus/softbus_listener.cpp | 4 +-- .../hichain_connector_fuzzer.cpp | 6 ++-- .../UTTest_discovery_filter.cpp | 30 ++++++++-------- .../UTTest_dm_auth_manager_first.cpp | 12 +++---- .../UTTest_dm_auth_manager_second.cpp | 18 +++++----- .../UTTest_dm_auth_manager_third.cpp | 16 ++++----- .../UTTest_dm_credential_manager.cpp | 16 ++++----- .../UTTest_dm_discovery_filter.cpp | 30 ++++++++-------- .../UTTest_hichain_auth_connector.cpp | 14 ++++---- .../UTTest_hichain_connector.cpp | 10 +++--- .../UTTest_mine_hichain_connector.cpp | 8 ++--- test/commonunittest/UTTest_pin_auth.cpp | 6 ++-- .../UTTest_mine_softbus_listener.cpp | 10 +++--- .../UTTest_softbus_session.cpp | 2 +- .../UTTest_auth_message_processor.cpp | 18 +++++----- test/unittest/UTTest_dm_pin_holder.cpp | 30 ++++++++-------- .../UTTest_ipc_cmd_parser_service.cpp | 4 +-- utils/src/kvadapter/dm_kv_info.cpp | 2 +- 33 files changed, 192 insertions(+), 192 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 4096baaf1..46aebde59 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -101,7 +101,7 @@ bool IsIdLengthValid(const std::string &inputID); bool IsMessageLengthValid(const std::string &inputMessage); bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId); bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent); -std::string SafeDump(const nlohmann::json &jsonObj); +std::string SafeyDump(const nlohmann::json &jsonObj); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 73bf8a471..bec2a8201 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -184,7 +184,7 @@ std::string ConvertMapToJsonString(const std::map &par for (const auto &it : paramMap) { jsonObj[it.first] = it.second; } - jsonStr = SafeDump(jsonObj); + jsonStr = SafeyDump(jsonObj); } return jsonStr; } @@ -366,7 +366,7 @@ bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent) return false; } -std::string SafeDump(const nlohmann::json &jsonObj) +std::string SafeyDump(const nlohmann::json &jsonObj) { int indent = -1; return jsonObj.dump(indent, ' ', false, nlohmann::detail::error_handler_t::ignore); 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 fdacce6f5..88854c816 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -674,7 +674,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetExtra(SafeDump(extraJson)); + req->SetExtra(SafeyDump(extraJson)); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); @@ -1493,7 +1493,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetBindParam(SafeDump(paramJson)); + req->SetBindParam(SafeyDump(paramJson)); req->SetBindType(bindType); req->SetDeviceId(deviceId); int32_t ret = ipcClientProxy_->SendRequest(BIND_DEVICE, req, rsp); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index deb53b23c..4588803d5 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1203,7 +1203,7 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr; jsonObj[BIND_LEVEL] = bindLevel; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = SafeDump(jsonObj); + extra = SafeyDump(jsonObj); LOGI("appOperationLen %{public}zu, customDescriptionLen %{public}zu", appOperationStr.size(), customDescriptionStr.size()); } @@ -1274,7 +1274,7 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob jsonObj[AUTH_TYPE] = authType; jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = SafeDump(jsonObj); + extra = SafeyDump(jsonObj); } void DeviceManagerNapi::JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index c36bad407..c70d6a175 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -330,7 +330,7 @@ void JsToBindParam(const napi_env &env, const napi_value &object, std::string &b jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP); jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort; jsonObj[BIND_LEVEL] = bindLevel; - bindParam = SafeDump(jsonObj); + bindParam = SafeyDump(jsonObj); } bool IsSystemApp() @@ -395,7 +395,7 @@ void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::st if (deviceType != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) { jsonObj["deviceType"] = deviceType; } - extra = SafeDump(jsonObj); + extra = SafeyDump(jsonObj); LOGI("JsToDmDiscoveryExtra, extra :%{public}s", extra.c_str()); } diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index ba6cdc029..479daaadb 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -202,7 +202,7 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = SafeDump(param); + std::string paramStr = SafeyDump(param); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index edee3a0f4..cf4b5bf15 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -87,7 +87,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1; jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; GetJsonObj(jsonObj); - jsonStrVec.push_back(SafeDump(jsonObj)); + jsonStrVec.push_back(SafeyDump(jsonObj)); for (int32_t idx = 0; idx < thumbnailSlice; idx++) { nlohmann::json jsonThumbnailObj; jsonThumbnailObj[TAG_VER] = DM_ITF_VER; @@ -101,7 +101,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() LOGI("TAG_APP_THUMBNAIL encode, idx %{public}d, sliceLen %{public}d, thumbnailSize %{public}d", idx, (uint32_t)sliceLen, thumbnailSize); jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); - jsonStrVec.push_back(SafeDump(jsonThumbnailObj)); + jsonStrVec.push_back(SafeyDump(jsonThumbnailObj)); } return jsonStrVec; } @@ -138,7 +138,7 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) default: break; } - return SafeDump(jsonObj); + return SafeyDump(jsonObj); } void AuthMessageProcessor::CreatePublicKeyMessageExt(nlohmann::json &json) @@ -593,7 +593,7 @@ std::string AuthMessageProcessor::CreateDeviceAuthMessage(int32_t msgType, const std::string authDataStr = std::string(reinterpret_cast(data), dataLen); jsonObj[TAG_DATA] = authDataStr; jsonObj[TAG_DATA_LEN] = dataLen; - return SafeDump(jsonObj); + return SafeyDump(jsonObj); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index 25a06c8dd..51292896b 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -62,7 +62,7 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) } nlohmann::json jsonObj; jsonObj[UI_STATE_MSG] = msg; - std::string paramJson = SafeDump(jsonObj); + std::string paramJson = SafeyDump(jsonObj); std::lock_guard lock(pkgSetMutex_); for (auto item : pkgSet_) { listener_->OnUiCall(item, paramJson); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index b31fcb485..933f035de 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -609,7 +609,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId jsonObj[PIN_TOKEN] = authResponseContext_->token; jsonObj[QR_CODE_KEY] = GenerateGroupName(); jsonObj[NFC_CODE_KEY] = GenerateGroupName(); - authResponseContext_->authToken = SafeDump(jsonObj); + authResponseContext_->authToken = SafeyDump(jsonObj); LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); authResponseContext_->groupId = groupId; authResponseContext_->code = pinCode; @@ -1176,7 +1176,7 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) jsonObject[PIN_CODE_KEY] = pinCode; jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; - std::string connectInfo = SafeDump(jsonObject); + std::string connectInfo = SafeyDump(jsonObject); if (timer_ != nullptr) { timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { @@ -1441,7 +1441,7 @@ void DmAuthManager::ShowConfigDialog() jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; - const std::string params = SafeDump(jsonObj); + const std::string params = SafeyDump(jsonObj); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); @@ -1478,7 +1478,7 @@ void DmAuthManager::ShowAuthInfoDialog() } nlohmann::json jsonObj; jsonObj[PIN_CODE_KEY] = authResponseContext_->code; - std::string authParam = SafeDump(jsonObj); + std::string authParam = SafeyDump(jsonObj); DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); } @@ -1650,7 +1650,7 @@ bool DmAuthManager::IsIdenticalAccount() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = SafeDump(jsonObj); + std::string queryParams = SafeyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1690,7 +1690,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = SafeDump(jsonObj); + std::string queryParams = SafeyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1705,7 +1705,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() for (auto &groupInfo : groupList) { jsonAccountObj.push_back(Crypto::GetGroupIdHash(groupInfo.groupId)); } - return SafeDump(jsonAccountObj); + return SafeyDump(jsonAccountObj); } int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) @@ -1893,7 +1893,7 @@ std::string DmAuthManager::GenerateBindResultContent() Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); jsonObj[TAG_DEVICE_ID] = deviceIdHash; } - std::string content = SafeDump(jsonObj); + std::string content = SafeyDump(jsonObj); return content; } @@ -2237,7 +2237,7 @@ void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) } } jsonObject[TAG_CRYPTO_SUPPORT] = false; - message = SafeDump(jsonObject); + message = SafeyDump(jsonObject); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2248,7 +2248,7 @@ void DmAuthManager::ProcIncompatible(const int32_t &sessionId) respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; respNegotiateMsg[TAG_VER] = DM_ITF_VER; respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; - std::string message = SafeDump(respNegotiateMsg); + std::string message = SafeyDump(respNegotiateMsg); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2370,7 +2370,7 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); nlohmann::json jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = SafeDump(jsonObj); + std::string message = SafeyDump(jsonObj); softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index e0ba29e97..1c269dd28 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -113,7 +113,7 @@ int32_t DmCredentialManager::RequestCredential(const std::string &reqJsonStr, st jsonObj[FIELD_CREDENTIAL_VERSION] = credentialVersion; jsonObj[FIELD_USER_ID] = userId; jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string tmpStr = SafeDump(jsonObj); + std::string tmpStr = SafeyDump(jsonObj); return hiChainConnector_->getRegisterInfo(tmpStr.c_str(), returnJsonStr); } @@ -364,7 +364,7 @@ void from_json(const nlohmann::json &jsonObject, CredentialDataInfo &credentialD } if (IsString(jsonObject, FIELD_PKINFO)) { nlohmann::json jsonPkInfo = jsonObject[FIELD_PKINFO]; - credentialDataInfo.pkInfo = SafeDump(jsonPkInfo); + credentialDataInfo.pkInfo = SafeyDump(jsonPkInfo); } } else if (credentialDataInfo.credentialType == SYMMETRY_CREDENTIAL_TYPE) { if (IsString(jsonObject, FIELD_AUTH_CODE)) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 845b537be..2b116e05a 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -56,7 +56,7 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s authParamJson["osAccountId"] = osAccountId; authParamJson["pinCode"] = std::to_string(pinCode); authParamJson["acquireType"] = AcquireType::P2P_BIND; - std::string authParam = SafeDump(authParamJson); + std::string authParam = SafeyDump(authParamJson); LOGI("StartAuthDevice authParam %{public}s ,requestId %{public}" PRId64, GetAnonyString(authParam).c_str(), requestId); int32_t ret = StartAuthDevice(requestId, authParam.c_str(), &deviceAuthCallback_); @@ -73,7 +73,7 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut nlohmann::json jsonAuthParam; jsonAuthParam["osAccountId"] = osAccountId; jsonAuthParam["data"] = authData; - int32_t ret = ProcessAuthDevice(requestId, SafeDump(jsonAuthParam).c_str(), &deviceAuthCallback_); + int32_t ret = ProcessAuthDevice(requestId, SafeyDump(jsonAuthParam).c_str(), &deviceAuthCallback_); if (ret != HC_SUCCESS) { LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; @@ -111,7 +111,7 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = SafeDump(jsonObj); + std::string jsonStr = SafeyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -159,7 +159,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = SafeDump(jsonObj); + std::string requestParam = SafeyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_CREATE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain generate credential failed."); @@ -192,7 +192,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = SafeDump(jsonObj); + std::string requestParam = SafeyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -223,7 +223,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = SafeDump(jsonObj); + std::string requestParam = SafeyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -255,7 +255,7 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; - std::string requestParam = SafeDump(jsonObj); + std::string requestParam = SafeyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_IMPORT, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -286,7 +286,7 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; - std::string requestParam = SafeDump(jsonObj); + std::string requestParam = SafeyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 8bb080d75..fc7b71c8b 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -154,7 +154,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, SafeDump(jsonObj).c_str()); + int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, SafeyDump(jsonObj).c_str()); struct RadarInfo info = { .funcName = "CreateGroup", .toCallPkg = HICHAINNAME, @@ -178,7 +178,7 @@ bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInf { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = SafeDump(jsonObj); + std::string queryParams = SafeyDump(jsonObj); std::vector groupList; if (GetGroupInfo(queryParams, groupList)) { groupInfo = groupList[0]; @@ -191,7 +191,7 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = SafeDump(jsonObj); + std::string queryParams = SafeyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -343,7 +343,7 @@ int32_t HiChainConnector::AddMember(const std::string &deviceId, const std::stri jsonObj[FIELD_DEVICE_ID] = localDeviceId; jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME].get(); jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str(); - std::string tmpStr = SafeDump(jsonObj); + std::string tmpStr = SafeyDump(jsonObj); int64_t requestId = jsonObject[TAG_REQUEST_ID].get(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { @@ -486,7 +486,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string jsonStr = SafeDump(jsonObj); + std::string jsonStr = SafeyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -511,7 +511,7 @@ std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string r } jsonObject[DEVICE_ID] = reqDeviceId; - return SafeDump(jsonObject); + return SafeyDump(jsonObject); } int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vector &groupList) @@ -602,7 +602,7 @@ int32_t HiChainConnector::DelMemberFromGroup(const std::string &groupId, const s nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_DELETE_ID] = deviceId; - std::string deleteParams = SafeDump(jsonObj); + std::string deleteParams = SafeyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -621,7 +621,7 @@ int32_t HiChainConnector::DeleteGroup(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeDump(jsonObj); + std::string disbandParams = SafeyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -641,7 +641,7 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeDump(jsonObj); + std::string disbandParams = SafeyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -661,7 +661,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use networkStyle_ = CREDENTIAL_NETWORK; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = SafeDump(jsonObj); + std::string queryParams = SafeyDump(jsonObj); std::vector groupList; if (!GetGroupInfo(queryParams, groupList)) { LOGE("failed to get device join groups"); @@ -682,7 +682,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use return ERR_DM_FAILED; } jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeDump(jsonObj); + std::string disbandParams = SafeyDump(jsonObj); g_deleteGroupFlag = false; int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -792,7 +792,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const return ERR_DM_FAILED; } int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, - SafeDump(jsonObj).c_str()); + SafeyDump(jsonObj).c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); return ERR_DM_CREATE_GROUP_FAILED; @@ -842,7 +842,7 @@ int32_t HiChainConnector::GetGroupId(const std::string &userId, const int32_t gr { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = SafeDump(jsonObjGroup); + std::string queryParams = SafeyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -875,7 +875,7 @@ int32_t HiChainConnector::ParseRemoteCredential(const int32_t groupType, const s jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = groupType; jsonObj[FIELD_DEVICE_LIST] = jsonDeviceList[FIELD_DEVICE_LIST]; - params = SafeDump(jsonObj); + params = SafeyDump(jsonObj); osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { LOGE("get current process account user id failed"); @@ -929,7 +929,7 @@ int32_t HiChainConnector::GetGroupIdExt(const std::string &userId, const int32_t { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = SafeDump(jsonObjGroup); + std::string queryParams = SafeyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -983,7 +983,7 @@ int32_t HiChainConnector::ParseRemoteCredentialExt(const std::string &credential return ERR_DM_FAILED; } jsonObj[FIELD_DEVICE_LIST] = jsonObject[FIELD_DEVICE_LIST]; - params = SafeDump(jsonObj); + params = SafeyDump(jsonObj); return DM_OK; } @@ -1158,7 +1158,7 @@ int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeDump(jsonObj); + std::string disbandParams = SafeyDump(jsonObj); int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); if (ret != 0) { LOGE("[HICHAIN]fail to delete group with ret:%{public}d.", ret); @@ -1248,7 +1248,7 @@ int32_t HiChainConnector::DeleteGroupByACL(std::vector groupList; if (!GetGroupInfo(userId, queryParams, groupList)) { diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index 3b846d967..06e822f01 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -136,7 +136,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) { nlohmann::json jsonObj; jsonObj[FIELD_IS_DELETE_ALL] = true; - std::string params = SafeDump(jsonObj); + std::string params = SafeyDump(jsonObj); #if (defined(MINE_HARMONY)) char *returnInfo = nullptr; int32_t retValue = g_deviceGroupManager->processCredential(DELETE_SELF_CREDENTIAL, params.c_str(), &returnInfo); @@ -174,7 +174,7 @@ int32_t MineHiChainConnector::CreateGroup(const std::string &reqJsonStr) jsonObj[FIELD_GROUP_NAME] = DEVICE_MANAGER_GROUPNAME; jsonObj[FIELD_DEVICE_ID] = std::string(deviceUdid); jsonObj[FIELD_GROUP_TYPE] = IDENTICAL_ACCOUNT_GROUP; - std::string createParams = SafeDump(jsonObj); + std::string createParams = SafeyDump(jsonObj); retValue = g_deviceGroupManager->createGroup(DEFAULT_OS_ACCOUNT, requestId, DM_PKG_NAME, createParams.c_str()); if (retValue != HC_SUCCESS) { LOGE("failed to create group with ret:%{public}d.", retValue); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index a76a974ee..36bc8412d 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -342,7 +342,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = SafeDump(jsonPara); + connectAddr = SafeyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); @@ -350,20 +350,20 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafeDump(jsonPara); + connectAddr = SafeyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafeDump(jsonPara); + connectAddr = SafeyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = SafeDump(jsonPara); + connectAddr = SafeyDump(jsonPara); return addr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 4d7eb3f3c..8898dc055 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -178,7 +178,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget jsonObj[TAG_PIN_TYPE] = pinType; jsonObj[TAG_PAYLOAD] = payload; pinType_ = pinType; - std::string message = SafeDump(jsonObj); + std::string message = SafeyDump(jsonObj); LOGI("DestroyPinHolder, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER, pinType); ret = session_->SendData(sessionId_, message); @@ -212,7 +212,7 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() jsonObj[TAG_PAYLOAD] = payload_; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; jsonObj[TAG_DM_VERSION] = ""; - std::string message = SafeDump(jsonObj); + std::string message = SafeyDump(jsonObj); LOGI("CreateGeneratePinHolderMsg, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER, pinType_); int32_t ret = session_->SendData(sessionId_, message); @@ -290,12 +290,12 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; - std::string content = SafeDump(jsonContent); + std::string content = SafeyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; - std::string msg = SafeDump(jsonObj); + std::string msg = SafeyDump(jsonObj); LOGI("ProcessCreateMsg, message type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -370,13 +370,13 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; - std::string content = SafeDump(jsonContent); + std::string content = SafeyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); isDestroy_.store(true); } } - std::string msg = SafeDump(jsonObj); + std::string msg = SafeyDump(jsonObj); LOGI("ProcessDestroyMsg, message type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -394,13 +394,13 @@ void PinHolder::CloseSession(const std::string &name) } nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = SafeDump(jsonObj); + std::string payload = SafeyDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = SafeDump(jsonContent); + std::string content = SafeyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); isDestroy_.store(true); } @@ -461,7 +461,7 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) LOGE("another session opened, close this sessionId: %{public}d.", sessionId); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; - std::string msg = SafeDump(jsonObj); + std::string msg = SafeyDump(jsonObj); int32_t ret = session_->SendData(sessionId, msg); if (ret != DM_OK) { LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); @@ -563,13 +563,13 @@ void PinHolder::OnSessionClosed(int32_t sessionId) isRemoteSupported_ = false; nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = SafeDump(jsonObj); + std::string payload = SafeyDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = SafeDump(jsonContent); + std::string content = SafeyDump(jsonContent); if (destroyState_ == STATE_UNKNOW) { listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); } else if (destroyState_ == STATE_REMOTE_WRONG) { @@ -629,7 +629,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; jsonObj[TAG_PIN_TYPE] = pinType; - std::string message = SafeDump(jsonObj); + std::string message = SafeyDump(jsonObj); LOGI("NotifyPinHolderEvent, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE, pinType); int32_t ret = session_->SendData(sessionId_, message); @@ -666,7 +666,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; - std::string content = SafeDump(jsonContent); + std::string content = SafeyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); if (timer_ != nullptr) { timer_->DeleteAll(); @@ -677,7 +677,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) } } - std::string msg = SafeDump(jsonObj); + std::string msg = SafeyDump(jsonObj); LOGI("ProcessChangeMsg, message type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index e37b669fe..376918f18 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -868,7 +868,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe const ConnectionAddr *addrInfo = &(device.addr)[0]; if (addrInfo == nullptr) { LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); - dmDevice.extraData = SafeDump(jsonObj); + dmDevice.extraData = SafeyDump(jsonObj); return; } jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; @@ -896,7 +896,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } - dmDevice.extraData = SafeDump(jsonObj); + dmDevice.extraData = SafeyDump(jsonObj); } int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index e45b450df..db9309318 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -316,13 +316,13 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObj[key] = 1; jsonObj["deviceName"] = "devieName1"; hichainConnector->GetJsonInt(jsonObj, "devieName"); - hichainConnector->AddMember(deviceId, SafeDump(jsonObj)); + hichainConnector->AddMember(deviceId, SafeyDump(jsonObj)); jsonObj[TAG_DEVICE_ID] = "deviceId_001"; jsonObj[PIN_CODE_KEY] = 1; jsonObj[TAG_GROUP_ID] = "groupId"; jsonObj[TAG_REQUEST_ID] = 1; jsonObj[TAG_GROUP_NAME] = "groupName"; - hichainConnector->AddMember(deviceId, SafeDump(jsonObj)); + hichainConnector->AddMember(deviceId, SafeyDump(jsonObj)); nlohmann::json jsonObjCre; std::string params; @@ -332,7 +332,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObjCre[FIELD_OPERATION_CODE] = 1; jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; - std::string credentialInfo = SafeDump(jsonObjCre); + std::string credentialInfo = SafeyDump(jsonObjCre); hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); int32_t groupType = *(reinterpret_cast(data)); nlohmann::json jsonDeviceList; diff --git a/test/commonunittest/UTTest_discovery_filter.cpp b/test/commonunittest/UTTest_discovery_filter.cpp index f7f95c255..5442a0220 100644 --- a/test/commonunittest/UTTest_discovery_filter.cpp +++ b/test/commonunittest/UTTest_discovery_filter.cpp @@ -45,7 +45,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Level0 { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -55,7 +55,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Level0 DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -66,7 +66,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Level0 nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -77,7 +77,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Level0 nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -89,7 +89,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -101,7 +101,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -116,7 +116,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -132,7 +132,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -148,7 +148,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Level myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -165,7 +165,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSize. { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -175,7 +175,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSize. DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -186,7 +186,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -198,7 +198,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSize. jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -211,7 +211,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -224,7 +224,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 4f287ee3e..7885b58fc 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1076,7 +1076,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived002, testing::ext::TestSize. int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_DATA] = 123; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1087,7 +1087,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived003, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = "123"; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1099,7 +1099,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived004, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = "123"; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1111,7 +1111,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived005, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = 123; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1336,7 +1336,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - extra = SafeDump(jsonObject); + extra = SafeyDump(jsonObject); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1346,7 +1346,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); jsonObject["bindLevel"] = 15; - extra = SafeDump(jsonObject); + extra = SafeyDump(jsonObject); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index d42f9141b..f50b3e350 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -109,7 +109,7 @@ HWTEST_F(DmAuthManagerTest, OnDataReceived_007, testing::ext::TestSize.Level0) int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = 200; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); authManager_->OnDataReceived(sessionId, message); authManager_->authRequestState_ = nullptr; authManager_->authResponseState_ = nullptr; @@ -1323,7 +1323,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; jsonObject["targetPkgName"] = 1234; - std::string extra = SafeDump(jsonObject); + std::string extra = SafeyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1336,7 +1336,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_003, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = 1234; - std::string extra = SafeDump(jsonObject); + std::string extra = SafeyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1350,7 +1350,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_004, testing::ext::TestSize.Level0) jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = 1234; - std::string extra = SafeDump(jsonObject); + std::string extra = SafeyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1365,7 +1365,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_005, testing::ext::TestSize.Level0) jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = 1234; - std::string extra = SafeDump(jsonObject); + std::string extra = SafeyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1381,7 +1381,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_006, testing::ext::TestSize.Level0) jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = "1234"; - std::string extra = SafeDump(jsonObject); + std::string extra = SafeyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1398,7 +1398,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_007, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = "1234"; - std::string extra = SafeDump(jsonObject); + std::string extra = SafeyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1415,7 +1415,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_008, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = 1234; - std::string extra = SafeDump(jsonObject); + std::string extra = SafeyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1509,7 +1509,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level nlohmann::json jsonPeerGroupIdObj; jsonPeerGroupIdObj["groupId"] = "123456"; - authManager_->authResponseContext_->accountGroupIdHash = SafeDump(jsonPeerGroupIdObj); + authManager_->authResponseContext_->accountGroupIdHash = SafeyDump(jsonPeerGroupIdObj); EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index 12350e670..e4e236ec1 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -142,13 +142,13 @@ void DmAuthManagerTest::TearDownTestCase() {} HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); int32_t sessionId = 0; authManager_->remoteDeviceId_ = "ProcRespNegotiate001"; authManager_->ProcRespNegotiate(sessionId); jsonObject[TAG_CRYPTO_SUPPORT] = false; - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; @@ -157,7 +157,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = ""; authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; @@ -165,7 +165,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->ProcRespNegotiate(sessionId); authManager_->authResponseState_->context_ = std::make_shared(); - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -175,7 +175,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_NAME] = "test"; - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -188,13 +188,13 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); int32_t sessionId = 0; authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->remoteDeviceId_ = "ProcRespNegotiate002"; authManager_->importAuthCode_ = "test"; @@ -208,7 +208,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = SafeDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index b6692c693..fd9054026 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -181,7 +181,7 @@ HWTEST_F(DmCredentialManagerTest, RequestCredential_001, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["userId"] = "test"; jsonObject["version"] = "test"; - reqJsonStr = SafeDump(jsonObject); + reqJsonStr = SafeyDump(jsonObject); ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -279,22 +279,22 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_001, testing::ext::TestSize.L nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); jsonObject["TType"] = 1; jsonObject["processType"] = 1; - credentialInfo = SafeDump(jsonObject); + credentialInfo = SafeyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = -1; - credentialInfo = SafeDump(jsonObject); + credentialInfo = SafeyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = 2; - credentialInfo = SafeDump(jsonObject); + credentialInfo = SafeyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["TType"] = "test"; - credentialInfo = SafeDump(jsonObject); + credentialInfo = SafeyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -717,13 +717,13 @@ HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_001, testing::ext::Test jsonObject[FIELD_USER_ID] = 0; jsonObject[FIELD_PEER_USER_ID] = "peerUserId"; - std::string credentialInfo = SafeDump(jsonObject); + std::string credentialInfo = SafeyDump(jsonObject); dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject[FIELD_CREDENTIAL_DATA] = 0; - credentialInfo = SafeDump(jsonObject); + credentialInfo = SafeyDump(jsonObject); ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1655,7 +1655,7 @@ HWTEST_F(DmCredentialManagerTest, from_json_001, testing::ext::TestSize.Level0) nlohmann::json jsonPkInfo; jsonOutObj[FIELD_SERVER_PK] = "serverPk"; jsonOutObj[FIELD_PKINFO_SIGNATURE] = "pkInfoSignature"; - jsonOutObj[FIELD_PKINFO] = SafeDump(jsonPkInfo); + jsonOutObj[FIELD_PKINFO] = SafeyDump(jsonPkInfo); jsonOutObj[FIELD_PEER_DEVICE_ID] = "peerDeviceId"; from_json(jsonOutObj, credentialDataInfo); EXPECT_FALSE(credentialDataInfo.serverPk.empty()); diff --git a/test/commonunittest/UTTest_dm_discovery_filter.cpp b/test/commonunittest/UTTest_dm_discovery_filter.cpp index 04582ba5f..e33301e20 100644 --- a/test/commonunittest/UTTest_dm_discovery_filter.cpp +++ b/test/commonunittest/UTTest_dm_discovery_filter.cpp @@ -58,7 +58,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Leve { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -74,7 +74,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Leve DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -91,7 +91,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Leve nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -108,7 +108,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Leve nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -126,7 +126,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -144,7 +144,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -165,7 +165,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -187,7 +187,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -209,7 +209,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Lev myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -238,7 +238,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSiz { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -254,7 +254,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSiz DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -271,7 +271,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSiz nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -289,7 +289,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSiz jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -308,7 +308,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -327,7 +327,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = SafeDump(jsonObject); + std::string str = SafeyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 6352ef6a7..622ce24d3 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -315,7 +315,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeDump(jsonObject); + std::string localUdid = SafeyDump(jsonObject); int32_t osAccountId = 1245; bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); @@ -326,7 +326,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeDump(jsonObject); + std::string localUdid = SafeyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; int32_t osAccountId = 1245; @@ -339,7 +339,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeDump(jsonObject); + std::string localUdid = SafeyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -352,7 +352,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeDump(jsonObject); + std::string localUdid = SafeyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -365,7 +365,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeDump(jsonObject); + std::string localUdid = SafeyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; int32_t osAccountId = 1245; @@ -378,7 +378,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeDump(jsonObject); + std::string localUdid = SafeyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t osAccountId = 1245; @@ -391,7 +391,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeDump(jsonObject); + std::string localUdid = SafeyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; int32_t osAccountId = 1245; diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index 2d29be6c1..1997960e3 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1200,7 +1200,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_001, testing::ext::TestS HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = SafeDump(jsonObj); + std::string credentialInfo = SafeyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1219,7 +1219,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_003, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 1; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = SafeDump(jsonObj); + std::string credentialInfo = SafeyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1238,7 +1238,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_004, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 4; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = SafeDump(jsonObj); + std::string credentialInfo = SafeyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1270,7 +1270,7 @@ HWTEST_F(HichainConnectorTest, addMultiMembersExt_001, testing::ext::TestSize.Le HWTEST_F(HichainConnectorTest, addMultiMembersExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = SafeDump(jsonObj); + std::string credentialInfo = SafeyDump(jsonObj); std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->addMultiMembersExt(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -1314,7 +1314,7 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_001, testing::ext::TestSize HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string jsonStr = SafeDump(jsonObj); + std::string jsonStr = SafeyDump(jsonObj); std::vector udidList; std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr.c_str(), udidList); diff --git a/test/commonunittest/UTTest_mine_hichain_connector.cpp b/test/commonunittest/UTTest_mine_hichain_connector.cpp index 6fff3e5f2..b322d45c9 100644 --- a/test/commonunittest/UTTest_mine_hichain_connector.cpp +++ b/test/commonunittest/UTTest_mine_hichain_connector.cpp @@ -113,7 +113,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_002, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = SafeDump(jsonObject); + std::string reqJsonStr = SafeyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -123,7 +123,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_003, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string reqJsonStr = SafeDump(jsonObject); + std::string reqJsonStr = SafeyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -133,7 +133,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, RequestCredential_001, testing::ext::Test std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string returnJsonStr = SafeDump(jsonObject); + std::string returnJsonStr = SafeyDump(jsonObject); int32_t ret = minHiChain->RequestCredential(returnJsonStr); EXPECT_EQ(ret, DM_OK); } @@ -170,7 +170,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestS std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = SafeDump(jsonObject); + std::string reqJsonStr = SafeyDump(jsonObject); std::string returnJsonStr; int32_t ret = minHiChain->ImportCredential(reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_REGISTER_CALLBACK); diff --git a/test/commonunittest/UTTest_pin_auth.cpp b/test/commonunittest/UTTest_pin_auth.cpp index a20ad3dad..efe6123ac 100644 --- a/test/commonunittest/UTTest_pin_auth.cpp +++ b/test/commonunittest/UTTest_pin_auth.cpp @@ -74,7 +74,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_002, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_TOKEN] = 123456; - std::string authToken = SafeDump(jsonObject); + std::string authToken = SafeyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -90,7 +90,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_003, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = SafeDump(jsonObject); + std::string authToken = SafeyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, nullptr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -106,7 +106,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_004, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = SafeDump(jsonObject); + std::string authToken = SafeyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 38d673cfb..0963ce366 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -67,7 +67,7 @@ HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_002, testing::ext::TestSize. nlohmann::json jsonObj; jsonObj["findDeviceMode"] = 4; string pkgName; - string searchJson = SafeDump(jsonObj); + string searchJson = SafeyDump(jsonObj); DmSubscribeInfo dmSubscribeInfo; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->RefreshSoftbusLNN(pkgName, searchJson, dmSubscribeInfo); @@ -145,7 +145,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_002, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(1); string pkgName; - string searchJson = SafeDump(jsonObj); + string searchJson = SafeyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -158,7 +158,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_003, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(2); string pkgName; - string searchJson = SafeDump(jsonObj); + string searchJson = SafeyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -171,7 +171,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_004, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(3); string pkgName; - string searchJson = SafeDump(jsonObj); + string searchJson = SafeyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -184,7 +184,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_005, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(4); string pkgName; - string searchJson = SafeDump(jsonObj); + string searchJson = SafeyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, DM_OK); diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index a60d72896..511b1ad8f 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -107,7 +107,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) nlohmann::json jsonObj; jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = msgType; - std::string message = SafeDump(jsonObj); + std::string message = SafeyDump(jsonObj); int32_t sessionId = 0; if (softbusSession == nullptr) { softbusSession = std::make_shared(); diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index 6c33c1d7d..0109df72a 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -133,7 +133,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes authMessageProcessor->SetResponseContext(authResponseContext); authMessageProcessor->cryptoAdapter_ = nullptr; authMessageProcessor->CreateNegotiateMessage(jsonObj); - std::string str1 = SafeDump(jsonObj); + std::string str1 = SafeyDump(jsonObj); authMessageProcessor->cryptoAdapter_ = std::make_shared(); authMessageProcessor->CreateNegotiateMessage(jsonObj); @@ -146,7 +146,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes jsonObject[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsonObject[TAG_LOCAL_DEVICE_ID] = authMessageProcessor->authResponseContext_->localDeviceId; jsonObject[TAG_HOST] = ""; - std::string str2 = SafeDump(jsonObject); + std::string str2 = SafeyDump(jsonObject); ASSERT_NE(str1, str2); } @@ -172,8 +172,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateSyncGroupMessage_001, testing::ext::Tes jsona[TAG_DEVICE_ID] = authMessageProcessor->authRequestContext_->deviceId; jsona[TAG_GROUPIDS] = authMessageProcessor->authRequestContext_->syncGroupList; authMessageProcessor->CreateSyncGroupMessage(jsonObj); - std::string str1 = SafeDump(jsona); - std::string str2 = SafeDump(jsonObj); + std::string str1 = SafeyDump(jsona); + std::string str2 = SafeyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -198,7 +198,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: nlohmann::json jsonb; jsonb[TAG_GROUP_ID] = "123456"; authMessageProcessor->authResponseContext_->groupId = - SafeDump(jsonb); + SafeyDump(jsonb); authMessageProcessor->authResponseContext_->authToken = "123456"; authMessageProcessor->authResponseContext_->networkId = "11112222"; authMessageProcessor->authResponseContext_->requestId = 222222; @@ -212,8 +212,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: jsona[TAG_GROUP_ID] = "123456"; jsona[TAG_GROUP_NAME] = authMessageProcessor->authResponseContext_->groupName; authMessageProcessor->CreateResponseAuthMessage(jsonObj); - std::string str1 = SafeDump(jsona); - std::string str2 = SafeDump(jsonObj); + std::string str1 = SafeyDump(jsona); + std::string str2 = SafeyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -236,8 +236,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseFinishMessage_001, testing::ext jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsona[TAG_AUTH_FINISH] = authMessageProcessor->authResponseContext_->isFinish; authMessageProcessor->CreateResponseFinishMessage(jsonObj); - std::string str1 = SafeDump(jsona); - std::string str2 = SafeDump(jsonObj); + std::string str1 = SafeyDump(jsona); + std::string str2 = SafeyDump(jsonObj); ASSERT_EQ(str1, str2); } diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index 40dd4eb14..cf09bffff 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -460,7 +460,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -471,7 +471,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -483,7 +483,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -493,7 +493,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_101, testing::ext::TestSize.Level std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -504,7 +504,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_102, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->listener_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -516,7 +516,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_103, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::SUPER_SONIC; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -528,7 +528,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_104, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -559,7 +559,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -570,7 +570,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -582,7 +582,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -604,7 +604,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_101, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -616,7 +616,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_102, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -628,7 +628,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_103, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -640,7 +640,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_104, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -653,7 +653,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_105, testing::ext::TestSize.Level0) int32_t data = 300; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = data; - std::string message = SafeDump(jsonObject); + std::string message = SafeyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index b0af3cb80..53c6310d4 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -1250,7 +1250,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_053, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_OH; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = SafeDump(jsonObject); + std::string credentialInfo = SafeyDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); @@ -1288,7 +1288,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_054, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_MINE; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = SafeDump(jsonObject); + std::string credentialInfo = SafeyDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); diff --git a/utils/src/kvadapter/dm_kv_info.cpp b/utils/src/kvadapter/dm_kv_info.cpp index 199603c88..d41c86c38 100644 --- a/utils/src/kvadapter/dm_kv_info.cpp +++ b/utils/src/kvadapter/dm_kv_info.cpp @@ -28,7 +28,7 @@ void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) jsonObj[ANOY_DEVICE_ID_KEY] = kvValue.anoyDeviceId; jsonObj[SALT_KEY] = kvValue.salt; jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; - result = SafeDump(jsonObj); + result = SafeyDump(jsonObj); } void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) -- Gitee From 9101da58b0452457d87df2d83946a7a702b8978c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Fri, 6 Dec 2024 09:37:25 +0800 Subject: [PATCH 510/520] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=80=81=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=9D=83=E9=99=90=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- services/service/src/device_manager_service.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fcf4dd9d9..d7fc32201 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1195,7 +1195,8 @@ void DeviceManagerService::UnloadDMServiceAdapter() int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName, const std::map &discoverParam, const std::map &filterOptions) { - if (!PermissionManager::GetInstance().CheckNewPermission()) { + if (!PermissionManager::GetInstance().CheckNewPermission() && + !PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } @@ -1214,7 +1215,8 @@ int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName, int32_t DeviceManagerService::StopDiscovering(const std::string &pkgName, const std::map &discoverParam) { - if (!PermissionManager::GetInstance().CheckNewPermission()) { + if (!PermissionManager::GetInstance().CheckNewPermission() && + !PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } -- Gitee From 8845f8545621f39893961ecb0f6417f20d4007c3 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Fri, 6 Dec 2024 18:11:40 +0800 Subject: [PATCH 511/520] =?UTF-8?q?kill=20=E6=80=BB=E7=BA=BF=E6=B8=85?= =?UTF-8?q?=E7=90=86=E7=BC=93=E5=AD=98=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../native_cpp/src/device_manager_impl.cpp | 2 +- .../service/include/softbus/softbus_listener.h | 1 + services/service/src/device_manager_service.cpp | 2 ++ .../service/src/softbus/softbus_listener.cpp | 16 ++++++++++++++++ services/softbuscache/include/dm_softbus_cache.h | 1 + services/softbuscache/src/dm_softbus_cache.cpp | 6 ++++++ 6 files changed, 27 insertions(+), 1 deletion(-) 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 112ebecd6..05d7234d3 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -565,7 +565,7 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgNameTemp); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); req->SetFirstParam(discParaStr); int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); if (ret != DM_OK) { diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 1ccbaa02e..5e507442a 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -105,6 +105,7 @@ public: static int32_t GetNetworkIdByUdid(const std::string &udid, std::string &networkId); int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); int32_t SetForegroundUserIdsToDSoftBus(const std::string &remoteUserId, const std::vector &userIds); + void DeleteCacheDeviceInfo(); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fcf4dd9d9..3b93b2000 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -201,6 +201,8 @@ void DeviceManagerService::QueryDependsSwitchState() void DeviceManagerService::UninitSoftbusListener() { + CHECK_NULL_VOID(softbusListener_); + softbusListener_->DeleteCacheDeviceInfo(); softbusListener_ = nullptr; LOGI("SoftbusListener uninit."); } diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 6f3410be1..12484b968 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -1155,5 +1155,21 @@ int32_t SoftbusListener::SetForegroundUserIdsToDSoftBus(const std::string &remot #endif return DM_OK; } + +void SoftbusListener::DeleteCacheDeviceInfo() +{ + LOGI("DeleteCacheDeviceInfo start."); + std::vector onlineDevInfoVec; + SoftbusCache::GetInstance().GetDeviceInfoFromCache(onlineDevInfoVec); + if (onlineDevInfoVec.empty()) { + LOGE("onlineDevInfoVec is empty"); + return; + } + SoftbusCache::GetInstance().DeleteDeviceInfo(); + for (auto it : onlineDevInfoVec) { + LOGI("networkId: %{public}s", GetAnonyString(it.networkId).c_str()); + DeviceOffLine(it); + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/softbuscache/include/dm_softbus_cache.h b/services/softbuscache/include/dm_softbus_cache.h index 30f88aac9..5a174234d 100644 --- a/services/softbuscache/include/dm_softbus_cache.h +++ b/services/softbuscache/include/dm_softbus_cache.h @@ -32,6 +32,7 @@ class SoftbusCache { public: void SaveDeviceInfo(DmDeviceInfo deviceInfo); void DeleteDeviceInfo(const DmDeviceInfo &nodeInfo); + void DeleteDeviceInfo(); void ChangeDeviceInfo(const DmDeviceInfo deviceInfo); void SaveDeviceSecurityLevel(const char *networkId); void DeleteDeviceSecurityLevel(const char *networkId); diff --git a/services/softbuscache/src/dm_softbus_cache.cpp b/services/softbuscache/src/dm_softbus_cache.cpp index 6cbdb49a0..02347e776 100644 --- a/services/softbuscache/src/dm_softbus_cache.cpp +++ b/services/softbuscache/src/dm_softbus_cache.cpp @@ -164,6 +164,12 @@ void SoftbusCache::DeleteDeviceInfo(const DmDeviceInfo &nodeInfo) } } +void SoftbusCache::DeleteDeviceInfo() +{ + std::lock_guard mutexLock(deviceInfosMutex_); + deviceInfo_.clear(); +} + void SoftbusCache::ChangeDeviceInfo(const DmDeviceInfo deviceInfo) { LOGI("SoftbusCache::ChangeDeviceInfo"); -- Gitee From 9ac1eaa7df0d02cd7d0372c13edae271df62685e Mon Sep 17 00:00:00 2001 From: l60055366 Date: Sat, 7 Dec 2024 10:54:03 +0800 Subject: [PATCH 512/520] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dfoundation/distribute?= =?UTF-8?q?dhardware/device=5Fmanager=E6=A8=A1=E5=9D=97=E7=9A=84=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: l60055366 --- interfaces/kits/js4.0/src/dm_native_util.cpp | 3 ++- .../implementation/src/authentication/dm_auth_manager.cpp | 4 ++-- test/commonunittest/UTTest_dm_auth_manager_first.cpp | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index 414c2fe8a..f1fa3f787 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -40,11 +40,12 @@ const int32_t DM_NAPI_DISCOVER_EXTRA_INIT_ONE = -1; const int32_t DM_NAPI_DISCOVER_EXTRA_INIT_TWO = -2; const int32_t DM_NAPI_DESCRIPTION_BUF_LENGTH = 16384; const int32_t DM_NAPI_BUF_LENGTH = 256; +const int32_t MAX_OBJECT_LEN = 4096; void JsObjectToString(const napi_env &env, const napi_value &object, const std::string &fieldStr, char *dest, const int32_t destLen) { - if (dest == nullptr) { + if (dest == nullptr || destLen < 0 || destLen > MAX_OBJECT_LEN) { return; } bool hasProperty = false; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index e85d8fbcb..effda0a0d 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -323,9 +323,9 @@ int32_t DmAuthManager::UnAuthenticateDevice(const std::string &pkgName, const st int32_t DmAuthManager::StopAuthenticateDevice(const std::string &pkgName) { - if (pkgName.empty()) { + if (pkgName.empty() || authRequestContext_ == nullptr || authResponseContext_ == nullptr) { LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_FAILED; + return ERR_DM_INPUT_PARA_INVALID; } if (((authRequestState_!= nullptr && authRequestContext_->hostPkgName == pkgName) || (authResponseContext_ != nullptr && authResponseContext_->hostPkgName == pkgName)) && diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 35050401f..d784fa4a7 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1371,7 +1371,7 @@ HWTEST_F(DmAuthManagerTest, StopAuthenticateDevice_001, testing::ext::TestSize.L { std::string pkgName; int32_t ret = authManager_->StopAuthenticateDevice(pkgName); - ASSERT_EQ(ret, ERR_DM_FAILED); + ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); pkgName = "pkgName_001"; int64_t requestId = 12; -- Gitee From 52a7e1128996c390f5c447cfd6ffb849ffc814d0 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 9 Dec 2024 18:12:13 +0800 Subject: [PATCH 513/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9inactive=E3=80=81acti?= =?UTF-8?q?ve=E9=A1=BA=E5=BA=8F=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- commondependency/src/deviceprofile_connector.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 35543e39c..3aa529075 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -1119,13 +1119,15 @@ int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, { LOGI("Start."); std::vector profiles = GetAllAccessControlProfile(); + std::vector activeProfiles; + std::vector inActiveProfiles; for (auto &item : profiles) { if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && item.GetAccesser().GetAccesserUserId() == beforeUserId && item.GetStatus() == ACTIVE) || (item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccessee().GetAccesseeUserId() == beforeUserId && item.GetStatus() == ACTIVE)) { item.SetStatus(INACTIVE); - DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + inActiveProfiles.push_back(item); continue; } if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && @@ -1133,10 +1135,16 @@ int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, item.GetAccessee().GetAccesseeDeviceId() == localUdid && item.GetAccessee().GetAccesseeUserId() == currentUserId && item.GetStatus() == INACTIVE)) { item.SetStatus(ACTIVE); - DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + activeProfiles.push_back(item); continue; } } + for (auto &item : inActiveProfiles) { + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + for (auto &item : activeProfiles) { + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } return DM_OK; } -- Gitee From 7217f054633c507732118d0103812a8d25763897 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=B2=E6=99=93=E6=99=93?= Date: Tue, 10 Dec 2024 15:20:59 +0800 Subject: [PATCH 514/520] =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 史晓晓 --- common/include/dm_anonymous.h | 2 +- common/src/dm_anonymous.cpp | 4 +-- .../native_cpp/src/device_manager_impl.cpp | 4 +-- .../kits/js/src/native_devicemanager_js.cpp | 4 +-- interfaces/kits/js4.0/src/dm_native_util.cpp | 4 +-- .../ability/standard/dm_dialog_manager.cpp | 2 +- .../authentication/auth_message_processor.cpp | 8 ++--- .../authentication/auth_ui_state_manager.cpp | 2 +- .../src/authentication/dm_auth_manager.cpp | 22 ++++++------ .../src/credential/dm_credential_manager.cpp | 4 +-- .../hichain/hichain_auth_connector.cpp | 16 ++++----- .../dependency/hichain/hichain_connector.cpp | 36 +++++++++---------- .../hichain/mine_hichain_connector.cpp | 4 +-- .../dependency/softbus/softbus_connector.cpp | 8 ++--- services/service/src/pinholder/pin_holder.cpp | 28 +++++++-------- .../service/src/softbus/softbus_listener.cpp | 4 +-- .../hichain_connector_fuzzer.cpp | 6 ++-- .../UTTest_discovery_filter.cpp | 30 ++++++++-------- .../UTTest_dm_auth_manager_first.cpp | 12 +++---- .../UTTest_dm_auth_manager_second.cpp | 18 +++++----- .../UTTest_dm_auth_manager_third.cpp | 16 ++++----- .../UTTest_dm_credential_manager.cpp | 16 ++++----- .../UTTest_dm_discovery_filter.cpp | 30 ++++++++-------- .../UTTest_hichain_auth_connector.cpp | 14 ++++---- .../UTTest_hichain_connector.cpp | 10 +++--- .../UTTest_mine_hichain_connector.cpp | 8 ++--- test/commonunittest/UTTest_pin_auth.cpp | 6 ++-- .../UTTest_mine_softbus_listener.cpp | 10 +++--- .../UTTest_softbus_session.cpp | 2 +- .../UTTest_auth_message_processor.cpp | 18 +++++----- test/unittest/UTTest_dm_pin_holder.cpp | 30 ++++++++-------- .../UTTest_ipc_cmd_parser_service.cpp | 4 +-- utils/src/kvadapter/dm_kv_info.cpp | 2 +- 33 files changed, 192 insertions(+), 192 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 46aebde59..8c9787dd1 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -101,7 +101,7 @@ bool IsIdLengthValid(const std::string &inputID); bool IsMessageLengthValid(const std::string &inputMessage); bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId); bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent); -std::string SafeyDump(const nlohmann::json &jsonObj); +std::string SafetyDump(const nlohmann::json &jsonObj); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index bec2a8201..f23e723d2 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -184,7 +184,7 @@ std::string ConvertMapToJsonString(const std::map &par for (const auto &it : paramMap) { jsonObj[it.first] = it.second; } - jsonStr = SafeyDump(jsonObj); + jsonStr = SafetyDump(jsonObj); } return jsonStr; } @@ -366,7 +366,7 @@ bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent) return false; } -std::string SafeyDump(const nlohmann::json &jsonObj) +std::string SafetyDump(const nlohmann::json &jsonObj) { int indent = -1; return jsonObj.dump(indent, ' ', false, nlohmann::detail::error_handler_t::ignore); 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 88854c816..8eff56e8c 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -674,7 +674,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetExtra(SafeyDump(extraJson)); + req->SetExtra(SafetyDump(extraJson)); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); @@ -1493,7 +1493,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetBindParam(SafeyDump(paramJson)); + req->SetBindParam(SafetyDump(paramJson)); req->SetBindType(bindType); req->SetDeviceId(deviceId); int32_t ret = ipcClientProxy_->SendRequest(BIND_DEVICE, req, rsp); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 4588803d5..410ae5b50 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1203,7 +1203,7 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr; jsonObj[BIND_LEVEL] = bindLevel; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = SafeyDump(jsonObj); + extra = SafetyDump(jsonObj); LOGI("appOperationLen %{public}zu, customDescriptionLen %{public}zu", appOperationStr.size(), customDescriptionStr.size()); } @@ -1274,7 +1274,7 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob jsonObj[AUTH_TYPE] = authType; jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = SafeyDump(jsonObj); + extra = SafetyDump(jsonObj); } void DeviceManagerNapi::JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index c70d6a175..576262866 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -330,7 +330,7 @@ void JsToBindParam(const napi_env &env, const napi_value &object, std::string &b jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP); jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort; jsonObj[BIND_LEVEL] = bindLevel; - bindParam = SafeyDump(jsonObj); + bindParam = SafetyDump(jsonObj); } bool IsSystemApp() @@ -395,7 +395,7 @@ void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::st if (deviceType != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) { jsonObj["deviceType"] = deviceType; } - extra = SafeyDump(jsonObj); + extra = SafetyDump(jsonObj); LOGI("JsToDmDiscoveryExtra, extra :%{public}s", extra.c_str()); } diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 479daaadb..28cbb121f 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -202,7 +202,7 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = SafeyDump(param); + std::string paramStr = SafetyDump(param); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index cf4b5bf15..e7a2cb902 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -87,7 +87,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1; jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; GetJsonObj(jsonObj); - jsonStrVec.push_back(SafeyDump(jsonObj)); + jsonStrVec.push_back(SafetyDump(jsonObj)); for (int32_t idx = 0; idx < thumbnailSlice; idx++) { nlohmann::json jsonThumbnailObj; jsonThumbnailObj[TAG_VER] = DM_ITF_VER; @@ -101,7 +101,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() LOGI("TAG_APP_THUMBNAIL encode, idx %{public}d, sliceLen %{public}d, thumbnailSize %{public}d", idx, (uint32_t)sliceLen, thumbnailSize); jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); - jsonStrVec.push_back(SafeyDump(jsonThumbnailObj)); + jsonStrVec.push_back(SafetyDump(jsonThumbnailObj)); } return jsonStrVec; } @@ -138,7 +138,7 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) default: break; } - return SafeyDump(jsonObj); + return SafetyDump(jsonObj); } void AuthMessageProcessor::CreatePublicKeyMessageExt(nlohmann::json &json) @@ -593,7 +593,7 @@ std::string AuthMessageProcessor::CreateDeviceAuthMessage(int32_t msgType, const std::string authDataStr = std::string(reinterpret_cast(data), dataLen); jsonObj[TAG_DATA] = authDataStr; jsonObj[TAG_DATA_LEN] = dataLen; - return SafeyDump(jsonObj); + return SafetyDump(jsonObj); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index 51292896b..ed9e95d7a 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -62,7 +62,7 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) } nlohmann::json jsonObj; jsonObj[UI_STATE_MSG] = msg; - std::string paramJson = SafeyDump(jsonObj); + std::string paramJson = SafetyDump(jsonObj); std::lock_guard lock(pkgSetMutex_); for (auto item : pkgSet_) { listener_->OnUiCall(item, paramJson); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 933f035de..09bf66b5b 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -609,7 +609,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId jsonObj[PIN_TOKEN] = authResponseContext_->token; jsonObj[QR_CODE_KEY] = GenerateGroupName(); jsonObj[NFC_CODE_KEY] = GenerateGroupName(); - authResponseContext_->authToken = SafeyDump(jsonObj); + authResponseContext_->authToken = SafetyDump(jsonObj); LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); authResponseContext_->groupId = groupId; authResponseContext_->code = pinCode; @@ -1176,7 +1176,7 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) jsonObject[PIN_CODE_KEY] = pinCode; jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; - std::string connectInfo = SafeyDump(jsonObject); + std::string connectInfo = SafetyDump(jsonObject); if (timer_ != nullptr) { timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { @@ -1441,7 +1441,7 @@ void DmAuthManager::ShowConfigDialog() jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; - const std::string params = SafeyDump(jsonObj); + const std::string params = SafetyDump(jsonObj); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); @@ -1478,7 +1478,7 @@ void DmAuthManager::ShowAuthInfoDialog() } nlohmann::json jsonObj; jsonObj[PIN_CODE_KEY] = authResponseContext_->code; - std::string authParam = SafeyDump(jsonObj); + std::string authParam = SafetyDump(jsonObj); DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); } @@ -1650,7 +1650,7 @@ bool DmAuthManager::IsIdenticalAccount() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = SafeyDump(jsonObj); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1690,7 +1690,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = SafeyDump(jsonObj); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1705,7 +1705,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() for (auto &groupInfo : groupList) { jsonAccountObj.push_back(Crypto::GetGroupIdHash(groupInfo.groupId)); } - return SafeyDump(jsonAccountObj); + return SafetyDump(jsonAccountObj); } int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) @@ -1893,7 +1893,7 @@ std::string DmAuthManager::GenerateBindResultContent() Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); jsonObj[TAG_DEVICE_ID] = deviceIdHash; } - std::string content = SafeyDump(jsonObj); + std::string content = SafetyDump(jsonObj); return content; } @@ -2237,7 +2237,7 @@ void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) } } jsonObject[TAG_CRYPTO_SUPPORT] = false; - message = SafeyDump(jsonObject); + message = SafetyDump(jsonObject); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2248,7 +2248,7 @@ void DmAuthManager::ProcIncompatible(const int32_t &sessionId) respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; respNegotiateMsg[TAG_VER] = DM_ITF_VER; respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; - std::string message = SafeyDump(respNegotiateMsg); + std::string message = SafetyDump(respNegotiateMsg); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2370,7 +2370,7 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); nlohmann::json jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = SafeyDump(jsonObj); + std::string message = SafetyDump(jsonObj); softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 1c269dd28..ec374658e 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -113,7 +113,7 @@ int32_t DmCredentialManager::RequestCredential(const std::string &reqJsonStr, st jsonObj[FIELD_CREDENTIAL_VERSION] = credentialVersion; jsonObj[FIELD_USER_ID] = userId; jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string tmpStr = SafeyDump(jsonObj); + std::string tmpStr = SafetyDump(jsonObj); return hiChainConnector_->getRegisterInfo(tmpStr.c_str(), returnJsonStr); } @@ -364,7 +364,7 @@ void from_json(const nlohmann::json &jsonObject, CredentialDataInfo &credentialD } if (IsString(jsonObject, FIELD_PKINFO)) { nlohmann::json jsonPkInfo = jsonObject[FIELD_PKINFO]; - credentialDataInfo.pkInfo = SafeyDump(jsonPkInfo); + credentialDataInfo.pkInfo = SafetyDump(jsonPkInfo); } } else if (credentialDataInfo.credentialType == SYMMETRY_CREDENTIAL_TYPE) { if (IsString(jsonObject, FIELD_AUTH_CODE)) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 2b116e05a..f0614dcf2 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -56,7 +56,7 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s authParamJson["osAccountId"] = osAccountId; authParamJson["pinCode"] = std::to_string(pinCode); authParamJson["acquireType"] = AcquireType::P2P_BIND; - std::string authParam = SafeyDump(authParamJson); + std::string authParam = SafetyDump(authParamJson); LOGI("StartAuthDevice authParam %{public}s ,requestId %{public}" PRId64, GetAnonyString(authParam).c_str(), requestId); int32_t ret = StartAuthDevice(requestId, authParam.c_str(), &deviceAuthCallback_); @@ -73,7 +73,7 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut nlohmann::json jsonAuthParam; jsonAuthParam["osAccountId"] = osAccountId; jsonAuthParam["data"] = authData; - int32_t ret = ProcessAuthDevice(requestId, SafeyDump(jsonAuthParam).c_str(), &deviceAuthCallback_); + int32_t ret = ProcessAuthDevice(requestId, SafetyDump(jsonAuthParam).c_str(), &deviceAuthCallback_); if (ret != HC_SUCCESS) { LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; @@ -111,7 +111,7 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = SafeyDump(jsonObj); + std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -159,7 +159,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = SafeyDump(jsonObj); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_CREATE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain generate credential failed."); @@ -192,7 +192,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = SafeyDump(jsonObj); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -223,7 +223,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = SafeyDump(jsonObj); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -255,7 +255,7 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; - std::string requestParam = SafeyDump(jsonObj); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_IMPORT, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -286,7 +286,7 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; - std::string requestParam = SafeyDump(jsonObj); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index fc7b71c8b..c1b4f837b 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -154,7 +154,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, SafeyDump(jsonObj).c_str()); + int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, SafetyDump(jsonObj).c_str()); struct RadarInfo info = { .funcName = "CreateGroup", .toCallPkg = HICHAINNAME, @@ -178,7 +178,7 @@ bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInf { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = SafeyDump(jsonObj); + std::string queryParams = SafetyDump(jsonObj); std::vector groupList; if (GetGroupInfo(queryParams, groupList)) { groupInfo = groupList[0]; @@ -191,7 +191,7 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = SafeyDump(jsonObj); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -343,7 +343,7 @@ int32_t HiChainConnector::AddMember(const std::string &deviceId, const std::stri jsonObj[FIELD_DEVICE_ID] = localDeviceId; jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME].get(); jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str(); - std::string tmpStr = SafeyDump(jsonObj); + std::string tmpStr = SafetyDump(jsonObj); int64_t requestId = jsonObject[TAG_REQUEST_ID].get(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { @@ -486,7 +486,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string jsonStr = SafeyDump(jsonObj); + std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -511,7 +511,7 @@ std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string r } jsonObject[DEVICE_ID] = reqDeviceId; - return SafeyDump(jsonObject); + return SafetyDump(jsonObject); } int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vector &groupList) @@ -602,7 +602,7 @@ int32_t HiChainConnector::DelMemberFromGroup(const std::string &groupId, const s nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_DELETE_ID] = deviceId; - std::string deleteParams = SafeyDump(jsonObj); + std::string deleteParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -621,7 +621,7 @@ int32_t HiChainConnector::DeleteGroup(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeyDump(jsonObj); + std::string disbandParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -641,7 +641,7 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeyDump(jsonObj); + std::string disbandParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -661,7 +661,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use networkStyle_ = CREDENTIAL_NETWORK; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = SafeyDump(jsonObj); + std::string queryParams = SafetyDump(jsonObj); std::vector groupList; if (!GetGroupInfo(queryParams, groupList)) { LOGE("failed to get device join groups"); @@ -682,7 +682,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use return ERR_DM_FAILED; } jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeyDump(jsonObj); + std::string disbandParams = SafetyDump(jsonObj); g_deleteGroupFlag = false; int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -792,7 +792,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const return ERR_DM_FAILED; } int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, - SafeyDump(jsonObj).c_str()); + SafetyDump(jsonObj).c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); return ERR_DM_CREATE_GROUP_FAILED; @@ -842,7 +842,7 @@ int32_t HiChainConnector::GetGroupId(const std::string &userId, const int32_t gr { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = SafeyDump(jsonObjGroup); + std::string queryParams = SafetyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -875,7 +875,7 @@ int32_t HiChainConnector::ParseRemoteCredential(const int32_t groupType, const s jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = groupType; jsonObj[FIELD_DEVICE_LIST] = jsonDeviceList[FIELD_DEVICE_LIST]; - params = SafeyDump(jsonObj); + params = SafetyDump(jsonObj); osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { LOGE("get current process account user id failed"); @@ -929,7 +929,7 @@ int32_t HiChainConnector::GetGroupIdExt(const std::string &userId, const int32_t { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = SafeyDump(jsonObjGroup); + std::string queryParams = SafetyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -983,7 +983,7 @@ int32_t HiChainConnector::ParseRemoteCredentialExt(const std::string &credential return ERR_DM_FAILED; } jsonObj[FIELD_DEVICE_LIST] = jsonObject[FIELD_DEVICE_LIST]; - params = SafeyDump(jsonObj); + params = SafetyDump(jsonObj); return DM_OK; } @@ -1158,7 +1158,7 @@ int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = SafeyDump(jsonObj); + std::string disbandParams = SafetyDump(jsonObj); int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); if (ret != 0) { LOGE("[HICHAIN]fail to delete group with ret:%{public}d.", ret); @@ -1248,7 +1248,7 @@ int32_t HiChainConnector::DeleteGroupByACL(std::vector groupList; if (!GetGroupInfo(userId, queryParams, groupList)) { diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index 06e822f01..a4df42a1a 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -136,7 +136,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) { nlohmann::json jsonObj; jsonObj[FIELD_IS_DELETE_ALL] = true; - std::string params = SafeyDump(jsonObj); + std::string params = SafetyDump(jsonObj); #if (defined(MINE_HARMONY)) char *returnInfo = nullptr; int32_t retValue = g_deviceGroupManager->processCredential(DELETE_SELF_CREDENTIAL, params.c_str(), &returnInfo); @@ -174,7 +174,7 @@ int32_t MineHiChainConnector::CreateGroup(const std::string &reqJsonStr) jsonObj[FIELD_GROUP_NAME] = DEVICE_MANAGER_GROUPNAME; jsonObj[FIELD_DEVICE_ID] = std::string(deviceUdid); jsonObj[FIELD_GROUP_TYPE] = IDENTICAL_ACCOUNT_GROUP; - std::string createParams = SafeyDump(jsonObj); + std::string createParams = SafetyDump(jsonObj); retValue = g_deviceGroupManager->createGroup(DEFAULT_OS_ACCOUNT, requestId, DM_PKG_NAME, createParams.c_str()); if (retValue != HC_SUCCESS) { LOGE("failed to create group with ret:%{public}d.", retValue); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 36bc8412d..607bce135 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -342,7 +342,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = SafeyDump(jsonPara); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); @@ -350,20 +350,20 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafeyDump(jsonPara); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = SafeyDump(jsonPara); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = SafeyDump(jsonPara); + connectAddr = SafetyDump(jsonPara); return addr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 8898dc055..5463d1866 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -178,7 +178,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget jsonObj[TAG_PIN_TYPE] = pinType; jsonObj[TAG_PAYLOAD] = payload; pinType_ = pinType; - std::string message = SafeyDump(jsonObj); + std::string message = SafetyDump(jsonObj); LOGI("DestroyPinHolder, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER, pinType); ret = session_->SendData(sessionId_, message); @@ -212,7 +212,7 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() jsonObj[TAG_PAYLOAD] = payload_; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; jsonObj[TAG_DM_VERSION] = ""; - std::string message = SafeyDump(jsonObj); + std::string message = SafetyDump(jsonObj); LOGI("CreateGeneratePinHolderMsg, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER, pinType_); int32_t ret = session_->SendData(sessionId_, message); @@ -290,12 +290,12 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; - std::string content = SafeyDump(jsonContent); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; - std::string msg = SafeyDump(jsonObj); + std::string msg = SafetyDump(jsonObj); LOGI("ProcessCreateMsg, message type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -370,13 +370,13 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; - std::string content = SafeyDump(jsonContent); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); isDestroy_.store(true); } } - std::string msg = SafeyDump(jsonObj); + std::string msg = SafetyDump(jsonObj); LOGI("ProcessDestroyMsg, message type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -394,13 +394,13 @@ void PinHolder::CloseSession(const std::string &name) } nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = SafeyDump(jsonObj); + std::string payload = SafetyDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = SafeyDump(jsonContent); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); isDestroy_.store(true); } @@ -461,7 +461,7 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) LOGE("another session opened, close this sessionId: %{public}d.", sessionId); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; - std::string msg = SafeyDump(jsonObj); + std::string msg = SafetyDump(jsonObj); int32_t ret = session_->SendData(sessionId, msg); if (ret != DM_OK) { LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); @@ -563,13 +563,13 @@ void PinHolder::OnSessionClosed(int32_t sessionId) isRemoteSupported_ = false; nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = SafeyDump(jsonObj); + std::string payload = SafetyDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = SafeyDump(jsonContent); + std::string content = SafetyDump(jsonContent); if (destroyState_ == STATE_UNKNOW) { listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); } else if (destroyState_ == STATE_REMOTE_WRONG) { @@ -629,7 +629,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; jsonObj[TAG_PIN_TYPE] = pinType; - std::string message = SafeyDump(jsonObj); + std::string message = SafetyDump(jsonObj); LOGI("NotifyPinHolderEvent, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE, pinType); int32_t ret = session_->SendData(sessionId_, message); @@ -666,7 +666,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; - std::string content = SafeyDump(jsonContent); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); if (timer_ != nullptr) { timer_->DeleteAll(); @@ -677,7 +677,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) } } - std::string msg = SafeyDump(jsonObj); + std::string msg = SafetyDump(jsonObj); LOGI("ProcessChangeMsg, message type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 376918f18..21ec55bb8 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -868,7 +868,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe const ConnectionAddr *addrInfo = &(device.addr)[0]; if (addrInfo == nullptr) { LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); - dmDevice.extraData = SafeyDump(jsonObj); + dmDevice.extraData = SafetyDump(jsonObj); return; } jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; @@ -896,7 +896,7 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } - dmDevice.extraData = SafeyDump(jsonObj); + dmDevice.extraData = SafetyDump(jsonObj); } int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index db9309318..19c2f68e2 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -316,13 +316,13 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObj[key] = 1; jsonObj["deviceName"] = "devieName1"; hichainConnector->GetJsonInt(jsonObj, "devieName"); - hichainConnector->AddMember(deviceId, SafeyDump(jsonObj)); + hichainConnector->AddMember(deviceId, SafetyDump(jsonObj)); jsonObj[TAG_DEVICE_ID] = "deviceId_001"; jsonObj[PIN_CODE_KEY] = 1; jsonObj[TAG_GROUP_ID] = "groupId"; jsonObj[TAG_REQUEST_ID] = 1; jsonObj[TAG_GROUP_NAME] = "groupName"; - hichainConnector->AddMember(deviceId, SafeyDump(jsonObj)); + hichainConnector->AddMember(deviceId, SafetyDump(jsonObj)); nlohmann::json jsonObjCre; std::string params; @@ -332,7 +332,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObjCre[FIELD_OPERATION_CODE] = 1; jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; - std::string credentialInfo = SafeyDump(jsonObjCre); + std::string credentialInfo = SafetyDump(jsonObjCre); hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); int32_t groupType = *(reinterpret_cast(data)); nlohmann::json jsonDeviceList; diff --git a/test/commonunittest/UTTest_discovery_filter.cpp b/test/commonunittest/UTTest_discovery_filter.cpp index 5442a0220..1122727bb 100644 --- a/test/commonunittest/UTTest_discovery_filter.cpp +++ b/test/commonunittest/UTTest_discovery_filter.cpp @@ -45,7 +45,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Level0 { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -55,7 +55,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Level0 DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -66,7 +66,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Level0 nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -77,7 +77,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Level0 nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -89,7 +89,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -101,7 +101,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -116,7 +116,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -132,7 +132,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -148,7 +148,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Level myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -165,7 +165,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSize. { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -175,7 +175,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSize. DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -186,7 +186,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -198,7 +198,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSize. jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -211,7 +211,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -224,7 +224,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 7885b58fc..2ff09f6bd 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -1076,7 +1076,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived002, testing::ext::TestSize. int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_DATA] = 123; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1087,7 +1087,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived003, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = "123"; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1099,7 +1099,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived004, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = "123"; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1111,7 +1111,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived005, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = 123; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1336,7 +1336,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - extra = SafeyDump(jsonObject); + extra = SafetyDump(jsonObject); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1346,7 +1346,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); jsonObject["bindLevel"] = 15; - extra = SafeyDump(jsonObject); + extra = SafetyDump(jsonObject); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index f50b3e350..6263dd703 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -109,7 +109,7 @@ HWTEST_F(DmAuthManagerTest, OnDataReceived_007, testing::ext::TestSize.Level0) int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = 200; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); authManager_->OnDataReceived(sessionId, message); authManager_->authRequestState_ = nullptr; authManager_->authResponseState_ = nullptr; @@ -1323,7 +1323,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; jsonObject["targetPkgName"] = 1234; - std::string extra = SafeyDump(jsonObject); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1336,7 +1336,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_003, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = 1234; - std::string extra = SafeyDump(jsonObject); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1350,7 +1350,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_004, testing::ext::TestSize.Level0) jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = 1234; - std::string extra = SafeyDump(jsonObject); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1365,7 +1365,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_005, testing::ext::TestSize.Level0) jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = 1234; - std::string extra = SafeyDump(jsonObject); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1381,7 +1381,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_006, testing::ext::TestSize.Level0) jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = "1234"; - std::string extra = SafeyDump(jsonObject); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1398,7 +1398,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_007, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = "1234"; - std::string extra = SafeyDump(jsonObject); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1415,7 +1415,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_008, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = 1234; - std::string extra = SafeyDump(jsonObject); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1509,7 +1509,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level nlohmann::json jsonPeerGroupIdObj; jsonPeerGroupIdObj["groupId"] = "123456"; - authManager_->authResponseContext_->accountGroupIdHash = SafeyDump(jsonPeerGroupIdObj); + authManager_->authResponseContext_->accountGroupIdHash = SafetyDump(jsonPeerGroupIdObj); EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index e4e236ec1..d4c1150f5 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -142,13 +142,13 @@ void DmAuthManagerTest::TearDownTestCase() {} HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); int32_t sessionId = 0; authManager_->remoteDeviceId_ = "ProcRespNegotiate001"; authManager_->ProcRespNegotiate(sessionId); jsonObject[TAG_CRYPTO_SUPPORT] = false; - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; @@ -157,7 +157,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = ""; authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; @@ -165,7 +165,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->ProcRespNegotiate(sessionId); authManager_->authResponseState_->context_ = std::make_shared(); - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -175,7 +175,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_NAME] = "test"; - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -188,13 +188,13 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); int32_t sessionId = 0; authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->remoteDeviceId_ = "ProcRespNegotiate002"; authManager_->importAuthCode_ = "test"; @@ -208,7 +208,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = SafeyDump(jsonObject); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index fd9054026..c2da8eabb 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -181,7 +181,7 @@ HWTEST_F(DmCredentialManagerTest, RequestCredential_001, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["userId"] = "test"; jsonObject["version"] = "test"; - reqJsonStr = SafeyDump(jsonObject); + reqJsonStr = SafetyDump(jsonObject); ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -279,22 +279,22 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_001, testing::ext::TestSize.L nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); jsonObject["TType"] = 1; jsonObject["processType"] = 1; - credentialInfo = SafeyDump(jsonObject); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = -1; - credentialInfo = SafeyDump(jsonObject); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = 2; - credentialInfo = SafeyDump(jsonObject); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["TType"] = "test"; - credentialInfo = SafeyDump(jsonObject); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -717,13 +717,13 @@ HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_001, testing::ext::Test jsonObject[FIELD_USER_ID] = 0; jsonObject[FIELD_PEER_USER_ID] = "peerUserId"; - std::string credentialInfo = SafeyDump(jsonObject); + std::string credentialInfo = SafetyDump(jsonObject); dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject[FIELD_CREDENTIAL_DATA] = 0; - credentialInfo = SafeyDump(jsonObject); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1655,7 +1655,7 @@ HWTEST_F(DmCredentialManagerTest, from_json_001, testing::ext::TestSize.Level0) nlohmann::json jsonPkInfo; jsonOutObj[FIELD_SERVER_PK] = "serverPk"; jsonOutObj[FIELD_PKINFO_SIGNATURE] = "pkInfoSignature"; - jsonOutObj[FIELD_PKINFO] = SafeyDump(jsonPkInfo); + jsonOutObj[FIELD_PKINFO] = SafetyDump(jsonPkInfo); jsonOutObj[FIELD_PEER_DEVICE_ID] = "peerDeviceId"; from_json(jsonOutObj, credentialDataInfo); EXPECT_FALSE(credentialDataInfo.serverPk.empty()); diff --git a/test/commonunittest/UTTest_dm_discovery_filter.cpp b/test/commonunittest/UTTest_dm_discovery_filter.cpp index e33301e20..07e3f591c 100644 --- a/test/commonunittest/UTTest_dm_discovery_filter.cpp +++ b/test/commonunittest/UTTest_dm_discovery_filter.cpp @@ -58,7 +58,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Leve { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -74,7 +74,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Leve DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -91,7 +91,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Leve nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -108,7 +108,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Leve nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -126,7 +126,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -144,7 +144,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -165,7 +165,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -187,7 +187,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -209,7 +209,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Lev myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -238,7 +238,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSiz { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -254,7 +254,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSiz DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -271,7 +271,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSiz nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -289,7 +289,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSiz jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -308,7 +308,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -327,7 +327,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = SafeyDump(jsonObject); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 622ce24d3..538aceac9 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -315,7 +315,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeyDump(jsonObject); + std::string localUdid = SafetyDump(jsonObject); int32_t osAccountId = 1245; bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); @@ -326,7 +326,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeyDump(jsonObject); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; int32_t osAccountId = 1245; @@ -339,7 +339,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeyDump(jsonObject); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -352,7 +352,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeyDump(jsonObject); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -365,7 +365,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeyDump(jsonObject); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; int32_t osAccountId = 1245; @@ -378,7 +378,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeyDump(jsonObject); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t osAccountId = 1245; @@ -391,7 +391,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = SafeyDump(jsonObject); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; int32_t osAccountId = 1245; diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index 1997960e3..1e7e7fc29 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1200,7 +1200,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_001, testing::ext::TestS HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = SafeyDump(jsonObj); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1219,7 +1219,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_003, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 1; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = SafeyDump(jsonObj); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1238,7 +1238,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_004, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 4; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = SafeyDump(jsonObj); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1270,7 +1270,7 @@ HWTEST_F(HichainConnectorTest, addMultiMembersExt_001, testing::ext::TestSize.Le HWTEST_F(HichainConnectorTest, addMultiMembersExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = SafeyDump(jsonObj); + std::string credentialInfo = SafetyDump(jsonObj); std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->addMultiMembersExt(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -1314,7 +1314,7 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_001, testing::ext::TestSize HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string jsonStr = SafeyDump(jsonObj); + std::string jsonStr = SafetyDump(jsonObj); std::vector udidList; std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr.c_str(), udidList); diff --git a/test/commonunittest/UTTest_mine_hichain_connector.cpp b/test/commonunittest/UTTest_mine_hichain_connector.cpp index b322d45c9..f7c37a746 100644 --- a/test/commonunittest/UTTest_mine_hichain_connector.cpp +++ b/test/commonunittest/UTTest_mine_hichain_connector.cpp @@ -113,7 +113,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_002, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = SafeyDump(jsonObject); + std::string reqJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -123,7 +123,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_003, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string reqJsonStr = SafeyDump(jsonObject); + std::string reqJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -133,7 +133,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, RequestCredential_001, testing::ext::Test std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string returnJsonStr = SafeyDump(jsonObject); + std::string returnJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->RequestCredential(returnJsonStr); EXPECT_EQ(ret, DM_OK); } @@ -170,7 +170,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestS std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = SafeyDump(jsonObject); + std::string reqJsonStr = SafetyDump(jsonObject); std::string returnJsonStr; int32_t ret = minHiChain->ImportCredential(reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_REGISTER_CALLBACK); diff --git a/test/commonunittest/UTTest_pin_auth.cpp b/test/commonunittest/UTTest_pin_auth.cpp index efe6123ac..c9889e2b3 100644 --- a/test/commonunittest/UTTest_pin_auth.cpp +++ b/test/commonunittest/UTTest_pin_auth.cpp @@ -74,7 +74,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_002, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_TOKEN] = 123456; - std::string authToken = SafeyDump(jsonObject); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -90,7 +90,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_003, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = SafeyDump(jsonObject); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, nullptr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -106,7 +106,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_004, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = SafeyDump(jsonObject); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 0963ce366..753c15a8b 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -67,7 +67,7 @@ HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_002, testing::ext::TestSize. nlohmann::json jsonObj; jsonObj["findDeviceMode"] = 4; string pkgName; - string searchJson = SafeyDump(jsonObj); + string searchJson = SafetyDump(jsonObj); DmSubscribeInfo dmSubscribeInfo; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->RefreshSoftbusLNN(pkgName, searchJson, dmSubscribeInfo); @@ -145,7 +145,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_002, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(1); string pkgName; - string searchJson = SafeyDump(jsonObj); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -158,7 +158,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_003, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(2); string pkgName; - string searchJson = SafeyDump(jsonObj); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -171,7 +171,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_004, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(3); string pkgName; - string searchJson = SafeyDump(jsonObj); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -184,7 +184,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_005, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(4); string pkgName; - string searchJson = SafeyDump(jsonObj); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, DM_OK); diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index 511b1ad8f..0bee60540 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -107,7 +107,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) nlohmann::json jsonObj; jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = msgType; - std::string message = SafeyDump(jsonObj); + std::string message = SafetyDump(jsonObj); int32_t sessionId = 0; if (softbusSession == nullptr) { softbusSession = std::make_shared(); diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index 0109df72a..dba95a853 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -133,7 +133,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes authMessageProcessor->SetResponseContext(authResponseContext); authMessageProcessor->cryptoAdapter_ = nullptr; authMessageProcessor->CreateNegotiateMessage(jsonObj); - std::string str1 = SafeyDump(jsonObj); + std::string str1 = SafetyDump(jsonObj); authMessageProcessor->cryptoAdapter_ = std::make_shared(); authMessageProcessor->CreateNegotiateMessage(jsonObj); @@ -146,7 +146,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes jsonObject[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsonObject[TAG_LOCAL_DEVICE_ID] = authMessageProcessor->authResponseContext_->localDeviceId; jsonObject[TAG_HOST] = ""; - std::string str2 = SafeyDump(jsonObject); + std::string str2 = SafetyDump(jsonObject); ASSERT_NE(str1, str2); } @@ -172,8 +172,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateSyncGroupMessage_001, testing::ext::Tes jsona[TAG_DEVICE_ID] = authMessageProcessor->authRequestContext_->deviceId; jsona[TAG_GROUPIDS] = authMessageProcessor->authRequestContext_->syncGroupList; authMessageProcessor->CreateSyncGroupMessage(jsonObj); - std::string str1 = SafeyDump(jsona); - std::string str2 = SafeyDump(jsonObj); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -198,7 +198,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: nlohmann::json jsonb; jsonb[TAG_GROUP_ID] = "123456"; authMessageProcessor->authResponseContext_->groupId = - SafeyDump(jsonb); + SafetyDump(jsonb); authMessageProcessor->authResponseContext_->authToken = "123456"; authMessageProcessor->authResponseContext_->networkId = "11112222"; authMessageProcessor->authResponseContext_->requestId = 222222; @@ -212,8 +212,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: jsona[TAG_GROUP_ID] = "123456"; jsona[TAG_GROUP_NAME] = authMessageProcessor->authResponseContext_->groupName; authMessageProcessor->CreateResponseAuthMessage(jsonObj); - std::string str1 = SafeyDump(jsona); - std::string str2 = SafeyDump(jsonObj); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -236,8 +236,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseFinishMessage_001, testing::ext jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsona[TAG_AUTH_FINISH] = authMessageProcessor->authResponseContext_->isFinish; authMessageProcessor->CreateResponseFinishMessage(jsonObj); - std::string str1 = SafeyDump(jsona); - std::string str2 = SafeyDump(jsonObj); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index cf09bffff..ea1a4a52a 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -460,7 +460,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -471,7 +471,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -483,7 +483,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -493,7 +493,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_101, testing::ext::TestSize.Level std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -504,7 +504,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_102, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->listener_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -516,7 +516,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_103, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::SUPER_SONIC; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -528,7 +528,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_104, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -559,7 +559,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -570,7 +570,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -582,7 +582,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -604,7 +604,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_101, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -616,7 +616,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_102, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -628,7 +628,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_103, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -640,7 +640,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_104, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -653,7 +653,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_105, testing::ext::TestSize.Level0) int32_t data = 300; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = data; - std::string message = SafeyDump(jsonObject); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 53c6310d4..e8bd5e2a7 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -1250,7 +1250,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_053, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_OH; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = SafeyDump(jsonObject); + std::string credentialInfo = SafetyDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); @@ -1288,7 +1288,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_054, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_MINE; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = SafeyDump(jsonObject); + std::string credentialInfo = SafetyDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); diff --git a/utils/src/kvadapter/dm_kv_info.cpp b/utils/src/kvadapter/dm_kv_info.cpp index d41c86c38..e3197f74d 100644 --- a/utils/src/kvadapter/dm_kv_info.cpp +++ b/utils/src/kvadapter/dm_kv_info.cpp @@ -28,7 +28,7 @@ void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) jsonObj[ANOY_DEVICE_ID_KEY] = kvValue.anoyDeviceId; jsonObj[SALT_KEY] = kvValue.salt; jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; - result = SafeyDump(jsonObj); + result = SafetyDump(jsonObj); } void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) -- Gitee From 32f7e5cdd05d711ede8da75356a497de9ec11780 Mon Sep 17 00:00:00 2001 From: Charlie Date: Tue, 10 Dec 2024 16:27:24 +0800 Subject: [PATCH 515/520] =?UTF-8?q?=E6=94=AF=E6=8C=81USB=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charlie --- common/include/dm_constants.h | 6 ++++++ services/service/src/discovery/discovery_manager.cpp | 5 ++++- services/service/src/softbus/softbus_listener.cpp | 5 +++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 056c80a7a..09bfd45bd 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -199,9 +199,13 @@ constexpr const char* FILTER_PARA_INCLUDE_TRUST = "FILTER_INCLUDE_TRUST"; constexpr const char* CONN_ADDR_TYPE_ID = "ID_TYPE"; constexpr const char* CONN_ADDR_TYPE_BR = "BR_TYPE"; constexpr const char* CONN_ADDR_TYPE_BLE = "BLE_TYPE"; +constexpr const char* CONN_ADDR_TYPE_USB = "USB_TYPE"; constexpr const char* CONN_ADDR_TYPE_WLAN_IP = "WLAN_IP_TYPE"; constexpr const char* CONN_ADDR_TYPE_ETH_IP = "ETH_IP_TYPE"; +// Softbus connection address type int +constexpr int32_t CONNECTION_ADDR_USB = 5; + // Parameter Key constexpr const char* PARAM_KEY_META_TYPE = "META_TYPE"; constexpr const char* PARAM_KEY_TARGET_ID = "TARGET_ID"; @@ -209,6 +213,8 @@ constexpr const char* PARAM_KEY_BR_MAC = "BR_MAC"; constexpr const char* PARAM_KEY_BLE_MAC = "BLE_MAC"; constexpr const char* PARAM_KEY_WIFI_IP = "WIFI_IP"; constexpr const char* PARAM_KEY_WIFI_PORT = "WIFI_PORT"; +constexpr const char* PARAM_KEY_USB_IP = "USB_IP"; +constexpr const char* PARAM_KEY_USB_PORT = "USB_PORT"; constexpr const char* PARAM_KEY_AUTH_TOKEN = "AUTH_TOKEN"; constexpr const char* PARAM_KEY_AUTH_TYPE = "AUTH_TYPE"; constexpr const char* PARAM_KEY_PIN_CODE = "PIN_CODE"; diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index ba78be029..3078a37ea 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -101,7 +101,10 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, std::lock_guard capLock(capabilityMapLocks_); capabilityMap_[pkgNameTemp] = std::string(dmSubInfo.capability); } - + if (discoverParam.find(PARAM_KEY_DISC_MEDIUM) != discoverParam.end()) { + int32_t medium = std::atoi((discoverParam.find(PARAM_KEY_DISC_MEDIUM)->second).c_str()); + dmSubInfo.medium = static_cast(medium); + } int32_t ret = softbusListener_->RefreshSoftbusLNN(DM_PKG_NAME, dmSubInfo, LNN_DISC_CAPABILITY); if (ret != DM_OK) { LOGE("EnableDiscoveryListener failed, softbus refresh lnn ret: %{public}d.", ret); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 12484b968..8bc8e4c9f 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -893,6 +893,11 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe std::string udidHash(ConvertBytesToUpperCaseHexString((addrInfo->info).ble.udidHash, sizeof((addrInfo->info).ble.udidHash) / sizeof(*((addrInfo->info).ble.udidHash)))); jsonObj[PARAM_KEY_BLE_UDID_HASH] = udidHash; + } else if (addrInfo->type == CONNECTION_ADDR_USB) { + std::string usbIp((addrInfo->info).ip.ip); + jsonObj[PARAM_KEY_USB_IP] = usbIp; + jsonObj[PARAM_KEY_USB_PORT] = (addrInfo->info).ip.port; + jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_USB; } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } -- Gitee From 9b3ba5696385efb1b176f6367403e76a3f1e9cff Mon Sep 17 00:00:00 2001 From: Charlie Date: Wed, 11 Dec 2024 14:14:40 +0800 Subject: [PATCH 516/520] =?UTF-8?q?=E6=94=AF=E6=8C=81USB=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charlie --- .../include/softbus/softbus_listener.h | 2 + .../service/src/softbus/softbus_listener.cpp | 47 ++++++++++--------- 2 files changed, 28 insertions(+), 21 deletions(-) diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 5e507442a..7a916e435 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -34,6 +34,7 @@ #include "inner_session.h" #include "session.h" #include "socket.h" +#include "dm_anonymous.h" namespace OHOS { namespace DistributedHardware { @@ -108,6 +109,7 @@ public: void DeleteCacheDeviceInfo(); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); + static void ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj); int32_t InitSoftPublishLNN(); private: diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 8bc8e4c9f..357a94b1c 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -23,7 +23,6 @@ #include #include "device_manager_service.h" -#include "dm_anonymous.h" #include "dm_crypto.h" #include "dm_constants.h" #include "dm_device_info.h" @@ -851,27 +850,8 @@ int32_t SoftbusListener::FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo & return DM_OK; } -void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj) { - if (FillDeviceInfo(device, dmDevice) != DM_OK) { - LOGE("FillDeviceInfo failed."); - return; - } - - dmDevice.deviceTypeId = device.devType; - dmDevice.range = device.range; - - nlohmann::json jsonObj; - std::string customData = ConvertCharArray2String(device.custData, DISC_MAX_CUST_DATA_LEN); - jsonObj[PARAM_KEY_CUSTOM_DATA] = customData; - - const ConnectionAddr *addrInfo = &(device.addr)[0]; - if (addrInfo == nullptr) { - LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); - dmDevice.extraData = jsonObj.dump(); - return; - } - jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { std::string wifiIp((addrInfo->info).ip.ip); jsonObj[PARAM_KEY_WIFI_IP] = wifiIp; @@ -901,6 +881,31 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } +} + +void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +{ + if (FillDeviceInfo(device, dmDevice) != DM_OK) { + LOGE("FillDeviceInfo failed."); + return; + } + + dmDevice.deviceTypeId = device.devType; + dmDevice.range = device.range; + + nlohmann::json jsonObj; + std::string customData = ConvertCharArray2String(device.custData, DISC_MAX_CUST_DATA_LEN); + jsonObj[PARAM_KEY_CUSTOM_DATA] = customData; + + const ConnectionAddr *addrInfo = &(device.addr)[0]; + if (addrInfo == nullptr) { + LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); + dmDevice.extraData = jsonObj.dump(); + return; + } + jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; + + ParseConnAddrInfo(addrInfo, jsonObj); dmDevice.extraData = jsonObj.dump(); } -- Gitee From bdf7f27c09f59e0cf81c19838906c353f6f5345f Mon Sep 17 00:00:00 2001 From: Charlie Date: Wed, 11 Dec 2024 14:14:40 +0800 Subject: [PATCH 517/520] =?UTF-8?q?=E6=94=AF=E6=8C=81USB=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charlie --- common/include/dm_anonymous.h | 1 + common/src/dm_anonymous.cpp | 8 +++- .../native_cpp/src/device_manager_impl.cpp | 4 +- .../kits/js/src/native_devicemanager_js.cpp | 4 +- interfaces/kits/js4.0/src/dm_native_util.cpp | 4 +- .../ability/standard/dm_dialog_manager.cpp | 2 +- .../authentication/auth_message_processor.cpp | 8 ++-- .../authentication/auth_ui_state_manager.cpp | 3 +- .../src/authentication/dm_auth_manager.cpp | 22 ++++----- .../src/credential/dm_credential_manager.cpp | 4 +- .../hichain/hichain_auth_connector.cpp | 16 +++---- .../dependency/hichain/hichain_connector.cpp | 37 +++++++------- .../hichain/mine_hichain_connector.cpp | 5 +- .../dependency/softbus/softbus_connector.cpp | 8 ++-- .../include/softbus/softbus_listener.h | 2 + .../service/src/device_manager_service.cpp | 6 ++- services/service/src/pinholder/pin_holder.cpp | 28 +++++------ .../service/src/softbus/softbus_listener.cpp | 48 ++++++++++--------- .../hichain_connector_fuzzer.cpp | 7 +-- .../UTTest_discovery_filter.cpp | 30 ++++++------ .../UTTest_dm_auth_manager_first.cpp | 13 ++--- .../UTTest_dm_auth_manager_second.cpp | 19 ++++---- .../UTTest_dm_auth_manager_third.cpp | 17 +++---- .../UTTest_dm_credential_manager.cpp | 16 +++---- .../UTTest_dm_discovery_filter.cpp | 30 ++++++------ .../UTTest_hichain_auth_connector.cpp | 15 +++--- .../UTTest_hichain_connector.cpp | 10 ++-- .../UTTest_mine_hichain_connector.cpp | 9 ++-- test/commonunittest/UTTest_pin_auth.cpp | 7 +-- .../UTTest_mine_softbus_listener.cpp | 10 ++-- .../UTTest_softbus_session.cpp | 2 +- .../UTTest_auth_message_processor.cpp | 20 ++++---- test/unittest/UTTest_dm_pin_holder.cpp | 31 ++++++------ .../UTTest_ipc_cmd_parser_service.cpp | 5 +- utils/src/kvadapter/dm_kv_info.cpp | 2 +- 35 files changed, 241 insertions(+), 212 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index f9a7356f6..8c9787dd1 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -101,6 +101,7 @@ bool IsIdLengthValid(const std::string &inputID); bool IsMessageLengthValid(const std::string &inputMessage); bool IsValueExist(const std::multimap unorderedmap, const std::string &udid, int32_t userId); bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent); +std::string SafetyDump(const nlohmann::json &jsonObj); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index a421a8a74..f23e723d2 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -184,7 +184,7 @@ std::string ConvertMapToJsonString(const std::map &par for (const auto &it : paramMap) { jsonObj[it.first] = it.second; } - jsonStr = jsonObj.dump(); + jsonStr = SafetyDump(jsonObj); } return jsonStr; } @@ -365,5 +365,11 @@ bool IsDmCommonNotifyEventValid(DmCommonNotifyEvent dmCommonNotifyEvent) } return false; } + +std::string SafetyDump(const nlohmann::json &jsonObj) +{ + int indent = -1; + return jsonObj.dump(indent, ' ', false, nlohmann::detail::error_handler_t::ignore); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 05d7234d3..a799d988f 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -674,7 +674,7 @@ int32_t DeviceManagerImpl::AuthenticateDevice(const std::string &pkgName, int32_ std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetExtra(extraJson.dump()); + req->SetExtra(SafetyDump(extraJson)); req->SetAuthType(authType); req->SetDeviceInfo(deviceInfo); int32_t ret = ipcClientProxy_->SendRequest(AUTHENTICATE_DEVICE, req, rsp); @@ -1493,7 +1493,7 @@ int32_t DeviceManagerImpl::BindDevice(const std::string &pkgName, int32_t bindTy std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); req->SetPkgName(pkgName); - req->SetBindParam(paramJson.dump()); + req->SetBindParam(SafetyDump(paramJson)); req->SetBindType(bindType); req->SetDeviceId(deviceId); int32_t ret = ipcClientProxy_->SendRequest(BIND_DEVICE, req, rsp); diff --git a/interfaces/kits/js/src/native_devicemanager_js.cpp b/interfaces/kits/js/src/native_devicemanager_js.cpp index 1307a8092..410ae5b50 100644 --- a/interfaces/kits/js/src/native_devicemanager_js.cpp +++ b/interfaces/kits/js/src/native_devicemanager_js.cpp @@ -1203,7 +1203,7 @@ void DeviceManagerNapi::JsToDmExtra(const napi_env &env, const napi_value &objec jsonObj[CUSTOM_DESCRIPTION] = customDescriptionStr; jsonObj[BIND_LEVEL] = bindLevel; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(); + extra = SafetyDump(jsonObj); LOGI("appOperationLen %{public}zu, customDescriptionLen %{public}zu", appOperationStr.size(), customDescriptionStr.size()); } @@ -1274,7 +1274,7 @@ void DeviceManagerNapi::JsToDmAuthInfo(const napi_env &env, const napi_value &ob jsonObj[AUTH_TYPE] = authType; jsonObj[PIN_TOKEN] = token; JsToJsonObject(env, object, "extraInfo", jsonObj); - extra = jsonObj.dump(); + extra = SafetyDump(jsonObj); } void DeviceManagerNapi::JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::string &extra) diff --git a/interfaces/kits/js4.0/src/dm_native_util.cpp b/interfaces/kits/js4.0/src/dm_native_util.cpp index f1fa3f787..a3b0eb5c8 100644 --- a/interfaces/kits/js4.0/src/dm_native_util.cpp +++ b/interfaces/kits/js4.0/src/dm_native_util.cpp @@ -331,7 +331,7 @@ void JsToBindParam(const napi_env &env, const napi_value &object, std::string &b jsonObj[PARAM_KEY_WIFI_IP] = std::string(wifiIP); jsonObj[PARAM_KEY_WIFI_PORT] = wifiPort; jsonObj[BIND_LEVEL] = bindLevel; - bindParam = jsonObj.dump(); + bindParam = SafetyDump(jsonObj); } bool IsSystemApp() @@ -396,7 +396,7 @@ void JsToDmDiscoveryExtra(const napi_env &env, const napi_value &object, std::st if (deviceType != DM_NAPI_DISCOVER_EXTRA_INIT_ONE) { jsonObj["deviceType"] = deviceType; } - extra = jsonObj.dump(); + extra = SafetyDump(jsonObj); LOGI("JsToDmDiscoveryExtra, extra :%{public}s", extra.c_str()); } diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 7b6912134..28cbb121f 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -202,7 +202,7 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = param.dump(); + std::string paramStr = SafetyDump(param); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 26ab14c88..e7a2cb902 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -87,7 +87,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() jsonObj[TAG_SLICE_NUM] = thumbnailSlice + 1; jsonObj[TAG_THUMBNAIL_SIZE] = thumbnailSize; GetJsonObj(jsonObj); - jsonStrVec.push_back(jsonObj.dump()); + jsonStrVec.push_back(SafetyDump(jsonObj)); for (int32_t idx = 0; idx < thumbnailSlice; idx++) { nlohmann::json jsonThumbnailObj; jsonThumbnailObj[TAG_VER] = DM_ITF_VER; @@ -101,7 +101,7 @@ std::vector AuthMessageProcessor::CreateAuthRequestMessage() LOGI("TAG_APP_THUMBNAIL encode, idx %{public}d, sliceLen %{public}d, thumbnailSize %{public}d", idx, (uint32_t)sliceLen, thumbnailSize); jsonObj[TAG_APP_THUMBNAIL] = authRequestContext_->appThumbnail.substr(idx * MSG_MAX_SIZE, sliceLen); - jsonStrVec.push_back(jsonThumbnailObj.dump()); + jsonStrVec.push_back(SafetyDump(jsonThumbnailObj)); } return jsonStrVec; } @@ -138,7 +138,7 @@ std::string AuthMessageProcessor::CreateSimpleMessage(int32_t msgType) default: break; } - return jsonObj.dump(); + return SafetyDump(jsonObj); } void AuthMessageProcessor::CreatePublicKeyMessageExt(nlohmann::json &json) @@ -593,7 +593,7 @@ std::string AuthMessageProcessor::CreateDeviceAuthMessage(int32_t msgType, const std::string authDataStr = std::string(reinterpret_cast(data), dataLen); jsonObj[TAG_DATA] = authDataStr; jsonObj[TAG_DATA_LEN] = dataLen; - return jsonObj.dump(); + return SafetyDump(jsonObj); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index d338980d7..ed9e95d7a 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -14,6 +14,7 @@ */ #include "auth_ui_state_manager.h" +#include "dm_anonymous.h" #include "dm_log.h" #include "nlohmann/json.hpp" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -61,7 +62,7 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) } nlohmann::json jsonObj; jsonObj[UI_STATE_MSG] = msg; - std::string paramJson = jsonObj.dump(); + std::string paramJson = SafetyDump(jsonObj); std::lock_guard lock(pkgSetMutex_); for (auto item : pkgSet_) { listener_->OnUiCall(item, paramJson); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index effda0a0d..a7772eb63 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -609,7 +609,7 @@ void DmAuthManager::OnGroupCreated(int64_t requestId, const std::string &groupId jsonObj[PIN_TOKEN] = authResponseContext_->token; jsonObj[QR_CODE_KEY] = GenerateGroupName(); jsonObj[NFC_CODE_KEY] = GenerateGroupName(); - authResponseContext_->authToken = jsonObj.dump(); + authResponseContext_->authToken = SafetyDump(jsonObj); LOGI("DmAuthManager::OnGroupCreated start group id %{public}s", GetAnonyString(groupId).c_str()); authResponseContext_->groupId = groupId; authResponseContext_->code = pinCode; @@ -1176,7 +1176,7 @@ int32_t DmAuthManager::AddMember(int32_t pinCode) jsonObject[PIN_CODE_KEY] = pinCode; jsonObject[TAG_REQUEST_ID] = authResponseContext_->requestId; jsonObject[TAG_DEVICE_ID] = authResponseContext_->deviceId; - std::string connectInfo = jsonObject.dump(); + std::string connectInfo = SafetyDump(jsonObject); if (timer_ != nullptr) { timer_->StartTimer(std::string(ADD_TIMEOUT_TASK), GetTaskTimeout(ADD_TIMEOUT_TASK, ADD_TIMEOUT), [this] (std::string name) { @@ -1441,7 +1441,7 @@ void DmAuthManager::ShowConfigDialog() jsonObj[TAG_LOCAL_DEVICE_TYPE] = authResponseContext_->deviceTypeId; jsonObj[TAG_REQUESTER] = authResponseContext_->deviceName; jsonObj[TAG_HOST_PKGLABEL] = authResponseContext_->hostPkgLabel; - const std::string params = jsonObj.dump(); + const std::string params = SafetyDump(jsonObj); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); @@ -1478,7 +1478,7 @@ void DmAuthManager::ShowAuthInfoDialog() } nlohmann::json jsonObj; jsonObj[PIN_CODE_KEY] = authResponseContext_->code; - std::string authParam = jsonObj.dump(); + std::string authParam = SafetyDump(jsonObj); DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); } @@ -1650,7 +1650,7 @@ bool DmAuthManager::IsIdenticalAccount() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1690,7 +1690,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = GROUP_TYPE_IDENTICAL_ACCOUNT_GROUP; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -1705,7 +1705,7 @@ std::string DmAuthManager::GetAccountGroupIdHash() for (auto &groupInfo : groupList) { jsonAccountObj.push_back(Crypto::GetGroupIdHash(groupInfo.groupId)); } - return jsonAccountObj.dump(); + return SafetyDump(jsonAccountObj); } int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) @@ -1893,7 +1893,7 @@ std::string DmAuthManager::GenerateBindResultContent() Crypto::GetUdidHash(remoteDeviceId_, reinterpret_cast(deviceIdHash)); jsonObj[TAG_DEVICE_ID] = deviceIdHash; } - std::string content = jsonObj.dump(); + std::string content = SafetyDump(jsonObj); return content; } @@ -2243,7 +2243,7 @@ void DmAuthManager::ProcRespNegotiate(const int32_t &sessionId) } } jsonObject[TAG_CRYPTO_SUPPORT] = false; - message = jsonObject.dump(); + message = SafetyDump(jsonObject); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2254,7 +2254,7 @@ void DmAuthManager::ProcIncompatible(const int32_t &sessionId) respNegotiateMsg[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; respNegotiateMsg[TAG_VER] = DM_ITF_VER; respNegotiateMsg[TAG_MSG_TYPE] = MSG_TYPE_RESP_NEGOTIATE; - std::string message = respNegotiateMsg.dump(); + std::string message = SafetyDump(respNegotiateMsg); softbusConnector_->GetSoftbusSession()->SendData(sessionId, message); } @@ -2380,7 +2380,7 @@ void DmAuthManager::HandleSessionHeartbeat(std::string name) LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); nlohmann::json jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); softbusConnector_->GetSoftbusSession()->SendHeartbeatData(authResponseContext_->sessionId, message); if (authRequestState_ != nullptr) { diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 274de3be8..ec374658e 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -113,7 +113,7 @@ int32_t DmCredentialManager::RequestCredential(const std::string &reqJsonStr, st jsonObj[FIELD_CREDENTIAL_VERSION] = credentialVersion; jsonObj[FIELD_USER_ID] = userId; jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string tmpStr = jsonObj.dump(); + std::string tmpStr = SafetyDump(jsonObj); return hiChainConnector_->getRegisterInfo(tmpStr.c_str(), returnJsonStr); } @@ -364,7 +364,7 @@ void from_json(const nlohmann::json &jsonObject, CredentialDataInfo &credentialD } if (IsString(jsonObject, FIELD_PKINFO)) { nlohmann::json jsonPkInfo = jsonObject[FIELD_PKINFO]; - credentialDataInfo.pkInfo = jsonPkInfo.dump(); + credentialDataInfo.pkInfo = SafetyDump(jsonPkInfo); } } else if (credentialDataInfo.credentialType == SYMMETRY_CREDENTIAL_TYPE) { if (IsString(jsonObject, FIELD_AUTH_CODE)) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 427b94a36..f0614dcf2 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -56,7 +56,7 @@ int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, s authParamJson["osAccountId"] = osAccountId; authParamJson["pinCode"] = std::to_string(pinCode); authParamJson["acquireType"] = AcquireType::P2P_BIND; - std::string authParam = authParamJson.dump(); + std::string authParam = SafetyDump(authParamJson); LOGI("StartAuthDevice authParam %{public}s ,requestId %{public}" PRId64, GetAnonyString(authParam).c_str(), requestId); int32_t ret = StartAuthDevice(requestId, authParam.c_str(), &deviceAuthCallback_); @@ -73,7 +73,7 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut nlohmann::json jsonAuthParam; jsonAuthParam["osAccountId"] = osAccountId; jsonAuthParam["data"] = authData; - int32_t ret = ProcessAuthDevice(requestId, jsonAuthParam.dump().c_str(), &deviceAuthCallback_); + int32_t ret = ProcessAuthDevice(requestId, SafetyDump(jsonAuthParam).c_str(), &deviceAuthCallback_); if (ret != HC_SUCCESS) { LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; @@ -111,7 +111,7 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -159,7 +159,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_CREATE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain generate credential failed."); @@ -192,7 +192,7 @@ bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAcc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -223,7 +223,7 @@ int32_t HiChainAuthConnector::GetCredential(std::string &localUdid, int32_t osAc jsonObj["deviceId"] = localUdid; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["flag"] = 1; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_QUERY, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -255,7 +255,7 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["publicKey"] = publicKey; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_IMPORT, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); @@ -286,7 +286,7 @@ int32_t HiChainAuthConnector::DeleteCredential(const std::string &deviceId, int3 jsonObj["deviceId"] = deviceId; jsonObj["acquireType"] = AcquireType::P2P_BIND; jsonObj["osAccountId"] = userId; - std::string requestParam = jsonObj.dump(); + std::string requestParam = SafetyDump(jsonObj); char *returnData = nullptr; if (ProcessCredential(CRED_OP_DELETE, requestParam.c_str(), &returnData) != HC_SUCCESS) { LOGE("Hichain query credential failed."); diff --git a/services/implementation/src/dependency/hichain/hichain_connector.cpp b/services/implementation/src/dependency/hichain/hichain_connector.cpp index 7a00f3859..c1b4f837b 100644 --- a/services/implementation/src/dependency/hichain/hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_connector.cpp @@ -154,7 +154,7 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, const std::string &grou LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); + int32_t ret = deviceGroupManager_->createGroup(userId, requestId, DM_PKG_NAME, SafetyDump(jsonObj).c_str()); struct RadarInfo info = { .funcName = "CreateGroup", .toCallPkg = HICHAINNAME, @@ -178,7 +178,7 @@ bool HiChainConnector::IsGroupCreated(std::string groupName, GroupInfo &groupInf { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_NAME] = groupName.c_str(); - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); std::vector groupList; if (GetGroupInfo(queryParams, groupList)) { groupInfo = groupList[0]; @@ -191,7 +191,7 @@ bool HiChainConnector::IsRedundanceGroup(const std::string &userId, int32_t auth { nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -343,7 +343,7 @@ int32_t HiChainConnector::AddMember(const std::string &deviceId, const std::stri jsonObj[FIELD_DEVICE_ID] = localDeviceId; jsonObj[FIELD_GROUP_NAME] = jsonObject[TAG_GROUP_NAME].get(); jsonObj[FIELD_CONNECT_PARAMS] = connectInfomation.c_str(); - std::string tmpStr = jsonObj.dump(); + std::string tmpStr = SafetyDump(jsonObj); int64_t requestId = jsonObject[TAG_REQUEST_ID].get(); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { @@ -486,7 +486,7 @@ char *HiChainConnector::onRequest(int64_t requestId, int operationCode, const ch GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); jsonObj[FIELD_DEVICE_ID] = localDeviceId; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; } @@ -511,7 +511,7 @@ std::string HiChainConnector::GetConnectPara(std::string deviceId, std::string r } jsonObject[DEVICE_ID] = reqDeviceId; - return jsonObject.dump(); + return SafetyDump(jsonObject); } int32_t HiChainConnector::GetRelatedGroups(const std::string &deviceId, std::vector &groupList) @@ -602,7 +602,7 @@ int32_t HiChainConnector::DelMemberFromGroup(const std::string &groupId, const s nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_DELETE_ID] = deviceId; - std::string deleteParams = jsonObj.dump(); + std::string deleteParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -621,7 +621,7 @@ int32_t HiChainConnector::DeleteGroup(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -641,7 +641,7 @@ int32_t HiChainConnector::DeleteGroupExt(std::string &groupId) int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = SafetyDump(jsonObj); int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); if (userId < 0) { LOGE("get current process account user id failed"); @@ -661,7 +661,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use networkStyle_ = CREDENTIAL_NETWORK; nlohmann::json jsonObj; jsonObj[FIELD_GROUP_TYPE] = authType; - std::string queryParams = jsonObj.dump(); + std::string queryParams = SafetyDump(jsonObj); std::vector groupList; if (!GetGroupInfo(queryParams, groupList)) { LOGE("failed to get device join groups"); @@ -682,7 +682,7 @@ int32_t HiChainConnector::DeleteGroup(int64_t requestId_, const std::string &use return ERR_DM_FAILED; } jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = SafetyDump(jsonObj); g_deleteGroupFlag = false; int32_t osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { @@ -791,7 +791,8 @@ int32_t HiChainConnector::CreateGroup(int64_t requestId, int32_t authType, const LOGE("get current process account user id failed"); return ERR_DM_FAILED; } - int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, jsonObj.dump().c_str()); + int32_t ret = deviceGroupManager_->createGroup(osAccountUserId, requestId, DM_PKG_NAME, + SafetyDump(jsonObj).c_str()); if (ret != DM_OK) { LOGE("[HICHAIN]fail to create group with ret:%{public}d, requestId:%{public}" PRId64, ret, requestId); return ERR_DM_CREATE_GROUP_FAILED; @@ -841,7 +842,7 @@ int32_t HiChainConnector::GetGroupId(const std::string &userId, const int32_t gr { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(); + std::string queryParams = SafetyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -874,7 +875,7 @@ int32_t HiChainConnector::ParseRemoteCredential(const int32_t groupType, const s jsonObj[FIELD_GROUP_ID] = groupId; jsonObj[FIELD_GROUP_TYPE] = groupType; jsonObj[FIELD_DEVICE_LIST] = jsonDeviceList[FIELD_DEVICE_LIST]; - params = jsonObj.dump(); + params = SafetyDump(jsonObj); osAccountUserId = MultipleUserConnector::GetCurrentAccountUserID(); if (osAccountUserId < 0) { LOGE("get current process account user id failed"); @@ -928,7 +929,7 @@ int32_t HiChainConnector::GetGroupIdExt(const std::string &userId, const int32_t { nlohmann::json jsonObjGroup; jsonObjGroup[FIELD_GROUP_TYPE] = groupType; - std::string queryParams = jsonObjGroup.dump(); + std::string queryParams = SafetyDump(jsonObjGroup); std::vector groupList; if (!GetGroupInfo(queryParams.c_str(), groupList)) { @@ -982,7 +983,7 @@ int32_t HiChainConnector::ParseRemoteCredentialExt(const std::string &credential return ERR_DM_FAILED; } jsonObj[FIELD_DEVICE_LIST] = jsonObject[FIELD_DEVICE_LIST]; - params = jsonObj.dump(); + params = SafetyDump(jsonObj); return DM_OK; } @@ -1157,7 +1158,7 @@ int32_t HiChainConnector::DeleteGroup(const int32_t userId, std::string &groupId int64_t requestId = GenRequestId(); nlohmann::json jsonObj; jsonObj[FIELD_GROUP_ID] = groupId; - std::string disbandParams = jsonObj.dump(); + std::string disbandParams = SafetyDump(jsonObj); int32_t ret = deviceGroupManager_->deleteGroup(userId, requestId, DM_PKG_NAME, disbandParams.c_str()); if (ret != 0) { LOGE("[HICHAIN]fail to delete group with ret:%{public}d.", ret); @@ -1247,7 +1248,7 @@ int32_t HiChainConnector::DeleteGroupByACL(std::vector groupList; if (!GetGroupInfo(userId, queryParams, groupList)) { diff --git a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp index c5d37fd50..a4df42a1a 100644 --- a/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp +++ b/services/implementation/src/dependency/hichain/mine_hichain_connector.cpp @@ -22,6 +22,7 @@ #include "device_auth.h" #include "device_auth_defines.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "nlohmann/json.hpp" @@ -135,7 +136,7 @@ int32_t MineHiChainConnector::DeleteCredentialAndGroup(void) { nlohmann::json jsonObj; jsonObj[FIELD_IS_DELETE_ALL] = true; - std::string params = jsonObj.dump(); + std::string params = SafetyDump(jsonObj); #if (defined(MINE_HARMONY)) char *returnInfo = nullptr; int32_t retValue = g_deviceGroupManager->processCredential(DELETE_SELF_CREDENTIAL, params.c_str(), &returnInfo); @@ -173,7 +174,7 @@ int32_t MineHiChainConnector::CreateGroup(const std::string &reqJsonStr) jsonObj[FIELD_GROUP_NAME] = DEVICE_MANAGER_GROUPNAME; jsonObj[FIELD_DEVICE_ID] = std::string(deviceUdid); jsonObj[FIELD_GROUP_TYPE] = IDENTICAL_ACCOUNT_GROUP; - std::string createParams = jsonObj.dump(); + std::string createParams = SafetyDump(jsonObj); retValue = g_deviceGroupManager->createGroup(DEFAULT_OS_ACCOUNT, requestId, DM_PKG_NAME, createParams.c_str()); if (retValue != HC_SUCCESS) { LOGE("failed to create group with ret:%{public}d.", retValue); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 560959b0d..9e5770cf4 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -342,7 +342,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); @@ -350,20 +350,20 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { jsonPara[BLE_MAC] = addr->info.ble.bleMac; - connectAddr = jsonPara.dump(); + connectAddr = SafetyDump(jsonPara); return addr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 5e507442a..7a916e435 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -34,6 +34,7 @@ #include "inner_session.h" #include "session.h" #include "socket.h" +#include "dm_anonymous.h" namespace OHOS { namespace DistributedHardware { @@ -108,6 +109,7 @@ public: void DeleteCacheDeviceInfo(); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); + static void ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj); int32_t InitSoftPublishLNN(); private: diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 3b93b2000..82b1b3af9 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1197,7 +1197,8 @@ void DeviceManagerService::UnloadDMServiceAdapter() int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName, const std::map &discoverParam, const std::map &filterOptions) { - if (!PermissionManager::GetInstance().CheckNewPermission()) { + if (!PermissionManager::GetInstance().CheckNewPermission() && + !PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } @@ -1216,7 +1217,8 @@ int32_t DeviceManagerService::StartDiscovering(const std::string &pkgName, int32_t DeviceManagerService::StopDiscovering(const std::string &pkgName, const std::map &discoverParam) { - if (!PermissionManager::GetInstance().CheckNewPermission()) { + if (!PermissionManager::GetInstance().CheckNewPermission() && + !PermissionManager::GetInstance().CheckPermission()) { LOGE("The caller does not have permission to call"); return ERR_DM_NO_PERMISSION; } diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index d91ee920b..5463d1866 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -178,7 +178,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget jsonObj[TAG_PIN_TYPE] = pinType; jsonObj[TAG_PAYLOAD] = payload; pinType_ = pinType; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); LOGI("DestroyPinHolder, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER, pinType); ret = session_->SendData(sessionId_, message); @@ -212,7 +212,7 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() jsonObj[TAG_PAYLOAD] = payload_; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; jsonObj[TAG_DM_VERSION] = ""; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); LOGI("CreateGeneratePinHolderMsg, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER, pinType_); int32_t ret = session_->SendData(sessionId_, message); @@ -290,12 +290,12 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; - std::string content = jsonContent.dump(); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; - std::string msg = jsonObj.dump(); + std::string msg = SafetyDump(jsonObj); LOGI("ProcessCreateMsg, message type is: %{public}d.", MSG_TYPE_CREATE_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -370,13 +370,13 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); isDestroy_.store(true); } } - std::string msg = jsonObj.dump(); + std::string msg = SafetyDump(jsonObj); LOGI("ProcessDestroyMsg, message type is: %{public}d.", MSG_TYPE_DESTROY_PIN_HOLDER_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { @@ -394,13 +394,13 @@ void PinHolder::CloseSession(const std::string &name) } nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(); + std::string payload = SafetyDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); isDestroy_.store(true); } @@ -461,7 +461,7 @@ void PinHolder::OnDataReceived(int32_t sessionId, std::string message) LOGE("another session opened, close this sessionId: %{public}d.", sessionId); nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_CLOSE_SESSION; - std::string msg = jsonObj.dump(); + std::string msg = SafetyDump(jsonObj); int32_t ret = session_->SendData(sessionId, msg); if (ret != DM_OK) { LOGE("[SOFTBUS] SendBytes failed. ret: %{public}d.", ret); @@ -563,13 +563,13 @@ void PinHolder::OnSessionClosed(int32_t sessionId) isRemoteSupported_ = false; nlohmann::json jsonObj; jsonObj[DM_CONNECTION_DISCONNECTED] = true; - std::string payload = jsonObj.dump(); + std::string payload = SafetyDump(jsonObj); if (listener_ != nullptr && !isDestroy_.load()) { listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; - std::string content = jsonContent.dump(); + std::string content = SafetyDump(jsonContent); if (destroyState_ == STATE_UNKNOW) { listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); } else if (destroyState_ == STATE_REMOTE_WRONG) { @@ -629,7 +629,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = MSG_TYPE_PIN_HOLDER_CHANGE; jsonObj[TAG_PIN_TYPE] = pinType; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); LOGI("NotifyPinHolderEvent, message type is: %{public}d, pin type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE, pinType); int32_t ret = session_->SendData(sessionId_, message); @@ -666,7 +666,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; - std::string content = jsonContent.dump(); + std::string content = SafetyDump(jsonContent); listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); if (timer_ != nullptr) { timer_->DeleteAll(); @@ -677,7 +677,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) } } - std::string msg = jsonObj.dump(); + std::string msg = SafetyDump(jsonObj); LOGI("ProcessChangeMsg, message type is: %{public}d.", MSG_TYPE_PIN_HOLDER_CHANGE_RESP); int32_t ret = session_->SendData(sessionId_, msg); if (ret != DM_OK) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 8bc8e4c9f..7bc25c50a 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -23,7 +23,6 @@ #include #include "device_manager_service.h" -#include "dm_anonymous.h" #include "dm_crypto.h" #include "dm_constants.h" #include "dm_device_info.h" @@ -851,27 +850,8 @@ int32_t SoftbusListener::FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo & return DM_OK; } -void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj) { - if (FillDeviceInfo(device, dmDevice) != DM_OK) { - LOGE("FillDeviceInfo failed."); - return; - } - - dmDevice.deviceTypeId = device.devType; - dmDevice.range = device.range; - - nlohmann::json jsonObj; - std::string customData = ConvertCharArray2String(device.custData, DISC_MAX_CUST_DATA_LEN); - jsonObj[PARAM_KEY_CUSTOM_DATA] = customData; - - const ConnectionAddr *addrInfo = &(device.addr)[0]; - if (addrInfo == nullptr) { - LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); - dmDevice.extraData = jsonObj.dump(); - return; - } - jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { std::string wifiIp((addrInfo->info).ip.ip); jsonObj[PARAM_KEY_WIFI_IP] = wifiIp; @@ -901,7 +881,31 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe } else { LOGI("Unknown connection address type: %{public}d.", addrInfo->type); } - dmDevice.extraData = jsonObj.dump(); +} + +void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) +{ + if (FillDeviceInfo(device, dmDevice) != DM_OK) { + LOGE("FillDeviceInfo failed."); + return; + } + + dmDevice.deviceTypeId = device.devType; + dmDevice.range = device.range; + + nlohmann::json jsonObj; + std::string customData = ConvertCharArray2String(device.custData, DISC_MAX_CUST_DATA_LEN); + jsonObj[PARAM_KEY_CUSTOM_DATA] = customData; + + const ConnectionAddr *addrInfo = &(device.addr)[0]; + if (addrInfo == nullptr) { + LOGE("ConvertDeviceInfoToDmDevice: addrInfo is nullptr."); + dmDevice.extraData = SafetyDump(jsonObj); + return; + } + jsonObj[PARAM_KEY_DISC_CAPABILITY] = device.capabilityBitmap[0]; + ParseConnAddrInfo(addrInfo, jsonObj); + dmDevice.extraData = SafetyDump(jsonObj); } int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) diff --git a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp index dce86d574..19c2f68e2 100644 --- a/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp +++ b/test/commonfuzztest/hichainconnector_fuzzer/hichain_connector_fuzzer.cpp @@ -20,6 +20,7 @@ #include #include "device_manager_service_listener.h" +#include "dm_anonymous.h" #include "dm_auth_manager.h" #include "hichain_connector.h" @@ -315,13 +316,13 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObj[key] = 1; jsonObj["deviceName"] = "devieName1"; hichainConnector->GetJsonInt(jsonObj, "devieName"); - hichainConnector->AddMember(deviceId, jsonObj.dump()); + hichainConnector->AddMember(deviceId, SafetyDump(jsonObj)); jsonObj[TAG_DEVICE_ID] = "deviceId_001"; jsonObj[PIN_CODE_KEY] = 1; jsonObj[TAG_GROUP_ID] = "groupId"; jsonObj[TAG_REQUEST_ID] = 1; jsonObj[TAG_GROUP_NAME] = "groupName"; - hichainConnector->AddMember(deviceId, jsonObj.dump()); + hichainConnector->AddMember(deviceId, SafetyDump(jsonObj)); nlohmann::json jsonObjCre; std::string params; @@ -331,7 +332,7 @@ void HiChainConnectorSixthFuzzTest(const uint8_t* data, size_t size) jsonObjCre[FIELD_OPERATION_CODE] = 1; jsonObjCre[FIELD_META_NODE_TYPE] = "metaNode_002"; jsonObjCre[FIELD_DEVICE_LIST] = "deviceList"; - std::string credentialInfo = jsonObjCre.dump(); + std::string credentialInfo = SafetyDump(jsonObjCre); hichainConnector->ParseRemoteCredentialExt(credentialInfo, params, groupOwner); int32_t groupType = *(reinterpret_cast(data)); nlohmann::json jsonDeviceList; diff --git a/test/commonunittest/UTTest_discovery_filter.cpp b/test/commonunittest/UTTest_discovery_filter.cpp index 092d38f22..1122727bb 100644 --- a/test/commonunittest/UTTest_discovery_filter.cpp +++ b/test/commonunittest/UTTest_discovery_filter.cpp @@ -45,7 +45,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Level0 { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -55,7 +55,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Level0 DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -66,7 +66,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Level0 nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -77,7 +77,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Level0 nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -89,7 +89,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -101,7 +101,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Level0 int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -116,7 +116,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -132,7 +132,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Level0 myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -148,7 +148,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Level myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -165,7 +165,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSize. { DeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -175,7 +175,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSize. DeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -186,7 +186,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -198,7 +198,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSize. jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -211,7 +211,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -224,7 +224,7 @@ HWTEST_F(DiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSize. jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index d784fa4a7..a219f1a5e 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -19,6 +19,7 @@ #include "common_event_support.h" #include "device_manager_service_listener.h" #include "dm_auth_manager.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "dm_radar_helper.h" @@ -1075,7 +1076,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived002, testing::ext::TestSize. int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_DATA] = 123; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1086,7 +1087,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived003, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = "123"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1098,7 +1099,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived004, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = "123"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1110,7 +1111,7 @@ HWTEST_F(DmAuthManagerTest, OnAuthDeviceDataReceived005, testing::ext::TestSize. jsonObject[TAG_DATA] = "123"; jsonObject[TAG_DATA_LEN] = 123; jsonObject[TAG_MSG_TYPE] = 123; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnAuthDeviceDataReceived(sessionId, message); ASSERT_EQ(authManager_->isAuthDevice_, false); } @@ -1335,7 +1336,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize int32_t ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, DM_OK); - extra = jsonObject.dump(); + extra = SafetyDump(jsonObject); EXPECT_CALL(*appManagerMock_, IsSystemSA()).WillOnce(Return(false)); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1345,7 +1346,7 @@ HWTEST_F(DmAuthManagerTest, CheckAuthParamVaildExtra_001, testing::ext::TestSize EXPECT_EQ(ret, DM_OK); jsonObject["bindLevel"] = 15; - extra = jsonObject.dump(); + extra = SafetyDump(jsonObject); ret = authManager_->CheckAuthParamVaildExtra(extra); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_second.cpp b/test/commonunittest/UTTest_dm_auth_manager_second.cpp index 9561e1df7..6263dd703 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_second.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_second.cpp @@ -18,6 +18,7 @@ #include "auth_message_processor.h" #include "device_manager_service_listener.h" #include "dm_auth_manager.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_dialog_manager.h" @@ -108,7 +109,7 @@ HWTEST_F(DmAuthManagerTest, OnDataReceived_007, testing::ext::TestSize.Level0) int32_t sessionId = 0; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = 200; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); authManager_->OnDataReceived(sessionId, message); authManager_->authRequestState_ = nullptr; authManager_->authResponseState_ = nullptr; @@ -1322,7 +1323,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; jsonObject["targetPkgName"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1335,7 +1336,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_003, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1349,7 +1350,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_004, testing::ext::TestSize.Level0) jsonObject["targetPkgName"] = "1234"; jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1364,7 +1365,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_005, testing::ext::TestSize.Level0) jsonObject["appOperation"] = "1234"; jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1380,7 +1381,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_006, testing::ext::TestSize.Level0) jsonObject["customDescription"] = "1234"; jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = "1234"; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1397,7 +1398,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_007, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = "1234"; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1414,7 +1415,7 @@ HWTEST_F(DmAuthManagerTest, GetAuthParam_008, testing::ext::TestSize.Level0) jsonObject["appThumbnail"] = "1234"; jsonObject["tokenId"] = 1234; jsonObject["bindLevel"] = 1234; - std::string extra = jsonObject.dump(); + std::string extra = SafetyDump(jsonObject); int32_t authType = 5; std::string pkgName = "ohos_test"; std::string deviceId = "512156"; @@ -1508,7 +1509,7 @@ HWTEST_F(DmAuthManagerTest, IsIdenticalAccount_201, testing::ext::TestSize.Level nlohmann::json jsonPeerGroupIdObj; jsonPeerGroupIdObj["groupId"] = "123456"; - authManager_->authResponseContext_->accountGroupIdHash = jsonPeerGroupIdObj.dump(); + authManager_->authResponseContext_->accountGroupIdHash = SafetyDump(jsonPeerGroupIdObj); EXPECT_CALL(*multipleUserConnectorMock_, GetCurrentAccountUserID()).WillOnce(Return(0)); EXPECT_CALL(*hiChainConnectorMock_, GetGroupInfo(_, _, _)).WillOnce(Return(true)); ret = authManager_->IsIdenticalAccount(); diff --git a/test/commonunittest/UTTest_dm_auth_manager_third.cpp b/test/commonunittest/UTTest_dm_auth_manager_third.cpp index e760738ff..d4c1150f5 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_third.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_third.cpp @@ -19,6 +19,7 @@ #include "device_manager_service_listener.h" #include "deviceprofile_connector.h" #include "dm_auth_manager.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_dialog_manager.h" #include "dm_log.h" @@ -141,13 +142,13 @@ void DmAuthManagerTest::TearDownTestCase() {} HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); int32_t sessionId = 0; authManager_->remoteDeviceId_ = "ProcRespNegotiate001"; authManager_->ProcRespNegotiate(sessionId); jsonObject[TAG_CRYPTO_SUPPORT] = false; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseContext_->authType = AUTH_TYPE_CRE; @@ -156,7 +157,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseContext_ = std::make_shared(); authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = ""; authManager_->authResponseContext_->authType = AUTH_TYPE_IMPORT_AUTH_CODE; @@ -164,7 +165,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->ProcRespNegotiate(sessionId); authManager_->authResponseState_->context_ = std::make_shared(); - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -174,7 +175,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_NAME] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = true; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); @@ -187,13 +188,13 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate001, testing::ext::TestSize.Level0) HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) { nlohmann::json jsonObject; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); int32_t sessionId = 0; authManager_->authResponseState_->context_ = std::make_shared(); jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->remoteDeviceId_ = "ProcRespNegotiate002"; authManager_->importAuthCode_ = "test"; @@ -207,7 +208,7 @@ HWTEST_F(DmAuthManagerTest, ProcRespNegotiate002, testing::ext::TestSize.Level0) jsonObject[TAG_CRYPTO_SUPPORT] = true; jsonObject[TAG_CRYPTO_NAME] = "test"; jsonObject[TAG_CRYPTO_VERSION] = "test"; - g_createSimpleMessageReturnDataStr = jsonObject.dump(); + g_createSimpleMessageReturnDataStr = SafetyDump(jsonObject); g_isIdenticalAccountReturnBoolValue = false; authManager_->importAuthCode_ = "test"; authManager_->authResponseContext_ = std::make_shared(); diff --git a/test/commonunittest/UTTest_dm_credential_manager.cpp b/test/commonunittest/UTTest_dm_credential_manager.cpp index 02e813563..c2da8eabb 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.cpp +++ b/test/commonunittest/UTTest_dm_credential_manager.cpp @@ -181,7 +181,7 @@ HWTEST_F(DmCredentialManagerTest, RequestCredential_001, testing::ext::TestSize. nlohmann::json jsonObject; jsonObject["userId"] = "test"; jsonObject["version"] = "test"; - reqJsonStr = jsonObject.dump(); + reqJsonStr = SafetyDump(jsonObject); ret = dmCreMgr_->RequestCredential(reqJsonStr, returnJsonStr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -279,22 +279,22 @@ HWTEST_F(DmCredentialManagerTest, ImportCredential_001, testing::ext::TestSize.L nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); jsonObject["TType"] = 1; jsonObject["processType"] = 1; - credentialInfo = jsonObject.dump(); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = -1; - credentialInfo = jsonObject.dump(); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["processType"] = 2; - credentialInfo = jsonObject.dump(); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject["TType"] = "test"; - credentialInfo = jsonObject.dump(); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportCredential(pkgName, credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -717,13 +717,13 @@ HWTEST_F(DmCredentialManagerTest, ImportRemoteCredential_001, testing::ext::Test jsonObject[FIELD_USER_ID] = 0; jsonObject[FIELD_PEER_USER_ID] = "peerUserId"; - std::string credentialInfo = jsonObject.dump(); + std::string credentialInfo = SafetyDump(jsonObject); dmCreMgr_->hiChainConnector_->deviceGroupManager_ = nullptr; int32_t ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); jsonObject[FIELD_CREDENTIAL_DATA] = 0; - credentialInfo = jsonObject.dump(); + credentialInfo = SafetyDump(jsonObject); ret = dmCreMgr_->ImportRemoteCredential(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -1655,7 +1655,7 @@ HWTEST_F(DmCredentialManagerTest, from_json_001, testing::ext::TestSize.Level0) nlohmann::json jsonPkInfo; jsonOutObj[FIELD_SERVER_PK] = "serverPk"; jsonOutObj[FIELD_PKINFO_SIGNATURE] = "pkInfoSignature"; - jsonOutObj[FIELD_PKINFO] = jsonPkInfo.dump(); + jsonOutObj[FIELD_PKINFO] = SafetyDump(jsonPkInfo); jsonOutObj[FIELD_PEER_DEVICE_ID] = "peerDeviceId"; from_json(jsonOutObj, credentialDataInfo); EXPECT_FALSE(credentialDataInfo.serverPk.empty()); diff --git a/test/commonunittest/UTTest_dm_discovery_filter.cpp b/test/commonunittest/UTTest_dm_discovery_filter.cpp index 42e305d8f..07e3f591c 100644 --- a/test/commonunittest/UTTest_dm_discovery_filter.cpp +++ b/test/commonunittest/UTTest_dm_discovery_filter.cpp @@ -58,7 +58,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_002, testing::ext::TestSize.Leve { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -74,7 +74,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_003, testing::ext::TestSize.Leve DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject[FILTERS_KEY] = "filters"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -91,7 +91,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_004, testing::ext::TestSize.Leve nlohmann::json jsonObject; std::vector myArray; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -108,7 +108,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_005, testing::ext::TestSize.Leve nlohmann::json jsonObject; int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -126,7 +126,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_006, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = 12345; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -144,7 +144,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_007, testing::ext::TestSize.Leve int myArray[5] = {1, 2, 3, 4, 5}; jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -165,7 +165,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_008, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -187,7 +187,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_009, testing::ext::TestSize.Leve myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -209,7 +209,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterJson_0010, testing::ext::TestSize.Lev myArray.push_back(object); jsonObject[FILTERS_KEY] = myArray; jsonObject[FILTER_OP_KEY] = "filter_op"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); int32_t ret = filterOption.ParseFilterJson(str); EXPECT_EQ(ret, DM_OK); } @@ -238,7 +238,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_002, testing::ext::TestSiz { DmDeviceFilterOption filterOption; nlohmann::json jsonObject; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -254,7 +254,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_003, testing::ext::TestSiz DmDeviceFilterOption filterOption; nlohmann::json jsonObject; jsonObject["credible"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -271,7 +271,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_004, testing::ext::TestSiz nlohmann::json jsonObject; jsonObject["credible"] = 1; jsonObject["isTrusted"] = "123"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -289,7 +289,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_005, testing::ext::TestSiz jsonObject["credible"] = 1; jsonObject["isTrusted"] = 2; jsonObject["authForm"] = "3"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -308,7 +308,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_006, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = "4"; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } @@ -327,7 +327,7 @@ HWTEST_F(DmDiscoveryFilterTest, ParseFilterOptionJson_007, testing::ext::TestSiz jsonObject["isTrusted"] = 2; jsonObject["authForm"] = 3; jsonObject["deviceType"] = 4; - std::string str = jsonObject.dump(); + std::string str = SafetyDump(jsonObject); filterOption.ParseFilterOptionJson(str); EXPECT_EQ(filterOption.filterOp_ == "AND", true); } diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index 6469f5222..538aceac9 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -14,6 +14,7 @@ */ #include #include "UTTest_hichain_auth_connector.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "hichain_auth_connector.h" @@ -314,7 +315,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_002, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); int32_t osAccountId = 1245; bool ret = hiChain_->QueryCredential(localUdid, osAccountId); EXPECT_EQ(ret, false); @@ -325,7 +326,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_003, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = "{invalid_json}"; int32_t osAccountId = 1245; @@ -338,7 +339,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_004, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": "not_an_int", "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -351,7 +352,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_005, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": -1, "publicKey": "key"})"; int32_t osAccountId = 1245; @@ -364,7 +365,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_006, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": 0})"; int32_t osAccountId = 1245; @@ -377,7 +378,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_007, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 1, "publicKey": "string"})"; int32_t osAccountId = 1245; @@ -390,7 +391,7 @@ HWTEST_F(HiChainAuthConnectorTest, QueryCredential_008, testing::ext::TestSize.L nlohmann::json jsonObject; jsonObject["result"] = 15; jsonObject["publicKey"] = 0; - std::string localUdid = jsonObject.dump(); + std::string localUdid = SafetyDump(jsonObject); g_processCredentialResultCode = HC_SUCCESS; g_processCredentialReturnDataStr = R"({"result": 2, "publicKey": "string"})"; int32_t osAccountId = 1245; diff --git a/test/commonunittest/UTTest_hichain_connector.cpp b/test/commonunittest/UTTest_hichain_connector.cpp index f3176758f..1e7e7fc29 100755 --- a/test/commonunittest/UTTest_hichain_connector.cpp +++ b/test/commonunittest/UTTest_hichain_connector.cpp @@ -1200,7 +1200,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_001, testing::ext::TestS HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1219,7 +1219,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_003, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 1; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1238,7 +1238,7 @@ HWTEST_F(HichainConnectorTest, ParseRemoteCredentialExt_004, testing::ext::TestS nlohmann::json jsonObj; jsonObj["authType"] = 4; jsonObj[FIELD_USER_ID] = "156103"; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::string params; std::string groupOwner; std::shared_ptr hiChainConnector = std::make_shared(); @@ -1270,7 +1270,7 @@ HWTEST_F(HichainConnectorTest, addMultiMembersExt_001, testing::ext::TestSize.Le HWTEST_F(HichainConnectorTest, addMultiMembersExt_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string credentialInfo = jsonObj.dump(); + std::string credentialInfo = SafetyDump(jsonObj); std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->addMultiMembersExt(credentialInfo); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -1314,7 +1314,7 @@ HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_001, testing::ext::TestSize HWTEST_F(HichainConnectorTest, GetTrustedDevicesUdid_002, testing::ext::TestSize.Level0) { nlohmann::json jsonObj; - std::string jsonStr = jsonObj.dump(); + std::string jsonStr = SafetyDump(jsonObj); std::vector udidList; std::shared_ptr hiChainConnector = std::make_shared(); int32_t ret = hiChainConnector->GetTrustedDevicesUdid(jsonStr.c_str(), udidList); diff --git a/test/commonunittest/UTTest_mine_hichain_connector.cpp b/test/commonunittest/UTTest_mine_hichain_connector.cpp index 1769a1282..f7c37a746 100644 --- a/test/commonunittest/UTTest_mine_hichain_connector.cpp +++ b/test/commonunittest/UTTest_mine_hichain_connector.cpp @@ -15,6 +15,7 @@ #include "UTTest_mine_hichain_connector.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "mine_hichain_connector.h" @@ -112,7 +113,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_002, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -122,7 +123,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, CreateGroup_003, testing::ext::TestSize.L std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->CreateGroup(reqJsonStr); EXPECT_EQ(ret, ERR_DM_FAILED); } @@ -132,7 +133,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, RequestCredential_001, testing::ext::Test std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = "123456789"; - std::string returnJsonStr = jsonObject.dump(); + std::string returnJsonStr = SafetyDump(jsonObject); int32_t ret = minHiChain->RequestCredential(returnJsonStr); EXPECT_EQ(ret, DM_OK); } @@ -169,7 +170,7 @@ HWTEST_F(MiniHiChainAuthConnectorTest, ImportCredential_002, testing::ext::TestS std::shared_ptr minHiChain = std::make_shared(); nlohmann::json jsonObject; jsonObject["userId"] = 123456789; - std::string reqJsonStr = jsonObject.dump(); + std::string reqJsonStr = SafetyDump(jsonObject); std::string returnJsonStr; int32_t ret = minHiChain->ImportCredential(reqJsonStr, returnJsonStr); EXPECT_EQ(ret, ERR_DM_HICHAIN_REGISTER_CALLBACK); diff --git a/test/commonunittest/UTTest_pin_auth.cpp b/test/commonunittest/UTTest_pin_auth.cpp index febbdeaab..c9889e2b3 100644 --- a/test/commonunittest/UTTest_pin_auth.cpp +++ b/test/commonunittest/UTTest_pin_auth.cpp @@ -18,6 +18,7 @@ #include #include +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "nlohmann/json.hpp" @@ -73,7 +74,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_002, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_TOKEN] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -89,7 +90,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_003, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, nullptr); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -105,7 +106,7 @@ HWTEST_F(PinAuthTest, ShowAuthInfo_004, testing::ext::TestSize.Level0) std::shared_ptr pinAuth = std::make_shared(); nlohmann::json jsonObject; jsonObject[PIN_CODE_KEY] = 123456; - std::string authToken = jsonObject.dump(); + std::string authToken = SafetyDump(jsonObject); int32_t ret = pinAuth->ShowAuthInfo(authToken, authManager); ASSERT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/softbusunittest/UTTest_mine_softbus_listener.cpp b/test/softbusunittest/UTTest_mine_softbus_listener.cpp index 9799617a8..753c15a8b 100644 --- a/test/softbusunittest/UTTest_mine_softbus_listener.cpp +++ b/test/softbusunittest/UTTest_mine_softbus_listener.cpp @@ -67,7 +67,7 @@ HWTEST_F(MineSoftbusListenerTest, RefreshSoftbusLNN_002, testing::ext::TestSize. nlohmann::json jsonObj; jsonObj["findDeviceMode"] = 4; string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); DmSubscribeInfo dmSubscribeInfo; std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->RefreshSoftbusLNN(pkgName, searchJson, dmSubscribeInfo); @@ -145,7 +145,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_002, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(1); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -158,7 +158,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_003, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(2); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -171,7 +171,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_004, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(3); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, ERR_DM_FAILED); @@ -184,7 +184,7 @@ HWTEST_F(MineSoftbusListenerTest, ParseSearchJson_005, testing::ext::TestSize.Le nlohmann::json jsonObj; jsonObj["findDeviceMode"] = static_cast(4); string pkgName; - string searchJson = jsonObj.dump(); + string searchJson = SafetyDump(jsonObj); std::shared_ptr mineListener = std::make_shared(); int32_t ret = mineListener->ParseSearchJson(pkgName, searchJson, output, &outLen); EXPECT_EQ(ret, DM_OK); diff --git a/test/softbusunittest/UTTest_softbus_session.cpp b/test/softbusunittest/UTTest_softbus_session.cpp index 155da5f75..0bee60540 100644 --- a/test/softbusunittest/UTTest_softbus_session.cpp +++ b/test/softbusunittest/UTTest_softbus_session.cpp @@ -107,7 +107,7 @@ HWTEST_F(SoftbusSessionTest, SendData_002, testing::ext::TestSize.Level0) nlohmann::json jsonObj; jsonObj[TAG_VER] = DM_ITF_VER; jsonObj[TAG_MSG_TYPE] = msgType; - std::string message = jsonObj.dump(); + std::string message = SafetyDump(jsonObj); int32_t sessionId = 0; if (softbusSession == nullptr) { softbusSession = std::make_shared(); diff --git a/test/unittest/UTTest_auth_message_processor.cpp b/test/unittest/UTTest_auth_message_processor.cpp index eb392b1ee..dba95a853 100644 --- a/test/unittest/UTTest_auth_message_processor.cpp +++ b/test/unittest/UTTest_auth_message_processor.cpp @@ -16,6 +16,7 @@ #include "UTTest_auth_message_processor.h" #include "dm_log.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "auth_message_processor.h" #include "softbus_connector.h" @@ -132,7 +133,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes authMessageProcessor->SetResponseContext(authResponseContext); authMessageProcessor->cryptoAdapter_ = nullptr; authMessageProcessor->CreateNegotiateMessage(jsonObj); - std::string str1 = jsonObj.dump(); + std::string str1 = SafetyDump(jsonObj); authMessageProcessor->cryptoAdapter_ = std::make_shared(); authMessageProcessor->CreateNegotiateMessage(jsonObj); @@ -145,7 +146,7 @@ HWTEST_F(AuthMessageProcessorTest, CreateNegotiateMessage_001, testing::ext::Tes jsonObject[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsonObject[TAG_LOCAL_DEVICE_ID] = authMessageProcessor->authResponseContext_->localDeviceId; jsonObject[TAG_HOST] = ""; - std::string str2 = jsonObject.dump(); + std::string str2 = SafetyDump(jsonObject); ASSERT_NE(str1, str2); } @@ -171,8 +172,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateSyncGroupMessage_001, testing::ext::Tes jsona[TAG_DEVICE_ID] = authMessageProcessor->authRequestContext_->deviceId; jsona[TAG_GROUPIDS] = authMessageProcessor->authRequestContext_->syncGroupList; authMessageProcessor->CreateSyncGroupMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -196,7 +197,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: authMessageProcessor->authResponseContext_->token = "11"; nlohmann::json jsonb; jsonb[TAG_GROUP_ID] = "123456"; - authMessageProcessor->authResponseContext_->groupId = jsonb.dump(); + authMessageProcessor->authResponseContext_->groupId = + SafetyDump(jsonb); authMessageProcessor->authResponseContext_->authToken = "123456"; authMessageProcessor->authResponseContext_->networkId = "11112222"; authMessageProcessor->authResponseContext_->requestId = 222222; @@ -210,8 +212,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseAuthMessage_001, testing::ext:: jsona[TAG_GROUP_ID] = "123456"; jsona[TAG_GROUP_NAME] = authMessageProcessor->authResponseContext_->groupName; authMessageProcessor->CreateResponseAuthMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } @@ -234,8 +236,8 @@ HWTEST_F(AuthMessageProcessorTest, CreateResponseFinishMessage_001, testing::ext jsona[TAG_REPLY] = authMessageProcessor->authResponseContext_->reply; jsona[TAG_AUTH_FINISH] = authMessageProcessor->authResponseContext_->isFinish; authMessageProcessor->CreateResponseFinishMessage(jsonObj); - std::string str1 = jsona.dump(); - std::string str2 = jsonObj.dump(); + std::string str1 = SafetyDump(jsona); + std::string str2 = SafetyDump(jsonObj); ASSERT_EQ(str1, str2); } diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index 45268bfc9..ea1a4a52a 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -19,6 +19,7 @@ #include #include "accesstoken_kit.h" #include "device_manager_notify.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_log.h" #include "ipc_authenticate_device_req.h" @@ -459,7 +460,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -470,7 +471,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -482,7 +483,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -492,7 +493,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_101, testing::ext::TestSize.Level std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -503,7 +504,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_102, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->listener_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -515,7 +516,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_103, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -527,7 +528,7 @@ HWTEST_F(DmPinHolderTest, ProcessCreateRespMsg_104, testing::ext::TestSize.Level std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_REPLY] = DmPinType::NUMBER_PIN_CODE; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->session_ = nullptr; pinHolder->ProcessCreateRespMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); @@ -558,7 +559,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_103, testing::ext::TestSize.Level0) std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -569,7 +570,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_104, testing::ext::TestSize.Level0) std::shared_ptr pinHolder = std::make_shared(listener); nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = "TAG_PIN_TYPE"; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -581,7 +582,7 @@ HWTEST_F(DmPinHolderTest, ProcessDestroyMsg_105, testing::ext::TestSize.Level0) nlohmann::json jsonObject; jsonObject[TAG_PIN_TYPE] = DmPinType::SUPER_SONIC; jsonObject[TAG_PAYLOAD] = DmPinType::SUPER_SONIC; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->ProcessDestroyMsg(message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -603,7 +604,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_101, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -615,7 +616,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_102, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_CREATE_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -627,7 +628,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_103, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -639,7 +640,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_104, testing::ext::TestSize.Level0) int32_t sessionId = 1; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_DESTROY_PIN_HOLDER_RESP; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } @@ -652,7 +653,7 @@ HWTEST_F(DmPinHolderTest, OnDataReceived_105, testing::ext::TestSize.Level0) int32_t data = 300; nlohmann::json jsonObject; jsonObject[TAG_MSG_TYPE] = data; - std::string message = jsonObject.dump(); + std::string message = SafetyDump(jsonObject); pinHolder->OnDataReceived(sessionId, message); ASSERT_NE(pinHolder->timer_, nullptr); } diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 00ba99d82..e8bd5e2a7 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -19,6 +19,7 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_notify.h" +#include "dm_anonymous.h" #include "dm_constants.h" #include "dm_device_info.h" #include "ipc_client_manager.h" @@ -1249,7 +1250,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_053, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_OH; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = jsonObject.dump(); + std::string credentialInfo = SafetyDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); @@ -1287,7 +1288,7 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_054, testing::ext::TestSize.Level nlohmann::json jsonObject; jsonObject[DM_CREDENTIAL_TYPE] = DM_TYPE_MINE; jsonObject[DM_CREDENTIAL_REQJSONSTR] = ""; - std::string credentialInfo = jsonObject.dump(); + std::string credentialInfo = SafetyDump(jsonObject); data.WriteString(pkgName); data.WriteString(credentialInfo); OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); diff --git a/utils/src/kvadapter/dm_kv_info.cpp b/utils/src/kvadapter/dm_kv_info.cpp index 2a251d6fa..e3197f74d 100644 --- a/utils/src/kvadapter/dm_kv_info.cpp +++ b/utils/src/kvadapter/dm_kv_info.cpp @@ -28,7 +28,7 @@ void ConvertDmKVValueToJson(const DmKVValue &kvValue, std::string &result) jsonObj[ANOY_DEVICE_ID_KEY] = kvValue.anoyDeviceId; jsonObj[SALT_KEY] = kvValue.salt; jsonObj[LAST_MODIFY_TIME_KEY] = kvValue.lastModifyTime; - result = jsonObj.dump(); + result = SafetyDump(jsonObj); } void ConvertJsonToDmKVValue(const std::string &result, DmKVValue &kvValue) -- Gitee From 665163260a9237c97e856189f4bf26faa386b701 Mon Sep 17 00:00:00 2001 From: Charlie Date: Wed, 11 Dec 2024 15:09:51 +0800 Subject: [PATCH 518/520] =?UTF-8?q?=E6=94=AF=E6=8C=81USB=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charlie --- .../include/discovery/discovery_manager.h | 1 + .../service/src/discovery/discovery_manager.cpp | 16 +++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index 6e9fb7f6c..ca122d021 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -97,6 +97,7 @@ private: void OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara); void UpdateInfoFreq(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); + void UpdateInfoMedium(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); std::string AddMultiUserIdentify(const std::string &pkgName); std::string RemoveMultiUserIdentify(const std::string &pkgName); void GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, int32_t &userId); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 3078a37ea..a68fe4667 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -69,7 +69,6 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, DmSubscribeInfo dmSubInfo; dmSubInfo.subscribeId = DM_INVALID_FLAG_ID; dmSubInfo.mode = DmDiscoverMode::DM_DISCOVER_MODE_PASSIVE; - dmSubInfo.medium = DmExchangeMedium::DM_BLE; dmSubInfo.freq = DmExchangeFreq::DM_LOW; dmSubInfo.isSameAccount = false; dmSubInfo.isWakeRemote = false; @@ -101,10 +100,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, std::lock_guard capLock(capabilityMapLocks_); capabilityMap_[pkgNameTemp] = std::string(dmSubInfo.capability); } - if (discoverParam.find(PARAM_KEY_DISC_MEDIUM) != discoverParam.end()) { - int32_t medium = std::atoi((discoverParam.find(PARAM_KEY_DISC_MEDIUM)->second).c_str()); - dmSubInfo.medium = static_cast(medium); - } + UpdateInfoMedium(discoverParam, dmSubInfo); int32_t ret = softbusListener_->RefreshSoftbusLNN(DM_PKG_NAME, dmSubInfo, LNN_DISC_CAPABILITY); if (ret != DM_OK) { LOGE("EnableDiscoveryListener failed, softbus refresh lnn ret: %{public}d.", ret); @@ -542,6 +538,16 @@ void DiscoveryManager::UpdateInfoFreq( } } +void DiscoveryManager::UpdateInfoMedium( + const std::map &discoverParam, DmSubscribeInfo &dmSubInfo) +{ + dmSubInfo.medium = DmExchangeMedium::DM_BLE; + if (discoverParam.find(PARAM_KEY_DISC_MEDIUM) != discoverParam.end()) { + int32_t medium = std::atoi((discoverParam.find(PARAM_KEY_DISC_MEDIUM)->second).c_str()); + dmSubInfo.medium = static_cast(medium); + } +} + int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, int32_t &authForm) { -- Gitee From 6ed9a7760d054d72fa7fbc8771da2c5feab18de8 Mon Sep 17 00:00:00 2001 From: Charlie Date: Wed, 11 Dec 2024 15:09:51 +0800 Subject: [PATCH 519/520] =?UTF-8?q?=E6=94=AF=E6=8C=81USB=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charlie --- .../include/discovery/discovery_manager.h | 1 + .../src/discovery/discovery_manager.cpp | 16 +++-- .../service/src/softbus/softbus_listener.cpp | 66 +++++++++---------- 3 files changed, 45 insertions(+), 38 deletions(-) diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index 6e9fb7f6c..ca122d021 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -97,6 +97,7 @@ private: void OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara); void UpdateInfoFreq(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); + void UpdateInfoMedium(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); std::string AddMultiUserIdentify(const std::string &pkgName); std::string RemoveMultiUserIdentify(const std::string &pkgName); void GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, int32_t &userId); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 3078a37ea..a68fe4667 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -69,7 +69,6 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, DmSubscribeInfo dmSubInfo; dmSubInfo.subscribeId = DM_INVALID_FLAG_ID; dmSubInfo.mode = DmDiscoverMode::DM_DISCOVER_MODE_PASSIVE; - dmSubInfo.medium = DmExchangeMedium::DM_BLE; dmSubInfo.freq = DmExchangeFreq::DM_LOW; dmSubInfo.isSameAccount = false; dmSubInfo.isWakeRemote = false; @@ -101,10 +100,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, std::lock_guard capLock(capabilityMapLocks_); capabilityMap_[pkgNameTemp] = std::string(dmSubInfo.capability); } - if (discoverParam.find(PARAM_KEY_DISC_MEDIUM) != discoverParam.end()) { - int32_t medium = std::atoi((discoverParam.find(PARAM_KEY_DISC_MEDIUM)->second).c_str()); - dmSubInfo.medium = static_cast(medium); - } + UpdateInfoMedium(discoverParam, dmSubInfo); int32_t ret = softbusListener_->RefreshSoftbusLNN(DM_PKG_NAME, dmSubInfo, LNN_DISC_CAPABILITY); if (ret != DM_OK) { LOGE("EnableDiscoveryListener failed, softbus refresh lnn ret: %{public}d.", ret); @@ -542,6 +538,16 @@ void DiscoveryManager::UpdateInfoFreq( } } +void DiscoveryManager::UpdateInfoMedium( + const std::map &discoverParam, DmSubscribeInfo &dmSubInfo) +{ + dmSubInfo.medium = DmExchangeMedium::DM_BLE; + if (discoverParam.find(PARAM_KEY_DISC_MEDIUM) != discoverParam.end()) { + int32_t medium = std::atoi((discoverParam.find(PARAM_KEY_DISC_MEDIUM)->second).c_str()); + dmSubInfo.medium = static_cast(medium); + } +} + int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, int32_t &authForm) { diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 7bc25c50a..f275f7a9e 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -850,39 +850,6 @@ int32_t SoftbusListener::FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo & return DM_OK; } -void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj) -{ - if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { - std::string wifiIp((addrInfo->info).ip.ip); - jsonObj[PARAM_KEY_WIFI_IP] = wifiIp; - jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port; - jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_ETH_IP; - } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) { - std::string wifiIp((addrInfo->info).ip.ip); - jsonObj[PARAM_KEY_WIFI_IP] = wifiIp; - jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port; - jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_WLAN_IP; - } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) { - std::string brMac((addrInfo->info).br.brMac); - jsonObj[PARAM_KEY_BR_MAC] = brMac; - jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BR; - } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) { - std::string bleMac((addrInfo->info).ble.bleMac); - jsonObj[PARAM_KEY_BLE_MAC] = bleMac; - jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BLE; - std::string udidHash(ConvertBytesToUpperCaseHexString((addrInfo->info).ble.udidHash, - sizeof((addrInfo->info).ble.udidHash) / sizeof(*((addrInfo->info).ble.udidHash)))); - jsonObj[PARAM_KEY_BLE_UDID_HASH] = udidHash; - } else if (addrInfo->type == CONNECTION_ADDR_USB) { - std::string usbIp((addrInfo->info).ip.ip); - jsonObj[PARAM_KEY_USB_IP] = usbIp; - jsonObj[PARAM_KEY_USB_PORT] = (addrInfo->info).ip.port; - jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_USB; - } else { - LOGI("Unknown connection address type: %{public}d.", addrInfo->type); - } -} - void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDeviceInfo &dmDevice) { if (FillDeviceInfo(device, dmDevice) != DM_OK) { @@ -927,6 +894,39 @@ int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t & return SoftbusCache::GetInstance().GetSecurityDeviceLevel(networkId, securityLevel); } +void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj) +{ + if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { + std::string wifiIp((addrInfo->info).ip.ip); + jsonObj[PARAM_KEY_WIFI_IP] = wifiIp; + jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port; + jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_ETH_IP; + } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_WLAN) { + std::string wifiIp((addrInfo->info).ip.ip); + jsonObj[PARAM_KEY_WIFI_IP] = wifiIp; + jsonObj[PARAM_KEY_WIFI_PORT] = (addrInfo->info).ip.port; + jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_WLAN_IP; + } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BR) { + std::string brMac((addrInfo->info).br.brMac); + jsonObj[PARAM_KEY_BR_MAC] = brMac; + jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BR; + } else if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_BLE) { + std::string bleMac((addrInfo->info).ble.bleMac); + jsonObj[PARAM_KEY_BLE_MAC] = bleMac; + jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_BLE; + std::string udidHash(ConvertBytesToUpperCaseHexString((addrInfo->info).ble.udidHash, + sizeof((addrInfo->info).ble.udidHash) / sizeof(*((addrInfo->info).ble.udidHash)))); + jsonObj[PARAM_KEY_BLE_UDID_HASH] = udidHash; + } else if (addrInfo->type == CONNECTION_ADDR_USB) { + std::string usbIp((addrInfo->info).ip.ip); + jsonObj[PARAM_KEY_USB_IP] = usbIp; + jsonObj[PARAM_KEY_USB_PORT] = (addrInfo->info).ip.port; + jsonObj[PARAM_KEY_CONN_ADDR_TYPE] = CONN_ADDR_TYPE_USB; + } else { + LOGI("Unknown connection address type: %{public}d.", addrInfo->type); + } +} + void SoftbusListener::CacheDiscoveredDevice(const DeviceInfo *device) { std::shared_ptr infoPtr = std::make_shared(); -- Gitee From a0b4dfc013b33184153c1c0c0793d410c52850be Mon Sep 17 00:00:00 2001 From: Charlie Date: Wed, 11 Dec 2024 15:21:48 +0800 Subject: [PATCH 520/520] =?UTF-8?q?=E6=94=AF=E6=8C=81USB=E5=8F=91=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Charlie --- .../service/src/softbus/softbus_listener.cpp | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index f275f7a9e..d528c2494 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -875,25 +875,6 @@ void SoftbusListener::ConvertDeviceInfoToDmDevice(const DeviceInfo &device, DmDe dmDevice.extraData = SafetyDump(jsonObj); } -int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) -{ - int32_t tempNetworkType = -1; - int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_NETWORK_TYPE, - reinterpret_cast(&tempNetworkType), LNN_COMMON_LEN); - if (ret != DM_OK) { - LOGE("[SOFTBUS]GetNodeKeyInfo networkType failed."); - return ret; - } - networkType = tempNetworkType; - LOGI("GetNetworkTypeByNetworkId networkType %{public}d.", tempNetworkType); - return DM_OK; -} - -int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) -{ - return SoftbusCache::GetInstance().GetSecurityDeviceLevel(networkId, securityLevel); -} - void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann::json &jsonObj) { if (addrInfo->type == ConnectionAddrType::CONNECTION_ADDR_ETH) { @@ -927,6 +908,25 @@ void SoftbusListener::ParseConnAddrInfo(const ConnectionAddr *addrInfo, nlohmann } } +int32_t SoftbusListener::GetNetworkTypeByNetworkId(const char *networkId, int32_t &networkType) +{ + int32_t tempNetworkType = -1; + int32_t ret = GetNodeKeyInfo(DM_PKG_NAME, networkId, NodeDeviceInfoKey::NODE_KEY_NETWORK_TYPE, + reinterpret_cast(&tempNetworkType), LNN_COMMON_LEN); + if (ret != DM_OK) { + LOGE("[SOFTBUS]GetNodeKeyInfo networkType failed."); + return ret; + } + networkType = tempNetworkType; + LOGI("GetNetworkTypeByNetworkId networkType %{public}d.", tempNetworkType); + return DM_OK; +} + +int32_t SoftbusListener::GetDeviceSecurityLevel(const char *networkId, int32_t &securityLevel) +{ + return SoftbusCache::GetInstance().GetSecurityDeviceLevel(networkId, securityLevel); +} + void SoftbusListener::CacheDiscoveredDevice(const DeviceInfo *device) { std::shared_ptr infoPtr = std::make_shared(); -- Gitee