diff --git a/bundle.json b/bundle.json index f726ee71c84c0c228f6dba4f83660ed9992b734b..8b898570193d2f7d3acd3bb396f20d8c793bb717 100644 --- a/bundle.json +++ b/bundle.json @@ -94,8 +94,7 @@ "openssl", "json", "dmsfwk", - "data_object", - "init" + "data_object" ], "third_party": [ "libuv", diff --git a/services/distributeddataservice/adapter/bundle_mgr/bundlemgr_adapter.cpp b/services/distributeddataservice/adapter/bundle_mgr/bundlemgr_adapter.cpp deleted file mode 100644 index fd17f542764623eb737e1411ee49372e5760e30c..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/bundle_mgr/bundlemgr_adapter.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -* Copyright (c) 2025 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -#define LOG_TAG "BundleMgrAdapter" - -#include "bundlemgr_adapter.h" -#include -#include "accesstoken_kit.h" -#include "bundlemgr/bundle_mgr_proxy.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "log_print.h" -#include "system_ability_definition.h" - -namespace OHOS { -namespace DistributedData { -BundleMgrAdapter::BundleMgrAdapter() -{ -} -BundleMgrAdapter::~BundleMgrAdapter() -{ -} -BundleMgrAdapter& BundleMgrAdapter::GetInstance() -{ - static BundleMgrAdapter instance; - return instance; -} - -std::string BundleMgrAdapter::GetKey(const std::string &bundleName, int32_t userId) -{ - return bundleName + "###" + std::to_string(userId); -} - -std::string BundleMgrAdapter::GetAppidFromCache(const std::string &bundleName, int32_t userId) -{ - std::string appId; - std::string key = GetKey(bundleName, userId); - appIds_.Get(key, appId); - return appId; -} - -std::string BundleMgrAdapter::GetBundleAppId(const std::string &bundleName, int32_t userId) -{ - std::string appId = GetAppidFromCache(bundleName, userId); - if (!appId.empty()) { - return appId; - } - auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgrProxy == nullptr) { - ZLOGE("Failed to get system ability mgr."); - return ""; - } - auto bundleMgrProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (bundleMgrProxy == nullptr) { - ZLOGE("Failed to Get BMS SA."); - return ""; - } - auto bundleManager = iface_cast(bundleMgrProxy); - if (bundleManager == nullptr) { - ZLOGE("Failed to get bundle manager"); - return ""; - } - appId = bundleManager->GetAppIdByBundleName(bundleName, userId); - if (appId.empty()) { - ZLOGE("GetAppIdByBundleName failed appId:%{public}s, bundleName:%{public}s, uid:%{public}d", - appId.c_str(), bundleName.c_str(), userId); - } else { - appIds_.Set(GetKey(bundleName, userId), appId); - } - return appId; -} - -void BundleMgrAdapter::DeleteCache(const std::string &bundleName, int32_t user) -{ - std::string key = GetKey(bundleName, user); - appIds_.Delete(key); -} - -void BundleMgrAdapter::ClearCache() -{ - appIds_.ResetCapacity(0); - appIds_.ResetCapacity(CACHE_SIZE); -} -} // namespace DistributedData -} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn index 54392bffff00f494340fe1a7013c090819c3d76a..b3c1e72797f90adad5c737f907a0601ae34be7a2 100644 --- a/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn +++ b/services/distributeddataservice/adapter/communicator/test/fuzztest/softbusadapter_fuzzer/BUILD.gn @@ -35,7 +35,17 @@ ohos_fuzztest("SoftBusAdapterFuzzTest") { "-fno-omit-frame-pointer", ] - sources = [ "softbusadapter_fuzzer.cpp" ] + sources = [ + "${data_service_path}/adapter/communicator/src/communicator_context.cpp", + "${data_service_path}/adapter/communicator/src/device_manager_adapter.cpp", + "${data_service_path}/adapter/communicator/src/softbus_client.cpp", + "softbusadapter_fuzzer.cpp", + ] + + deps = [ + "${data_service_path}/adapter/utils:distributeddata_utils", + "${data_service_path}/framework:distributeddatasvcfwk", + ] external_deps = [ "access_token:libaccesstoken_sdk", diff --git a/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp b/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp index f6a82fe28a770ad1f9d5f56adb94e2a1951739b1..35e0ceaff77ffcbcc0885856e928c5e7046bbd41 100644 --- a/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp +++ b/services/distributeddataservice/adapter/dfx/src/hiview_adapter.cpp @@ -135,6 +135,7 @@ void HiViewAdapter::ReportDBFault(int dfxCode, const DBFaultMsg &msg, std::share return; } ExecutorPool::Task task([dfxCode, msg]() { + std::string storeId = Anonymous::Change(msg.storeId); struct HiSysEventParam params[] = { { .name = { *APP_ID }, .t = HISYSEVENT_STRING, @@ -142,7 +143,7 @@ void HiViewAdapter::ReportDBFault(int dfxCode, const DBFaultMsg &msg, std::share .arraySize = 0 }, { .name = { *STORE_ID }, .t = HISYSEVENT_STRING, - .v = { .s = const_cast(Anonymous::Change(msg.storeId).c_str()) }, + .v = { .s = const_cast(storeId.c_str()) }, .arraySize = 0 }, { .name = { *MODULE_NAME }, .t = HISYSEVENT_STRING, @@ -172,6 +173,7 @@ void HiViewAdapter::ReportCommFault(int dfxCode, const CommFaultMsg &msg, std::s } ExecutorPool ::Task task([dfxCode, msg]() { std::string message; + std::string storeId = Anonymous::Change(msg.storeId); for (size_t i = 0; i < msg.deviceId.size(); i++) { message.append("No: ").append(std::to_string(i)) .append(" sync to device: ").append(msg.deviceId[i]) @@ -188,7 +190,7 @@ void HiViewAdapter::ReportCommFault(int dfxCode, const CommFaultMsg &msg, std::s .arraySize = 0 }, { .name = { *STORE_ID }, .t = HISYSEVENT_STRING, - .v = { .s = const_cast(Anonymous::Change(msg.storeId).c_str()) }, + .v = { .s = const_cast(storeId.c_str()) }, .arraySize = 0 }, { .name = { *SYNC_ERROR_INFO }, .t = HISYSEVENT_STRING, @@ -244,6 +246,7 @@ void HiViewAdapter::ReportBehaviour(int dfxCode, const BehaviourMsg &msg, std::s } ExecutorPool::Task task([dfxCode, msg]() { std::string message; + std::string storeId = Anonymous::Change(msg.storeId); message.append("Behaviour type : ").append(std::to_string(static_cast(msg.behaviourType))) .append(" behaviour info : ").append(msg.extensionInfo); struct HiSysEventParam params[] = { @@ -257,7 +260,7 @@ void HiViewAdapter::ReportBehaviour(int dfxCode, const BehaviourMsg &msg, std::s .arraySize = 0 }, { .name = { *STORE_ID }, .t = HISYSEVENT_STRING, - .v = { .s = const_cast(Anonymous::Change(msg.storeId).c_str()) }, + .v = { .s = const_cast(storeId.c_str()) }, .arraySize = 0 }, { .name = { *BEHAVIOUR_INFO }, .t = HISYSEVENT_STRING, @@ -303,7 +306,7 @@ void HiViewAdapter::ReportDbSize(const StatisticWrap &stat) if (!vh.CalcValueHash(stat.val.userId, userId)) { return; } - + std::string storeId = Anonymous::Change(stat.val.storeId); struct HiSysEventParam params[] = { { .name = { *USER_ID }, .t = HISYSEVENT_STRING, @@ -315,7 +318,7 @@ void HiViewAdapter::ReportDbSize(const StatisticWrap &stat) .arraySize = 0 }, { .name = { *STORE_ID }, .t = HISYSEVENT_STRING, - .v = { .s = const_cast(Anonymous::Change(stat.val.storeId).c_str()) }, + .v = { .s = const_cast(storeId.c_str()) }, .arraySize = 0 }, { .name = { *DB_SIZE }, .t = HISYSEVENT_UINT64, .v = { .ui64 = dbSize }, .arraySize = 0 }, }; @@ -384,6 +387,7 @@ void HiViewAdapter::InvokeTraffic() if (!vh.CalcValueHash(kv.second.val.deviceId, deviceId)) { continue; } + std::string devId = Anonymous::Change(deviceId); struct HiSysEventParam params[] = { { .name = { *TAG }, .t = HISYSEVENT_STRING, .v = { .s = const_cast(POWERSTATS) }, .arraySize = 0 }, { .name = { *APP_ID }, @@ -392,7 +396,7 @@ void HiViewAdapter::InvokeTraffic() .arraySize = 0 }, { .name = { *DEVICE_ID }, .t = HISYSEVENT_STRING, - .v = { .s = const_cast(Anonymous::Change(deviceId).c_str()) }, + .v = { .s = const_cast(devId.c_str()) }, .arraySize = 0 }, { .name = { *SEND_SIZE }, .t = HISYSEVENT_INT64, diff --git a/services/distributeddataservice/adapter/include/bundle_mgr/bundlemgr_adapter.h b/services/distributeddataservice/adapter/include/bundle_mgr/bundlemgr_adapter.h deleted file mode 100644 index 5519c9b105b12093cbf1ee67e69b56470e3d047d..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/include/bundle_mgr/bundlemgr_adapter.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2025 Huawei Device Co., Ltd. -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR 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_DATA_SERVICES_BUNDLEMGR_ADAPTER_H -#define OHOS_DISTRIBUTED_DATA_SERVICES_BUNDLEMGR_ADAPTER_H -#include "lru_bucket.h" -#include "visibility.h" -namespace OHOS { -namespace DistributedData { -class BundleMgrAdapter { -public: - BundleMgrAdapter(); - ~BundleMgrAdapter(); - API_EXPORT static BundleMgrAdapter& GetInstance(); - API_EXPORT std::string GetBundleAppId(const std::string &bundleName, int32_t userId); - API_EXPORT void DeleteCache(const std::string &bundleName, int32_t user); - API_EXPORT void ClearCache(); - -private: - std::string GetAppidFromCache(const std::string &bundleName, int32_t userId); - std::string GetKey(const std::string &bundleName, int32_t userId); - static constexpr int32_t CACHE_SIZE = 32; - LRUBucket appIds_ {CACHE_SIZE}; -}; -} // namespace DistributedData -} // namespace OHOS -#endif // OHOS_DISTRIBUTED_DATA_SERVICES_BUNDLEMGR_ADAPTER_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/schema_helper/BUILD.gn b/services/distributeddataservice/adapter/schema_helper/BUILD.gn index c3516c441a77a4c80451f2493c5568a9e1419b4a..4bdf79b0c67a044f0784069be32aeb14dd6a3e43 100644 --- a/services/distributeddataservice/adapter/schema_helper/BUILD.gn +++ b/services/distributeddataservice/adapter/schema_helper/BUILD.gn @@ -31,7 +31,6 @@ ohos_source_set("distributeddata_schema_helper") { cflags_cc = [ "-fvisibility=hidden", - "-fstack-protector-strong", ] public_configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/adapter/screenlock/BUILD.gn b/services/distributeddataservice/adapter/screenlock/BUILD.gn index 766eb3f9e9d0530888a346939f9609656e56ad60..453ee8212d056adc850f1bc5cc1dcc05065fa43e 100644 --- a/services/distributeddataservice/adapter/screenlock/BUILD.gn +++ b/services/distributeddataservice/adapter/screenlock/BUILD.gn @@ -31,7 +31,6 @@ ohos_source_set("distributeddata_screenlock") { cflags_cc = [ "-fvisibility=hidden", - "-fstack-protector-strong", ] public_configs = [ ":module_public_config" ] diff --git a/services/distributeddataservice/adapter/screenlock/test/screen_lock_test.cpp b/services/distributeddataservice/adapter/screenlock/test/screen_lock_test.cpp index 9374568e57385ac1ca1fa5a348bfa796271fd8a5..5384155bcb5dc94b87ca1164aa6286e4ddb4fe07 100644 --- a/services/distributeddataservice/adapter/screenlock/test/screen_lock_test.cpp +++ b/services/distributeddataservice/adapter/screenlock/test/screen_lock_test.cpp @@ -53,6 +53,8 @@ public: void TearDown() { } +protected: + static constexpr int32_t MAX_RETRY_TIME = 300; }; /** @@ -125,4 +127,57 @@ HWTEST_F(ScreenLockTest, SubscribeScreenEvent001, TestSize.Level0) screenLock->UnsubscribeScreenEvent(); screenLock->executors_ = nullptr; } + +/** +* @tc.name: SubscribeScreenEvent002 +* @tc.desc: subscribe ScreenEvent +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(ScreenLockTest, SubscribeScreenEvent002, TestSize.Level0) +{ + auto screenLock = std::make_shared(); + EXPECT_EQ(screenLock->executors_, nullptr); + EXPECT_EQ(screenLock->eventSubscriber_, nullptr); + screenLock->SubscribeScreenEvent(); + EXPECT_NE(screenLock->eventSubscriber_, nullptr); + screenLock->UnsubscribeScreenEvent(); +} + +/** +* @tc.name: GetTask001 +* @tc.desc: subscribe ScreenEvent +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(ScreenLockTest, GetTask001, TestSize.Level0) +{ + auto screenLock = std::make_shared(); + EXPECT_EQ(screenLock->executors_, nullptr); + EXPECT_EQ(screenLock->eventSubscriber_, nullptr); + auto Task = screenLock->GetTask(0); + Task(); + auto executor = std::make_shared(12, 5); + screenLock->BindExecutor(executor); + ASSERT_NE(screenLock->executors_, nullptr); + Task = screenLock->GetTask(MAX_RETRY_TIME - 1); + Task(); +} + +/** +* @tc.name: GetTask002 +* @tc.desc: subscribe ScreenEvent +* @tc.type: FUNC +* @tc.author: +*/ +HWTEST_F(ScreenLockTest, GetTask002, TestSize.Level0) +{ + auto screenLock = std::make_shared(); + EXPECT_EQ(screenLock->executors_, nullptr); + EXPECT_EQ(screenLock->eventSubscriber_, nullptr); + screenLock->SubscribeScreenEvent(); + EXPECT_NE(screenLock->eventSubscriber_, nullptr); + auto Task = screenLock->GetTask(0); + Task(); +} } // namespace \ No newline at end of file diff --git a/services/distributeddataservice/app/src/checker/BUILD.gn b/services/distributeddataservice/app/src/checker/BUILD.gn index 0ad405bb94ee9c00e84585aa25c2561e1d55fb58..f0fa8dd258432a3254d58b3173dd84958c6fa2d7 100644 --- a/services/distributeddataservice/app/src/checker/BUILD.gn +++ b/services/distributeddataservice/app/src/checker/BUILD.gn @@ -32,10 +32,7 @@ ohos_source_set("distributeddata_checker") { "-Oz", ] - include_dirs = [ - "${data_service_path}/adapter/include", - "${data_service_path}/framework/include", - ] + include_dirs = [ "${data_service_path}/framework/include" ] if (build_public_version) { cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.cpp b/services/distributeddataservice/app/src/checker/bundle_checker.cpp index 1bfc0fd2187febc30e4630d7bf1ba727ba7071e5..b726ab915be6d6ba3efe6693eb0825b2b93122bb 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.cpp +++ b/services/distributeddataservice/app/src/checker/bundle_checker.cpp @@ -18,7 +18,6 @@ #include #include "accesstoken_kit.h" #include "bundlemgr/bundle_mgr_proxy.h" -#include "bundle_mgr/bundlemgr_adapter.h" #include "hap_token_info.h" #include "ipc_skeleton.h" #include "iservice_registry.h" @@ -62,13 +61,63 @@ bool BundleChecker::SetSwitchesInfo(const CheckerManager::Switches &switches) return true; } +std::string BundleChecker::GetKey(const std::string &bundleName, int32_t userId) +{ + return bundleName + "###" + std::to_string(userId); +} + +std::string BundleChecker::GetAppidFromCache(const std::string &bundleName, int32_t userId) +{ + std::string appId; + std::string key = GetKey(bundleName, userId); + appIds_.Get(key, appId); + return appId; +} + std::string BundleChecker::GetBundleAppId(const CheckerManager::StoreInfo &info) { int32_t userId = info.uid / OHOS::AppExecFwk::Constants::BASE_USER_RANGE; - std::string appId = BundleMgrAdapter::GetInstance().GetBundleAppId(info.bundleName, userId); + std::string appId = GetAppidFromCache(info.bundleName, userId); + if (!appId.empty()) { + return appId; + } + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ZLOGE("Failed to get system ability mgr."); + return ""; + } + auto bundleMgrProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleMgrProxy == nullptr) { + ZLOGE("Failed to Get BMS SA."); + return ""; + } + auto bundleManager = iface_cast(bundleMgrProxy); + if (bundleManager == nullptr) { + ZLOGE("Failed to get bundle manager"); + return ""; + } + appId = bundleManager->GetAppIdByBundleName(info.bundleName, userId); + if (appId.empty()) { + ZLOGE("GetAppIdByBundleName failed appId:%{public}s, bundleName:%{public}s, uid:%{public}d", + appId.c_str(), info.bundleName.c_str(), userId); + } else { + appIds_.Set(GetKey(info.bundleName, userId), appId); + } return appId; } +void BundleChecker::DeleteCache(const std::string &bundleName, int32_t user, int32_t index) +{ + std::string key = GetKey(bundleName, user); + appIds_.Delete(key); +} + +void BundleChecker::ClearCache() +{ + appIds_.ResetCapacity(0); + appIds_.ResetCapacity(CACHE_SIZE); +} + std::string BundleChecker::GetAppId(const CheckerManager::StoreInfo &info) { if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) { diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.h b/services/distributeddataservice/app/src/checker/bundle_checker.h index b0c63431a207cd374abb37605c3bebaf3e1227ed..d5c655bb92add0fc2b61a427e906c18e33c19c2a 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.h +++ b/services/distributeddataservice/app/src/checker/bundle_checker.h @@ -16,6 +16,7 @@ #ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_BUNDLE_CHECKER_H #define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_BUNDLE_CHECKER_H #include "checker/checker_manager.h" +#include "lru_bucket.h" namespace OHOS { namespace DistributedData { class BundleChecker : public CheckerManager::Checker { @@ -36,7 +37,12 @@ public: std::vector GetStaticStores() override; bool IsDynamic(const CheckerManager::StoreInfo &info) override; bool IsStatic(const CheckerManager::StoreInfo &info) override; + void DeleteCache(const std::string &bundleName, int32_t user, int32_t index) override; + void ClearCache() override; private: + static constexpr int32_t CACHE_SIZE = 32; + std::string GetAppidFromCache(const std::string &bundleName, int32_t userId); + std::string GetKey(const std::string &bundleName, int32_t userId); static BundleChecker instance_; std::map trusts_; std::map distrusts_; @@ -44,6 +50,7 @@ private: std::vector dynamicStores_; std::vector staticStores_; std::string GetBundleAppId(const CheckerManager::StoreInfo &info); + LRUBucket appIds_ { CACHE_SIZE }; }; } // namespace DistributedData } // namespace OHOS diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 9d505889925ad35805c945fb680a6bbaf6fba55d..3e85949f941e598a7bd1e9a79cf09afffcbdcfd4 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -29,7 +29,6 @@ #include "auth_delegate.h" #include "auto_launch_export.h" #include "bootstrap.h" -#include "bundle_mgr/bundlemgr_adapter.h" #include "checker/checker_manager.h" #include "communication_provider.h" #include "communicator_context.h" @@ -365,10 +364,6 @@ void KvStoreDataService::OnStart() Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1, std::placeholders::_2); DumpManager::GetInstance().AddHandler("STORE_INFO", uintptr_t(this), handlerStoreInfo); - RegisterUserInfo(); - Handler handlerUserInfo = std::bind(&KvStoreDataService::DumpUserInfo, this, std::placeholders::_1, - std::placeholders::_2); - DumpManager::GetInstance().AddHandler("USER_INFO", uintptr_t(this), handlerUserInfo); RegisterBundleInfo(); Handler handlerBundleInfo = std::bind(&KvStoreDataService::DumpBundleInfo, this, std::placeholders::_1, std::placeholders::_2); @@ -931,7 +926,7 @@ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) MetaDataManager::GetInstance().DelMeta(StoreMetaMapping(meta).GetKey(), true); PermitDelegate::GetInstance().DelCache(meta.GetKeyWithoutPath()); } - BundleMgrAdapter::GetInstance().ClearCache(); + CheckerManager::GetInstance().ClearCache(); g_kvStoreAccountEventStatus = 0; break; } @@ -983,8 +978,6 @@ void KvStoreDataService::NotifyAccountEvent(const AccountEventInfo &eventInfo) void KvStoreDataService::InitSecurityAdapter(std::shared_ptr executors) { - auto ret = DATASL_OnStart(); - ZLOGI("datasl on start ret:%d", ret); security_ = std::make_shared(executors); if (security_ == nullptr) { ZLOGE("security is nullptr."); @@ -1051,7 +1044,7 @@ void KvStoreDataService::OnSessionReady(const AppDistributedKv::DeviceInfo &info int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t user, int32_t index) { - BundleMgrAdapter::GetInstance().DeleteCache(bundleName, user); + CheckerManager::GetInstance().DeleteCache(bundleName, user, index); auto staticActs = FeatureSystem::GetInstance().GetStaticActs(); staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr& acts) { acts->OnAppUninstall(bundleName, user, index); @@ -1062,7 +1055,7 @@ int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t u int32_t KvStoreDataService::OnUpdate(const std::string &bundleName, int32_t user, int32_t index) { - BundleMgrAdapter::GetInstance().DeleteCache(bundleName, user); + CheckerManager::GetInstance().DeleteCache(bundleName, user, index); auto staticActs = FeatureSystem::GetInstance().GetStaticActs(); staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr& acts) { acts->OnAppUpdate(bundleName, user, index); @@ -1073,7 +1066,7 @@ int32_t KvStoreDataService::OnUpdate(const std::string &bundleName, int32_t user int32_t KvStoreDataService::OnInstall(const std::string &bundleName, int32_t user, int32_t index) { - BundleMgrAdapter::GetInstance().DeleteCache(bundleName, user); + CheckerManager::GetInstance().DeleteCache(bundleName, user, index); auto staticActs = FeatureSystem::GetInstance().GetStaticActs(); staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr& acts) { acts->OnAppInstall(bundleName, user, index); @@ -1094,7 +1087,7 @@ int32_t KvStoreDataService::OnScreenUnlocked(int32_t user) int32_t KvStoreDataService::ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, int32_t tokenId) { - BundleMgrAdapter::GetInstance().DeleteCache(bundleName, userId); + CheckerManager::GetInstance().DeleteCache(bundleName, userId, appIndex); auto callerToken = IPCSkeleton::GetCallingTokenID(); NativeTokenInfo nativeTokenInfo; if (AccessTokenKit::GetNativeTokenInfo(callerToken, nativeTokenInfo) != RET_SUCCESS || @@ -1161,7 +1154,14 @@ void KvStoreDataService::DumpStoreInfo(int fd, std::map metas; std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) { + int user = 0; + auto ret = AccountDelegate::GetInstance()->QueryForegroundUserId(user); + if (!ret) { + ZLOGE("get foreground userid failed"); + return; + } + if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId, std::to_string(user) }), + metas, true)) { ZLOGE("get full meta failed"); return; } @@ -1247,21 +1247,6 @@ std::string KvStoreDataService::GetIndentation(int size) return indentation; } -void KvStoreDataService::RegisterUserInfo() -{ - DumpManager::Config userInfoConfig; - userInfoConfig.fullCmd = "--user-info"; - userInfoConfig.abbrCmd = "-u"; - userInfoConfig.dumpName = "USER_INFO"; - userInfoConfig.countPrintf = PRINTF_COUNT_2; - userInfoConfig.infoName = " "; - userInfoConfig.minParamsNum = 0; - userInfoConfig.maxParamsNum = MAXIMUM_PARAMETER_LIMIT; // User contains no more than three parameters - userInfoConfig.childNode = "BUNDLE_INFO"; - userInfoConfig.dumpCaption = { "| Display all the user statistics", "| Display the user statistics by UserId" }; - DumpManager::GetInstance().AddConfig(userInfoConfig.dumpName, userInfoConfig); -} - void KvStoreDataService::BuildData(std::map &datas, const std::vector &metas) { for (auto &meta : metas) { @@ -1311,20 +1296,6 @@ void KvStoreDataService::PrintfInfo(int fd, const std::map> ¶ms) -{ - std::vector metas; - std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) { - ZLOGE("get full meta failed"); - return; - } - FilterData(metas, params); - std::map datas; - BuildData(datas, metas); - PrintfInfo(fd, datas); -} - void KvStoreDataService::RegisterBundleInfo() { DumpManager::Config bundleInfoConfig; @@ -1415,7 +1386,14 @@ void KvStoreDataService::DumpBundleInfo(int fd, std::map metas; std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) { + int user = 0; + auto ret = AccountDelegate::GetInstance()->QueryForegroundUserId(user); + if (!ret) { + ZLOGE("get foreground userid failed"); + return; + } + if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId, std::to_string(user) }), + metas, true)) { ZLOGE("get full meta failed"); return; } diff --git a/services/distributeddataservice/app/src/security/sensitive.cpp b/services/distributeddataservice/app/src/security/sensitive.cpp index 0cf9aa50630c0316b7c97a9333ccbd8b504b8b82..dcc023e3caf053f596218626f6cdd49ee53a7ce4 100644 --- a/services/distributeddataservice/app/src/security/sensitive.cpp +++ b/services/distributeddataservice/app/src/security/sensitive.cpp @@ -113,9 +113,14 @@ uint32_t Sensitive::GetSensitiveLevel(const std::string &udid) ZLOGE("init query params failed! udid:[%{public}s]", Anonymous::Change(udid).c_str()); return DATA_SEC_LEVEL1; } - + auto result = DATASL_OnStart(); + if (result != DEVSL_SUCCESS) { + ZLOGE("datasl on start failed, ret:%{public}d", result); + return DATA_SEC_LEVEL1; + } uint32_t level = DATA_SEC_LEVEL1; - int32_t result = DATASL_GetHighestSecLevel(&query, &level); + result = DATASL_GetHighestSecLevel(&query, &level); + DATASL_OnStop(); if (result != DEVSL_SUCCESS) { ZLOGE("get highest level failed(%{public}s)! level: %{public}d, error: %d", Anonymous::Change(udid).c_str(), securityLevel, result); diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 80725c641980d70476245e9e674f7dd0e17ceedc..d79c567b82e43464b623d1a8631c8cd23ef2f959 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -560,6 +560,30 @@ ohos_unittest("RouteHeadHandlerImplTest") { part_name = "datamgr_service" } +ohos_unittest("BundleCheckerTest") { + module_out_path = module_output_path + sources = [ "unittest/bundle_checker_test.cpp" ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken_shared", + "c_utils:utils", + "googletest:gtest_main", + "hilog:libhilog", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", + ] + + deps = [ + "${data_service_path}/app/src/checker:distributeddata_checker", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + ] +} + ############################################################################### group("unittest") { @@ -567,6 +591,7 @@ group("unittest") { deps = [] deps += [ + ":BundleCheckerTest", ":FeatureStubImplTest", ":KvStoreDataServiceClearTest", ":KvStoreDataServiceTest", diff --git a/services/distributeddataservice/app/test/unittest/bundle_checker_test.cpp b/services/distributeddataservice/app/test/unittest/bundle_checker_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..deb5c7def0c2f786a65477ee618ac6e1146cd0b4 --- /dev/null +++ b/services/distributeddataservice/app/test/unittest/bundle_checker_test.cpp @@ -0,0 +1,118 @@ +/* +* Copyright (c) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include +#include "accesstoken_kit.h" +#include "checker/bundle_checker.h" +#include "bootstrap.h" +#include "hap_token_info.h" +#include "nativetoken_kit.h" +#include "utils/crypto.h" +using namespace testing::ext; +using namespace OHOS::DistributedData; +using namespace OHOS::Security::AccessToken; +class BundleCheckerTest : public testing::Test { +public: + static void SetUpTestCase(void) {} + static void TearDownTestCase(void) {} + void SetUp(); + void TearDown(); + NativeTokenInfoParams infoInstance{0}; +}; + +void BundleCheckerTest::SetUp(void) +{ + infoInstance.dcapsNum = 0; + infoInstance.permsNum = 0; + infoInstance.aclsNum = 0; + infoInstance.dcaps = nullptr; + infoInstance.perms = nullptr; + infoInstance.acls = nullptr; + infoInstance.processName = "BundleCheckerTest"; + infoInstance.aplStr = "system_core"; + + HapInfoParams info = { + .userID = 100, + .bundleName = "com.ohos.dlpmanager", + .instIndex = 0, + .appIDDesc = "com.ohos.dlpmanager" + }; + PermissionDef infoManagerTestPermDef = { + .permissionName = "ohos.permission.test", + .bundleName = "ohos.test.demo", + .grantMode = 1, + .availableLevel = APL_NORMAL, + .label = "label", + .labelId = 1, + .description = "open the door", + .descriptionId = 1 + }; + PermissionStateFull infoManagerTestState = { + .permissionName = "ohos.permission.test", + .isGeneral = true, + .resDeviceID = {"local"}, + .grantStatus = {PermissionState::PERMISSION_GRANTED}, + .grantFlags = {1} + }; + HapPolicyParams policy = { + .apl = APL_NORMAL, + .domain = "test.domain", + .permList = {infoManagerTestPermDef}, + .permStateList = {infoManagerTestState} + }; + AccessTokenKit::AllocHapToken(info, policy); + + Bootstrap::GetInstance().LoadComponents(); + Bootstrap::GetInstance().LoadDirectory(); + Bootstrap::GetInstance().LoadCheckers(); + Bootstrap::GetInstance().LoadNetworks(); +} + +void BundleCheckerTest::TearDown() +{ + auto tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.dlpmanager", 0); + AccessTokenKit::DeleteToken(tokenId); +} + +/** +* @tc.name: GetAppIdTest001 +* @tc.desc: get appId from cache. +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(BundleCheckerTest, GetAppIdTest001, TestSize.Level0) +{ + CheckerManager::StoreInfo info; + auto tokenId = AccessTokenKit::GetHapTokenID(100, "com.ohos.dlpmanager", 0); + info.uid = 100 * 200000; + info.tokenId = tokenId; + info.bundleName = "com.ohos.dlpmanager"; + BundleChecker checker; + std::string appIdInCache; + ASSERT_TRUE(!checker.GetAppId(info).empty()); + checker.appIds_.Get("com.ohos.dlpmanager###100", appIdInCache); + ASSERT_FALSE(appIdInCache.empty()); + ASSERT_EQ(Crypto::Sha256(appIdInCache), checker.GetAppId(info)); + + checker.DeleteCache(info.bundleName, 100, 0); + std::string appIdInCache1; + checker.appIds_.Get("com.ohos.dlpmanager###100", appIdInCache1); + ASSERT_TRUE(appIdInCache1.empty()); + + checker.GetAppId(info); + ASSERT_GE(checker.appIds_.Size(), 1); + checker.ClearCache(); + ASSERT_EQ(checker.appIds_.Size(), 0); +} \ No newline at end of file diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp index fcaec79835ac63af1c971838a56b02d92a48b727..18167c5daefe90f0dbaddd421be0b87de963782e 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp @@ -673,21 +673,6 @@ HWTEST_F(KvStoreDataServiceTest, BuildData002, TestSize.Level0) EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.BuildData(datas, metas)); } -/** -* @tc.name: DumpUserInfo001 -* @tc.desc: test DumpUserInfo function -* @tc.type: FUNC -* @tc.require: -* @tc.author: SQL -*/ -HWTEST_F(KvStoreDataServiceTest, DumpUserInfo001, TestSize.Level0) -{ - KvStoreDataService kvStoreDataServiceTest; - int fd = 0; - std::map> params = {}; - EXPECT_NO_FATAL_FAILURE(kvStoreDataServiceTest.DumpUserInfo(fd, params)); -} - /** * @tc.name: DumpBundleInfo001 * @tc.desc: test DumpBundleInfo function diff --git a/services/distributeddataservice/framework/checker/checker_manager.cpp b/services/distributeddataservice/framework/checker/checker_manager.cpp index e02f50c64a219711e8456453445ac5c0bb8d33d3..739ff5ce6fec69087428a17f5ccc03e48ccf1093 100644 --- a/services/distributeddataservice/framework/checker/checker_manager.cpp +++ b/services/distributeddataservice/framework/checker/checker_manager.cpp @@ -47,6 +47,26 @@ void CheckerManager::RegisterPlugin(const std::string &checker, std::functionDeleteCache(bundleName, user, index); + } +} + +void CheckerManager::ClearCache() +{ + for (auto &[name, checker] : checkers_) { + if (checker == nullptr) { + continue; + } + checker->ClearCache(); + } +} + std::string CheckerManager::GetAppId(const StoreInfo &info) { for (auto &[name, checker] : checkers_) { diff --git a/services/distributeddataservice/framework/include/checker/checker_manager.h b/services/distributeddataservice/framework/include/checker/checker_manager.h index b0ad878e150a71fd97d486cdf014da85be637f33..f42f43c616b4a4f1b5626e6a8aa79f0ccf038270 100644 --- a/services/distributeddataservice/framework/include/checker/checker_manager.h +++ b/services/distributeddataservice/framework/include/checker/checker_manager.h @@ -53,6 +53,8 @@ public: virtual std::vector GetStaticStores() = 0; virtual bool IsDynamic(const StoreInfo &info) = 0; virtual bool IsStatic(const StoreInfo &info) = 0; + virtual void DeleteCache(const std::string &bundleName, int32_t user, int32_t index){}; + virtual void ClearCache(){}; protected: API_EXPORT ~Checker() = default; }; @@ -68,6 +70,8 @@ public: API_EXPORT bool IsSwitches(const StoreInfo &info); API_EXPORT void LoadCheckers(std::vector &checkers); API_EXPORT Checker *GetChecker(const std::string &checker); + API_EXPORT void DeleteCache(const std::string &bundleName, int32_t user, int32_t index); + API_EXPORT void ClearCache(); private: std::map checkers_; diff --git a/services/distributeddataservice/framework/include/metadata/appid_meta_data.h b/services/distributeddataservice/framework/include/metadata/appid_meta_data.h index 1707a360c45349d557dfa3e26331f39e9c0b6dfb..627440f1ad3a8a9f20d1c791d12f3be4307798ae 100644 --- a/services/distributeddataservice/framework/include/metadata/appid_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/appid_meta_data.h @@ -26,6 +26,7 @@ struct API_EXPORT AppIDMetaData final : public Serializable { API_EXPORT AppIDMetaData(); API_EXPORT AppIDMetaData(const std::string &appId, const std::string &bundleName); API_EXPORT ~AppIDMetaData(); + API_EXPORT bool operator==(const AppIDMetaData &appIdMetaData) const; API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; API_EXPORT std::string GetKey() const; diff --git a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h index cb546472bfc129b8d9db2b7b895c4fc64475e88b..57a95079d946236f2202e0332599dfdc3bc3447b 100644 --- a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h @@ -27,6 +27,8 @@ struct API_EXPORT SecretKeyMetaData final : public Serializable { API_EXPORT SecretKeyMetaData(); API_EXPORT ~SecretKeyMetaData(); + API_EXPORT bool operator==(const SecretKeyMetaData &secretKey) const; + API_EXPORT bool operator!=(const SecretKeyMetaData &secretKey) const; API_EXPORT bool Marshal(json &node) const override; API_EXPORT bool Unmarshal(const json &node) override; diff --git a/services/distributeddataservice/framework/metadata/appid_meta_data.cpp b/services/distributeddataservice/framework/metadata/appid_meta_data.cpp index 71b61792f33c04942b741756538c589cbeab79a3..1a1a7c856ecbfaf7c35b9aafd489e65847a14524 100644 --- a/services/distributeddataservice/framework/metadata/appid_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/appid_meta_data.cpp @@ -43,6 +43,11 @@ AppIDMetaData::~AppIDMetaData() { } +bool AppIDMetaData::operator==(const AppIDMetaData &appIdMetaData) const +{ + return (appId == appIdMetaData.appId && bundleName == appIdMetaData.bundleName); +} + std::string AppIDMetaData::GetKey() const { return appId; diff --git a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp index 3af423fb1c686d09c1adc5454ed0e84d5fb55586..08e1ef42f3a2756d53ae6c93c444c904c511db89 100644 --- a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp @@ -27,6 +27,17 @@ SecretKeyMetaData::~SecretKeyMetaData() nonce.assign(nonce.size(), 0); } +bool SecretKeyMetaData::operator==(const SecretKeyMetaData &secretKey) const +{ + return sKey == secretKey.sKey && nonce == secretKey.nonce && storeType == secretKey.storeType && + area == secretKey.area; +} + +bool SecretKeyMetaData::operator!=(const SecretKeyMetaData &secretKey) const +{ + return !(*this == secretKey); +} + bool SecretKeyMetaData::Marshal(json &node) const { SetValue(node[GET_NAME(time)], time); diff --git a/services/distributeddataservice/framework/screen/screen_manager.cpp b/services/distributeddataservice/framework/screen/screen_manager.cpp index 6b939376e54a8a5acb6047c262967a3908412025..c2f7d5d3ad7d5a6ade28f23a6c0a8220d3ff4551 100644 --- a/services/distributeddataservice/framework/screen/screen_manager.cpp +++ b/services/distributeddataservice/framework/screen/screen_manager.cpp @@ -39,6 +39,7 @@ bool ScreenManager::RegisterInstance(std::shared_ptr instance) return true; } +// LCOV_EXCL_START void ScreenManager::Subscribe(std::shared_ptr observer) { return; @@ -63,7 +64,7 @@ void ScreenManager::UnsubscribeScreenEvent() { return; } - +// LCOV_EXCL_STOP bool ScreenManager::IsLocked() { return false; diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn index 2f754c7c10efd11e33e9ec191100cb747fafa073..37a5bafddd07269758be7cb49b3601c027d7f709 100644 --- a/services/distributeddataservice/framework/test/BUILD.gn +++ b/services/distributeddataservice/framework/test/BUILD.gn @@ -366,7 +366,6 @@ ohos_unittest("ServiceMetaDataTest") { deps = [ "${data_service_path}/adapter/account:distributeddata_account", - "${data_service_path}/adapter/bundle_mgr:distributedata_bundlemgr", "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/utils:distributeddata_utils", "${data_service_path}/app/src/checker:distributeddata_checker", diff --git a/services/distributeddataservice/framework/test/fuzztest/BUILD.gn b/services/distributeddataservice/framework/test/fuzztest/BUILD.gn index b35cb67af178f4630b3f50d1f4cbd1170d81ff2c..e54fc7ba32202fb2ee7af39ea54a443214ea938e 100644 --- a/services/distributeddataservice/framework/test/fuzztest/BUILD.gn +++ b/services/distributeddataservice/framework/test/fuzztest/BUILD.gn @@ -18,8 +18,5 @@ import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") group("fuzztest") { testonly = true - deps = [ - "storedebuginfo_fuzzer:fuzztest", - "screenmanager_fuzzer:fuzztest", - ] + deps = [ "storedebuginfo_fuzzer:fuzztest" ] } \ No newline at end of file diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn index b0cfab3778c3c9456474daa915167f2216b42daf..799699962afa099106f9e7689d8452ef1fc65e57 100644 --- a/services/distributeddataservice/service/BUILD.gn +++ b/services/distributeddataservice/service/BUILD.gn @@ -71,7 +71,6 @@ ohos_shared_library("distributeddatasvc") { deps = [ "${data_service_path}/adapter/account:distributeddata_account", - "${data_service_path}/adapter/bundle_mgr:distributedata_bundlemgr", "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/adapter/network:distributeddata_network", diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index 3179ab11376288d127fe3f4e7c81c42f98aaa90b..a1f141257df3005726d47cb56ef3601b201cdbe0 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -805,10 +805,10 @@ int32_t CloudServiceImpl::OnReady(const std::string &device) return NETWORK_ERROR; } for (auto user : users) { - DoKvCloudSync(user, "", MODE_ONLINE); Execute(GenTask(0, user, CloudSyncScene::NETWORK_RECOVERY, - { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB })); + { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_SUB })); } + syncManager_.OnNetworkConnected(); return SUCCESS; } @@ -825,6 +825,7 @@ int32_t CloudServiceImpl::Offline(const std::string &device) } auto it = users.begin(); syncManager_.StopCloudSync(*it); + syncManager_.OnNetworkDisconnected(); return SUCCESS; } diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp index d35bd45e87626780c474155eaf21e403ca03d144..ea2bc3db7a141858dac4bc1067d88bffd6b75cbe 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -16,6 +16,7 @@ #include "sync_manager.h" #include +#include #include "account/account_delegate.h" #include "bootstrap.h" @@ -47,6 +48,7 @@ using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Defer = EventCenter::Defer; std::atomic SyncManager::genId_ = 0; constexpr int32_t SYSTEM_USER_ID = 0; +constexpr int32_t NETWORK_DISCONNECT_TIMEOUT_HOURS = 20; static constexpr const char *FT_GET_STORE = "GET_STORE"; static constexpr const char *FT_CALLBACK = "CALLBACK"; SyncManager::SyncInfo::SyncInfo( @@ -364,6 +366,9 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount UpdateStartSyncInfo(cloudSyncInfos); auto code = IsValid(info, cloud); if (code != E_OK) { + if (code == E_NETWORK_ERROR) { + networkRecoveryManager_.RecordSyncApps(info.user_, info.bundleName_); + } BatchUpdateFinishState(cloudSyncInfos, code); BatchReport(info.user_, traceIds, SyncStage::END, code, "!IsValid"); return; @@ -510,6 +515,9 @@ bool SyncManager::HandleRetryFinished(const SyncInfo &info, int32_t user, int32_ if (code == E_OK || code == E_SYNC_TASK_MERGED) { return true; } + if (code == E_NETWORK_ERROR) { + networkRecoveryManager_.RecordSyncApps(user, info.bundleName_); + } info.SetError(code); RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_, dbCode }, @@ -1081,4 +1089,94 @@ int32_t SyncManager::ConvertValidGeneralCode(int32_t code) { return (code >= E_OK && code < E_BUSY) ? code : E_ERROR; } + +void SyncManager::OnNetworkDisconnected() +{ + networkRecoveryManager_.OnNetworkDisconnected(); +} + +void SyncManager::OnNetworkConnected() +{ + networkRecoveryManager_.OnNetworkConnected(); +} + +void SyncManager::NetworkRecoveryManager::OnNetworkDisconnected() +{ + ZLOGI("network disconnected."); + std::lock_guard lock(eventMutex_); + currentEvent_ = std::make_unique(); + currentEvent_->disconnectTime = std::chrono::system_clock::now(); +} + +void SyncManager::NetworkRecoveryManager::OnNetworkConnected() +{ + std::unique_ptr event; + { + std::lock_guard lock(eventMutex_); + if (currentEvent_ == nullptr) { + ZLOGE("network connected, but currentEvent_ is not initialized."); + return; + } + event = std::move(currentEvent_); + } + auto now = std::chrono::system_clock::now(); + auto duration = now - event->disconnectTime; + auto hours = std::chrono::duration_cast(duration).count(); + bool timeout = (hours > NETWORK_DISCONNECT_TIMEOUT_HOURS); + std::vector users; + if (!Account::GetInstance()->QueryForegroundUsers(users) || users.empty()) { + ZLOGE("no foreground user, skip sync."); + return; + } + for (auto user : users) { + const auto &syncApps = timeout ? GetAppList(user) : event->syncApps[user]; + for (const auto &bundleName : syncApps) { + ZLOGI("sync start bundleName:%{public}s, user:%{public}d", bundleName.c_str(), user); + syncManager_.DoCloudSync(SyncInfo(user, bundleName, "", {}, MODE_ONLINE)); + } + } + ZLOGI("network connected success, network disconnect duration :%{public}ld hours", hours); +} + +void SyncManager::NetworkRecoveryManager::RecordSyncApps(const int32_t user, const std::string &bundleName) +{ + std::lock_guard lock(eventMutex_); + if (currentEvent_ != nullptr) { + auto &syncApps = currentEvent_->syncApps[user]; + if (std::find(syncApps.begin(), syncApps.end(), bundleName) == syncApps.end()) { + syncApps.push_back(bundleName); + ZLOGI("record sync user:%{public}d, bundleName:%{public}s", user, bundleName.c_str()); + } + } +} + +std::vector SyncManager::NetworkRecoveryManager::GetAppList(const int32_t user) +{ + CloudInfo cloud; + cloud.user = user; + if (!MetaDataManager::GetInstance().LoadMeta(cloud.GetKey(), cloud, true)) { + ZLOGE("load cloud info fail, user:%{public}d", user); + return {}; + } + const size_t totalCount = cloud.apps.size(); + std::vector appList; + appList.reserve(totalCount); + std::unordered_set uniqueSet; + uniqueSet.reserve(totalCount); + auto addApp = [&](std::string bundleName) { + if (uniqueSet.insert(bundleName).second) { + appList.push_back(std::move(bundleName)); + } + }; + auto stores = CheckerManager::GetInstance().GetDynamicStores(); + auto staticStores = CheckerManager::GetInstance().GetStaticStores(); + stores.insert(stores.end(), staticStores.begin(), staticStores.end()); + for (const auto &store : stores) { + addApp(std::move(store.bundleName)); + } + for (const auto &[_, app] : cloud.apps) { + addApp(std::move(app.bundleName)); + } + return appList; +} } // namespace OHOS::CloudData \ No newline at end of file diff --git a/services/distributeddataservice/service/cloud/sync_manager.h b/services/distributeddataservice/service/cloud/sync_manager.h index a24f0ae6649a07bb18c8ec6dd8ea8882972cc0be..1e152ca1016457eb312abe14e37f94438aebc057 100644 --- a/services/distributeddataservice/service/cloud/sync_manager.h +++ b/services/distributeddataservice/service/cloud/sync_manager.h @@ -104,8 +104,29 @@ public: void OnScreenUnlocked(int32_t user); void CleanCompensateSync(int32_t userId); static std::string GetPath(const StoreMetaData &meta); + void OnNetworkDisconnected(); + void OnNetworkConnected(); private: + class NetworkRecoveryManager { + public: + explicit NetworkRecoveryManager(SyncManager &syncManager) : syncManager_(syncManager) + { + } + void OnNetworkDisconnected(); + void OnNetworkConnected(); + void RecordSyncApps(const int32_t user, const std::string &bundleName); + + private: + std::vector GetAppList(const int32_t user); + struct NetWorkEvent { + std::chrono::system_clock::time_point disconnectTime; + std::map> syncApps; + }; + std::mutex eventMutex_; + std::unique_ptr currentEvent_; + SyncManager &syncManager_; + }; using Event = DistributedData::Event; using Task = ExecutorPool::Task; using TaskId = ExecutorPool::TaskId; @@ -149,7 +170,7 @@ private: const std::string &message = ""); static void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, int32_t code); - static bool HandleRetryFinished(const SyncInfo &info, int32_t user, int32_t code, int32_t dbCode, + bool HandleRetryFinished(const SyncInfo &info, int32_t user, int32_t code, int32_t dbCode, const std::string &prepareTraceId); Task GetSyncTask(int32_t times, bool retry, RefCount ref, SyncInfo &&syncInfo); void UpdateSchema(const SyncInfo &syncInfo); @@ -185,6 +206,7 @@ private: ConcurrentMap> lastSyncInfos_; std::set kvApps_; ConcurrentMap>> compensateSyncInfos_; + NetworkRecoveryManager networkRecoveryManager_{ *this }; }; } // namespace OHOS::CloudData #endif // OHOS_DISTRIBUTED_DATA_SERVICES_CLOUD_SYNC_MANAGER_H \ No newline at end of file diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn index 788eceec20f2224e530a7c8ab12c7646d772dd0a..f39ed7a352025105123f426dfcf3974d0ed09567 100644 --- a/services/distributeddataservice/service/data_share/BUILD.gn +++ b/services/distributeddataservice/service/data_share/BUILD.gn @@ -130,7 +130,6 @@ ohos_source_set("data_share_service") { "hicollie:libhicollie", "hilog:libhilog", "hisysevent:libhisysevent", - "init:libbegetutil", "ipc:ipc_core", "json:nlohmann_json_static", "kv_store:datamgr_common", diff --git a/services/distributeddataservice/service/data_share/common/db_delegate.cpp b/services/distributeddataservice/service/data_share/common/db_delegate.cpp index 9e77bcbb4dece55fc62f1ac907b7be2f95bbed01..2915b83f8deb1be8b1c051281a57aacd1b7cc01c 100644 --- a/services/distributeddataservice/service/data_share/common/db_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/db_delegate.cpp @@ -145,9 +145,9 @@ void DBDelegate::StartTimer(bool encrypt) dstTaskIdTemp = Executor::INVALID_TASK_ID; }; if (encrypt) { - stores_.DoActionIfEmpty(task); - } else { storesEncrypt_.DoActionIfEmpty(task); + } else { + stores_.DoActionIfEmpty(task); } }, std::chrono::seconds(INTERVAL), std::chrono::seconds(INTERVAL)); diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp index 1c2375d436fc28151aa10bed469093ab6922e147..d9f4d194c0a7f093cd4088eb2aeb298c64459ebb 100644 --- a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp @@ -282,7 +282,7 @@ std::pair KvDelegate::Upsert(const std::string &collectionName int version = -1; if (GetVersion(collectionName, id, version)) { if (value.GetVersion() <= version) { - ZLOGE("GetVersion failed,%{public}s id %{private}s %{public}d %{public}d", collectionName.c_str(), + ZLOGE("GetVersion failed,%{public}s id %{public}s %{public}d %{public}d", collectionName.c_str(), id.c_str(), value.GetVersion(), version); return std::make_pair(E_VERSION_NOT_NEWER, 0); } diff --git a/services/distributeddataservice/service/data_share/common/proxy_data_manager.cpp b/services/distributeddataservice/service/data_share/common/proxy_data_manager.cpp index 18a7b53638bba26d8af0210612673f6166ae8932..8a9988e0c401e94e7e8333b63500074246cc894a 100644 --- a/services/distributeddataservice/service/data_share/common/proxy_data_manager.cpp +++ b/services/distributeddataservice/service/data_share/common/proxy_data_manager.cpp @@ -337,7 +337,7 @@ int32_t PublishedProxyData::Delete(const std::string &uri, const BundleInfo &cal ProxyDataNode oldData; if (!ProxyDataNode::Unmarshall(queryResult, oldData)) { - ZLOGE("Unmarshall failed, %{private}s", queryResult.c_str()); + ZLOGE("Unmarshall failed, %{public}s", StringUtils::GeneralAnonymous(queryResult).c_str()); return INNER_ERROR; } if (callerBundleInfo.tokenId != oldData.tokenId) { diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp index 940f599c448413ab291344275d46ff19207f4951..2edad984d468c517a0ede1053320ece226cfc9e4 100644 --- a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp @@ -31,6 +31,7 @@ #include "scheduler_manager.h" #include "string_wrapper.h" #include "utils/anonymous.h" +#include "utils.h" #include "want_params.h" #include "db_delegate.h" #include "log_debug.h" @@ -298,7 +299,7 @@ std::string RdbDelegate::Query(const std::string &sql, const std::vectorQueryByStep(sql, selectionArgs); if (resultSet == nullptr) { - ZLOGE("Query failed %{private}s", sql.c_str()); + ZLOGE("Query failed %{public}s", StringUtils::GeneralAnonymous(sql).c_str()); return ""; } int rowCount; @@ -318,7 +319,7 @@ std::shared_ptr RdbDelegate::QuerySql(const std::string &s } auto resultSet = store_->QuerySql(sql); if (resultSet == nullptr) { - ZLOGE("Query failed %{private}s", sql.c_str()); + ZLOGE("Query failed %{public}s", StringUtils::GeneralAnonymous(sql).c_str()); return resultSet; } int rowCount; @@ -375,4 +376,4 @@ bool RdbDelegate::IsLimit(int count, int32_t callingPid, uint32_t callingTokenId HiViewFaultAdapter::ReportDataFault(faultInfo); return true; } -} // namespace OHOS::DataShare \ No newline at end of file +} // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp index fa7ec6a969581674ccc00a3ed10535173db59c8d..d8a87a67db954a61d92b3825f7e60b3f74f67627 100644 --- a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp +++ b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp @@ -209,14 +209,14 @@ void SchedulerManager::SetTimer( duration, key.subscriberId, key.bundleName.c_str()); auto it = timerCache_.find(key); if (it != timerCache_.end()) { - ZLOGD_MACRO("has current taskId: %{private}s, subscriberId is %{public}" PRId64 ", bundleName is %{public}s", + ZLOGD_MACRO("has current taskId: %{public}s, subscriberId is %{public}" PRId64 ", bundleName is %{public}s", URIUtils::Anonymous(key.uri).c_str(), key.subscriberId, key.bundleName.c_str()); auto timerId = it->second; ResetTimerTask(timerId, reminderTime); return; } auto callback = [key, metaData, userId, this]() { - ZLOGI("schedule notify start, uri is %{private}s, subscriberId is %{public}" PRId64 ", bundleName is " + ZLOGI("schedule notify start, uri is %{public}s, subscriberId is %{public}" PRId64 ", bundleName is " "%{public}s", URIUtils::Anonymous(key.uri).c_str(), key.subscriberId, key.bundleName.c_str()); int64_t timerId = EraseTimerTaskId(key); diff --git a/services/distributeddataservice/service/data_share/data/template_data.cpp b/services/distributeddataservice/service/data_share/data/template_data.cpp index 79219aedefc4cb40bb85498c80b35a826049e236..af7bbb26ea18202f8f68a1fbcfd83b86942a7b78 100644 --- a/services/distributeddataservice/service/data_share/data/template_data.cpp +++ b/services/distributeddataservice/service/data_share/data/template_data.cpp @@ -15,6 +15,8 @@ #define LOG_TAG "TemplateData" #include "template_data.h" #include "log_print.h" +#include "utils.h" + namespace OHOS::DataShare { bool TemplateNode::Marshal(DistributedData::Serializable::json &node) const { @@ -121,7 +123,7 @@ int32_t TemplateData::Query(const std::string &filter, Template &aTemplate) } TemplateRootNode data; if (!DistributedData::Serializable::Unmarshall(queryResult, data)) { - ZLOGE("Unmarshall failed, %{private}s", queryResult.c_str()); + ZLOGE("Unmarshall failed, %{public}s", StringUtils::GeneralAnonymous(queryResult).c_str()); return E_ERROR; } aTemplate = data.ToTemplate(); @@ -207,4 +209,4 @@ bool PredicatesNode::Unmarshal(const DistributedData::Serializable::json &node) ret = ret && GetValue(node, GET_NAME(selectSql), selectSql); return ret; } -} // namespace OHOS::DataShare \ No newline at end of file +} // namespace OHOS::DataShare diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index 0b3e7c81b499d48ccdcf57dac0174ae10c8379ca..23a91bd71dab6b06bba070f64e38a80ce9446fcc 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -60,7 +60,6 @@ #include "utils/anonymous.h" #include "xcollie.h" #include "log_debug.h" -#include "parameters.h" #include "dataproxy_handle_common.h" #include "proxy_data_manager.h" #include "datashare_observer.h" @@ -262,9 +261,9 @@ int32_t DataShareServiceImpl::AddTemplate(const std::string &uri, const int64_t ZLOGE("get bundleName error, %{public}s", URIUtils::Anonymous(uri).c_str()); return ERROR; } - ZLOGI("Add template, uri %{private}s, subscriberId %{public}" PRIi64 ", bundleName %{public}s," + ZLOGI("Add template, uri %{public}s, subscriberId %{public}" PRIi64 ", bundleName %{public}s," "predicates size %{public}zu.", - uri.c_str(), subscriberId, tpltId.bundleName_.c_str(), tplt.predicates_.size()); + URIUtils::Anonymous(uri).c_str(), subscriberId, tpltId.bundleName_.c_str(), tplt.predicates_.size()); return templateStrategy_.Execute(context, [&uri, &tpltId, &tplt, &context]() -> int32_t { auto result = TemplateManager::GetInstance().Add( Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->visitedUserId, tplt); @@ -282,7 +281,7 @@ int32_t DataShareServiceImpl::DelTemplate(const std::string &uri, const int64_t ZLOGE("get bundleName error, %{public}s", URIUtils::Anonymous(uri).c_str()); return ERROR; } - ZLOGI("Delete template, uri %{private}s, subscriberId %{public}" PRIi64 ", bundleName %{public}s.", + ZLOGI("Delete template, uri %{public}s, subscriberId %{public}" PRIi64 ", bundleName %{public}s.", URIUtils::Anonymous(uri).c_str(), subscriberId, tpltId.bundleName_.c_str()); return templateStrategy_.Execute(context, [&uri, &tpltId, &context]() -> int32_t { return TemplateManager::GetInstance().Delete( @@ -871,15 +870,15 @@ int32_t DataShareServiceImpl::OnAppUpdate(const std::string &bundleName, int32_t void DataShareServiceImpl::NotifyObserver(const std::string &uri) { auto anonymous = URIUtils::Anonymous(uri); - ZLOGD_MACRO("%{private}s try notified", anonymous.c_str()); + ZLOGD_MACRO("%{public}s try notified", anonymous.c_str()); auto context = std::make_shared(uri); if (!GetCallerBundleName(context->callerBundleName)) { - ZLOGE("get bundleName error, %{private}s", anonymous.c_str()); + ZLOGE("get bundleName error, %{public}s", anonymous.c_str()); return; } auto ret = rdbNotifyStrategy_.Execute(context); if (ret) { - ZLOGI("%{private}s start notified", anonymous.c_str()); + ZLOGI("%{public}s start notified", anonymous.c_str()); RdbSubscriberManager::GetInstance().Emit(uri, context); } } @@ -1144,8 +1143,7 @@ bool DataShareServiceImpl::VerifyAcrossAccountsPermission(int32_t currentUserId, if (currentUserId == 0 || currentUserId == visitedUserId) { return true; } - return system::GetBoolParameter(CONNECT_SUPPORT_CROSS_USER, false) && - PermitDelegate::VerifyPermission(acrossAccountsPermission, callerTokenId); + return PermitDelegate::VerifyPermission(acrossAccountsPermission, callerTokenId); } std::pair DataShareServiceImpl::ExecuteEx(const std::string &uri, const std::string &extUri, diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.h b/services/distributeddataservice/service/data_share/data_share_service_impl.h index 41b2965e584bdcb1b660c8659e854106e9678da8..c86cf2fa26163fe1dae231d1ce204d46df9717f4 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.h +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.h @@ -160,7 +160,6 @@ private: static constexpr const char *PROXY_URI_SCHEMA = "datashareproxy"; static constexpr const char *EXT_URI_SCHEMA = "datashare://"; static constexpr const char *NO_PERMISSION = "noPermission"; - static constexpr const char *CONNECT_SUPPORT_CROSS_USER = "const.abilityms.connect_support_cross_user"; PublishStrategy publishStrategy_; GetDataStrategy getDataStrategy_; SubscribeStrategy subscribeStrategy_; diff --git a/services/distributeddataservice/service/dumper/src/dump_helper.cpp b/services/distributeddataservice/service/dumper/src/dump_helper.cpp index 04c125b06b043335b06342a2fa3fabec516990e0..287033dbd3d7c8103aa2e87e4ec98870d372f561 100644 --- a/services/distributeddataservice/service/dumper/src/dump_helper.cpp +++ b/services/distributeddataservice/service/dumper/src/dump_helper.cpp @@ -264,9 +264,9 @@ void DumpHelper::DumpHelpInfo(int fd, std::map\nwhere possible options include:\n%s\nWhen -u/-u , -b/-b " - " or -s/-s is simultaneously selected,\nwe display the lowest level statistics where -u " - "> -b > -s\nand the statistics is filterd by the upper level options\n", + "Usage: hidumper -s 1301 -a \nwhere possible options include:\n%s\nWhen -b/-b " + " or -s/-s is simultaneously selected,\nwe display the lowest level statistics where " + "-b > -s\nand the statistics is filterd by the upper level options\n", info.c_str()); } diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp index b825f970c85d4e4392cb8a82c523df6d05ec1819..f18d59547fa5cbb3b8d3605abf5c8d9c1dba174c 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.cpp @@ -443,8 +443,8 @@ std::pair KVDBGeneralStore::Sync(const Devices &devices, GenQu dbStatus = delegate_->UnSubscribeRemoteQuery(devices, GetDBSyncCompleteCB(std::move(async)), dbQuery, false); } else if (syncMode < NEARBY_END) { - DeviceSyncOption syncOption = { .devices = devices, .mode = dbMode, .query = dbQuery, .isWait = false, - .isRetry = syncParam.isRetry }; + DeviceSyncOption syncOption = { .devices = devices, .mode = dbMode, .isQuery = !kvQuery->IsEmpty(), + .query = dbQuery, .isWait = false, .isRetry = syncParam.isRetry }; dbStatus = delegate_->Sync(syncOption, GetDBSyncCompleteCB(std::move(async))); } else { ZLOGE("Err sync mode! sync mode:%{public}d", syncMode); diff --git a/services/distributeddataservice/service/kvdb/kvdb_general_store.h b/services/distributeddataservice/service/kvdb/kvdb_general_store.h index 80e030f05502be847d9d51d4c89f70fc2ca9d1f3..b5849b0182705bfbd3ac8e54ceed7cfc52feefc5 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_general_store.h +++ b/services/distributeddataservice/service/kvdb/kvdb_general_store.h @@ -97,8 +97,8 @@ private: DBProcessCB GetDBProcessCB(DetailAsync async); DBStatus CloudSync(const Devices &devices, DistributedDB::SyncMode cloudSyncMode, DetailAsync async, int64_t wait, const std::string &prepareTraceId); - void GetIdentifierParams( - std::vector &devices, const std::vector &uuids, int32_t authType); + void GetIdentifierParams(std::vector &devices, + const std::vector &uuids, int32_t authType); void Report(const std::string &faultType, int32_t errCode, const std::string &appendix); class ObserverProxy : public DistributedDB::KvStoreObserver { public: diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index c497a1288eb9c3d409f49d361888856b94368bbb..5bce7eda4fb46886a5e4551eca23119f1459e490 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -104,9 +104,9 @@ void KVDBServiceImpl::Init() StoreMetaMapping meta(storeInfo); meta.deviceId = DMAdapter::GetInstance().GetLocalDevice().uuid; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true)) { + ZLOGE("meta empty, bundleName:%{public}s, storeId:%{public}s, user = %{public}s", meta.bundleName.c_str(), + meta.GetStoreAlias().c_str(), meta.user.c_str()); if (meta.user == "0") { - ZLOGE("meta empty, bundleName:%{public}s, storeId:%{public}s, user = %{public}s", - meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), meta.user.c_str()); return; } meta.user = "0"; diff --git a/services/distributeddataservice/service/object/src/object_service_impl.cpp b/services/distributeddataservice/service/object/src/object_service_impl.cpp index ff6d5ee3af5e31e993f6ab2e0808f161c010aaba..12346d8923df6270280a79737511edde2d39225d 100644 --- a/services/distributeddataservice/service/object/src/object_service_impl.cpp +++ b/services/distributeddataservice/service/object/src/object_service_impl.cpp @@ -416,20 +416,24 @@ ObjectServiceImpl::ObjectServiceImpl() void ObjectServiceImpl::RegisterObjectServiceInfo() { + // LCOV_EXCL_START DumpManager::Config serviceInfoConfig; serviceInfoConfig.fullCmd = "--feature-info"; serviceInfoConfig.abbrCmd = "-f"; serviceInfoConfig.dumpName = "FEATURE_INFO"; serviceInfoConfig.dumpCaption = { "| Display all the service statistics" }; DumpManager::GetInstance().AddConfig("FEATURE_INFO", serviceInfoConfig); + // LCOV_EXCL_STOP } void ObjectServiceImpl::RegisterHandler() { + // LCOV_EXCL_START Handler handler = [this](int fd, std::map> ¶ms) { DumpObjectServiceInfo(fd, params); }; DumpManager::GetInstance().AddHandler("FEATURE_INFO", uintptr_t(this), handler); + // LCOV_EXCL_STOP } void ObjectServiceImpl::DumpObjectServiceInfo(int fd, std::map> ¶ms) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 43c0c7cfb7742388bdae43d9884de443089ea025..b62f047ea50a692578e343317ac41748c4191696 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -914,13 +914,17 @@ void RdbServiceImpl::SaveSecretKeyMeta(const StoreMetaData &metaData, const std: auto encryptKey = CryptoManager::GetInstance().Encrypt(password, encryptParams); if (!encryptKey.empty() && !encryptParams.nonce.empty()) { SecretKeyMetaData secretKey; + SecretKeyMetaData oldSecretKey; secretKey.storeType = metaData.storeType; secretKey.area = metaData.area; secretKey.sKey = encryptKey; secretKey.nonce = encryptParams.nonce; auto time = system_clock::to_time_t(system_clock::now()); secretKey.time = { reinterpret_cast(&time), reinterpret_cast(&time) + sizeof(time) }; - MetaDataManager::GetInstance().SaveMeta(metaData.GetSecretKey(), secretKey, true); + if (!MetaDataManager::GetInstance().LoadMeta(metaData.GetSecretKey(), oldSecretKey, true) || + secretKey != oldSecretKey) { + MetaDataManager::GetInstance().SaveMeta(metaData.GetSecretKey(), secretKey, true); + } } SecretKeyMetaData cloneKey; auto metaKey = metaData.GetCloneSecretKey(); @@ -988,8 +992,12 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) bool RdbServiceImpl::SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaData &old) { AppIDMetaData appIdMeta; + AppIDMetaData oldAppIdMeta; appIdMeta.bundleName = meta.bundleName; appIdMeta.appId = meta.appId; + if (MetaDataManager::GetInstance().LoadMeta(appIdMeta.GetKey(), oldAppIdMeta, true) && appIdMeta == oldAppIdMeta) { + return true; + } if (!MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true)) { ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, @@ -1741,6 +1749,12 @@ int32_t RdbServiceImpl::SavePromiseInfo(const StoreMetaData &metaData, const Rdb return RDB_OK; } StoreMetaDataLocal localMeta; + if (MetaDataManager::GetInstance().LoadMeta(metaData.GetKeyLocal(), localMeta, true)) { + if (param.tokenIds_ == localMeta.promiseInfo.tokenIds && param.uids_ == localMeta.promiseInfo.uids && + param.permissionNames_ == localMeta.promiseInfo.permissionNames) { + return RDB_OK; + } + } localMeta.promiseInfo.tokenIds = param.tokenIds_; localMeta.promiseInfo.uids = param.uids_; localMeta.promiseInfo.permissionNames = param.permissionNames_; diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 98c13fef7209ebd20d4b87ac18c56c8738452f45..5d0f0f1720bb73df1e519047e32e453b233ff417 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -188,6 +188,7 @@ ohos_unittest("CloudServiceImplTest") { "${data_service_path}/service/cloud/sync_strategies/network_sync_strategy.cpp", "${data_service_path}/service/test/mock/checker_mock.cpp", "cloud_service_impl_test.cpp", + "mock/account_delegate_mock.cpp", ] configs = [ ":module_private_config" ] diff --git a/services/distributeddataservice/service/test/cloud_service_impl_test.cpp b/services/distributeddataservice/service/test/cloud_service_impl_test.cpp index ed40cca5ad9eef4a73600c10d12b4b360a081ec5..6238c5271fd9fe30811acdcaad51a16f24565005 100644 --- a/services/distributeddataservice/service/test/cloud_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/cloud_service_impl_test.cpp @@ -39,6 +39,7 @@ #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" #include "metadata/store_meta_data_local.h" +#include "mock/account_delegate_mock.h" #include "mock/db_store_mock.h" #include "mock/general_store_mock.h" #include "mock/meta_data_manager_mock.h" @@ -69,6 +70,8 @@ static constexpr const char *TEST_CLOUD_BUNDLE = "test_cloud_bundleName"; static constexpr const char *TEST_CLOUD_APPID = "test_cloud_appid"; static constexpr const char *TEST_CLOUD_STORE = "test_cloud_store"; static constexpr const char *TEST_CLOUD_DATABASE_ALIAS_1 = "test_cloud_database_alias_1"; +constexpr const int32_t DISCONNECT_TIME = 21; +constexpr const int32_t MOCK_USER = 200; class CloudServiceImplTest : public testing::Test { public: static void SetUpTestCase(void); @@ -80,9 +83,12 @@ public: static void CheckDelMeta(StoreMetaMapping &metaMapping, StoreMetaData &meta, StoreMetaData &meta1); static std::shared_ptr cloudServiceImpl_; static NetworkDelegateMock delegate_; + static auto ReturnWithUserList(const std::vector& users); + protected: static std::shared_ptr dbStoreMock_; static StoreMetaData metaData_; + static inline AccountDelegateMock *accountDelegateMock = nullptr; }; std::shared_ptr CloudServiceImplTest::cloudServiceImpl_ = std::make_shared(); @@ -127,12 +133,22 @@ void CloudServiceImplTest::InitMetaData() metaData_.dataDir = "/test_cloud_service_impl_store"; } +auto CloudServiceImplTest::ReturnWithUserList(const std::vector &users) +{ + return Invoke([=](std::vector &outUsers) -> bool { + outUsers = users; + return true; + }); +} + void CloudServiceImplTest::SetUpTestCase(void) { size_t max = 12; size_t min = 5; auto executor = std::make_shared(max, min); DeviceManagerAdapter::GetInstance().Init(executor); + cloudServiceImpl_->OnBind( + { "CloudServiceImplTest", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); Bootstrap::GetInstance().LoadCheckers(); CryptoManager::GetInstance().GenerateRootKey(); MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, ""); @@ -961,5 +977,181 @@ HWTEST_F(ComponentConfigTest, ComponentConfig, TestSize.Level0) EXPECT_EQ(node["constructor"], componentConfig.constructor); EXPECT_EQ(node["destructor"], componentConfig.destructor); } + +/** + * @tc.name: NetworkRecoveryTest001 + * @tc.desc: test the compensatory sync strategy for network disconnection times of less than 20 hours + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(CloudServiceImplTest, NetworkRecoveryTest001, TestSize.Level0) +{ + ASSERT_NE(cloudServiceImpl_, nullptr); + accountDelegateMock = new (std::nothrow) AccountDelegateMock(); + ASSERT_NE(accountDelegateMock, nullptr); + AccountDelegate::instance_ = nullptr; + AccountDelegate::RegisterAccountInstance(accountDelegateMock); + + EXPECT_CALL(*accountDelegateMock, IsLoginAccount()).WillOnce(Return(true)); + EXPECT_CALL(*accountDelegateMock, IsVerified(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*accountDelegateMock, QueryUsers(_)).WillOnce(ReturnWithUserList({ MOCK_USER })); + // 2 means that the QueryForegroundUsers interface will be called twice + EXPECT_CALL(*accountDelegateMock, QueryForegroundUsers(_)) + .Times(2) + .WillRepeatedly(ReturnWithUserList({ MOCK_USER })); + EXPECT_CALL(*accountDelegateMock, GetUserByToken(_)).WillOnce(Return(MOCK_USER)); + delegate_.isNetworkAvailable_ = false; + CloudInfo::AppInfo appInfo; + appInfo.bundleName = TEST_CLOUD_BUNDLE; + appInfo.cloudSwitch = true; + std::map apps; + apps.emplace(TEST_CLOUD_BUNDLE, appInfo); + CloudInfo cloudInfo; + cloudInfo.apps = apps; + cloudInfo.user = MOCK_USER; + cloudInfo.enableCloud = true; + MetaDataManager::GetInstance().SaveMeta(cloudInfo.GetKey(), cloudInfo, true); + auto &recoveryManager = cloudServiceImpl_->syncManager_.networkRecoveryManager_; + cloudServiceImpl_->Offline(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + ASSERT_NE(recoveryManager.currentEvent_, nullptr); + + SchemaMeta schemaMeta; + schemaMeta.bundleName = TEST_CLOUD_BUNDLE; + SchemaMeta::Database database; + database.name = TEST_CLOUD_STORE; + schemaMeta.databases.emplace_back(database); + MetaDataManager::GetInstance().SaveMeta(CloudInfo::GetSchemaKey(cloudInfo.user, TEST_CLOUD_BUNDLE), schemaMeta, + true); + CloudData::CloudService::Option option; + option.syncMode = DistributedData::GeneralStore::CLOUD_BEGIN; + auto async = [](const DistributedRdb::Details &details) {}; + cloudServiceImpl_->CloudSync(TEST_CLOUD_BUNDLE, TEST_CLOUD_STORE, option, async); + EXPECT_CALL(*accountDelegateMock, GetUserByToken(_)).WillOnce(Return(MOCK_USER)); + cloudServiceImpl_->CloudSync(TEST_CLOUD_BUNDLE, TEST_CLOUD_STORE, option, async); + sleep(1); + EXPECT_EQ(recoveryManager.currentEvent_->syncApps.size(), 1); + delegate_.isNetworkAvailable_ = true; + cloudServiceImpl_->OnReady(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + EXPECT_EQ(recoveryManager.currentEvent_, nullptr); +} + +/** + * @tc.name: NetworkRecoveryTest002 + * @tc.desc: test the compensatory sync strategy for network disconnection times of more than 20 hours + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(CloudServiceImplTest, NetworkRecoveryTest002, TestSize.Level0) +{ + ASSERT_NE(cloudServiceImpl_, nullptr); + EXPECT_CALL(*accountDelegateMock, IsVerified(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*accountDelegateMock, IsLoginAccount()).WillOnce(Return(true)); + EXPECT_CALL(*accountDelegateMock, QueryUsers(_)).WillOnce(Invoke([&](std::vector &users) -> bool { + users = { MOCK_USER }; + return true; + })); + // 2 means that the QueryForegroundUsers interface will be called twice + EXPECT_CALL(*accountDelegateMock, QueryForegroundUsers(_)) + .Times(2) + .WillRepeatedly(ReturnWithUserList({ MOCK_USER })); + auto &recoveryManager = cloudServiceImpl_->syncManager_.networkRecoveryManager_; + cloudServiceImpl_->Offline(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + ASSERT_NE(recoveryManager.currentEvent_, nullptr); + recoveryManager.currentEvent_->disconnectTime -= std::chrono::hours(DISCONNECT_TIME); + cloudServiceImpl_->OnReady(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + EXPECT_EQ(recoveryManager.currentEvent_, nullptr); +} + +/** + * @tc.name: NetworkRecoveryTest003 + * @tc.desc: The test only calls the network connection interface but not disconnect + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(CloudServiceImplTest, NetworkRecoveryTest003, TestSize.Level0) +{ + ASSERT_NE(cloudServiceImpl_, nullptr); + EXPECT_CALL(*accountDelegateMock, IsVerified(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*accountDelegateMock, IsLoginAccount()).WillOnce(Return(true)); + EXPECT_CALL(*accountDelegateMock, QueryForegroundUsers(_)).WillOnce(ReturnWithUserList({ MOCK_USER })); + auto &recoveryManager = cloudServiceImpl_->syncManager_.networkRecoveryManager_; + CloudData::CloudService::Option option; + option.syncMode = DistributedData::GeneralStore::CLOUD_BEGIN; + auto async = [](const DistributedRdb::Details &details) {}; + EXPECT_CALL(*accountDelegateMock, GetUserByToken(_)).WillOnce(Return(MOCK_USER)); + cloudServiceImpl_->CloudSync(TEST_CLOUD_BUNDLE, TEST_CLOUD_STORE, option, async); + sleep(1); + cloudServiceImpl_->OnReady(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + EXPECT_EQ(recoveryManager.currentEvent_, nullptr); +} + +/** + * @tc.name: NetworkRecoveryTest004 + * @tc.desc: The QueryForegroundUsers interface call fails when the network is restored + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(CloudServiceImplTest, NetworkRecoveryTest004, TestSize.Level0) +{ + ASSERT_NE(cloudServiceImpl_, nullptr); + EXPECT_CALL(*accountDelegateMock, IsVerified(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*accountDelegateMock, QueryUsers(_)).WillOnce(ReturnWithUserList({ MOCK_USER })); + cloudServiceImpl_->Offline(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + auto &recoveryManager = cloudServiceImpl_->syncManager_.networkRecoveryManager_; + ASSERT_NE(recoveryManager.currentEvent_, nullptr); + + EXPECT_CALL(*accountDelegateMock, IsLoginAccount()).WillOnce(Return(true)); + EXPECT_CALL(*accountDelegateMock, QueryForegroundUsers(_)) + .WillOnce(ReturnWithUserList({ MOCK_USER })) + .WillOnce(Return(false)); + cloudServiceImpl_->OnReady(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + EXPECT_EQ(recoveryManager.currentEvent_, nullptr); + + EXPECT_CALL(*accountDelegateMock, QueryUsers(_)).WillOnce(ReturnWithUserList({ MOCK_USER })); + cloudServiceImpl_->Offline(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + ASSERT_NE(recoveryManager.currentEvent_, nullptr); + EXPECT_CALL(*accountDelegateMock, IsLoginAccount()).WillOnce(Return(true)); + EXPECT_CALL(*accountDelegateMock, QueryForegroundUsers(_)) + .WillOnce(ReturnWithUserList({ MOCK_USER })) + .WillOnce(ReturnWithUserList({})); + cloudServiceImpl_->OnReady(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + EXPECT_EQ(recoveryManager.currentEvent_, nullptr); +} + +/** + * @tc.name: NetworkRecoveryTest005 + * @tc.desc: The test network connection interface call fails when the load cloudInfo failed + * @tc.type: FUNC + * @tc.require: + * @tc.author: + */ +HWTEST_F(CloudServiceImplTest, NetworkRecoveryTest005, TestSize.Level0) +{ + ASSERT_NE(cloudServiceImpl_, nullptr); + EXPECT_CALL(*accountDelegateMock, IsVerified(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*accountDelegateMock, IsLoginAccount()).WillOnce(Return(true)); + EXPECT_CALL(*accountDelegateMock, QueryUsers(_)).WillOnce(ReturnWithUserList({ MOCK_USER })); + // 2 means that the QueryForegroundUsers interface will be called twice + EXPECT_CALL(*accountDelegateMock, QueryForegroundUsers(_)) + .Times(2) + .WillRepeatedly(ReturnWithUserList({ MOCK_USER })); + CloudInfo cloudInfo; + cloudInfo.user = MOCK_USER; + MetaDataManager::GetInstance().DelMeta(cloudInfo.GetKey(), true); + auto &recoveryManager = cloudServiceImpl_->syncManager_.networkRecoveryManager_; + cloudServiceImpl_->Offline(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + ASSERT_NE(recoveryManager.currentEvent_, nullptr); + recoveryManager.currentEvent_->disconnectTime -= std::chrono::hours(DISCONNECT_TIME); + cloudServiceImpl_->OnReady(DeviceManagerAdapter::CLOUD_DEVICE_UUID); + EXPECT_EQ(recoveryManager.currentEvent_, nullptr); + if (accountDelegateMock != nullptr) { + delete accountDelegateMock; + accountDelegateMock = nullptr; + } +} } // namespace DistributedDataTest } // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/BUILD.gn index 107fde072f00517c48d248546298c1d07c45abc9..6dd680bddd17f5ab4b50dcc87f545b0acdfbb1f1 100644 --- a/services/distributeddataservice/service/test/fuzztest/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/BUILD.gn @@ -30,7 +30,9 @@ group("fuzztest") { if (datamgr_service_object) { deps += [ "objectservicestub_fuzzer:fuzztest", - "objectserviceimp_fuzzer:fuzztest", + "objectserviceimp1_fuzzer:fuzztest", + "objectserviceimp2_fuzzer:fuzztest", + "objectserviceimp3_fuzzer:fuzztest", "objectservicelistener_fuzzer:fuzztest", ] } diff --git a/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/BUILD.gn index baa4fa6efdd1a20dfbe11b2d162431452b184ad8..22cb65f5eabc12299009aa89a9c72b7fd14d7bce 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/BUILD.gn @@ -98,6 +98,7 @@ ohos_fuzztest("DataShareServiceImplFuzzTest") { "${data_service_path}/service/data_share/sys_event_subscriber.cpp", "${data_service_path}/service/kvdb/user_delegate.cpp", "${data_service_path}/service/permission/src/permit_delegate.cpp", + "${data_service_path}/service/permission/src/permission_validator.cpp", "datashareserviceimpl_fuzzer.cpp", ] diff --git a/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/datashareserviceimpl_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/datashareserviceimpl_fuzzer.cpp index 83644b248371376d72cb6b254448f89af95edfc3..a61ead41633ff12b695bce18cd71d892e6736131 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/datashareserviceimpl_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/datashareserviceimpl_fuzzer/datashareserviceimpl_fuzzer.cpp @@ -172,6 +172,8 @@ void TimerReceiverOnReceiveEventFuzz(FuzzedDataProvider &provider) { DataShareServiceImpl::TimerReceiver tmerReceiver; EventFwk::Want want; + std::string action = provider.ConsumeRandomLengthString(); + want.SetAction(action); EventFwk::CommonEventData commonEventData(want); commonEventData.SetWant(want); tmerReceiver.OnReceiveEvent(commonEventData); @@ -336,12 +338,6 @@ void SaveLaunchInfoFuzz(FuzzedDataProvider &provider) dataShareServiceImpl->SaveLaunchInfo(bundleName, userId, deviceId); } -void OnConnectDoneFuzz(FuzzedDataProvider &provider) -{ - std::shared_ptr dataShareServiceImpl = std::make_shared(); - dataShareServiceImpl->OnConnectDone(); -} - void DataShareStaticOnAppUpdate(FuzzedDataProvider &provider) { DataShareServiceImpl::DataShareStatic dataShareStatic; @@ -357,6 +353,7 @@ void EnableSilentProxyFuzz(FuzzedDataProvider &provider) std::string uri = provider.ConsumeRandomLengthString(); bool enable = provider.ConsumeBool(); dataShareServiceImpl->EnableSilentProxy(uri, enable); + dataShareServiceImpl->OnConnectDone(); } } // namespace OHOS @@ -392,7 +389,6 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) OHOS::SubscribePublishedDataFuzz(provider); OHOS::DisablePubSubsFuzz(provider); OHOS::SaveLaunchInfoFuzz(provider); - OHOS::OnConnectDoneFuzz(provider); OHOS::DataShareStaticOnAppUpdate(provider); OHOS::EnableSilentProxyFuzz(provider); return 0; diff --git a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn index 5824983758ed23c0ab72fde32937e49601f7e9c2..2b158d7b0a95be9140237aabefa3c2909174fe55 100644 --- a/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/datashareservicestub_fuzzer/BUILD.gn @@ -96,6 +96,7 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "${data_service_path}/service/data_share/sys_event_subscriber.cpp", "${data_service_path}/service/kvdb/user_delegate.cpp", "${data_service_path}/service/permission/src/permit_delegate.cpp", + "${data_service_path}/service/permission/src/permission_validator.cpp", "datashareservicestub_fuzzer.cpp", ] @@ -126,7 +127,6 @@ ohos_fuzztest("DataShareServiceStubFuzzTest") { "hilog:libhilog", "hisysevent:libhisysevent", "huks:libhukssdk", - "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddb", diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/BUILD.gn similarity index 94% rename from services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/BUILD.gn rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/BUILD.gn index 039f0bf8e697b736d46a178f9b682e1b763e54d1..8d654ce30dbfb53d27aa58e48d760a2358a10283 100644 --- a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/BUILD.gn @@ -16,7 +16,7 @@ import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") ##############################fuzztest########################################## -ohos_fuzztest("ObjectServiceImpFuzzTest") { +ohos_fuzztest("ObjectServiceImp1FuzzTest") { module_out_path = "datamgr_service/datamgr_service" include_dirs = [ @@ -24,7 +24,7 @@ ohos_fuzztest("ObjectServiceImpFuzzTest") { ] fuzz_config_file = - "${data_service_path}/service/test/fuzztest/objectserviceimp_fuzzer" + "${data_service_path}/service/test/fuzztest/objectserviceimp1_fuzzer" cflags = [ "-g", @@ -35,7 +35,7 @@ ohos_fuzztest("ObjectServiceImpFuzzTest") { ] sources = [ - "objectserviceimp_fuzzer.cpp", + "objectserviceimp1_fuzzer.cpp", ] deps = [ @@ -69,6 +69,6 @@ ohos_fuzztest("ObjectServiceImpFuzzTest") { group("fuzztest") { testonly = true - deps = [ ":ObjectServiceImpFuzzTest" ] + deps = [ ":ObjectServiceImp1FuzzTest" ] } ############################################################################### diff --git a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/corpus/init b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/corpus/init similarity index 100% rename from services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/corpus/init rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/corpus/init diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/objectserviceimp1_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/objectserviceimp1_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..000754166c4d6ae8c81cfa5c1fa9db97a8e19f33 --- /dev/null +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/objectserviceimp1_fuzzer.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "objectserviceimp1_fuzzer.h" +#include "object_service_impl.h" +#include "account/account_delegate.h" + +using namespace OHOS::DistributedObject; + +namespace OHOS { + +void ObjectStoreSaveFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + sptr callback; + std::string bundleName = provider.ConsumeRandomLengthString(100); + std::string sessionId = provider.ConsumeRandomLengthString(100); + std::string deviceId = provider.ConsumeRandomLengthString(100); + std::map> data; + std::vector remainingData = provider.ConsumeRemainingBytes(); + data["key1"] = remainingData; + objectServiceImpl->ObjectStoreSave(bundleName, sessionId, deviceId, data, callback); +} + +void OnUserChangeFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + uint32_t code = static_cast(AccountStatus::DEVICE_ACCOUNT_SWITCHED); + std::string user = provider.ConsumeRandomLengthString(100); + std::string account = provider.ConsumeRandomLengthString(100); + objectServiceImpl->OnUserChange(code, user, account); +} + +void ObjectStoreRevokeSaveFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + sptr callback; + std::string bundleName = provider.ConsumeRandomLengthString(100); + std::string sessionId = provider.ConsumeRandomLengthString(100); + objectServiceImpl->ObjectStoreRevokeSave(bundleName, sessionId, callback); +} + +void ObjectStoreRetrieveFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + sptr callback; + std::string bundleName = provider.ConsumeRandomLengthString(100); + std::string sessionId = provider.ConsumeRandomLengthString(100); + objectServiceImpl->ObjectStoreRetrieve(bundleName, sessionId, callback); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + FuzzedDataProvider provider(data, size); + OHOS::ObjectStoreSaveFuzzTest(provider); + OHOS::OnUserChangeFuzzTest(provider); + OHOS::ObjectStoreRevokeSaveFuzzTest(provider); + OHOS::ObjectStoreRetrieveFuzzTest(provider); + return 0; +} \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/objectserviceimp_fuzzer.h b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/objectserviceimp1_fuzzer.h similarity index 78% rename from services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/objectserviceimp_fuzzer.h rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/objectserviceimp1_fuzzer.h index 8aa6bb0e28c86ea002b8918d3a5c0d7c35a67a0e..9969aa5a538be8b77b9a829015555fb47f54f7d9 100644 --- a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/objectserviceimp_fuzzer.h +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/objectserviceimp1_fuzzer.h @@ -13,9 +13,9 @@ * limitations under the License. */ -#ifndef OBJECT_SERVICE_IMP_FUZZER_H -#define OBJECT_SERVICE_IMP_FUZZER_H +#ifndef OBJECT_SERVICE_IMP1_FUZZER_H +#define OBJECT_SERVICE_IMP1_FUZZER_H -#define FUZZ_PROJECT_NAME "objectserviceimp_fuzzer" +#define FUZZ_PROJECT_NAME "objectserviceimp1_fuzzer" -#endif // OBJECT_SERVICE_IMP_FUZZER_H \ No newline at end of file +#endif // OBJECT_SERVICE_IMP1_FUZZER_H \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/project.xml b/services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/project.xml similarity index 100% rename from services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/project.xml rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp1_fuzzer/project.xml diff --git a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/BUILD.gn similarity index 56% rename from services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/BUILD.gn rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/BUILD.gn index f063faa15c3e8a5a0e1e28ad2119271ce4a6930b..57ebaece81c81df0660dd472bfe8eafd4f0bdc58 100644 --- a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/BUILD.gn @@ -16,33 +16,52 @@ import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") ##############################fuzztest########################################## -ohos_fuzztest("ScreenManagerFuzzTest") { +ohos_fuzztest("ObjectServiceImp2FuzzTest") { module_out_path = "datamgr_service/datamgr_service" include_dirs = [ - "${data_service_path}/framework/include", + "${data_service_path}/service/object/include", ] fuzz_config_file = - "${data_service_path}/framework/test/fuzztest/screenmanager_fuzzer" - - sources = [ "screenmanager_fuzzer.cpp" ] + "${data_service_path}/service/test/fuzztest/objectserviceimp2_fuzzer" cflags = [ "-g", "-O0", "-Wno-unused-variable", "-fno-omit-frame-pointer", + "-fno-access-control", + ] + + sources = [ + "objectserviceimp2_fuzzer.cpp", ] deps = [ + "${data_service_path}/adapter/account:distributeddata_account", + "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/object:distributeddata_object", ] external_deps = [ - "c_utils:utils", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "data_object:data_object_inner", + "data_object:distributeddataobject_impl", + "device_manager:devicemanagersdk", + "dfs_service:distributed_file_daemon_kit_inner", + "dmsfwk:distributed_sdk", "hilog:libhilog", - "kv_store:datamgr_common", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", ] } @@ -50,6 +69,6 @@ ohos_fuzztest("ScreenManagerFuzzTest") { group("fuzztest") { testonly = true - deps = [ ":ScreenManagerFuzzTest" ] + deps = [ ":ObjectServiceImp2FuzzTest" ] } -############################################################################### \ No newline at end of file +############################################################################### diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/corpus/init b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/corpus/init similarity index 100% rename from services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/corpus/init rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/corpus/init diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/objectserviceimp2_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/objectserviceimp2_fuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19775458e02b536a18cc5726461d9c35eff67cdc --- /dev/null +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/objectserviceimp2_fuzzer.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "objectserviceimp2_fuzzer.h" +#include "object_service_impl.h" +#include "account/account_delegate.h" + +using namespace OHOS::DistributedObject; + +namespace OHOS { + +void RegisterDataObserverFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + sptr callback; + std::string bundleName = provider.ConsumeRandomLengthString(100); + std::string sessionId = provider.ConsumeRandomLengthString(100); + objectServiceImpl->RegisterDataObserver(bundleName, sessionId, callback); +} + +void OnAppUninstallFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + std::string bundleName = provider.ConsumeRandomLengthString(100); + int32_t user = provider.ConsumeIntegral(); + int32_t index = provider.ConsumeIntegral(); + objectServiceImpl->factory_.staticActs_->OnAppUninstall(bundleName, user, index); +} + +void ResolveAutoLaunchFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + std::string identifier = provider.ConsumeRandomLengthString(100); + DistributedDB::AutoLaunchParam param; + objectServiceImpl->ResolveAutoLaunch(identifier, param); +} + +void OnAppExitFuzzTest(FuzzedDataProvider &provider) +{ + std::shared_ptr objectServiceImpl = std::make_shared(); + pid_t uid = provider.ConsumeIntegral(); + pid_t pid = provider.ConsumeIntegral(); + uint32_t tokenId = provider.ConsumeIntegral(); + std::string bundleName = provider.ConsumeRandomLengthString(100); + objectServiceImpl->OnAppExit(uid, pid, tokenId, bundleName); +} +} // namespace OHOS + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + FuzzedDataProvider provider(data, size); + OHOS::RegisterDataObserverFuzzTest(provider); + OHOS::OnAppUninstallFuzzTest(provider); + OHOS::ResolveAutoLaunchFuzzTest(provider); + OHOS::OnAppExitFuzzTest(provider); + return 0; +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/screenmanager_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/objectserviceimp2_fuzzer.h similarity index 45% rename from services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/screenmanager_fuzzer.cpp rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/objectserviceimp2_fuzzer.h index d944f95c32460f65b1dbaa5db93703e895cf2f26..0e38d64c098b9a92d522b28ab2f41a532d92f194 100644 --- a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/screenmanager_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/objectserviceimp2_fuzzer.h @@ -13,28 +13,9 @@ * limitations under the License. */ -#include -#include "screenmanager_fuzzer.h" -#include "screen/screen_manager.h" +#ifndef OBJECT_SERVICE_IMP2_FUZZER_H +#define OBJECT_SERVICE_IMP2_FUZZER_H -using namespace OHOS::DistributedData; +#define FUZZ_PROJECT_NAME "objectserviceimp2_fuzzer" -namespace OHOS { -void TestScreenManager(FuzzedDataProvider &provider) -{ - ScreenManager::GetInstance()->Subscribe(nullptr); - ScreenManager::GetInstance()->Unsubscribe(nullptr); - ScreenManager::GetInstance()->BindExecutor(nullptr); - ScreenManager::GetInstance()->SubscribeScreenEvent(); - ScreenManager::GetInstance()->UnsubscribeScreenEvent(); -} - -} // namespace OHOS - -/* Fuzzer entry point */ -extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) -{ - FuzzedDataProvider provider(data, size); - OHOS::TestScreenManager(provider); - return 0; -} \ No newline at end of file +#endif // OBJECT_SERVICE_IMP2_FUZZER_H \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/project.xml b/services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/project.xml similarity index 100% rename from services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/project.xml rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp2_fuzzer/project.xml diff --git a/services/distributeddataservice/adapter/bundle_mgr/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/BUILD.gn similarity index 30% rename from services/distributeddataservice/adapter/bundle_mgr/BUILD.gn rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/BUILD.gn index 93bb21bc3ce2157e61f30ba3750eebb27ea6028d..46a6be379d214b4d608b9a3dea5c2f72be7c5ae5 100644 --- a/services/distributeddataservice/adapter/bundle_mgr/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/BUILD.gn @@ -10,36 +10,65 @@ # WITHOUT 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") +##############################hydra-fuzz######################################## +import("//build/config/features.gni") +import("//build/test.gni") import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni") -ohos_source_set("distributedata_bundlemgr") { - branch_protector_ret = "pac_ret" - sanitize = { - cfi = true - cfi_cross_dso = true - debug = false - boundary_sanitize = true - ubsan = true - } - sources = [ "bundlemgr_adapter.cpp" ] +##############################fuzztest########################################## +ohos_fuzztest("ObjectServiceImp3FuzzTest") { + module_out_path = "datamgr_service/datamgr_service" - cflags_cc = [ "-fvisibility=hidden" ] + include_dirs = [ + "${data_service_path}/service/object/include", + ] - if (build_public_version) { - cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] - } + fuzz_config_file = + "${data_service_path}/service/test/fuzztest/objectserviceimp3_fuzzer" - include_dirs = [ "${data_service_path}/adapter/include/bundle_mgr" ] - ldflags = [ "-Wl,--exclude-libs,ALL" ] + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + "-fno-access-control", + ] + + sources = [ + "objectserviceimp3_fuzzer.cpp", + ] + + deps = [ + "${data_service_path}/adapter/account:distributeddata_account", + "${data_service_path}/adapter/communicator:distributeddata_communicator", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/object:distributeddata_object", + ] external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:dataobs_manager", "access_token:libaccesstoken_sdk", - "bundle_framework:appexecfwk_core", + "access_token:libtokenid_sdk", + "data_object:data_object_inner", + "data_object:distributeddataobject_impl", + "device_manager:devicemanagersdk", + "dfs_service:distributed_file_daemon_kit_inner", + "dmsfwk:distributed_sdk", "hilog:libhilog", - "kv_store:datamgr_common", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", ] - subsystem_name = "distributeddatamgr" - part_name = "datamgr_service" - defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] } + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":ObjectServiceImp3FuzzTest" ] +} +############################################################################### diff --git a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/screenmanager_fuzzer.h b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/corpus/init similarity index 80% rename from services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/screenmanager_fuzzer.h rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/corpus/init index ab2fe6fe3efc801f5bc6b74e8a7861e05babcbfb..7ade8a0faafeaedba7241e7d4a97b8e1f9691932 100644 --- a/services/distributeddataservice/framework/test/fuzztest/screenmanager_fuzzer/screenmanager_fuzzer.h +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/corpus/init @@ -13,9 +13,4 @@ * limitations under the License. */ -#ifndef SCREENMANAGER_FUZZER_H -#define SCREENMANAGER_FUZZER_H - -#define FUZZ_PROJECT_NAME "screenmanager_fuzzer" - -#endif // SCREENMANAGER_FUZZER_H +FUZZ \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/objectserviceimp_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/objectserviceimp3_fuzzer.cpp similarity index 44% rename from services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/objectserviceimp_fuzzer.cpp rename to services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/objectserviceimp3_fuzzer.cpp index de7adc4e9bf1bd6d6327991e3af180e96e7e32f3..fceecb58d8bc781aeebc88df22987fbbc0e2366a 100644 --- a/services/distributeddataservice/service/test/fuzztest/objectserviceimp_fuzzer/objectserviceimp_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/objectserviceimp3_fuzzer.cpp @@ -15,95 +15,14 @@ #include -#include "objectserviceimp_fuzzer.h" +#include "objectserviceimp3_fuzzer.h" #include "object_service_impl.h" #include "account/account_delegate.h" using namespace OHOS::DistributedObject; namespace OHOS { - -void ObjectStoreSaveFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - sptr callback; - std::string bundleName = provider.ConsumeRandomLengthString(100); - std::string sessionId = provider.ConsumeRandomLengthString(100); - std::string deviceId = provider.ConsumeRandomLengthString(100); - std::map> data; - std::vector remainingData = provider.ConsumeRemainingBytes(); - data["key1"] = remainingData; - objectServiceImpl->ObjectStoreSave(bundleName, sessionId, deviceId, data, callback); -} - -void OnUserChangeFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - uint32_t code = static_cast(AccountStatus::DEVICE_ACCOUNT_SWITCHED); - std::string user = provider.ConsumeRandomLengthString(100); - std::string account = provider.ConsumeRandomLengthString(100); - objectServiceImpl->OnUserChange(code, user, account); -} - -void ObjectStoreRevokeSaveFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - sptr callback; - std::string bundleName = provider.ConsumeRandomLengthString(100); - std::string sessionId = provider.ConsumeRandomLengthString(100); - objectServiceImpl->ObjectStoreRevokeSave(bundleName, sessionId, callback); -} - -void ObjectStoreRetrieveFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - sptr callback; - std::string bundleName = provider.ConsumeRandomLengthString(100); - std::string sessionId = provider.ConsumeRandomLengthString(100); - objectServiceImpl->ObjectStoreRetrieve(bundleName, sessionId, callback); -} - -void RegisterDataObserverFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - sptr callback; - std::string bundleName = provider.ConsumeRandomLengthString(100); - std::string sessionId = provider.ConsumeRandomLengthString(100); - objectServiceImpl->RegisterDataObserver(bundleName, sessionId, callback); -} - -void OnAppUninstallFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - if (objectServiceImpl->factory_.staticActs_ == nullptr) { - return; - } - std::string bundleName = provider.ConsumeRandomLengthString(100); - int32_t user = provider.ConsumeIntegral(); - int32_t index = provider.ConsumeIntegral(); - objectServiceImpl->factory_.staticActs_->OnAppUninstall(bundleName, user, index); -} - -void ResolveAutoLaunchFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - std::string identifier = provider.ConsumeRandomLengthString(100); - DistributedDB::AutoLaunchParam param; - objectServiceImpl->ResolveAutoLaunch(identifier, param); -} - -void OnAppExitFuzzTest(FuzzedDataProvider &provider) -{ - std::shared_ptr objectServiceImpl = std::make_shared(); - pid_t uid = provider.ConsumeIntegral(); - pid_t pid = provider.ConsumeIntegral(); - uint32_t tokenId = provider.ConsumeIntegral(); - std::string bundleName = provider.ConsumeRandomLengthString(100); - objectServiceImpl->OnAppExit(uid, pid, tokenId, bundleName); - objectServiceImpl->RegisterObjectServiceInfo(); - objectServiceImpl->RegisterHandler(); -} - + void DumpObjectServiceInfoFuzzTest(FuzzedDataProvider &provider) { std::shared_ptr objectServiceImpl = std::make_shared(); @@ -156,14 +75,6 @@ void BindAssetStoreFuzzTest(FuzzedDataProvider &provider) extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { FuzzedDataProvider provider(data, size); - OHOS::ObjectStoreSaveFuzzTest(provider); - OHOS::OnUserChangeFuzzTest(provider); - OHOS::ObjectStoreRevokeSaveFuzzTest(provider); - OHOS::ObjectStoreRetrieveFuzzTest(provider); - OHOS::RegisterDataObserverFuzzTest(provider); - OHOS::OnAppUninstallFuzzTest(provider); - OHOS::ResolveAutoLaunchFuzzTest(provider); - OHOS::OnAppExitFuzzTest(provider); OHOS::DumpObjectServiceInfoFuzzTest(provider); OHOS::SaveMetaDataFuzzTest(provider); OHOS::BindAssetStoreFuzzTest(provider); diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/objectserviceimp3_fuzzer.h b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/objectserviceimp3_fuzzer.h new file mode 100644 index 0000000000000000000000000000000000000000..a68ec2fe13519f5af00c54685af494cb478a4124 --- /dev/null +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/objectserviceimp3_fuzzer.h @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OBJECT_SERVICE_IMP3_FUZZER_H +#define OBJECT_SERVICE_IMP3_FUZZER_H + +#define FUZZ_PROJECT_NAME "objectserviceimp3_fuzzer" + +#endif // OBJECT_SERVICE_IMP3_FUZZER_H \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/project.xml b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..a37a23b1533f07ab59744732b0f46b2b5fd958d8 --- /dev/null +++ b/services/distributeddataservice/service/test/fuzztest/objectserviceimp3_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/BUILD.gn index 1be915e1eeb8cb45f524c5c23150e5c0921aeb27..2beeabbef2b7697a32dea655d744907efa9ee930 100644 --- a/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/BUILD.gn @@ -20,6 +20,7 @@ ohos_fuzztest("SyncStrategiesFuzzTest") { module_out_path = "datamgr_service/datamgr_service" include_dirs = [ + "${data_service_path}/adapter/network", "${data_service_path}/framework/include", "${data_service_path}/service/cloud", "${data_service_path}/service/common", @@ -40,6 +41,7 @@ ohos_fuzztest("SyncStrategiesFuzzTest") { deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx", + "${data_service_path}/adapter/network:distributeddata_network", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/cloud:distributeddata_cloud", "${data_service_path}/service/common:distributeddata_common", @@ -52,6 +54,7 @@ ohos_fuzztest("SyncStrategiesFuzzTest") { "access_token:libtoken_setproc", "access_token:libtokenid_sdk", "c_utils:utils", + "device_manager:devicemanagersdk", "hilog:libhilog", "json:nlohmann_json_static", "kv_store:datamgr_common", diff --git a/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/syncstrategies_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/syncstrategies_fuzzer.cpp index 2cf4591d3c4c8b83f6508c7d232574e4631d37e3..6a845885ebea47efaa32e302b88d59197578235e 100644 --- a/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/syncstrategies_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/syncstrategies_fuzzer/syncstrategies_fuzzer.cpp @@ -14,6 +14,7 @@ */ #include +#include "src/network_delegate_normal_impl.h" #include "syncstrategies_fuzzer.h" #include "sync_strategies/network_sync_strategy.h" @@ -25,6 +26,8 @@ void SyncStrategiesFuzz001(FuzzedDataProvider &provider) { int32_t user = provider.ConsumeIntegral(); std::string bundleName = provider.ConsumeRandomLengthString(100); + static NetworkDelegateNormalImpl delegate; + NetworkDelegate::RegisterNetworkInstance(&delegate); NetworkSyncStrategy strategy; StoreInfo storeInfo; storeInfo.user = user; diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index e40e04ef32966d50d40d7750f22de44ebe97e7e0..398162fcc317b76037c3d3ce7bb6fe90e603c982 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -44,7 +44,6 @@ ohos_fuzztest("UdmfServiceFuzzTest") { deps = [ "${data_service_path}/adapter/account:distributeddata_account", - "${data_service_path}/adapter/bundle_mgr:distributedata_bundlemgr", "${data_service_path}/adapter/communicator:distributeddata_communicator", "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/framework:distributeddatasvcfwk", diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/udmfservice_fuzzer.cpp b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/udmfservice_fuzzer.cpp index 59d2290c20b9e58d12e563ed55a2f3d345df4247..827a48d7c784e6cc8ebb603e1f3e469df210e06d 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/udmfservice_fuzzer.cpp +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/udmfservice_fuzzer.cpp @@ -387,7 +387,10 @@ void OnGetAppShareOptionFuzz(FuzzedDataProvider &provider) { "UdmfServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); MessageParcel requestUpdate; + std::vector remainingData = provider.ConsumeRemainingBytes(); requestUpdate.WriteInterfaceToken(INTERFACE_TOKEN); + requestUpdate.WriteBuffer(static_cast(remainingData.data()), remainingData.size()); + requestUpdate.RewindRead(0); CustomOption option = {.intention = Intention::UD_INTENTION_DRAG}; std::string intention = UD_INTENTION_MAP.at(option.intention); ITypesUtil::Marshal(requestUpdate, intention); @@ -658,16 +661,49 @@ void StoreSyncFuzz(FuzzedDataProvider &provider) void SetAppShareOptionFuzz(FuzzedDataProvider &provider) { std::shared_ptr udmfServiceImpl = std::make_shared(); - std::string intention = provider.ConsumeRandomLengthString(); - int32_t shareOption = provider.ConsumeIntegral(); - udmfServiceImpl->SetAppShareOption(intention, shareOption); + std::shared_ptr executor = std::make_shared(NUM_MAX, NUM_MIN); + udmfServiceImpl->OnBind( + { "UdmfServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); + + MessageParcel requestUpdate; + std::vector remainingData = provider.ConsumeRemainingBytes(); + requestUpdate.WriteInterfaceToken(INTERFACE_TOKEN); + requestUpdate.WriteBuffer(static_cast(remainingData.data()), remainingData.size()); + requestUpdate.RewindRead(0); + CustomOption option = {.intention = Intention::UD_INTENTION_DRAG}; + std::string intention = UD_INTENTION_MAP.at(option.intention); + ITypesUtil::Marshal(requestUpdate, intention); + + MessageParcel replyUpdate; + udmfServiceImpl->OnRemoteRequest(static_cast(UdmfServiceInterfaceCode::SET_APP_SHARE_OPTION), + requestUpdate, replyUpdate); + udmfServiceImpl->OnBind( + { "UdmfServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), nullptr }); + executor = nullptr; } void RemoveAppShareOptionFuzz(FuzzedDataProvider &provider) { std::shared_ptr udmfServiceImpl = std::make_shared(); - std::string intention = provider.ConsumeRandomLengthString(); - udmfServiceImpl->RemoveAppShareOption(intention); + std::shared_ptr executor = std::make_shared(NUM_MAX, NUM_MIN); + udmfServiceImpl->OnBind( + { "UdmfServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); + + MessageParcel requestUpdate; + std::vector remainingData = provider.ConsumeRemainingBytes(); + requestUpdate.WriteInterfaceToken(INTERFACE_TOKEN); + requestUpdate.WriteBuffer(static_cast(remainingData.data()), remainingData.size()); + requestUpdate.RewindRead(0); + CustomOption option = {.intention = Intention::UD_INTENTION_DRAG}; + std::string intention = UD_INTENTION_MAP.at(option.intention); + ITypesUtil::Marshal(requestUpdate, intention); + + MessageParcel replyUpdate; + udmfServiceImpl->OnRemoteRequest(static_cast(UdmfServiceInterfaceCode::REMOVE_APP_SHARE_OPTION), + requestUpdate, replyUpdate); + udmfServiceImpl->OnBind( + { "UdmfServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), nullptr }); + executor = nullptr; } void QueryDataCommonFuzz(FuzzedDataProvider &provider) @@ -698,8 +734,24 @@ void QueryDataCommonFuzz(FuzzedDataProvider &provider) void ClearAsynProcessByKeyFuzz(FuzzedDataProvider &provider) { std::shared_ptr udmfServiceImpl = std::make_shared(); + std::shared_ptr executor = std::make_shared(NUM_MAX, NUM_MIN); + udmfServiceImpl->OnBind( + { "UdmfServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), std::move(executor) }); + + MessageParcel requestUpdate; + std::vector remainingData = provider.ConsumeRemainingBytes(); + requestUpdate.WriteInterfaceToken(INTERFACE_TOKEN); + requestUpdate.WriteBuffer(static_cast(remainingData.data()), remainingData.size()); + requestUpdate.RewindRead(0); std::string businessUdKey = provider.ConsumeRandomLengthString(); - udmfServiceImpl->ClearAsynProcessByKey(businessUdKey); + ITypesUtil::Marshal(requestUpdate, businessUdKey); + + MessageParcel replyUpdate; + udmfServiceImpl->OnRemoteRequest(static_cast(UdmfServiceInterfaceCode::CLEAR_ASYN_PROCESS_BY_KEY), + requestUpdate, replyUpdate); + udmfServiceImpl->OnBind( + { "UdmfServiceStubFuzz", static_cast(IPCSkeleton::GetSelfTokenID()), nullptr }); + executor = nullptr; } void TransferToEntriesIfNeedFuzz(FuzzedDataProvider &provider) diff --git a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp index c34db72a617fcc3173e4615191b60aef0798a614..3566bb00790b96cd89b6509dd990ffe276c6cc99 100644 --- a/services/distributeddataservice/service/test/kvdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_general_store_test.cpp @@ -59,10 +59,9 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); - protected: - static constexpr const char *bundleName = "test_distributeddata"; - static constexpr const char *storeName = "test_service_meta"; + static constexpr const char *BUNDLE_NAME = "test_distributeddata"; + static constexpr const char *STORE_NAME = "test_service_meta"; void InitMetaData(); static std::vector Random(uint32_t len); @@ -76,15 +75,15 @@ static const uint32_t KEY_LENGTH = 32; void KVDBGeneralStoreTest::InitMetaData() { - metaData_.bundleName = bundleName; - metaData_.appId = bundleName; + metaData_.bundleName = BUNDLE_NAME; + metaData_.appId = BUNDLE_NAME; metaData_.user = "0"; metaData_.area = OHOS::DistributedKv::EL1; metaData_.instanceId = 0; metaData_.isAutoSync = true; metaData_.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; - metaData_.storeId = storeName; - metaData_.dataDir = "/data/service/el1/public/database/" + std::string(bundleName) + "/kvdb"; + metaData_.storeId = STORE_NAME; + metaData_.dataDir = "/data/service/el1/public/database/" + std::string(BUNDLE_NAME) + "/kvdb"; metaData_.securityLevel = SecurityLevel::S2; } @@ -404,7 +403,7 @@ HWTEST_F(KVDBGeneralStoreTest, BusyClose, TestSize.Level0) HWTEST_F(KVDBGeneralStoreTest, SyncTest, TestSize.Level0) { ZLOGI("SyncTest start"); - mkdir(("/data/service/el1/public/database/" + std::string(bundleName)).c_str(), + mkdir(("/data/service/el1/public/database/" + std::string(BUNDLE_NAME)).c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); @@ -540,14 +539,14 @@ HWTEST_F(KVDBGeneralStoreTest, CloudSync001, TestSize.Level0) { auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); - store->SetEqualIdentifier(bundleName, storeName); + store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME); KvStoreNbDelegateMock mockDelegate; store->delegate_ = &mockDelegate; std::vector devices = { "device1", "device2" }; auto asyncs = [](const GenDetails &result) {}; store->storeInfo_.user = 0; auto cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY; - store->SetEqualIdentifier(bundleName, storeName); + store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME); std::string prepareTraceId; std::vector users; EXPECT_CALL(*accountDelegateMock, QueryUsers(_)).Times(1).WillOnce(DoAll(SetArgReferee<0>(users), Return(false))); @@ -568,20 +567,22 @@ HWTEST_F(KVDBGeneralStoreTest, CloudSync002, TestSize.Level0) { auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); - store->SetEqualIdentifier(bundleName, storeName); + store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME); KvStoreNbDelegateMock mockDelegate; store->delegate_ = &mockDelegate; std::vector devices = { "device1", "device2" }; auto asyncs = [](const GenDetails &result) {}; store->storeInfo_.user = 0; auto cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY; - store->SetEqualIdentifier(bundleName, storeName); + store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME); std::string prepareTraceId; std::vector users; EXPECT_CALL(*accountDelegateMock, QueryUsers(_)) .Times(1) - .WillOnce( - DoAll(SetArgReferee<0>(users), Invoke([](std::vector &users) { users.clear(); }), Return(true))); + .WillOnce(DoAll( + SetArgReferee<0>(users), + Invoke([](std::vector& users) { users.clear(); }), + Return(true))); auto ret = store->CloudSync(devices, cloudSyncMode, asyncs, 0, prepareTraceId); EXPECT_EQ(ret, DBStatus::DB_ERROR); @@ -604,14 +605,14 @@ HWTEST_F(KVDBGeneralStoreTest, CloudSync003, TestSize.Level0) { auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); - store->SetEqualIdentifier(bundleName, storeName); + store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME); KvStoreNbDelegateMock mockDelegate; store->delegate_ = &mockDelegate; std::vector devices = { "device1", "device2" }; auto asyncs = [](const GenDetails &result) {}; store->storeInfo_.user = 0; auto cloudSyncMode = DistributedDB::SyncMode::SYNC_MODE_PUSH_ONLY; - store->SetEqualIdentifier(bundleName, storeName); + store->SetEqualIdentifier(BUNDLE_NAME, STORE_NAME); std::string prepareTraceId; std::vector users = {0, 1}; EXPECT_CALL(*accountDelegateMock, QueryUsers(_)) @@ -654,7 +655,7 @@ HWTEST_F(KVDBGeneralStoreTest, GetIdentifierParams, TestSize.Level0) */ HWTEST_F(KVDBGeneralStoreTest, Sync002, TestSize.Level0) { - mkdir(("/data/service/el1/public/database/" + std::string(bundleName)).c_str(), + mkdir(("/data/service/el1/public/database/" + std::string(BUNDLE_NAME)).c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); @@ -689,7 +690,7 @@ HWTEST_F(KVDBGeneralStoreTest, Sync002, TestSize.Level0) */ HWTEST_F(KVDBGeneralStoreTest, Sync003, TestSize.Level0) { - mkdir(("/data/service/el1/public/database/" + std::string(bundleName)).c_str(), + mkdir(("/data/service/el1/public/database/" + std::string(BUNDLE_NAME)).c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); @@ -974,7 +975,7 @@ HWTEST_F(KVDBGeneralStoreTest, GetDBOption001, TestSize.Level0) */ HWTEST_F(KVDBGeneralStoreTest, Sync001, TestSize.Level0) { - mkdir(("/data/service/el1/public/database/" + std::string(bundleName)).c_str(), + mkdir(("/data/service/el1/public/database/" + std::string(BUNDLE_NAME)).c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); auto store = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store, nullptr); @@ -1209,7 +1210,7 @@ HWTEST_F(KVDBGeneralStoreTest, ConstructorTest, TestSize.Level0) delete store3; // Test observer registration - metaData_.storeId = storeName; + metaData_.storeId = STORE_NAME; metaData_.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; auto store4 = new (std::nothrow) KVDBGeneralStore(metaData_); ASSERT_NE(store4, nullptr); diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index 039577976be7a8734d7a87fad25c39288a4dbbfc..1d0d7d625033cbec3f486044c71eda09b7c9fc87 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -325,6 +325,31 @@ HWTEST_F(KvdbServiceImplTest, OnInitialize001, TestSize.Level0) EXPECT_EQ(result, 1); // CODE_SYNC } +/** +* @tc.name: OnInitialize002 +* @tc.desc: OnInitialize function test. +* @tc.type: FUNC +* @tc.author: my +*/ +HWTEST_F(KvdbServiceImplTest, OnInitialize002, TestSize.Level0) +{ + auto result = kvdbServiceImpl_->OnInitialize(); + EXPECT_EQ(result, Status::SUCCESS); + DistributedData::StoreInfo storeInfo; + storeInfo.bundleName = "bundleName"; + storeInfo.storeName = "storeName"; + storeInfo.user = 100; + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillRepeatedly(testing::Return(true)); + + auto event = std::make_unique(CloudEvent::CLOUD_SYNC, storeInfo); + EXPECT_NE(event, nullptr); + result = EventCenter::GetInstance().PostEvent(move(event)); + EXPECT_EQ(result, 1); // CODE_SYNC +} + /** * @tc.name: GetStoreIdsTest001 * @tc.desc: GetStoreIds diff --git a/services/distributeddataservice/service/test/mock/distributed_file_daemon_manager_mock.h b/services/distributeddataservice/service/test/mock/distributed_file_daemon_manager_mock.h index cd68204fdba92f0a65aa554bd93f796e247974f1..eee09b060d2cc09804ccd1ee74f8908b87a1ef70 100644 --- a/services/distributeddataservice/service/test/mock/distributed_file_daemon_manager_mock.h +++ b/services/distributeddataservice/service/test/mock/distributed_file_daemon_manager_mock.h @@ -115,6 +115,18 @@ public: { return 0; } + int32_t RegisterFileDfsListener(const std::string &instanceId, const sptr &listener) override + { + return 0; + } + int32_t UnregisterFileDfsListener(const std::string &instanceId) override + { + return 0; + } + int32_t IsSameAccountDevice(const std::string &networkId, bool &isSameAccount) override + { + return 0; + } }; } // namespace DistributedFile } // namespace Storage diff --git a/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp b/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp index 7b7e648f109939bf02c65bcc6b71d6192f45bb4a..37238e41c4b1bcea9cc11f95e6abbdda68cfde60 100644 --- a/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp +++ b/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp @@ -82,13 +82,13 @@ int32_t PreProcessUtils::GetHapUidByToken(uint32_t tokenId, int &userId) return E_OK; } -bool PreProcessUtils::GetHapBundleNameByToken(int tokenId, std::string &bundleName) +bool PreProcessUtils::GetHapBundleNameByToken(uint32_t tokenId, std::string &bundleName) { bundleName = "processName"; return true; } -bool PreProcessUtils::GetNativeProcessNameByToken(int tokenId, std::string &processName) +bool PreProcessUtils::GetNativeProcessNameByToken(uint32_t tokenId, std::string &processName) { processName = "processName"; return true; @@ -188,8 +188,10 @@ bool PreProcessUtils::GetSpecificBundleName(const std::string &bundleName, int32 return true; } -bool PreProcessUtils::GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &bundleName) +bool PreProcessUtils::GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &specificBundleName, + std::string &bundleName) { + specificBundleName = "specificBundleName"; bundleName = "bundleName"; return true; } diff --git a/services/distributeddataservice/service/test/mock/preprocess_utils_mock.h b/services/distributeddataservice/service/test/mock/preprocess_utils_mock.h index e79e2bb6c6ea9e034cf3aa6930f685bf63c04c70..d71695fdbcad14b19e7f5d164e078c442949f84b 100644 --- a/services/distributeddataservice/service/test/mock/preprocess_utils_mock.h +++ b/services/distributeddataservice/service/test/mock/preprocess_utils_mock.h @@ -26,8 +26,8 @@ public: static std::string GenerateId(); static time_t GetTimestamp(); static int32_t GetHapUidByToken(uint32_t tokenId, int &userId); - static bool GetHapBundleNameByToken(int tokenId, std::string &bundleName); - static bool GetNativeProcessNameByToken(int tokenId, std::string &processName); + static bool GetHapBundleNameByToken(uint32_t tokenId, std::string &bundleName); + static bool GetNativeProcessNameByToken(uint32_t tokenId, std::string &processName); static std::string GetLocalDeviceId(); static void SetRemoteData(UnifiedData &data); static int32_t SetRemoteUri(uint32_t tokenId, UnifiedData &data); @@ -43,7 +43,8 @@ public: static void SetRecordUid(UnifiedData &data); static bool GetDetailsFromUData(const UnifiedData &data, UDDetails &details); static Status GetSummaryFromDetails(const UDDetails &details, Summary &summary); - static bool GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &bundleName); + static bool GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &specificBundleName, + std::string &bundleName); static std::string GetAppId(const std::string &bundleName); static sptr GetBundleMgr(); }; diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp index abe2488366efda20b6e61484c63261d102a69a26..f144db0ff33f5d7a7eaf7b850f10085b2a48ac81 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -25,6 +25,7 @@ #include "device_matrix.h" #include "event_center.h" #include "ipc_skeleton.h" +#include "metadata/appid_meta_data.h" #include "metadata/capability_meta_data.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" @@ -791,15 +792,34 @@ HWTEST_F(RdbServiceImplTest, AfterOpen002, TestSize.Level0) */ HWTEST_F(RdbServiceImplTest, AfterOpen003, TestSize.Level0) { - EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyWithoutPath(), metaData_, false), true); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true), true); RdbServiceImpl service; RdbSyncerParam param; param.bundleName_ = metaData_.bundleName; param.storeName_ = metaData_.storeId; + param.tokenIds_ = {123}; + param.uids_ = {123}; + param.permissionNames_ = {}; + AppIDMetaData appIdMeta; + appIdMeta.bundleName = metaData_.bundleName; + appIdMeta.appId = metaData_.appId; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true), true); + StoreMetaDataLocal localMeta; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyLocal(), localMeta, true), true); int32_t result = service.AfterOpen(param); - EXPECT_EQ(result, RDB_OK); EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyWithoutPath(), false), true); + param.tokenIds_ = {123}; + param.uids_ = {456}; + result = service.AfterOpen(param); + EXPECT_EQ(result, RDB_OK); + param.permissionNames_ = {"com.example.myapplication"}; + result = service.AfterOpen(param); + EXPECT_EQ(result, RDB_OK); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyLocal(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(appIdMeta.GetKey(), true), true); } /** diff --git a/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp index 93ea1516b8451fc3df93eaf167de190a0c963390..0ca8e3b2d4ec6e87c4fab2f08264fea705af809b 100644 --- a/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp +++ b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp @@ -16,6 +16,7 @@ #include "preprocess_utils.h" #include "gtest/gtest.h" #include "access_token_mock.h" +#include "ipc_skeleton.h" namespace OHOS::UDMF { using namespace testing; @@ -54,7 +55,7 @@ HWTEST_F(UdmfPreProcessUtilsMockTest, GetHapUidByToken001, TestSize.Level1) uint32_t tokenId = 0; int userId = 0; PreProcessUtils preProcessUtils; - EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillRepeatedly(Return(RET_SUCCESS)); int32_t ret = preProcessUtils.GetHapUidByToken(tokenId, userId); EXPECT_EQ(ret, E_OK); } @@ -70,8 +71,8 @@ HWTEST_F(UdmfPreProcessUtilsMockTest, GetInstIndex001, TestSize.Level1) uint32_t tokenId = 0; int32_t instIndex = 0; PreProcessUtils preProcessUtils; - EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillOnce(Return(TOKEN_HAP)); - EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillRepeatedly(Return(TOKEN_HAP)); + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillRepeatedly(Return(RET_SUCCESS)); bool ret = preProcessUtils.GetInstIndex(tokenId, instIndex); EXPECT_EQ(ret, true); } @@ -85,11 +86,12 @@ HWTEST_F(UdmfPreProcessUtilsMockTest, GetInstIndex001, TestSize.Level1) HWTEST_F(UdmfPreProcessUtilsMockTest, GetAlterableBundleNameByTokenId001, TestSize.Level1) { uint32_t tokenId = 0; - EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_FAILED)); - EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillOnce(Return(TOKEN_SHELL)); + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillRepeatedly(Return(RET_FAILED)); + EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillRepeatedly(Return(TOKEN_SHELL)); std::string bundleName = ""; + std::string specificBundleName = ""; PreProcessUtils preProcessUtils; - bool ret = preProcessUtils.GetSpecificBundleNameByTokenId(tokenId, bundleName); + bool ret = preProcessUtils.GetSpecificBundleNameByTokenId(tokenId, specificBundleName, bundleName); EXPECT_EQ(ret, false); } @@ -102,12 +104,13 @@ HWTEST_F(UdmfPreProcessUtilsMockTest, GetAlterableBundleNameByTokenId001, TestSi HWTEST_F(UdmfPreProcessUtilsMockTest, GetAlterableBundleNameByTokenId002, TestSize.Level1) { uint32_t tokenId = 999; - EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_FAILED)); - EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillOnce(Return(TOKEN_NATIVE)); - EXPECT_CALL(*accessTokenKitMock, GetNativeTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillRepeatedly(Return(RET_FAILED)); + EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillRepeatedly(Return(TOKEN_NATIVE)); + EXPECT_CALL(*accessTokenKitMock, GetNativeTokenInfo(_, _)).WillRepeatedly(Return(RET_SUCCESS)); std::string bundleName = ""; + std::string specificBundleName = ""; PreProcessUtils preProcessUtils; - bool ret = preProcessUtils.GetSpecificBundleNameByTokenId(tokenId, bundleName); + bool ret = preProcessUtils.GetSpecificBundleNameByTokenId(tokenId, specificBundleName, bundleName); EXPECT_EQ(ret, true); } @@ -120,10 +123,51 @@ HWTEST_F(UdmfPreProcessUtilsMockTest, GetAlterableBundleNameByTokenId002, TestSi HWTEST_F(UdmfPreProcessUtilsMockTest, GetAlterableBundleNameByTokenId003, TestSize.Level1) { uint32_t tokenId = 9999; - EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillOnce(Return(RET_SUCCESS)); + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillRepeatedly(Return(RET_SUCCESS)); std::string bundleName = ""; + std::string specificBundleName = ""; PreProcessUtils preProcessUtils; - bool ret = preProcessUtils.GetSpecificBundleNameByTokenId(tokenId, bundleName); + bool ret = preProcessUtils.GetSpecificBundleNameByTokenId(tokenId, specificBundleName, bundleName); EXPECT_EQ(ret, true); } + +/** +* @tc.name: GetAlterableBundleNameByTokenId004 +* @tc.desc: Abnormal test of GetSpecificBundleNameByTokenId for native +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsMockTest, GetAlterableBundleNameByTokenId004, TestSize.Level1) +{ + uint32_t tokenId = 999; + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillRepeatedly(Return(RET_FAILED)); + EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillRepeatedly(Return(TOKEN_NATIVE)); + EXPECT_CALL(*accessTokenKitMock, GetNativeTokenInfo(_, _)).WillRepeatedly(Return(RET_FAILED)); + std::string bundleName = ""; + std::string specificBundleName = ""; + PreProcessUtils preProcessUtils; + bool ret = preProcessUtils.GetSpecificBundleNameByTokenId(tokenId, specificBundleName, bundleName); + EXPECT_EQ(ret, false); +} + +/** +* @tc.name: FillRuntimeInfo001 +* @tc.desc: Normal test of FillRuntimeInfo +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfPreProcessUtilsMockTest, FillRuntimeInfo001, TestSize.Level1) +{ + EXPECT_CALL(*accessTokenKitMock, GetHapTokenInfo(_, _)).WillRepeatedly(Return(RET_FAILED)); + EXPECT_CALL(*accessTokenKitMock, GetTokenTypeFlag(_)).WillRepeatedly(Return(TOKEN_NATIVE)); + EXPECT_CALL(*accessTokenKitMock, GetNativeTokenInfo(_, _)).WillRepeatedly(Return(RET_SUCCESS)); + + UnifiedData data; + CustomOption option; + option.intention = UD_INTENTION_DATA_HUB; + option.tokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + PreProcessUtils preProcessUtils; + auto ret = preProcessUtils.FillRuntimeInfo(data, option); + EXPECT_EQ(ret, E_OK); +} }; // namespace UDMF \ No newline at end of file diff --git a/services/distributeddataservice/service/test/udmf_service_impl_mock_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_mock_test.cpp index 9daa166f47cbbd23c181584e9c5ac1e53bf42881..ec25391092b4b9e8184423dbfb993358c41a346b 100644 --- a/services/distributeddataservice/service/test/udmf_service_impl_mock_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_impl_mock_test.cpp @@ -73,25 +73,27 @@ HWTEST_F(UdmfServiceImplMockTest, IsNeedMetaSyncTest001, TestSize.Level0) StoreMetaData meta = StoreMetaData("100", "distributeddata", "drag"); std::vector devices = {"remote_device"}; - EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) - .WillOnce(Return(false)); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(false)); auto isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); EXPECT_EQ(isNeedSync, true); - EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) - .WillOnce(Return(false)); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(true)); isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); EXPECT_EQ(isNeedSync, true); - EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) - .WillOnce(Return(true)) - .WillOnce(Return(false)); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(true)) + .WillOnce(testing::Return(false)); isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); EXPECT_EQ(isNeedSync, true); - EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) - .WillOnce(Return(true)) - .WillOnce(Return(true)); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(true)) + .WillOnce(testing::Return(true)); isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); EXPECT_EQ(isNeedSync, true); } @@ -111,9 +113,9 @@ HWTEST_F(UdmfServiceImplMockTest, IsNeedMetaSyncTest002, TestSize.Level0) StoreMetaData meta = StoreMetaData("100", "distributeddata", "drag"); std::vector devices = {"remote_device"}; - EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) - .WillOnce(Return(false)) - .WillOnce(Return(false)); + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(false)); auto isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); EXPECT_EQ(isNeedSync, true); // mock mask diff --git a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp index 9a32e1587fb02ae3e7677a42a955c9476e9e38d4..541089c743ace704355e480b1607062a807c2b8d 100644 --- a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp @@ -32,13 +32,12 @@ #include "token_setproc.h" using namespace testing::ext; -using namespace OHOS::DistributedData; using namespace OHOS::Security::AccessToken; using namespace OHOS::UDMF; -using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Entry = DistributedDB::Entry; using Key = DistributedDB::Key; using Value = DistributedDB::Value; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using UnifiedData = OHOS::UDMF::UnifiedData; using Summary = OHOS::UDMF::Summary; namespace OHOS::Test { @@ -411,7 +410,7 @@ HWTEST_F(UdmfServiceImplTest, SyncTest001, TestSize.Level0) query.tokenId = 1; query.intention = UD_INTENTION_DRAG; UdmfServiceImpl udmfServiceImpl; - StoreMetaData meta = StoreMetaData("100", "distributeddata", "drag"); + DistributedData::StoreMetaData meta = DistributedData::StoreMetaData("100", "distributeddata", "drag"); std::vector devices = {"remote_device"}; auto ret = udmfServiceImpl.Sync(query, devices); @@ -541,6 +540,164 @@ HWTEST_F(UdmfServiceImplTest, IsValidInput004, TestSize.Level1) EXPECT_FALSE(result); } +/** + * @tc.name: UpdateData002 + * @tc.desc: invalid parameter + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, UpdateData002, TestSize.Level1) +{ + QueryOption query; + query.intention = Intention::UD_INTENTION_DATA_HUB; + query.key = "udmf://DataHub/aaa/N]2fIEMbrJj@wp:jMuPa7"; + query.tokenId = 99999; + UnifiedData unifiedData; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + unifiedData.AddRecord(record1); + unifiedData.AddRecord(record2); + + UdmfServiceImpl impl; + EXPECT_NE(impl.UpdateData(query, unifiedData), E_OK); +} + +/** + * @tc.name: UpdateData003 + * @tc.desc: invalid parameter + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, UpdateData003, TestSize.Level1) +{ + QueryOption query; + query.intention = Intention::UD_INTENTION_DATA_HUB; + query.key = "udmf://DataHub/aaa/N]2fIEMbrJj@wp:jMuPa7"; + query.tokenId = static_cast(IPCSkeleton::GetCallingTokenID()); + UnifiedData unifiedData; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + unifiedData.AddRecord(record1); + unifiedData.AddRecord(record2); + + UdmfServiceImpl impl; + EXPECT_NE(impl.UpdateData(query, unifiedData), E_OK); +} + +/** + * @tc.name: UpdateData004 + * @tc.desc: invalid parameter + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, UpdateData004, TestSize.Level1) +{ + QueryOption query; + UnifiedData unifiedData; + + query.key = "invalid_key"; + UdmfServiceImpl impl; + EXPECT_EQ(impl.UpdateData(query, unifiedData), E_INVALID_PARAMETERS); +} + +/** +* @tc.name: SaveData002 +* @tc.desc: invalid parameter +* @tc.type: FUNC +*/ +HWTEST_F(UdmfServiceImplTest, SaveData002, TestSize.Level1) +{ + CustomOption option; + QueryOption query; + UnifiedData unifiedData; + std::string key = ""; + + UdmfServiceImpl impl; + EXPECT_EQ(impl.SaveData(option, unifiedData, key), E_INVALID_PARAMETERS); +} + +/** +* @tc.name: SaveData003 +* @tc.desc: invalid parameter +* @tc.type: FUNC +*/ +HWTEST_F(UdmfServiceImplTest, SaveData003, TestSize.Level1) +{ + CustomOption option; + QueryOption query; + UnifiedData unifiedData; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + unifiedData.AddRecord(record1); + unifiedData.AddRecord(record2); + std::string key = ""; + option.intention = Intention::UD_INTENTION_BASE; + + UdmfServiceImpl impl; + EXPECT_EQ(impl.SaveData(option, unifiedData, key), E_INVALID_PARAMETERS); +} + +/** +* @tc.name: SaveData004 +* @tc.desc: invalid parameter +* @tc.type: FUNC +*/ +HWTEST_F(UdmfServiceImplTest, SaveData004, TestSize.Level1) +{ + CustomOption option; + QueryOption query; + UnifiedData unifiedData; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + unifiedData.AddRecord(record1); + unifiedData.AddRecord(record2); + std::string key = ""; + option.intention = Intention::UD_INTENTION_DATA_HUB; + option.tokenId = 99999; + + UdmfServiceImpl impl; + EXPECT_NE(impl.SaveData(option, unifiedData, key), E_OK); +} + +/** + * @tc.name: IsValidInput005 + * @tc.desc: valid input + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, IsValidInput005, TestSize.Level1) +{ + QueryOption query; + query.intention = Intention::UD_INTENTION_DRAG; + query.key = "udmf://drag/aaa/N]2fIEMbrJj@wp:jMuPa7"; + UnifiedData unifiedData; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + unifiedData.AddRecord(record1); + unifiedData.AddRecord(record2); + UnifiedKey key("udmf://drag/aaa/N]2fIEMbrJj@wp:jMuPa7"); + EXPECT_TRUE(key.IsValid()); + + UdmfServiceImpl impl; + bool result = impl.IsValidInput(query, unifiedData, key); + EXPECT_FALSE(result); +} + +/** + * @tc.name: PushDelayData001 + * @tc.desc: valid input + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, PushDelayData001, TestSize.Level1) +{ + UnifiedData unifiedData; + auto record1 = std::make_shared(); + auto record2 = std::make_shared(); + unifiedData.AddRecord(record1); + unifiedData.AddRecord(record2); + std::string key = "invalid key"; + + UdmfServiceImpl impl; + auto result = impl.PushDelayData(key, unifiedData); + EXPECT_NE(result, E_OK); +} + /** * @tc.name: CheckAppId001 * @tc.desc: invalid bundleName @@ -676,5 +833,158 @@ HWTEST_F(UdmfServiceImplTest, VerifyDataAccessPermission002, TestSize.Level1) EXPECT_EQ(runtime->privileges[0].tokenId, query.tokenId); EXPECT_EQ(result, OHOS::UDMF::E_OK); } + +/** + * @tc.name: HandleDelayLoad001 + * @tc.desc: Returns true when data not arrives + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, HandleDelayLoad001, TestSize.Level1) +{ + QueryOption query; + query.key = "k1"; + query.tokenId = 123; + + UnifiedData result; + int32_t res = UDMF::E_OK; + + UdmfServiceImpl service; + service.dataLoadCallback_.Insert(query.key, nullptr); + + using CacheData = BlockData, std::chrono::milliseconds>; + UdmfServiceImpl::BlockDelayData data; + data.tokenId = query.tokenId; + data.blockData = std::make_shared(100); + service.blockDelayDataCache_.Insert(query.key, data); + + bool handled = service.HandleDelayLoad(query, result, res); + + service.dataLoadCallback_.Erase(query.key); + service.blockDelayDataCache_.Erase(query.key); + + EXPECT_TRUE(handled); + EXPECT_EQ(res, UDMF::E_NOT_FOUND); +} + +/** + * @tc.name: HandleDelayLoad002 + * @tc.desc: Returns false when not exist + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, HandleDelayLoad002, TestSize.Level1) +{ + QueryOption query; + query.key = "k1"; + query.tokenId = 123; + + UnifiedData result; + int32_t res = UDMF::E_OK; + + UdmfServiceImpl service; + bool handled = service.HandleDelayLoad(query, result, res); + + EXPECT_FALSE(handled); +} + +/** + * @tc.name: HandleDelayLoad003 + * @tc.desc: Returns true when data arrives + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, HandleDelayLoad003, TestSize.Level1) +{ + QueryOption query; + query.key = "k1"; + query.tokenId = 123; + + UnifiedData result; + int32_t res = UDMF::E_OK; + + UnifiedData insertedData; + insertedData.AddRecord(std::make_shared()); + + UdmfServiceImpl service; + service.dataLoadCallback_.Insert(query.key, nullptr); + + using CacheData = BlockData, std::chrono::milliseconds>; + UdmfServiceImpl::BlockDelayData data; + data.tokenId = query.tokenId; + data.blockData = std::make_shared(100); + service.blockDelayDataCache_.Insert(query.key, data); + + data.blockData->SetValue(insertedData); + bool handled = service.HandleDelayLoad(query, result, res); + + EXPECT_TRUE(handled); + EXPECT_EQ(res, UDMF::E_OK); +} + +/** + * @tc.name: PushDelayData002 + * @tc.desc: DelayData callback and block cache not exist + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, PushDelayData002, TestSize.Level1) +{ + QueryOption query; + query.key = "k1"; + query.tokenId = 123; + UnifiedData insertedData; + insertedData.AddRecord(std::make_shared()); + + UdmfServiceImpl service; + auto status = service.PushDelayData(query.key, insertedData); + EXPECT_EQ(status, UDMF::E_ERROR); +} + +/** + * @tc.name: PushDelayData003 + * @tc.desc: No permission + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, PushDelayData003, TestSize.Level1) +{ + QueryOption query; + query.key = "k1"; + query.tokenId = 123; + + using CacheData = BlockData, std::chrono::milliseconds>; + UdmfServiceImpl::BlockDelayData data; + data.tokenId = query.tokenId; + data.blockData = std::make_shared(100); + UdmfServiceImpl service; + service.blockDelayDataCache_.Insert(query.key, data); + + UnifiedData insertedData; + auto status = service.PushDelayData(query.key, insertedData); + EXPECT_EQ(status, UDMF::E_NO_PERMISSION); +} + +/** + * @tc.name: PushDelayData004 + * @tc.desc: PushDelayData success + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplTest, PushDelayData004, TestSize.Level1) +{ + QueryOption query; + query.key = "k1"; + query.tokenId = IPCSkeleton::GetSelfTokenID(); + + using CacheData = BlockData, std::chrono::milliseconds>; + UdmfServiceImpl::BlockDelayData data; + data.tokenId = query.tokenId; + data.blockData = std::make_shared(100); + UdmfServiceImpl service; + service.blockDelayDataCache_.Insert(query.key, data); + + Privilege privilege; + privilege.tokenId = query.tokenId; + service.privilegeCache_[query.key] = privilege; + + UnifiedData insertedData; + auto status = service.PushDelayData(query.key, insertedData); + EXPECT_EQ(status, UDMF::E_OK); +} }; // namespace DistributedDataTest }; // namespace OHOS::Test diff --git a/services/distributeddataservice/service/udmf/BUILD.gn b/services/distributeddataservice/service/udmf/BUILD.gn index d1d7d3889b20f83f2aade1ca3ce2b8352b5c837b..6ac317304aabb349a8f08a37283c9d21f49a8e01 100644 --- a/services/distributeddataservice/service/udmf/BUILD.gn +++ b/services/distributeddataservice/service/udmf/BUILD.gn @@ -17,7 +17,6 @@ config("module_public_config") { visibility = [ ":*" ] include_dirs = [ - "${data_service_path}/adapter/include", "${data_service_path}/adapter/include/communicator", "${data_service_path}/service/matrix/include", "${data_service_path}/service/permission/include", diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp index f50c0f1c184ab5cb38202f13c6bef85c006aeb6e..9e7c45d1563629e1f42b2ae3522e045a5bc218af 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp @@ -16,13 +16,13 @@ #include "preprocess_utils.h" -#include #include #include "bundle_info.h" #include "dds_trace.h" #include "udmf_radar_reporter.h" #include "accesstoken_kit.h" +#include "checker/checker_manager.h" #include "device_manager_adapter.h" #include "file_mount_manager.h" #include "iservice_registry.h" @@ -33,7 +33,6 @@ #include "utils/crypto.h" #include "uri_permission_manager_client.h" #include "ipc_skeleton.h" -#include "bundle_mgr/bundlemgr_adapter.h" namespace OHOS { namespace UDMF { static constexpr int ID_LEN = 32; @@ -63,16 +62,17 @@ int32_t PreProcessUtils::FillRuntimeInfo(UnifiedData &data, CustomOption &option return E_ERROR; } std::string bundleName; - if (!GetSpecificBundleNameByTokenId(option.tokenId, bundleName)) { + std::string specificBundleName; + if (!GetSpecificBundleNameByTokenId(option.tokenId, specificBundleName, bundleName)) { ZLOGE("GetSpecificBundleNameByTokenId failed, tokenid:%{public}u", option.tokenId); return E_ERROR; } std::string intention = it->second; - UnifiedKey key(intention, bundleName, GenerateId()); + UnifiedKey key(intention, specificBundleName, GenerateId()); Privilege privilege; privilege.tokenId = option.tokenId; - int32_t userId = IPCSkeleton::GetCallingUid() / OHOS::AppExecFwk::Constants::BASE_USER_RANGE; - std::string appId = DistributedData::BundleMgrAdapter::GetInstance().GetBundleAppId(bundleName, userId); + std::string appId = DistributedData::CheckerManager::GetInstance().GetAppId( + { IPCSkeleton::GetCallingUid(), option.tokenId, bundleName }); Runtime runtime; runtime.key = key; runtime.privileges.emplace_back(privilege); @@ -111,6 +111,10 @@ time_t PreProcessUtils::GetTimestamp() int32_t PreProcessUtils::GetHapUidByToken(uint32_t tokenId, int &userId) { + if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) { + ZLOGE("TokenType is not TOKEN_HAP"); + return E_ERROR; + } Security::AccessToken::HapTokenInfo tokenInfo; auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo); if (result != Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { @@ -121,14 +125,8 @@ int32_t PreProcessUtils::GetHapUidByToken(uint32_t tokenId, int &userId) return E_OK; } -bool PreProcessUtils::GetHapBundleNameByToken(int tokenId, std::string &bundleName) +bool PreProcessUtils::GetHapBundleNameByToken(uint32_t tokenId, std::string &bundleName) { - Security::AccessToken::HapTokenInfo hapInfo; - if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo) - == Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { - bundleName = hapInfo.bundleName; - return true; - } if (UTILS::IsTokenNative()) { ZLOGD("TypeATokenTypeEnum is TOKEN_HAP"); std::string processName; @@ -137,11 +135,17 @@ bool PreProcessUtils::GetHapBundleNameByToken(int tokenId, std::string &bundleNa return true; } } + Security::AccessToken::HapTokenInfo hapInfo; + if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo) + == Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { + bundleName = hapInfo.bundleName; + return true; + } ZLOGE("Get bundle name faild"); return false; } -bool PreProcessUtils::GetNativeProcessNameByToken(int tokenId, std::string &processName) +bool PreProcessUtils::GetNativeProcessNameByToken(uint32_t tokenId, std::string &processName) { Security::AccessToken::NativeTokenInfo nativeInfo; if (Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeInfo) @@ -500,21 +504,24 @@ std::string PreProcessUtils::GetSdkVersionByToken(uint32_t tokenId) return std::to_string(hapTokenInfo.apiVersion); } -bool PreProcessUtils::GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &bundleName) +bool PreProcessUtils::GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &specificBundleName, + std::string &bundleName) { - Security::AccessToken::HapTokenInfo hapInfo; - if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo) - == Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { - return GetSpecificBundleName(hapInfo.bundleName, hapInfo.instIndex, bundleName); - } if (UTILS::IsTokenNative()) { ZLOGI("TypeATokenTypeEnum is TOKEN_NATIVE"); std::string processName; if (GetNativeProcessNameByToken(tokenId, processName)) { bundleName = std::move(processName); + specificBundleName = bundleName; return true; } } + Security::AccessToken::HapTokenInfo hapInfo; + if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo) + == Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) { + bundleName = hapInfo.bundleName; + return GetSpecificBundleName(hapInfo.bundleName, hapInfo.instIndex, specificBundleName); + } ZLOGE("Get bundle name faild, tokenid:%{public}u", tokenId); return false; } diff --git a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h index 8cd126f55ded11878fdafe991bf0419d26575d2f..1ebe94d0ba5fc618572df0b3aecd894e1b81960d 100644 --- a/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h +++ b/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h @@ -26,8 +26,8 @@ public: static std::string GenerateId(); static time_t GetTimestamp(); static int32_t GetHapUidByToken(uint32_t tokenId, int &userId); - static bool GetHapBundleNameByToken(int tokenId, std::string &bundleName); - static bool GetNativeProcessNameByToken(int tokenId, std::string &processName); + static bool GetHapBundleNameByToken(uint32_t tokenId, std::string &bundleName); + static bool GetNativeProcessNameByToken(uint32_t tokenId, std::string &processName); static std::string GetLocalDeviceId(); static void SetRemoteData(UnifiedData &data); static int32_t SetRemoteUri(uint32_t tokenId, UnifiedData &data); @@ -43,7 +43,8 @@ public: static void SetRecordUid(UnifiedData &data); static bool GetDetailsFromUData(const UnifiedData &data, UDDetails &details); static Status GetSummaryFromDetails(const UDDetails &details, Summary &summary); - static bool GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &bundleName); + static bool GetSpecificBundleNameByTokenId(uint32_t tokenId, std::string &specificBundleName, + std::string &bundleName); static sptr GetBundleMgr(); private: static bool CheckUriAuthorization(const std::vector& uris, uint32_t tokenId); diff --git a/services/distributeddataservice/service/udmf/store/store.h b/services/distributeddataservice/service/udmf/store/store.h index 1b215e2501fe6d1da3e81713600ac945307af125..a21f24b5682a862f564995a20478307f9bc01f13 100644 --- a/services/distributeddataservice/service/udmf/store/store.h +++ b/services/distributeddataservice/service/udmf/store/store.h @@ -16,6 +16,10 @@ #ifndef UDMF_STORE_H #define UDMF_STORE_H +#include +#include +#include + #include "unified_data.h" namespace OHOS { diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index 770a10c314cd1625203aae2819465649b28ea30a..4db92da9345e0d2be2dbf31620094a2a2e74ed73 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -25,6 +25,7 @@ #include "bootstrap.h" #include "bundle_info.h" #include "bundlemgr/bundle_mgr_proxy.h" +#include "checker/checker_manager.h" #include "checker_manager.h" #include "device_manager_adapter.h" #include "device_matrix.h" @@ -43,7 +44,6 @@ #include "unified_data_helper.h" #include "utils/anonymous.h" #include "permission_validator.h" -#include "bundle_mgr/bundlemgr_adapter.h" namespace OHOS { namespace UDMF { @@ -67,6 +67,7 @@ constexpr const char *DEVICE_PHONE_TAG = "phone"; constexpr const char *DEVICE_DEFAULT_TAG = "default"; constexpr const char *HAP_LIST[] = {"com.ohos.pasteboarddialog"}; constexpr uint32_t FOUNDATION_UID = 5523; +constexpr uint32_t WAIT_TIME = 800; __attribute__((used)) UdmfServiceImpl::Factory UdmfServiceImpl::factory_; UdmfServiceImpl::Factory::Factory() { @@ -174,12 +175,16 @@ int32_t UdmfServiceImpl::GetData(const QueryOption &query, UnifiedData &unifiedD std::string bundleName; if (!PreProcessUtils::GetHapBundleNameByToken(query.tokenId, bundleName)) { msg.appId = "unknown"; - res = E_ERROR; - } else { - msg.appId = bundleName; + Reporter::GetInstance()->GetBehaviourReporter()->UDMFReport(msg); + ZLOGE("Failed to get bundle name by token, token:%{public}d", query.tokenId); + return E_ERROR; + } + msg.appId = bundleName; + + bool handledByDelay = HandleDelayLoad(query, unifiedData, res); + if (!handledByDelay) { res = RetrieveData(query, unifiedData); } - TransferToEntriesIfNeed(query, unifiedData); auto errFind = ERROR_MAP.find(res); msg.result = errFind == ERROR_MAP.end() ? "E_ERROR" : errFind->second; for (const auto &record : unifiedData.GetRecords()) { @@ -190,9 +195,36 @@ int32_t UdmfServiceImpl::GetData(const QueryOption &query, UnifiedData &unifiedD msg.dataType = types; msg.dataSize = unifiedData.GetSize(); Reporter::GetInstance()->GetBehaviourReporter()->UDMFReport(msg); + if (res != E_OK) { + ZLOGE("GetData failed, res:%{public}d, key:%{public}s", res, query.key.c_str()); + } return res; } +bool UdmfServiceImpl::HandleDelayLoad(const QueryOption &query, UnifiedData &unifiedData, int32_t &res) +{ + return dataLoadCallback_.ComputeIfPresent(query.key, [&](const auto &key, auto &callback) { + std::shared_ptr, std::chrono::milliseconds>> blockData; + auto [found, cache] = blockDelayDataCache_.Find(key); + if (!found) { + blockData = std::make_shared, std::chrono::milliseconds>>(WAIT_TIME); + blockDelayDataCache_.Insert(key, BlockDelayData{query.tokenId, blockData}); + callback->HandleDelayObserver(key, DataLoadInfo()); + } else { + blockData = cache.blockData; + } + ZLOGI("Start waiting for data, key:%{public}s", key.c_str()); + auto dataOpt = blockData->GetValue(); + if (dataOpt.has_value()) { + unifiedData = *dataOpt; + blockDelayDataCache_.Erase(key); + return false; + } + res = E_NOT_FOUND; + return true; + }); +} + bool UdmfServiceImpl::CheckDragParams(UnifiedKey &key, const QueryOption &query) { if (!key.IsValid()) { @@ -247,11 +279,9 @@ int32_t UdmfServiceImpl::RetrieveData(const QueryOption &query, UnifiedData &uni return E_NO_PERMISSION; } } - if (!IsReadAndKeep(runtime->privileges, query)) { - if (LifeCycleManager::GetInstance().OnGot(key) != E_OK) { - ZLOGE("Remove data failed:%{public}s", key.intention.c_str()); - return E_DB_ERROR; - } + if (!IsReadAndKeep(runtime->privileges, query) && LifeCycleManager::GetInstance().OnGot(key) != E_OK) { + ZLOGE("Remove data failed:%{public}s", key.intention.c_str()); + return E_DB_ERROR; } { @@ -259,6 +289,7 @@ int32_t UdmfServiceImpl::RetrieveData(const QueryOption &query, UnifiedData &uni privilegeCache_.erase(query.key); } PreProcessUtils::SetRemoteData(unifiedData); + TransferToEntriesIfNeed(query, unifiedData); return E_OK; } @@ -417,11 +448,12 @@ int32_t UdmfServiceImpl::UpdateData(const QueryOption &query, UnifiedData &unifi return E_INVALID_PARAMETERS; } std::string bundleName; - if (!PreProcessUtils::GetSpecificBundleNameByTokenId(query.tokenId, bundleName)) { + std::string specificBundleName; + if (!PreProcessUtils::GetSpecificBundleNameByTokenId(query.tokenId, specificBundleName, bundleName)) { ZLOGE("GetSpecificBundleNameByTokenId failed, tokenid:%{public}u", query.tokenId); return E_ERROR; } - if (key.bundleName != bundleName && !HasDatahubPriviledge(bundleName)) { + if (key.bundleName != specificBundleName && !HasDatahubPriviledge(bundleName)) { ZLOGE("update data failed by %{public}s, key: %{public}s.", bundleName.c_str(), query.key.c_str()); return E_INVALID_PARAMETERS; } @@ -437,8 +469,27 @@ int32_t UdmfServiceImpl::UpdateData(const QueryOption &query, UnifiedData &unifi HandleDbError(key.intention, res); return res; } + auto verifyRes = VerifyUpdatePermission(query, data, bundleName); + if (verifyRes != E_OK) { + ZLOGE("VerifyUpdatePermission failed:%{public}d, key: %{public}s.", verifyRes, query.key.c_str()); + return verifyRes; + } + std::shared_ptr runtime = data.GetRuntime(); + runtime->lastModifiedTime = PreProcessUtils::GetTimestamp(); + unifiedData.SetRuntime(*runtime); + PreProcessUtils::SetRecordUid(unifiedData); + if ((res = store->Update(unifiedData)) != E_OK) { + ZLOGE("Unified data update failed:%{public}s", key.intention.c_str()); + HandleDbError(key.intention, res); + return E_DB_ERROR; + } + return E_OK; +} + +int32_t UdmfServiceImpl::VerifyUpdatePermission(const QueryOption &query, UnifiedData &data, std::string &bundleName) +{ if (data.IsEmpty()) { - ZLOGE("Invalid parameter, unified data has no record; intention: %{public}s.", key.intention.c_str()); + ZLOGE("Invalid parameter, unified data has no record"); return E_INVALID_PARAMETERS; } std::shared_ptr runtime = data.GetRuntime(); @@ -451,14 +502,6 @@ int32_t UdmfServiceImpl::UpdateData(const QueryOption &query, UnifiedData &unifi ZLOGE("Update failed: tokenId or appId mismatch, bundleName: %{public}s", bundleName.c_str()); return E_INVALID_PARAMETERS; } - runtime->lastModifiedTime = PreProcessUtils::GetTimestamp(); - unifiedData.SetRuntime(*runtime); - PreProcessUtils::SetRecordUid(unifiedData); - if ((res = store->Update(unifiedData)) != E_OK) { - ZLOGE("Unified data update failed:%{public}s", key.intention.c_str()); - HandleDbError(key.intention, res); - return E_DB_ERROR; - } return E_OK; } @@ -468,8 +511,8 @@ int32_t UdmfServiceImpl::CheckAppId(std::shared_ptr runtime, const std: ZLOGE("Update failed: Invalid parameter, runtime->appId is empty"); return E_INVALID_PARAMETERS; } - int32_t userId = IPCSkeleton::GetCallingUid() / OHOS::AppExecFwk::Constants::BASE_USER_RANGE; - std::string appId = BundleMgrAdapter::GetInstance().GetBundleAppId(bundleName, userId); + std::string appId = DistributedData::CheckerManager::GetInstance().GetAppId( + { IPCSkeleton::GetCallingUid(), runtime->tokenId, bundleName }); if (appId.empty() || appId != runtime->appId) { ZLOGE("Update failed: runtime->appId %{public}s and bundleName appId %{public}s mismatch", runtime->appId.c_str(), appId.c_str()); @@ -538,7 +581,8 @@ bool UdmfServiceImpl::CheckDeleteDataPermission(std::string &appId, const std::s return true; } std::string bundleName; - if (!PreProcessUtils::GetSpecificBundleNameByTokenId(query.tokenId, bundleName)) { + std::string specificBundleName; + if (!PreProcessUtils::GetSpecificBundleNameByTokenId(query.tokenId, specificBundleName, bundleName)) { ZLOGE("GetSpecificBundleNameByTokenId failed, tokenid:%{public}u", query.tokenId); return false; } @@ -1153,15 +1197,17 @@ bool UdmfServiceImpl::IsValidOptionsNonDrag(UnifiedKey &key, const std::string & return false; } -int32_t UdmfServiceImpl::SetDelayInfo(const DataLoadInfo &dataLoadInfo, sptr iUdmfNotifier, std::string &key) +int32_t UdmfServiceImpl::SetDelayInfo(const DataLoadInfo &dataLoadInfo, sptr iUdmfNotifier, + std::string &key) { std::string bundleName; + std::string specificBundleName; auto tokenId = static_cast(IPCSkeleton::GetCallingTokenID()); - if (!PreProcessUtils::GetSpecificBundleNameByTokenId(tokenId, bundleName)) { + if (!PreProcessUtils::GetSpecificBundleNameByTokenId(tokenId, specificBundleName, bundleName)) { ZLOGE("GetSpecificBundleNameByTokenId failed, tokenid:%{public}u", tokenId); return E_ERROR; } - UnifiedKey udkey(UD_INTENTION_MAP.at(UD_INTENTION_DRAG), bundleName, dataLoadInfo.sequenceKey); + UnifiedKey udkey(UD_INTENTION_MAP.at(UD_INTENTION_DRAG), specificBundleName, dataLoadInfo.sequenceKey); key = udkey.GetUnifiedKey(); dataLoadCallback_.Insert(key, iface_cast(iUdmfNotifier)); @@ -1184,6 +1230,14 @@ int32_t UdmfServiceImpl::SetDelayInfo(const DataLoadInfo &dataLoadInfo, sptr(IPCSkeleton::GetCallingTokenID()); @@ -1196,13 +1250,8 @@ int32_t UdmfServiceImpl::PushDelayData(const std::string &key, UnifiedData &unif ZLOGW("SetRemoteUri failed, ret:%{public}d, key:%{public}s.", ret, key.c_str()); } - auto it = delayDataCallback_.Find(key); - if (!it.first) { - ZLOGE("DelayData callback no exist, key:%{public}s", key.c_str()); - return E_ERROR; - } QueryOption query; - query.tokenId = it.second.tokenId; + query.tokenId = isDataLoading ? delayIt.second.tokenId : blockIt.second.tokenId; query.key = key; if (option.tokenId != query.tokenId && !IsPermissionInCache(query)) { ZLOGE("No permission"); @@ -1218,9 +1267,13 @@ int32_t UdmfServiceImpl::PushDelayData(const std::string &key, UnifiedData &unif privilegeCache_.erase(key); } PreProcessUtils::SetRemoteData(unifiedData); - TransferToEntriesIfNeed(query, unifiedData); - return HandleDelayDataCallback(it.second, unifiedData, key); + + if (!isDataLoading) { + blockIt.second.blockData->SetValue(unifiedData); + return E_OK; + } + return HandleDelayDataCallback(delayIt.second, unifiedData, key); } int32_t UdmfServiceImpl::HandleDelayDataCallback(DelayGetDataInfo &delayGetDataInfo, UnifiedData &unifiedData, diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 8b03412f1f88836c1e38b2fda375134f304fbba7..beef4dda4af40b975f557f4139e4a7d750f219ba 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -16,12 +16,13 @@ #ifndef UDMF_SERVICE_IMPL_H #define UDMF_SERVICE_IMPL_H -#include "store_cache.h" -#include "udmf_service_stub.h" +#include "block_data.h" +#include "checker_manager.h" #include "kv_store_delegate_manager.h" #include "metadata/store_meta_data.h" -#include "checker_manager.h" +#include "store_cache.h" #include "udmf_notifier_proxy.h" +#include "udmf_service_stub.h" namespace OHOS { namespace UDMF { /* @@ -91,6 +92,8 @@ private: const UnifiedData &unifiedData); std::vector ProcessResult(const std::map &results); DistributedData::StoreMetaData BuildMeta(const std::string &storeId, int userId); + int32_t VerifyUpdatePermission(const QueryOption &query, UnifiedData &unifiedData, std::string &bundleName); + bool HandleDelayLoad(const QueryOption &query, UnifiedData &unifiedData, int32_t &res); class Factory { public: @@ -109,6 +112,12 @@ private: std::unordered_map asyncProcessInfoMap_ {}; ConcurrentMap> dataLoadCallback_ {}; ConcurrentMap delayDataCallback_ {}; + + struct BlockDelayData { + uint32_t tokenId {0}; + std::shared_ptr, std::chrono::milliseconds>> blockData; + }; + ConcurrentMap blockDelayDataCache_ {}; }; } // namespace UDMF } // namespace OHOS diff --git a/services/distributeddataservice/service/udmf/udmf_service_stub.h b/services/distributeddataservice/service/udmf/udmf_service_stub.h index c5f617a9fb54da2375ef7aea2e04e71b3b363e1c..3ca1214b0a2d1df819ed29176da5be75b7057301 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_stub.h +++ b/services/distributeddataservice/service/udmf/udmf_service_stub.h @@ -45,7 +45,6 @@ private: int32_t OnRemoveAppShareOption(MessageParcel &data, MessageParcel &reply); int32_t OnObtainAsynProcess(MessageParcel &data, MessageParcel &reply); int32_t OnClearAsynProcessByKey(MessageParcel &data, MessageParcel &reply); - int32_t OnInvokeHap(MessageParcel &data, MessageParcel &reply); int32_t OnPushDelayData(MessageParcel &data, MessageParcel &reply); int32_t OnSetDelayInfo(MessageParcel &data, MessageParcel &reply); int32_t OnGetDataIfAvailable(MessageParcel &data, MessageParcel &reply);