From 4ebeabdf87c205e2016a52bd10a4df6a66d3fd1d Mon Sep 17 00:00:00 2001 From: wangbin Date: Fri, 1 Nov 2024 15:44:11 +0800 Subject: [PATCH 01/25] Fix security issues with appID Signed-off-by: wangbin --- .../app/src/checker/bundle_checker.cpp | 66 +++++++++++-------- .../app/src/checker/bundle_checker.h | 1 + .../framework/test/checker_manager_test.cpp | 19 ------ .../fuzztest/cloudservicestub_fuzzer/BUILD.gn | 2 + .../fuzztest/kvdbservicestub_fuzzer/BUILD.gn | 2 + 5 files changed, 45 insertions(+), 45 deletions(-) diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.cpp b/services/distributeddataservice/app/src/checker/bundle_checker.cpp index 8d61d9211..53e0b484c 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.cpp +++ b/services/distributeddataservice/app/src/checker/bundle_checker.cpp @@ -15,11 +15,16 @@ #define LOG_TAG "BundleChecker" #include "bundle_checker.h" +#include #include +#include #include "accesstoken_kit.h" +#include "bundlemgr/bundle_mgr_proxy.h" #include "hap_token_info.h" +#include "ipc_skeleton.h" #include "log_print.h" #include "utils/crypto.h" + namespace OHOS { namespace DistributedData { using namespace Security::AccessToken; @@ -56,27 +61,45 @@ bool BundleChecker::SetSwitchesInfo(const CheckerManager::Switches &switches) return true; } +std::string BundleChecker::GetBundleAppId(const CheckerManager::StoreInfo &info) +{ + 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 GetSystemAbility."); + return ""; + } + auto bundleManager = iface_cast(bundleMgrProxy); + if (bundleManager == nullptr) { + ZLOGE("Failed to get bundle manager"); + return ""; + } + int32_t userId = IPCSkeleton::GetCallingUid() / OHOS::AppExecFwk::Constants::BASE_USER_RANGE; + std::string 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); + return ""; + } + return appId; +} + std::string BundleChecker::GetAppId(const CheckerManager::StoreInfo &info) { - if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) { - return ""; - } - HapTokenInfo tokenInfo; - auto result = AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo); - if (result != RET_SUCCESS) { - ZLOGE("token:0x%{public}x, result:%{public}d", info.tokenId, result); - return ""; - } - if (!info.bundleName.empty() && tokenInfo.bundleName != info.bundleName) { - ZLOGE("bundlename:%{public}s <-> %{public}s", info.bundleName.c_str(), tokenInfo.bundleName.c_str()); + auto appId = GetBundleAppId(info); + if (appId.empty()) { return ""; } auto it = trusts_.find(info.bundleName); - if (it != trusts_.end() && (it->second == tokenInfo.appID)) { + if (it != trusts_.end() && (it->second == appId)) { return info.bundleName; } - ZLOGD("bundleName:%{public}s, appId:%{public}s", info.bundleName.c_str(), tokenInfo.appID.c_str()); - return Crypto::Sha256(tokenInfo.appID); + ZLOGD("bundleName:%{public}s, appId:%{public}s", info.bundleName.c_str(), appId.c_str()); + return Crypto::Sha256(appId); } bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info) @@ -95,21 +118,12 @@ bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info) bool BundleChecker::IsDistrust(const CheckerManager::StoreInfo &info) { - if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) { - return false; - } - HapTokenInfo tokenInfo; - auto result = AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo); - if (result != RET_SUCCESS) { - ZLOGE("token:0x%{public}x, result:%{public}d", info.tokenId, result); - return false; - } - if (!info.bundleName.empty() && tokenInfo.bundleName != info.bundleName) { - ZLOGE("bundlename:%{public}s <-> %{public}s", info.bundleName.c_str(), tokenInfo.bundleName.c_str()); + auto appId = GetBundleAppId(info); + if (appId.empty()) { return false; } auto it = distrusts_.find(info.bundleName); - if (it != distrusts_.end() && (it->second == tokenInfo.appID)) { + if (it != distrusts_.end() && (it->second == appId)) { return true; } return false; diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.h b/services/distributeddataservice/app/src/checker/bundle_checker.h index 794ceaa1d..1eba18e54 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.h +++ b/services/distributeddataservice/app/src/checker/bundle_checker.h @@ -44,6 +44,7 @@ private: std::map switches_; std::vector dynamicStores_; std::vector staticStores_; + std::string GetBundleAppId(const CheckerManager::StoreInfo &info); }; } // namespace DistributedData } // namespace OHOS diff --git a/services/distributeddataservice/framework/test/checker_manager_test.cpp b/services/distributeddataservice/framework/test/checker_manager_test.cpp index d95a7df7d..ca21b6068 100644 --- a/services/distributeddataservice/framework/test/checker_manager_test.cpp +++ b/services/distributeddataservice/framework/test/checker_manager_test.cpp @@ -153,25 +153,6 @@ HWTEST_F(CheckerManagerTest, SystemCheckerIVI, TestSize.Level0) ASSERT_TRUE(CheckerManager::GetInstance().IsValid(info)); } -/** -* @tc.name: BundleChecker -* @tc.desc: checker the bundle name of the bundle abilities. -* @tc.type: FUNC -* @tc.require: -* @tc.author: Sven Wang -*/ -HWTEST_F(CheckerManagerTest, BundleChecker, TestSize.Level0) -{ - CheckerManager::StoreInfo storeInfo; - storeInfo.uid = 2000000; - storeInfo.tokenId = AccessTokenKit::GetHapTokenID(100, "ohos.test.demo", 0); - storeInfo.bundleName = "ohos.test.demo"; - HapTokenInfo tokenInfo; - AccessTokenKit::GetHapTokenInfo(storeInfo.tokenId, tokenInfo); - ASSERT_EQ(Crypto::Sha256(tokenInfo.appID), CheckerManager::GetInstance().GetAppId(storeInfo)); - ASSERT_TRUE(CheckerManager::GetInstance().IsValid(storeInfo)); -} - /** * @tc.name: IsDynamic * @tc.desc: checker data type. diff --git a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 4f44b6a12..848e5900b 100644 --- a/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -128,6 +128,8 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] } diff --git a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn index 83c0d3984..1aad884a2 100644 --- a/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn @@ -117,6 +117,8 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "ipc:ipc_core", "kv_store:distributeddata_inner", "kv_store:distributeddata_mgr", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] } From 8aafe8da91bf2e97bdb67a68f70ea39f5ed1db84 Mon Sep 17 00:00:00 2001 From: wangbin Date: Mon, 4 Nov 2024 14:59:09 +0800 Subject: [PATCH 02/25] fix Signed-off-by: wangbin --- .../distributeddataservice/app/src/checker/bundle_checker.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.cpp b/services/distributeddataservice/app/src/checker/bundle_checker.cpp index 53e0b484c..4820e74f4 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.cpp +++ b/services/distributeddataservice/app/src/checker/bundle_checker.cpp @@ -78,7 +78,7 @@ std::string BundleChecker::GetBundleAppId(const CheckerManager::StoreInfo &info) ZLOGE("Failed to get bundle manager"); return ""; } - int32_t userId = IPCSkeleton::GetCallingUid() / OHOS::AppExecFwk::Constants::BASE_USER_RANGE; + int32_t userId = info.uid / OHOS::AppExecFwk::Constants::BASE_USER_RANGE; std::string appId = bundleManager->GetAppIdByBundleName(info.bundleName, userId); if (appId.empty()) { ZLOGE("GetAppIdByBundleName failed appId:%{public}s, bundleName:%{public}s, uid:%{public}d", From ffe48ad6c354ca494abce7135083b292b184726e Mon Sep 17 00:00:00 2001 From: wangbin Date: Tue, 5 Nov 2024 11:37:46 +0800 Subject: [PATCH 03/25] fix Signed-off-by: wangbin --- .../app/src/checker/bundle_checker.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.cpp b/services/distributeddataservice/app/src/checker/bundle_checker.cpp index 4820e74f4..674e09d59 100644 --- a/services/distributeddataservice/app/src/checker/bundle_checker.cpp +++ b/services/distributeddataservice/app/src/checker/bundle_checker.cpp @@ -15,14 +15,14 @@ #define LOG_TAG "BundleChecker" #include "bundle_checker.h" -#include #include -#include #include "accesstoken_kit.h" #include "bundlemgr/bundle_mgr_proxy.h" #include "hap_token_info.h" #include "ipc_skeleton.h" +#include "iservice_registry.h" #include "log_print.h" +#include "system_ability_definition.h" #include "utils/crypto.h" namespace OHOS { @@ -70,7 +70,7 @@ std::string BundleChecker::GetBundleAppId(const CheckerManager::StoreInfo &info) } auto bundleMgrProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); if (bundleMgrProxy == nullptr) { - ZLOGE("Failed to GetSystemAbility."); + ZLOGE("Failed to Get BMS SA."); return ""; } auto bundleManager = iface_cast(bundleMgrProxy); @@ -83,13 +83,15 @@ std::string BundleChecker::GetBundleAppId(const CheckerManager::StoreInfo &info) if (appId.empty()) { ZLOGE("GetAppIdByBundleName failed appId:%{public}s, bundleName:%{public}s, uid:%{public}d", appId.c_str(), info.bundleName.c_str(), userId); - return ""; } return appId; } std::string BundleChecker::GetAppId(const CheckerManager::StoreInfo &info) { + if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) { + return ""; + } auto appId = GetBundleAppId(info); if (appId.empty()) { return ""; @@ -118,6 +120,9 @@ bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info) bool BundleChecker::IsDistrust(const CheckerManager::StoreInfo &info) { + if (AccessTokenKit::GetTokenTypeFlag(info.tokenId) != TOKEN_HAP) { + return false; + } auto appId = GetBundleAppId(info); if (appId.empty()) { return false; From 4b8bd8e9cdfaedc1ffe3e62ab84fca310311e7a0 Mon Sep 17 00:00:00 2001 From: Cuiziyuan Date: Tue, 5 Nov 2024 12:26:29 +0800 Subject: [PATCH 04/25] cardUpdate Signed-off-by: Cuiziyuan --- .../service/data_share/common/db_delegate.h | 2 ++ .../service/data_share/common/rdb_delegate.cpp | 16 ++++++++++++++++ .../service/data_share/common/rdb_delegate.h | 1 + .../data_share/data_share_service_stub.cpp | 2 +- .../rdb_subscriber_manager.cpp | 7 +++++++ 5 files changed, 27 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/data_share/common/db_delegate.h b/services/distributeddataservice/service/data_share/common/db_delegate.h index 18e405237..05ed3b843 100644 --- a/services/distributeddataservice/service/data_share/common/db_delegate.h +++ b/services/distributeddataservice/service/data_share/common/db_delegate.h @@ -27,6 +27,7 @@ #include "metadata/store_meta_data.h" #include "result_set.h" #include "serializable/serializable.h" +#include "value_object.h" namespace OHOS::DataShare { class DBDelegate { @@ -40,6 +41,7 @@ public: virtual std::string Query( const std::string &sql, const std::vector &selectionArgs = std::vector()) = 0; virtual std::shared_ptr QuerySql(const std::string &sql) = 0; + virtual std::pair UpdateSql(const std::string &sql) = 0; virtual bool IsInvalid() = 0; static void SetExecutorPool(std::shared_ptr executor); static void EraseStoreCache(const int32_t tokenId); diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp index df25e9018..7b2ceb955 100644 --- a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp @@ -290,6 +290,22 @@ std::shared_ptr RdbDelegate::QuerySql(const std::string &s return resultSet; } +std::pair UpdateSql(const std::string &sql) +{ + if (store_ == nullptr) { + ZLOGE("store is null"); + return std::make_pair(E_ERROR, 0); + } + auto[ret, outValue] = store_->Execute(sql); + if (ret != E_OK) { + ZLOGE("execute update sql failed, err:%{public}d", ret); + return std::make_pair(ret, 0); + } + int64_t rowCount = 0; + outValue.GetLong(rowCount); + return std::make_pair(ret, rowCount); +} + bool RdbDelegate::IsInvalid() { return store_ == nullptr; diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.h b/services/distributeddataservice/service/data_share/common/rdb_delegate.h index b73ac3089..b65e6f9a4 100644 --- a/services/distributeddataservice/service/data_share/common/rdb_delegate.h +++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.h @@ -38,6 +38,7 @@ public: const int32_t callingPid) override; std::string Query(const std::string &sql, const std::vector &selectionArgs) override; std::shared_ptr QuerySql(const std::string &sql) override; + std::pair UpdateSql(const std::string &sql) override; bool IsInvalid() override; std::pair InsertEx(const std::string &tableName, const DataShareValuesBucket &valuesBucket) override; diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp index df4b59e52..fca1209d0 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp @@ -117,7 +117,7 @@ int32_t DataShareServiceStub::OnAddTemplate(MessageParcel &data, MessageParcel & std::string uri; int64_t subscriberId; Template tpl; - if (!ITypesUtil::Unmarshal(data, uri, subscriberId, tpl.predicates_, tpl.scheduler_)) { + if (!ITypesUtil::Unmarshal(data, uri, subscriberId, tpl.update_, tpl.predicates_, tpl.scheduler_)) { ZLOGW("read device list failed."); return -1; } diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp index db5a0c2ec..9dbc585af 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp @@ -343,6 +343,13 @@ int RdbSubscriberManager::Notify(const Key &key, int32_t userId, const std::vect } changeNode.data_.emplace_back("{\"" + predicate.key_ + "\":" + result + "}"); } + if (!tpl.update_.empty()) { + auto [errCode, rowCount] = delegate->UpdateSql(tpl.update_); + if (errCode != E_OK) { + ZLOGE("Update failed, err:%{public}d", errCode); + } + ZLOGI("Update finished, data changed:%{public}ld", rowCount); + } ZLOGI("emit, valSize: %{public}zu, dataSize:%{public}zu, uri:%{public}s,", val.size(), changeNode.data_.size(), DistributedData::Anonymous::Change(changeNode.uri_).c_str()); From 08ab74208f5ba3776c43c357e2954d4cae4eb987 Mon Sep 17 00:00:00 2001 From: Cuiziyuan Date: Wed, 6 Nov 2024 14:31:53 +0800 Subject: [PATCH 05/25] store Signed-off-by: Cuiziyuan --- .../service/data_share/common/rdb_delegate.cpp | 2 +- .../data_share/subscriber_managers/rdb_subscriber_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp index 7b2ceb955..6f952913d 100644 --- a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp @@ -290,7 +290,7 @@ std::shared_ptr RdbDelegate::QuerySql(const std::string &s return resultSet; } -std::pair UpdateSql(const std::string &sql) +std::pair RdbDelegate::UpdateSql(const std::string &sql) { if (store_ == nullptr) { ZLOGE("store is null"); diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp index 9dbc585af..0e9c17321 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp @@ -348,7 +348,7 @@ int RdbSubscriberManager::Notify(const Key &key, int32_t userId, const std::vect if (errCode != E_OK) { ZLOGE("Update failed, err:%{public}d", errCode); } - ZLOGI("Update finished, data changed:%{public}ld", rowCount); + ZLOGI("Update finished, data changed:%{public}lld", rowCount); } ZLOGI("emit, valSize: %{public}zu, dataSize:%{public}zu, uri:%{public}s,", From fc8050223f811a637ba2933c7bcb0510e190e5ff Mon Sep 17 00:00:00 2001 From: zqz Date: Thu, 7 Nov 2024 17:31:08 +0800 Subject: [PATCH 06/25] Signed-off-by: zqz Change-Id: Ica3814d03a3846b81805db03801b587efdeb993d --- .../service/data_share/common/kv_delegate.cpp | 2 +- .../service/data_share/common/kv_delegate.h | 2 +- .../service/data_share/common/rdb_delegate.cpp | 11 +++-------- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp index 23aa6a611..e9c66e2c2 100644 --- a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp @@ -42,7 +42,7 @@ const char* g_backupFiles[] = { const char* BACKUP_SUFFIX = ".backup"; // If isBackUp is true, remove db backup files. Otherwise remove source db files. -void KvDelegate::RemoveDbFile(bool isBackUp) +void KvDelegate::RemoveDbFile(bool isBackUp) const { for (auto &fileName: g_backupFiles) { std::string dbPath = path_ + "/" + fileName; diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.h b/services/distributeddataservice/service/data_share/common/kv_delegate.h index 13499f70d..3ec92c7cd 100644 --- a/services/distributeddataservice/service/data_share/common/kv_delegate.h +++ b/services/distributeddataservice/service/data_share/common/kv_delegate.h @@ -46,7 +46,7 @@ private: bool RestoreIfNeed(int32_t dbStatus); void Backup(); void Restore(); - void RemoveDbFile(bool isBackUp); + void RemoveDbFile(bool isBackUp) const; bool CopyFile(bool isBackup); std::recursive_mutex mutex_; std::string path_; diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp index df25e9018..34639edae 100644 --- a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp +++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp @@ -90,15 +90,10 @@ std::pair RdbDelegate::GetConfig(const DistributedData::Sto } RdbDelegate::RdbDelegate(const DistributedData::StoreMetaData &meta, int version, - bool registerFunction, const std::string &extUriData, const std::string &backup) + bool registerFunction, const std::string &extUri, const std::string &backup) + : tokenId_(meta.tokenId), bundleName_(meta.bundleName), storeName_(meta.storeId), + haMode_(meta.haMode), extUri_(extUri), backup_(backup) { - tokenId_ = meta.tokenId; - bundleName_ = meta.bundleName; - storeName_ = meta.storeId; - extUri_ = extUriData; - haMode_ = meta.haMode; - backup_ = backup; - auto [err, config] = GetConfig(meta, registerFunction); if (err != E_OK) { ZLOGW("Get rdbConfig failed, errCode is %{public}d, dir is %{public}s", err, From fb5dc62143472ec274aa9af3fea04c25a4706d6f Mon Sep 17 00:00:00 2001 From: Cuiziyuan Date: Fri, 8 Nov 2024 17:55:10 +0800 Subject: [PATCH 07/25] value Signed-off-by: Cuiziyuan --- .../service/data_share/data/template_data.h | 1 + 1 file changed, 1 insertion(+) diff --git a/services/distributeddataservice/service/data_share/data/template_data.h b/services/distributeddataservice/service/data_share/data/template_data.h index 859f0d2d3..f0fe0b30f 100644 --- a/services/distributeddataservice/service/data_share/data/template_data.h +++ b/services/distributeddataservice/service/data_share/data/template_data.h @@ -36,6 +36,7 @@ struct TemplateNode final: public DistributedData::Serializable { bool Unmarshal(const json &node) override; Template ToTemplate() const; private: + std::string update; std::vector predicates; std::string scheduler; }; From 79169f1f9886301fae6ef2fc1ec9a333efeef281 Mon Sep 17 00:00:00 2001 From: Cuiziyuan Date: Fri, 8 Nov 2024 20:11:01 +0800 Subject: [PATCH 08/25] template Signed-off-by: Cuiziyuan --- .../service/data_share/data/template_data.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/data_share/data/template_data.cpp b/services/distributeddataservice/service/data_share/data/template_data.cpp index f99bec09c..af4f32736 100644 --- a/services/distributeddataservice/service/data_share/data/template_data.cpp +++ b/services/distributeddataservice/service/data_share/data/template_data.cpp @@ -18,18 +18,20 @@ namespace OHOS::DataShare { bool TemplateNode::Marshal(DistributedData::Serializable::json &node) const { - bool ret = SetValue(node[GET_NAME(predicates)], predicates); + bool ret = SetValue(node[GET_NAME(update)], predicates); + ret = SetValue(node[GET_NAME(predicates)], predicates); ret = ret && SetValue(node[GET_NAME(scheduler)], scheduler); return ret; } bool TemplateNode::Unmarshal(const DistributedData::Serializable::json &node) { - bool ret = GetValue(node, GET_NAME(predicates), predicates); + bool ret = GetValue(node, GET_NAME(update), predicates); + ret = GetValue(node, GET_NAME(predicates), predicates); return ret && GetValue(node, GET_NAME(scheduler), scheduler); } -TemplateNode::TemplateNode(const Template &tpl) : scheduler(tpl.scheduler_) +TemplateNode::TemplateNode(const Template &tpl) : update(tpl.update_), scheduler(tpl.scheduler_) { for (auto &item:tpl.predicates_) { predicates.emplace_back(item.key_, item.selectSql_); @@ -42,7 +44,7 @@ Template TemplateNode::ToTemplate() const for (const auto &predicate: predicates) { nodes.emplace_back(predicate.key, predicate.selectSql); } - return Template(nodes, scheduler); + return Template(update, nodes, scheduler); } bool TemplateRootNode::Marshal(DistributedData::Serializable::json &node) const From 3736067046bdea2f1da3db4465cf3ecb8a318474 Mon Sep 17 00:00:00 2001 From: yanhui Date: Thu, 7 Nov 2024 11:25:07 +0800 Subject: [PATCH 09/25] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E9=80=8F=E4=BC=A0=E6=80=BB=E7=BA=BF=E9=94=99=E8=AF=AF=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: I28d62e953129d43e81ac9378bdffb1bcd942731b --- .../communicator/src/communicator_context.cpp | 17 +++++++++++------ .../src/process_communicator_impl.cpp | 4 ++-- .../adapter/communicator/src/softbus_client.cpp | 17 ++++++++--------- .../adapter/communicator/src/softbus_client.h | 2 +- .../communicator/app_device_change_listener.h | 2 +- .../include/communicator/communicator_context.h | 2 +- .../communicator/process_communicator_impl.h | 2 +- .../app/src/kvstore_device_listener.cpp | 3 ++- .../app/src/kvstore_device_listener.h | 2 +- .../service/kvdb/kvdb_service_impl.cpp | 15 +++++++++++++-- 10 files changed, 41 insertions(+), 25 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp b/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp index 691b0aed2..ec11a5c8a 100644 --- a/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp +++ b/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp @@ -17,6 +17,7 @@ #include "communicator_context.h" #include "log_print.h" #include "kvstore_utils.h" +#include "softbus_error_code.h" namespace OHOS::DistributedData { using KvUtils = OHOS::DistributedKv::KvStoreUtils; @@ -72,28 +73,32 @@ Status CommunicatorContext::UnRegSessionListener(const DevChangeListener *observ return Status::SUCCESS; } -void CommunicatorContext::NotifySessionReady(const std::string &deviceId) +void CommunicatorContext::NotifySessionReady(const std::string &deviceId, const int &errCode) { if (deviceId.empty()) { ZLOGE("deviceId empty"); return; } - devices_.Insert(deviceId, deviceId); + if (errCode == SOFTBUS_OK) { + devices_.Insert(deviceId, deviceId); + } DeviceInfo devInfo; devInfo.uuid = deviceId; { std::lock_guard lock(mutex_); for (const auto &observer : observers_) { if (observer != nullptr) { - observer->OnSessionReady(devInfo); + observer->OnSessionReady(devInfo, errCode); } } ZLOGI("Notify session begin, deviceId:%{public}s, observer count:%{public}zu", KvUtils::ToBeAnonymous(deviceId).c_str(), observers_.size()); } - std::lock_guard sessionLockGard(sessionMutex_); - if (closeListener_) { - closeListener_(deviceId); + if (errCode == SOFTBUS_OK) { + std::lock_guard sessionLockGard(sessionMutex_); + if (closeListener_) { + closeListener_(deviceId); + } } } diff --git a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp index 2de88fc75..6fb5e1377 100644 --- a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp @@ -221,7 +221,7 @@ void ProcessCommunicatorImpl::OnDeviceChanged(const DeviceInfo &info, const Devi onDeviceChangeHandler_(devInfo, (type == DeviceChangeType::DEVICE_ONLINE)); } -void ProcessCommunicatorImpl::OnSessionReady(const DeviceInfo &info) const +void ProcessCommunicatorImpl::OnSessionReady(const DeviceInfo &info, const int &errCode) const { std::lock_guard lock(sessionMutex_); if (sessionListener_ == nullptr) { @@ -229,7 +229,7 @@ void ProcessCommunicatorImpl::OnSessionReady(const DeviceInfo &info) const } DeviceInfos devInfos; devInfos.identifier = info.uuid; - sessionListener_(devInfos); + sessionListener_(devInfos, errCode); } std::shared_ptr ProcessCommunicatorImpl::GetExtendHeaderHandle(const ExtendInfo &info) diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp index 742628d5e..b01fadfbe 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp @@ -114,10 +114,8 @@ Status SoftBusClient::OpenConnect(const ISocketListener *listener) } ZLOGI("Bind Start, device:%{public}s socket:%{public}d type:%{public}u", KvStoreUtils::ToBeAnonymous(client->device_.deviceId).c_str(), clientSocket, type); - auto status = client->Open(clientSocket, QOS_INFOS[type % QOS_BUTT], listener); - if (status == Status::SUCCESS) { - Context::GetInstance().NotifySessionReady(client->device_.deviceId); - } + int32_t status = client->Open(clientSocket, QOS_INFOS[type % QOS_BUTT], listener); + Context::GetInstance().NotifySessionReady(client->device_.deviceId, status); client->isOpening_.store(false); }; Context::GetInstance().GetThreadPool()->Execute(task); @@ -138,7 +136,7 @@ Status SoftBusClient::CheckStatus() return Status::ERROR; } -Status SoftBusClient::Open(int32_t socket, const QosTV qos[], const ISocketListener *listener) +int32_t SoftBusClient::Open(int32_t socket, const QosTV qos[], const ISocketListener *listener) { int32_t status = ::Bind(socket, qos, QOS_COUNT, listener); ZLOGI("Bind %{public}s,session:%{public}s,socketId:%{public}d", @@ -148,14 +146,15 @@ Status SoftBusClient::Open(int32_t socket, const QosTV qos[], const ISocketListe ZLOGE("[Bind] device:%{public}s socket failed, session:%{public}s,result:%{public}d", KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), status); ::Shutdown(socket); - return Status::NETWORK_ERROR; + return status; } UpdateExpireTime(); uint32_t mtu = 0; std::tie(status, mtu) = GetMtu(socket); if (status != SOFTBUS_OK) { - ZLOGE("GetMtu failed, session:%{public}s, socket:%{public}d", pipe_.pipeId.c_str(), socket_); - return Status::NETWORK_ERROR; + ZLOGE("GetMtu failed, session:%{public}s, socket:%{public}d, status:%{public}d", pipe_.pipeId.c_str(), socket_, + status); + return status; } { std::lock_guard lock(mutex_); @@ -166,7 +165,7 @@ Status SoftBusClient::Open(int32_t socket, const QosTV qos[], const ISocketListe ZLOGI("open %{public}s, session:%{public}s success, socket:%{public}d", KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket_); ConnectManager::GetInstance()->OnSessionOpen(DmAdapter::GetInstance().GetDeviceInfo(device_.deviceId).networkId); - return Status::SUCCESS; + return status; } SoftBusClient::Time SoftBusClient::GetExpireTime() const diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h index 898a7ada7..4a9eeef21 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -52,7 +52,7 @@ public: bool isReuse = false; private: - Status Open(int32_t socket, const QosTV qos[], const ISocketListener *listener); + int32_t Open(int32_t socket, const QosTV qos[], const ISocketListener *listener); std::pair GetMtu(int32_t socket); Time CalcExpireTime() const; diff --git a/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h b/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h index 8d460299d..bba789978 100644 --- a/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h +++ b/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h @@ -32,7 +32,7 @@ public: { return ChangeLevelType::HIGH; } - API_EXPORT virtual void OnSessionReady(const DeviceInfo &info) const {} + API_EXPORT virtual void OnSessionReady(const DeviceInfo &info, const int &errCode) const {} }; } // namespace AppDistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/adapter/include/communicator/communicator_context.h b/services/distributeddataservice/adapter/include/communicator/communicator_context.h index a77a2db3a..1020c57de 100644 --- a/services/distributeddataservice/adapter/include/communicator/communicator_context.h +++ b/services/distributeddataservice/adapter/include/communicator/communicator_context.h @@ -36,7 +36,7 @@ public: std::shared_ptr GetThreadPool(); Status RegSessionListener(const DevChangeListener *observer); Status UnRegSessionListener(const DevChangeListener *observer); - void NotifySessionReady(const std::string &deviceId); + void NotifySessionReady(const std::string &deviceId, const int &errCode); void NotifySessionClose(const std::string &deviceId); void SetSessionListener(const OnCloseAble &closeAbleCallback); bool IsSessionReady(const std::string &deviceId); diff --git a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h index ee32d1418..f16c43d54 100644 --- a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h +++ b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h @@ -57,7 +57,7 @@ public: std::vector GetRemoteOnlineDeviceInfosList() override; bool IsSameProcessLabelStartedOnPeerDevice(const DeviceInfos &peerDevInfo) override; void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override; - void OnSessionReady(const DeviceInfo &info) const override; + void OnSessionReady(const DeviceInfo &info, const int &errCode) const override; API_EXPORT std::shared_ptr GetExtendHeaderHandle( const DistributedDB::ExtendInfo &info) override; diff --git a/services/distributeddataservice/app/src/kvstore_device_listener.cpp b/services/distributeddataservice/app/src/kvstore_device_listener.cpp index 1104cfc12..d3cd9cd52 100644 --- a/services/distributeddataservice/app/src/kvstore_device_listener.cpp +++ b/services/distributeddataservice/app/src/kvstore_device_listener.cpp @@ -34,8 +34,9 @@ void KvStoreDeviceListener::OnDeviceChanged( ZLOGI("device is %{public}d", type); } -void KvStoreDeviceListener::OnSessionReady(const AppDistributedKv::DeviceInfo &info) const +void KvStoreDeviceListener::OnSessionReady(const AppDistributedKv::DeviceInfo &info, const int &errCode) const { + (void)errCode; kvStoreDataService_.OnSessionReady(info); } diff --git a/services/distributeddataservice/app/src/kvstore_device_listener.h b/services/distributeddataservice/app/src/kvstore_device_listener.h index 037c367d1..849afdabe 100644 --- a/services/distributeddataservice/app/src/kvstore_device_listener.h +++ b/services/distributeddataservice/app/src/kvstore_device_listener.h @@ -26,7 +26,7 @@ public: void OnDeviceChanged( const AppDistributedKv::DeviceInfo &info, const AppDistributedKv::DeviceChangeType &type) const override; AppDistributedKv::ChangeLevelType GetChangeLevelType() const override; - void OnSessionReady(const AppDistributedKv::DeviceInfo &info) const override; + void OnSessionReady(const AppDistributedKv::DeviceInfo &info, const int &errCode = 0) const override; private: KvStoreDataService &kvStoreDataService_; diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 00911ffe6..9b61ca257 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -973,7 +973,7 @@ Status KVDBServiceImpl::DoSyncInOrder( if (uuids.empty()) { ZLOGW("no device seqId:0x%{public}" PRIx64 " remote:%{public}zu appId:%{public}s storeId:%{public}s", info.seqId, info.devices.size(), meta.bundleName.c_str(), Anonymous::Change(meta.storeId).c_str()); - return Status::ERROR; + return Status::DEVICE_NOT_ONLINE; } if (IsNeedMetaSync(meta, uuids)) { auto recv = DeviceMatrix::GetInstance().GetRecvLevel(uuids[0], @@ -1122,7 +1122,18 @@ Status KVDBServiceImpl::DoComplete(const StoreMetaData &meta, const SyncInfo &in std::to_string(info.syncId), DATA_TYPE, meta.dataType); std::map result; for (auto &[key, status] : dbResult) { - result[key] = ConvertDbStatus(status); + if (status < 0) { // pass on softbus error code + result[key] = static_cast(status); + } else { + if (status == DBStatus::COMM_FAILURE) { + if (DMAdapter::GetInstance().ToUUID(key).empty()) { + result[key] = Status::DEVICE_NOT_ONLINE; + } else { + result[key] = Status::PEER_DATABASE_NOT_EXIST; + } + } + result[key] = ConvertDbStatus(status); + } } for (const auto &device : info.devices) { auto it = result.find(device); From a545f5853859934d659c7142639824ff7869b6c9 Mon Sep 17 00:00:00 2001 From: Cuiziyuan Date: Mon, 11 Nov 2024 09:24:41 +0800 Subject: [PATCH 10/25] log Signed-off-by: Cuiziyuan --- .../service/data_share/data/template_data.cpp | 4 ++-- .../data_share/subscriber_managers/rdb_subscriber_manager.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/distributeddataservice/service/data_share/data/template_data.cpp b/services/distributeddataservice/service/data_share/data/template_data.cpp index af4f32736..baf5dc4d5 100644 --- a/services/distributeddataservice/service/data_share/data/template_data.cpp +++ b/services/distributeddataservice/service/data_share/data/template_data.cpp @@ -18,7 +18,7 @@ namespace OHOS::DataShare { bool TemplateNode::Marshal(DistributedData::Serializable::json &node) const { - bool ret = SetValue(node[GET_NAME(update)], predicates); + bool ret = SetValue(node[GET_NAME(update)], update); ret = SetValue(node[GET_NAME(predicates)], predicates); ret = ret && SetValue(node[GET_NAME(scheduler)], scheduler); return ret; @@ -26,7 +26,7 @@ bool TemplateNode::Marshal(DistributedData::Serializable::json &node) const bool TemplateNode::Unmarshal(const DistributedData::Serializable::json &node) { - bool ret = GetValue(node, GET_NAME(update), predicates); + bool ret = GetValue(node, GET_NAME(update), update); ret = GetValue(node, GET_NAME(predicates), predicates); return ret && GetValue(node, GET_NAME(scheduler), scheduler); } diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp index 0e9c17321..facb618c9 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp @@ -346,9 +346,9 @@ int RdbSubscriberManager::Notify(const Key &key, int32_t userId, const std::vect if (!tpl.update_.empty()) { auto [errCode, rowCount] = delegate->UpdateSql(tpl.update_); if (errCode != E_OK) { - ZLOGE("Update failed, err:%{public}d", errCode); + ZLOGE("Update failed, err:%{public}d, %{public}s, %{public}" PRId64 ", %{public}s", + errCode, DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str()); } - ZLOGI("Update finished, data changed:%{public}lld", rowCount); } ZLOGI("emit, valSize: %{public}zu, dataSize:%{public}zu, uri:%{public}s,", From 2f590927e827dacdcd2899920682056d55de1871 Mon Sep 17 00:00:00 2001 From: yanhui Date: Mon, 11 Nov 2024 15:09:29 +0800 Subject: [PATCH 11/25] =?UTF-8?q?=E9=9D=9Eratelimit=E5=9C=BA=E6=99=AF?= =?UTF-8?q?=E7=9A=84=E9=80=8F=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: I149e7aed49ada9886c0e051da6513ea67f8fb993 --- .../communicator/src/app_pipe_handler.cpp | 4 +-- .../communicator/src/app_pipe_handler.h | 2 +- .../adapter/communicator/src/app_pipe_mgr.cpp | 8 ++--- .../adapter/communicator/src/app_pipe_mgr.h | 2 +- .../src/communication_provider_impl.cpp | 4 +-- .../src/communication_provider_impl.h | 2 +- .../communicator/src/communicator_context.cpp | 2 +- .../src/process_communicator_impl.cpp | 17 +++++---- .../communicator/src/softbus_adapter.h | 6 ++-- .../src/softbus_adapter_standard.cpp | 36 +++++++++++-------- .../communicator/src/softbus_client.cpp | 7 ++++ .../adapter/communicator/src/softbus_client.h | 2 ++ .../communication_provider_impl_test.cpp | 20 +++++------ .../softbus_adapter_standard_test.cpp | 4 +-- .../communicator/app_device_change_listener.h | 2 +- .../communicator/communication_provider.h | 5 +-- .../communicator/communicator_context.h | 2 +- .../communicator/process_communicator_impl.h | 2 +- .../app/src/kvstore_device_listener.cpp | 2 +- .../app/src/kvstore_device_listener.h | 2 +- .../service/kvdb/kvdb_service_impl.cpp | 21 ++++++----- 21 files changed, 87 insertions(+), 65 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.cpp b/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.cpp index c29f60aa3..3820f25fe 100644 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.cpp +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.cpp @@ -43,8 +43,8 @@ AppPipeHandler::AppPipeHandler(const PipeInfo &pipeInfo) softbusAdapter_ = SoftBusAdapter::GetInstance(); } -Status AppPipeHandler::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, - uint32_t totalLength, const MessageInfo &info) +std::pair AppPipeHandler::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, + const DataInfo &dataInfo, uint32_t totalLength, const MessageInfo &info) { return softbusAdapter_->SendData(pipeInfo, deviceId, dataInfo, totalLength, info); } diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h b/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h index 2a2508c5d..1fddf667b 100644 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_handler.h @@ -42,7 +42,7 @@ public: // stop DataChangeListener to watch data change; Status StopWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo); // Send data to other device, function will be called back after sent to notify send result. - Status SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, + std::pair SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, uint32_t totalLength, const MessageInfo &info); bool IsSameStartedOnPeer(const struct PipeInfo &pipeInfo, const struct DeviceId &peer); diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp index f37941470..8073d0c83 100644 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.cpp @@ -58,13 +58,13 @@ Status AppPipeMgr::StopWatchDataChange(const AppDataChangeListener *observer, co } // Send data to other device, function will be called back after sent to notify send result. -Status AppPipeMgr::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, - uint32_t totalLength, const MessageInfo &info) +std::pair AppPipeMgr::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, + const DataInfo &dataInfo, uint32_t totalLength, const MessageInfo &info) { if (dataInfo.length > DataBuffer::MAX_TRANSFER_SIZE || dataInfo.length == 0 || dataInfo.data == nullptr || pipeInfo.pipeId.empty() || deviceId.deviceId.empty()) { ZLOGW("Input is invalid, maxSize:%u, current size:%u", DataBuffer::MAX_TRANSFER_SIZE, dataInfo.length); - return Status::ERROR; + return std::make_pair(Status::ERROR, 0); } ZLOGD("pipeInfo:%s ,size:%u, total length:%u", pipeInfo.pipeId.c_str(), dataInfo.length, totalLength); std::shared_ptr appPipeHandler; @@ -73,7 +73,7 @@ Status AppPipeMgr::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, auto it = dataBusMap_.find(pipeInfo.pipeId); if (it == dataBusMap_.end()) { ZLOGW("pipeInfo:%s not found", pipeInfo.pipeId.c_str()); - return Status::KEY_NOT_FOUND; + return std::make_pair(Status::KEY_NOT_FOUND, 0); } appPipeHandler = it->second; } diff --git a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h index 222248c5a..1ffb56599 100644 --- a/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h +++ b/services/distributeddataservice/adapter/communicator/src/app_pipe_mgr.h @@ -36,7 +36,7 @@ public: Status StopWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo); // Send data to other device, function will be called back after sent to notify send result. - Status SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, + std::pair SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, uint32_t totalLength, const MessageInfo &info); // start server Status Start(const PipeInfo &pipeInfo); diff --git a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp index 8b8eb4888..65869012d 100644 --- a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.cpp @@ -48,8 +48,8 @@ Status CommunicationProviderImpl::StopWatchDataChange(const AppDataChangeListene return appPipeMgr_.StopWatchDataChange(observer, pipeInfo); } -Status CommunicationProviderImpl::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, - uint32_t totalLength, const MessageInfo &info) +std::pair CommunicationProviderImpl::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, + const DataInfo &dataInfo, uint32_t totalLength, const MessageInfo &info) { return appPipeMgr_.SendData(pipeInfo, deviceId, dataInfo, totalLength, info); } diff --git a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h index aac05a9fe..5f13ab415 100644 --- a/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h +++ b/services/distributeddataservice/adapter/communicator/src/communication_provider_impl.h @@ -36,7 +36,7 @@ public: Status StopWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo) override; // Send data to other device, function will be called back after sent to notify send result. - Status SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, + std::pair SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, uint32_t totalLength, const MessageInfo &info) override; // start 1 server to listen data from other devices; diff --git a/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp b/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp index ec11a5c8a..76f63db9f 100644 --- a/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp +++ b/services/distributeddataservice/adapter/communicator/src/communicator_context.cpp @@ -73,7 +73,7 @@ Status CommunicatorContext::UnRegSessionListener(const DevChangeListener *observ return Status::SUCCESS; } -void CommunicatorContext::NotifySessionReady(const std::string &deviceId, const int &errCode) +void CommunicatorContext::NotifySessionReady(const std::string &deviceId, int32_t errCode) { if (deviceId.empty()) { ZLOGE("deviceId empty"); diff --git a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp index 6fb5e1377..361214579 100644 --- a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp @@ -139,14 +139,17 @@ DBStatus ProcessCommunicatorImpl::SendData(const DeviceInfos &dstDevInfo, const const DataInfo dataInfo = { const_cast(data), length}; DeviceId destination; destination.deviceId = dstDevInfo.identifier; - Status errCode = CommunicationProvider::GetInstance().SendData(pi, destination, dataInfo, totalLength); - if (errCode == Status::RATE_LIMIT) { - ZLOGD("commProvider_ opening session, status:%{public}d.", static_cast(errCode)); + auto errCode = CommunicationProvider::GetInstance().SendData(pi, destination, dataInfo, totalLength); + if (errCode.first == Status::RATE_LIMIT) { + ZLOGD("commProvider_ opening session, status:%{public}d.", static_cast(errCode.second)); return DBStatus::RATE_LIMIT; } - if (errCode != Status::SUCCESS) { - ZLOGE("commProvider_ SendData Fail."); - return DBStatus::DB_ERROR; + if (errCode.first != Status::SUCCESS) { + ZLOGE("commProvider_ SendData Fail. code:%{public}d", errCode.second); + if (errCode.second == 0) { + return DBStatus::DB_ERROR; + } + return static_cast(errCode.second); } return DBStatus::OK; } @@ -221,7 +224,7 @@ void ProcessCommunicatorImpl::OnDeviceChanged(const DeviceInfo &info, const Devi onDeviceChangeHandler_(devInfo, (type == DeviceChangeType::DEVICE_ONLINE)); } -void ProcessCommunicatorImpl::OnSessionReady(const DeviceInfo &info, const int &errCode) const +void ProcessCommunicatorImpl::OnSessionReady(const DeviceInfo &info, int32_t errCode) const { std::lock_guard lock(sessionMutex_); if (sessionListener_ == nullptr) { diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h index c1d5ffeaf..f478aaef7 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h @@ -52,8 +52,8 @@ public: Status StopWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo); // Send data to other device, function will be called back after sent to notify send result. - Status SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, uint32_t length, - const MessageInfo &info); + std::pair SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, + const DataInfo &dataInfo, uint32_t length, const MessageInfo &info); bool IsSameStartedOnPeer(const struct PipeInfo &pipeInfo, const struct DeviceId &peer); @@ -83,7 +83,6 @@ public: void OnDeviceChanged(const AppDistributedKv::DeviceInfo &info, const AppDistributedKv::DeviceChangeType &type) const override; - private: using Time = std::chrono::steady_clock::time_point; using Duration = std::chrono::steady_clock::duration; @@ -95,6 +94,7 @@ private: void Reuse(const PipeInfo &pipeInfo, const DeviceId &deviceId, uint32_t qosType, std::shared_ptr &conn); void GetExpireTime(std::shared_ptr &conn); + std::pair GetParams(const std::string &deviceId); static constexpr const char *PKG_NAME = "distributeddata-default"; static constexpr Time INVALID_NEXT = std::chrono::steady_clock::time_point::max(); static constexpr uint32_t QOS_COUNT = 3; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index 8edf7755d..d0aefae8c 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -189,40 +189,46 @@ void SoftBusAdapter::GetExpireTime(std::shared_ptr &conn) } } -Status SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, - uint32_t length, const MessageInfo &info) +std::pair SoftBusAdapter::GetParams(const std::string &deviceId) +{ + bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId); + uint32_t qosType = isOHOSType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; + return std::make_pair(qosType, isOHOSType); +} + +std::pair SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, + const DataInfo &dataInfo, uint32_t length, const MessageInfo &info) { std::shared_ptr conn; - bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId.deviceId); - uint32_t qosType = isOHOSType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; + auto param = GetParams(deviceId.deviceId); bool isReuse = false; - connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, isOHOSType, &isReuse](const auto &key, + connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, ¶m, &isReuse](const auto &key, std::vector> &connects) -> bool { for (auto &connect : connects) { - if (connect->GetQoSType() != qosType) { + if (connect->GetQoSType() != param.first) { continue; } - if (!isOHOSType && connect->needRemove) { + if (!param.second && connect->needRemove) { isReuse = true; return false; } conn = connect; return true; } - auto connect = std::make_shared(pipeInfo, deviceId, qosType); + auto connect = std::make_shared(pipeInfo, deviceId, param.first); connects.emplace_back(connect); conn = connect; return true; }); - if (!isOHOSType && isReuse) { - Reuse(pipeInfo, deviceId, qosType, conn); + if (!param.second && isReuse) { + Reuse(pipeInfo, deviceId, param.first, conn); } if (conn == nullptr) { - return Status::ERROR; + return std::make_pair(Status::ERROR, 0); } auto status = conn->CheckStatus(); if (status == Status::RATE_LIMIT) { - return Status::RATE_LIMIT; + return std::make_pair(Status::RATE_LIMIT, 0); } if (status != Status::SUCCESS) { auto task = [this, connect = std::weak_ptr(conn)]() { @@ -233,14 +239,14 @@ Status SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &device }; auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId.deviceId).networkId; ConnectManager::GetInstance()->ApplyConnect(networkId, task); - return Status::RATE_LIMIT; + return std::make_pair(Status::RATE_LIMIT, 0); } - status = conn->SendData(dataInfo, &clientListener_); if ((status != Status::NETWORK_ERROR) && (status != Status::RATE_LIMIT)) { GetExpireTime(conn); } - return status; + auto errCode = conn->GetInnerStatus(); + return std::make_pair(status, errCode); } void SoftBusAdapter::StartCloseSessionTask(const std::string &deviceId) diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp index b01fadfbe..e80ffb91f 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp @@ -75,12 +75,19 @@ Status SoftBusClient::SendData(const DataInfo &dataInfo, const ISocketListener * if (ret != SOFTBUS_OK) { expireTime_ = std::chrono::steady_clock::now(); ZLOGE("send data to socket%{public}d failed, ret:%{public}d.", socket_, ret); + innerError_ = ret; return Status::ERROR; } + innerError_ = 0; expireTime_ = CalcExpireTime(); return Status::SUCCESS; } +int32_t SoftBusClient::GetInnerStatus() +{ + return innerError_; +} + Status SoftBusClient::OpenConnect(const ISocketListener *listener) { std::lock_guard lock(mutex_); diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h index 4a9eeef21..9c5dcf4c2 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -48,6 +48,7 @@ public: int32_t GetSocket() const; uint32_t GetQoSType() const; void UpdateExpireTime(); + int32_t GetInnerStatus(); bool needRemove = false; bool isReuse = false; @@ -85,6 +86,7 @@ private: int32_t socket_ = INVALID_SOCKET_ID; int32_t bindState_ = -1; + int32_t innerError_ = 0; }; } // namespace OHOS::AppDistributedKv diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp index 58c8e5340..6c82c8b76 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/communication_provider_impl_test.cpp @@ -133,8 +133,8 @@ HWTEST_F(CommunicationProviderImplTest, CommunicationProvider005, TestSize.Level const uint8_t *t = reinterpret_cast(content.c_str()); DeviceId di17 = {"127.0.0.2"}; DataInfo data = { const_cast(t), static_cast(content.length())}; - Status status = CommunicationProvider::GetInstance().SendData(id17, di17, data, 0); - EXPECT_NE(status, Status::SUCCESS); + auto status = CommunicationProvider::GetInstance().SendData(id17, di17, data, 0); + EXPECT_NE(status.first, Status::SUCCESS); CommunicationProvider::GetInstance().StopWatchDataChange(dataListener17, id17); CommunicationProvider::GetInstance().Stop(id17); delete dataListener17; @@ -234,8 +234,8 @@ HWTEST_F(CommunicationProviderImplTest, CommunicationProvider011, TestSize.Level const uint8_t *t = reinterpret_cast(content.c_str()); DeviceId di = {"DeviceId"}; DataInfo data = { const_cast(t), static_cast(content.length())}; - Status status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); - EXPECT_EQ(status, Status::ERROR); + auto status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); + EXPECT_EQ(status.first, Status::ERROR); CommunicationProvider::GetInstance().StopWatchDataChange(dataListener, id); CommunicationProvider::GetInstance().Stop(id); delete dataListener; @@ -259,8 +259,8 @@ HWTEST_F(CommunicationProviderImplTest, CommunicationProvider012, TestSize.Level const uint8_t *t = reinterpret_cast(content.c_str()); DeviceId di = {""}; DataInfo data = { const_cast(t), static_cast(content.length())}; - Status status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); - EXPECT_EQ(status, Status::ERROR); + auto status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); + EXPECT_EQ(status.first, Status::ERROR); CommunicationProvider::GetInstance().StopWatchDataChange(dataListener, id); CommunicationProvider::GetInstance().Stop(id); delete dataListener; @@ -282,8 +282,8 @@ HWTEST_F(CommunicationProviderImplTest, CommunicationProvider013, TestSize.Level CommunicationProvider::GetInstance().Start(id); DeviceId di = {"DeviceId"}; DataInfo data = {nullptr, 0}; - Status status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); - EXPECT_EQ(status, Status::ERROR); + auto status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); + EXPECT_EQ(status.first, Status::ERROR); CommunicationProvider::GetInstance().StopWatchDataChange(dataListener, id); CommunicationProvider::GetInstance().Stop(id); delete dataListener; @@ -307,8 +307,8 @@ HWTEST_F(CommunicationProviderImplTest, CommunicationProvider014, TestSize.Level const uint8_t *t = reinterpret_cast(content.c_str()); DeviceId di = {"DeviceId"}; DataInfo data = { const_cast(t), static_cast(content.length())}; - Status status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); - EXPECT_EQ(status, Status::ERROR); + auto status = CommunicationProvider::GetInstance().SendData(id, di, data, 0); + EXPECT_EQ(status.first, Status::ERROR); CommunicationProvider::GetInstance().StopWatchDataChange(dataListener, id); CommunicationProvider::GetInstance().Stop(id); delete dataListener; diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp index 455f5249a..df8207da8 100644 --- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp +++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp @@ -155,8 +155,8 @@ HWTEST_F(SoftbusAdapterStandardTest, SendData, TestSize.Level1) const uint8_t *t = reinterpret_cast(content.c_str()); DeviceId di = {"DeviceId"}; DataInfo data = { const_cast(t), static_cast(content.length())}; - Status status = SoftBusAdapter::GetInstance()->SendData(id, di, data, 11, { MessageType::DEFAULT }); - EXPECT_NE(status, Status::SUCCESS); + auto status = SoftBusAdapter::GetInstance()->SendData(id, di, data, 11, { MessageType::DEFAULT }); + EXPECT_NE(status.first, Status::SUCCESS); SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, id); delete dataListener; } diff --git a/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h b/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h index bba789978..94b6b9f83 100644 --- a/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h +++ b/services/distributeddataservice/adapter/include/communicator/app_device_change_listener.h @@ -32,7 +32,7 @@ public: { return ChangeLevelType::HIGH; } - API_EXPORT virtual void OnSessionReady(const DeviceInfo &info, const int &errCode) const {} + API_EXPORT virtual void OnSessionReady(const DeviceInfo &info, int32_t errCode) const {} }; } // namespace AppDistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/adapter/include/communicator/communication_provider.h b/services/distributeddataservice/adapter/include/communicator/communication_provider.h index e694ae534..94cd0ed4e 100644 --- a/services/distributeddataservice/adapter/include/communicator/communication_provider.h +++ b/services/distributeddataservice/adapter/include/communicator/communication_provider.h @@ -45,8 +45,9 @@ public: virtual Status StopWatchDataChange(const AppDataChangeListener *observer, const PipeInfo &pipeInfo) = 0; // Send data to other device, function will be called back after sent to notify send result - virtual Status SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, - uint32_t totalLength, const MessageInfo &info = { MessageType::DEFAULT }) = 0; + virtual std::pair SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, + const DataInfo &dataInfo, uint32_t totalLength, + const MessageInfo &info = { MessageType::DEFAULT }) = 0; // start one server to listen data from other devices; virtual Status Start(const PipeInfo &pipeInfo) = 0; diff --git a/services/distributeddataservice/adapter/include/communicator/communicator_context.h b/services/distributeddataservice/adapter/include/communicator/communicator_context.h index 1020c57de..ce09ab58a 100644 --- a/services/distributeddataservice/adapter/include/communicator/communicator_context.h +++ b/services/distributeddataservice/adapter/include/communicator/communicator_context.h @@ -36,7 +36,7 @@ public: std::shared_ptr GetThreadPool(); Status RegSessionListener(const DevChangeListener *observer); Status UnRegSessionListener(const DevChangeListener *observer); - void NotifySessionReady(const std::string &deviceId, const int &errCode); + void NotifySessionReady(const std::string &deviceId, int32_t errCode); void NotifySessionClose(const std::string &deviceId); void SetSessionListener(const OnCloseAble &closeAbleCallback); bool IsSessionReady(const std::string &deviceId); diff --git a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h index f16c43d54..4620c0fc4 100644 --- a/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h +++ b/services/distributeddataservice/adapter/include/communicator/process_communicator_impl.h @@ -57,7 +57,7 @@ public: std::vector GetRemoteOnlineDeviceInfosList() override; bool IsSameProcessLabelStartedOnPeerDevice(const DeviceInfos &peerDevInfo) override; void OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const override; - void OnSessionReady(const DeviceInfo &info, const int &errCode) const override; + void OnSessionReady(const DeviceInfo &info, int32_t errCode) const override; API_EXPORT std::shared_ptr GetExtendHeaderHandle( const DistributedDB::ExtendInfo &info) override; diff --git a/services/distributeddataservice/app/src/kvstore_device_listener.cpp b/services/distributeddataservice/app/src/kvstore_device_listener.cpp index d3cd9cd52..65a741b59 100644 --- a/services/distributeddataservice/app/src/kvstore_device_listener.cpp +++ b/services/distributeddataservice/app/src/kvstore_device_listener.cpp @@ -34,7 +34,7 @@ void KvStoreDeviceListener::OnDeviceChanged( ZLOGI("device is %{public}d", type); } -void KvStoreDeviceListener::OnSessionReady(const AppDistributedKv::DeviceInfo &info, const int &errCode) const +void KvStoreDeviceListener::OnSessionReady(const AppDistributedKv::DeviceInfo &info, int32_t errCode) const { (void)errCode; kvStoreDataService_.OnSessionReady(info); diff --git a/services/distributeddataservice/app/src/kvstore_device_listener.h b/services/distributeddataservice/app/src/kvstore_device_listener.h index 849afdabe..f9ee50585 100644 --- a/services/distributeddataservice/app/src/kvstore_device_listener.h +++ b/services/distributeddataservice/app/src/kvstore_device_listener.h @@ -26,7 +26,7 @@ public: void OnDeviceChanged( const AppDistributedKv::DeviceInfo &info, const AppDistributedKv::DeviceChangeType &type) const override; AppDistributedKv::ChangeLevelType GetChangeLevelType() const override; - void OnSessionReady(const AppDistributedKv::DeviceInfo &info, const int &errCode = 0) const override; + void OnSessionReady(const AppDistributedKv::DeviceInfo &info, int32_t errCode = 0) const override; private: KvStoreDataService &kvStoreDataService_; diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 9b61ca257..1b4ea6fb4 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -1122,16 +1122,13 @@ Status KVDBServiceImpl::DoComplete(const StoreMetaData &meta, const SyncInfo &in std::to_string(info.syncId), DATA_TYPE, meta.dataType); std::map result; for (auto &[key, status] : dbResult) { - if (status < 0) { // pass on softbus error code - result[key] = static_cast(status); - } else { - if (status == DBStatus::COMM_FAILURE) { - if (DMAdapter::GetInstance().ToUUID(key).empty()) { - result[key] = Status::DEVICE_NOT_ONLINE; - } else { - result[key] = Status::PEER_DATABASE_NOT_EXIST; - } + if (status == DBStatus::COMM_FAILURE) { + if (DMAdapter::GetInstance().ToUUID(key).empty()) { + result[key] = Status::DEVICE_NOT_ONLINE; + } else { + result[key] = Status::PEER_DATABASE_NOT_EXIST; } + } else { result[key] = ConvertDbStatus(status); } } @@ -1179,6 +1176,12 @@ uint32_t KVDBServiceImpl::GetSyncDelayTime(uint32_t delay, const StoreId &storeI Status KVDBServiceImpl::ConvertDbStatus(DBStatus status) const { + auto innerStatus = static_cast(status); + if (innerStatus < 0) { + ZLOGW("passthrough error code:%{public}d", innerStatus); + return static_cast(status); + } + switch (status) { case DBStatus::BUSY: // fallthrough case DBStatus::DB_ERROR: From 14ab547e313619951b0630bdacf2921784167faf Mon Sep 17 00:00:00 2001 From: yanhui Date: Tue, 12 Nov 2024 14:33:36 +0800 Subject: [PATCH 12/25] =?UTF-8?q?=E9=9A=94=E7=A6=BB=E5=AF=B9JS=E4=BE=A7?= =?UTF-8?q?=E7=9A=84=E5=BD=B1=E5=93=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: I990774166cc6ac76b9ea14c6989ccf0449031397 --- .../service/kvdb/kvdb_service_impl.cpp | 35 +++++++++++-------- .../service/kvdb/kvdb_service_impl.h | 1 + 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 1b4ea6fb4..c6e6ae977 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -1121,14 +1121,10 @@ Status KVDBServiceImpl::DoComplete(const StoreMetaData &meta, const SyncInfo &in SYNC_STORE_ID, Anonymous::Change(meta.storeId), SYNC_APP_ID, meta.bundleName, CONCURRENT_ID, std::to_string(info.syncId), DATA_TYPE, meta.dataType); std::map result; - for (auto &[key, status] : dbResult) { - if (status == DBStatus::COMM_FAILURE) { - if (DMAdapter::GetInstance().ToUUID(key).empty()) { - result[key] = Status::DEVICE_NOT_ONLINE; - } else { - result[key] = Status::PEER_DATABASE_NOT_EXIST; - } - } else { + if (AccessTokenKit::GetTokenTypeFlag(meta.tokenId) != TOKEN_HAP) { + result = ConvertSyncStatusForNative(dbResult); + } else { + for (auto &[key, status] : dbResult) { result[key] = ConvertDbStatus(status); } } @@ -1153,6 +1149,23 @@ Status KVDBServiceImpl::DoComplete(const StoreMetaData &meta, const SyncInfo &in return SUCCESS; } +std::map KVDBServiceImpl::ConvertSyncStatusForNative(const DBResult &dbResult) +{ + std::map result; + for (auto &[key, status] : dbResult) { + auto innerStatus = static_cast(status); + if (innerStatus < 0) { + ZLOGW("Directly transmit error code. code:%{public}d", innerStatus); + result[key] = static_cast(status); + } else if (status == DBStatus::COMM_FAILURE) { + result[key] = Status::DEVICE_NOT_ONLINE; + } else { + result[key] = ConvertDbStatus(status); + } + } + return result; +} + uint32_t KVDBServiceImpl::GetSyncDelayTime(uint32_t delay, const StoreId &storeId) { if (delay != 0) { @@ -1176,12 +1189,6 @@ uint32_t KVDBServiceImpl::GetSyncDelayTime(uint32_t delay, const StoreId &storeI Status KVDBServiceImpl::ConvertDbStatus(DBStatus status) const { - auto innerStatus = static_cast(status); - if (innerStatus < 0) { - ZLOGW("passthrough error code:%{public}d", innerStatus); - return static_cast(status); - } - switch (status) { case DBStatus::BUSY: // fallthrough case DBStatus::DB_ERROR: diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h index c2fcef042..3d07db047 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h @@ -150,6 +150,7 @@ private: void TryToSync(const StoreMetaData &metaData, bool force = false); bool IsRemoteChange(const StoreMetaData &metaData, const std::string &device); bool IsOHOSType(const std::vector &ids); + std::map ConvertSyncStatusForNative(const DBResult &dbResult); static Factory factory_; ConcurrentMap syncAgents_; std::shared_ptr executors_; From 79bbc98b60208eeaa8e31a7d6463610fec8cad47 Mon Sep 17 00:00:00 2001 From: yanhui Date: Tue, 12 Nov 2024 23:21:43 +0800 Subject: [PATCH 13/25] =?UTF-8?q?=E8=AF=84=E5=AE=A1=E6=84=8F=E8=A7=81?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanhui Change-Id: If60053a03ed15440f1c62786926b3ba2ec13f278 --- .../src/process_communicator_impl.cpp | 15 +++--- .../communicator/src/softbus_adapter.h | 2 +- .../src/softbus_adapter_standard.cpp | 48 +++++++++---------- .../communicator/src/softbus_client.cpp | 9 ++-- .../adapter/communicator/src/softbus_client.h | 4 +- .../service/kvdb/kvdb_service_impl.cpp | 25 +++++----- .../service/kvdb/kvdb_service_impl.h | 2 +- 7 files changed, 52 insertions(+), 53 deletions(-) diff --git a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp index 361214579..b3d43e80a 100644 --- a/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp +++ b/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp @@ -139,17 +139,18 @@ DBStatus ProcessCommunicatorImpl::SendData(const DeviceInfos &dstDevInfo, const const DataInfo dataInfo = { const_cast(data), length}; DeviceId destination; destination.deviceId = dstDevInfo.identifier; - auto errCode = CommunicationProvider::GetInstance().SendData(pi, destination, dataInfo, totalLength); - if (errCode.first == Status::RATE_LIMIT) { - ZLOGD("commProvider_ opening session, status:%{public}d.", static_cast(errCode.second)); + auto [errCode, softBusErrCode] = + CommunicationProvider::GetInstance().SendData(pi, destination, dataInfo, totalLength); + if (errCode == Status::RATE_LIMIT) { + ZLOGD("commProvider_ opening session, status:%{public}d.", static_cast(softBusErrCode)); return DBStatus::RATE_LIMIT; } - if (errCode.first != Status::SUCCESS) { - ZLOGE("commProvider_ SendData Fail. code:%{public}d", errCode.second); - if (errCode.second == 0) { + if (errCode != Status::SUCCESS) { + ZLOGE("commProvider_ SendData Fail. code:%{public}d", softBusErrCode); + if (softBusErrCode == 0) { return DBStatus::DB_ERROR; } - return static_cast(errCode.second); + return static_cast(softBusErrCode); } return DBStatus::OK; } diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h index f478aaef7..5e70c3013 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter.h @@ -94,7 +94,7 @@ private: void Reuse(const PipeInfo &pipeInfo, const DeviceId &deviceId, uint32_t qosType, std::shared_ptr &conn); void GetExpireTime(std::shared_ptr &conn); - std::pair GetParams(const std::string &deviceId); + std::pair OpenConnect(const std::shared_ptr &conn, const DeviceId &deviceId); static constexpr const char *PKG_NAME = "distributeddata-default"; static constexpr Time INVALID_NEXT = std::chrono::steady_clock::time_point::max(); static constexpr uint32_t QOS_COUNT = 3; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp index d0aefae8c..73d1bbe1c 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp @@ -189,39 +189,33 @@ void SoftBusAdapter::GetExpireTime(std::shared_ptr &conn) } } -std::pair SoftBusAdapter::GetParams(const std::string &deviceId) -{ - bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId); - uint32_t qosType = isOHOSType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; - return std::make_pair(qosType, isOHOSType); -} - std::pair SoftBusAdapter::SendData(const PipeInfo &pipeInfo, const DeviceId &deviceId, const DataInfo &dataInfo, uint32_t length, const MessageInfo &info) { std::shared_ptr conn; - auto param = GetParams(deviceId.deviceId); + bool isOHOSType = DmAdapter::GetInstance().IsOHOSType(deviceId.deviceId); + uint32_t qosType = isOHOSType ? SoftBusClient::QOS_HML : SoftBusClient::QOS_BR; bool isReuse = false; - connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, ¶m, &isReuse](const auto &key, + connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, isOHOSType, &isReuse](const auto &key, std::vector> &connects) -> bool { for (auto &connect : connects) { - if (connect->GetQoSType() != param.first) { + if (connect->GetQoSType() != qosType) { continue; } - if (!param.second && connect->needRemove) { + if (!isOHOSType && connect->needRemove) { isReuse = true; return false; } conn = connect; return true; } - auto connect = std::make_shared(pipeInfo, deviceId, param.first); + auto connect = std::make_shared(pipeInfo, deviceId, qosType); connects.emplace_back(connect); conn = connect; return true; }); - if (!param.second && isReuse) { - Reuse(pipeInfo, deviceId, param.first, conn); + if (!isOHOSType && isReuse) { + Reuse(pipeInfo, deviceId, qosType, conn); } if (conn == nullptr) { return std::make_pair(Status::ERROR, 0); @@ -231,24 +225,30 @@ std::pair SoftBusAdapter::SendData(const PipeInfo &pipeInfo, co return std::make_pair(Status::RATE_LIMIT, 0); } if (status != Status::SUCCESS) { - auto task = [this, connect = std::weak_ptr(conn)]() { - auto conn = connect.lock(); - if (conn != nullptr) { - conn->OpenConnect(&clientListener_); - } - }; - auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId.deviceId).networkId; - ConnectManager::GetInstance()->ApplyConnect(networkId, task); - return std::make_pair(Status::RATE_LIMIT, 0); + return OpenConnect(conn, deviceId); } status = conn->SendData(dataInfo, &clientListener_); if ((status != Status::NETWORK_ERROR) && (status != Status::RATE_LIMIT)) { GetExpireTime(conn); } - auto errCode = conn->GetInnerStatus(); + auto errCode = conn->GetSoftBusError(); return std::make_pair(status, errCode); } +std::pair SoftBusAdapter::OpenConnect(const std::shared_ptr &conn, + const DeviceId &deviceId) +{ + auto task = [this, connect = std::weak_ptr(conn)]() { + auto conn = connect.lock(); + if (conn != nullptr) { + conn->OpenConnect(&clientListener_); + } + }; + auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId.deviceId).networkId; + ConnectManager::GetInstance()->ApplyConnect(networkId, task); + return std::make_pair(Status::RATE_LIMIT, 0); +} + void SoftBusAdapter::StartCloseSessionTask(const std::string &deviceId) { std::shared_ptr conn; diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp index e80ffb91f..9dfb23b2c 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp @@ -75,17 +75,18 @@ Status SoftBusClient::SendData(const DataInfo &dataInfo, const ISocketListener * if (ret != SOFTBUS_OK) { expireTime_ = std::chrono::steady_clock::now(); ZLOGE("send data to socket%{public}d failed, ret:%{public}d.", socket_, ret); - innerError_ = ret; + softBusError_ = ret; return Status::ERROR; } - innerError_ = 0; + softBusError_ = 0; expireTime_ = CalcExpireTime(); return Status::SUCCESS; } -int32_t SoftBusClient::GetInnerStatus() +int32_t SoftBusClient::GetSoftBusError() { - return innerError_; + std::lock_guard lock(mutex_); + return softBusError_; } Status SoftBusClient::OpenConnect(const ISocketListener *listener) diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h index 9c5dcf4c2..1547e32d8 100644 --- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h +++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h @@ -48,7 +48,7 @@ public: int32_t GetSocket() const; uint32_t GetQoSType() const; void UpdateExpireTime(); - int32_t GetInnerStatus(); + int32_t GetSoftBusError(); bool needRemove = false; bool isReuse = false; @@ -86,7 +86,7 @@ private: int32_t socket_ = INVALID_SOCKET_ID; int32_t bindState_ = -1; - int32_t innerError_ = 0; + int32_t softBusError_ = 0; }; } // namespace OHOS::AppDistributedKv diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index c6e6ae977..6748a6b6b 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -1122,7 +1122,9 @@ Status KVDBServiceImpl::DoComplete(const StoreMetaData &meta, const SyncInfo &in std::to_string(info.syncId), DATA_TYPE, meta.dataType); std::map result; if (AccessTokenKit::GetTokenTypeFlag(meta.tokenId) != TOKEN_HAP) { - result = ConvertSyncStatusForNative(dbResult); + for (auto &[key, status] : dbResult) { + result[key] = ConvertDbStatusNative(status); + } } else { for (auto &[key, status] : dbResult) { result[key] = ConvertDbStatus(status); @@ -1149,21 +1151,16 @@ Status KVDBServiceImpl::DoComplete(const StoreMetaData &meta, const SyncInfo &in return SUCCESS; } -std::map KVDBServiceImpl::ConvertSyncStatusForNative(const DBResult &dbResult) +Status KVDBServiceImpl::ConvertDbStatusNative(DBStatus status) { - std::map result; - for (auto &[key, status] : dbResult) { - auto innerStatus = static_cast(status); - if (innerStatus < 0) { - ZLOGW("Directly transmit error code. code:%{public}d", innerStatus); - result[key] = static_cast(status); - } else if (status == DBStatus::COMM_FAILURE) { - result[key] = Status::DEVICE_NOT_ONLINE; - } else { - result[key] = ConvertDbStatus(status); - } + auto innerStatus = static_cast(status); + if (innerStatus < 0) { + return static_cast(status); + } else if (status == DBStatus::COMM_FAILURE) { + return Status::DEVICE_NOT_ONLINE; + } else { + return ConvertDbStatus(status); } - return result; } uint32_t KVDBServiceImpl::GetSyncDelayTime(uint32_t delay, const StoreId &storeId) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h index 3d07db047..249578772 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.h +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.h @@ -150,7 +150,7 @@ private: void TryToSync(const StoreMetaData &metaData, bool force = false); bool IsRemoteChange(const StoreMetaData &metaData, const std::string &device); bool IsOHOSType(const std::vector &ids); - std::map ConvertSyncStatusForNative(const DBResult &dbResult); + Status ConvertDbStatusNative(DBStatus status); static Factory factory_; ConcurrentMap syncAgents_; std::shared_ptr executors_; From 2f05c4e9470e50c4f3a7f346b651fe0e73794e0f Mon Sep 17 00:00:00 2001 From: yangliu Date: Wed, 13 Nov 2024 20:37:28 +0800 Subject: [PATCH 14/25] update Signed-off-by: yangliu --- .../src/session_manager/route_head_handler_impl.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index 318891be6..f7fb971b3 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -78,15 +78,14 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize ZLOGI("meta data permitted"); return DistributedDB::OK; } + auto devInfo = DmAdapter::GetInstance().GetDeviceInfo(session_.targetDeviceId); + if (devInfo.osType != OH_OS_TYPE) { + ZLOGI("not ohos type. do not use get head size. devicdId:%{public}s", + Anonymous::Change(session_.targetDeviceId).c_str()); + return DistributedDB::OK; + } bool flag = false; auto peerCap = UpgradeManager::GetInstance().GetCapability(session_.targetDeviceId, flag); - auto devInfo = DmAdapter::GetInstance().GetDeviceInfo(session_.targetDeviceId); - if (devInfo.osType != OH_OS_TYPE && devInfo.deviceType == - static_cast(DistributedHardware::DmDeviceType::DEVICE_TYPE_CAR)) { - ZLOGI("type car set version. devicdId:%{public}s", Anonymous::Change(session_.targetDeviceId).c_str()); - flag = true; - peerCap.version = CapMetaData::CURRENT_VERSION; - } if (!flag) { ZLOGI("get peer cap failed"); return DistributedDB::DB_ERROR; From a7eec7aaa154cc4a91f4e17d5de737538ff6add1 Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 14 Nov 2024 09:07:25 +0800 Subject: [PATCH 15/25] update Signed-off-by: yangliu --- .../app/src/session_manager/route_head_handler_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index f7fb971b3..0d2b15417 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -80,7 +80,7 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize } auto devInfo = DmAdapter::GetInstance().GetDeviceInfo(session_.targetDeviceId); if (devInfo.osType != OH_OS_TYPE) { - ZLOGI("not ohos type. do not use get head size. devicdId:%{public}s", + ZLOGI("devicdId:%{public} is not oh type", Anonymous::Change(session_.targetDeviceId).c_str()); return DistributedDB::OK; } From 165c0fb3e16ee4ea0c9319bb33b3531f1d501f7d Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 14 Nov 2024 10:34:01 +0800 Subject: [PATCH 16/25] update Signed-off-by: yangliu --- .../app/src/session_manager/route_head_handler_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index 0d2b15417..90cde6246 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -80,7 +80,7 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize } auto devInfo = DmAdapter::GetInstance().GetDeviceInfo(session_.targetDeviceId); if (devInfo.osType != OH_OS_TYPE) { - ZLOGI("devicdId:%{public} is not oh type", + ZLOGI("devicdId:%{public}s is not oh type", Anonymous::Change(session_.targetDeviceId).c_str()); return DistributedDB::OK; } From f694c64d7333ba438812f6c87692fbda89658a69 Mon Sep 17 00:00:00 2001 From: yangliu Date: Thu, 14 Nov 2024 14:57:17 +0800 Subject: [PATCH 17/25] update Signed-off-by: yangliu --- .../app/src/session_manager/route_head_handler_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index 90cde6246..d602b206c 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -80,7 +80,7 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize } auto devInfo = DmAdapter::GetInstance().GetDeviceInfo(session_.targetDeviceId); if (devInfo.osType != OH_OS_TYPE) { - ZLOGI("devicdId:%{public}s is not oh type", + ZLOGD("devicdId:%{public}s is not oh type", Anonymous::Change(session_.targetDeviceId).c_str()); return DistributedDB::OK; } From b065b35dd53b1872e78083eca5ccd79d5575a0d1 Mon Sep 17 00:00:00 2001 From: yanhui Date: Fri, 1 Nov 2024 10:39:08 +0800 Subject: [PATCH 18/25] convert uuid after offline Signed-off-by: yanhui Change-Id: I57b73f2144f873d07b914f74156418c5eb55ca81 --- .../service/kvdb/kvdb_service_impl.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp index 00911ffe6..d756299d7 100644 --- a/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp +++ b/services/distributeddataservice/service/kvdb/kvdb_service_impl.cpp @@ -1398,7 +1398,15 @@ Status KVDBServiceImpl::RemoveDeviceData(const AppId &appId, const StoreId &stor if (device.empty()) { ret = store->Clean({}, KVDBGeneralStore::NEARBY_DATA, ""); } else { - ret = store->Clean({ DMAdapter::GetInstance().ToUUID(device) }, KVDBGeneralStore::NEARBY_DATA, ""); + auto uuid = DMAdapter::GetInstance().ToUUID(device); + if (uuid.empty()) { + auto tokenId = IPCSkeleton::GetCallingTokenID(); + if (AccessTokenKit::GetTokenTypeFlag(tokenId) != TOKEN_HAP) { + ZLOGW("uuid convert empty! device:%{public}s", Anonymous::Change(device).c_str()); + uuid = device; + } + } + ret = store->Clean({ uuid }, KVDBGeneralStore::NEARBY_DATA, ""); } return ConvertGeneralErr(GeneralError(ret)); } From 2fc775fa0c58b3bea13f7176568eb6c0c8511ee4 Mon Sep 17 00:00:00 2001 From: louzhihao Date: Thu, 14 Nov 2024 20:07:26 +0800 Subject: [PATCH 19/25] reduce timer Change-Id: Ia955b763bf486c99a4d11308473ae7b0cdffeabf Signed-off-by: louzhihao --- .../service/data_share/common/scheduler_manager.cpp | 2 +- .../service/data_share/data_share_service_impl.cpp | 2 +- .../subscriber_managers/rdb_subscriber_manager.cpp | 7 ++++--- .../subscriber_managers/rdb_subscriber_manager.h | 3 ++- .../service/test/data_share_subscriber_managers_test.cpp | 2 +- 5 files changed, 9 insertions(+), 7 deletions(-) diff --git a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp index e02fec3b0..8ed186976 100644 --- a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp +++ b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp @@ -91,7 +91,7 @@ void SchedulerManager::DestoryTimerTask(int64_t timerId) void SchedulerManager::ResetTimerTask(int64_t timerId, int64_t reminderTime) { - TimeServiceClient::GetInstance()->StopTimer(timerId); + // This start also means reset, new one will replace old one TimeServiceClient::GetInstance()->StartTimer(timerId, static_cast(reminderTime)); } 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 fe13493f6..1b31c377a 100644 --- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -216,7 +216,7 @@ int32_t DataShareServiceImpl::AddTemplate(const std::string &uri, const int64_t return templateStrategy_.Execute(context, [&uri, &tpltId, &tplt, &context]() -> int32_t { auto result = TemplateManager::GetInstance().Add( Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId, tplt); - RdbSubscriberManager::GetInstance().Emit(context->uri, tpltId.subscriberId_, context); + RdbSubscriberManager::GetInstance().Emit(context->uri, tpltId.subscriberId_, tpltId.bundleName_, context); return result; }); } diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp index db5a0c2ec..5b22fbce2 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp @@ -359,7 +359,7 @@ void RdbSubscriberManager::Clear() rdbCache_.Clear(); } -void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId, std::shared_ptr context) +void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId, const std::string &bundleName, std::shared_ptr context) { if (!URIUtils::IsDataProxyURI(uri)) { return; @@ -376,8 +376,9 @@ void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId, st SetObserverNotifyOnEnabled(val); return false; }); - SchedulerManager::GetInstance().Execute( - uri, context->currentUserId, context->calledSourceDir, context->version, context->calledBundleName); + Key executeKey(uri, subscriberId, bundleName); + SchedulerManager::GetInstance().Execute(executeKey, context->currentUserId, + context->calledSourceDir, context->version); } RdbSubscriberManager::ObserverNode::ObserverNode(const sptr &observer, uint32_t firstCallerTokenId, uint32_t callerTokenId) diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h index 751d64d5d..0c5272f05 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h @@ -61,7 +61,8 @@ public: void Delete(uint32_t callerTokenId); int Disable(const Key &key, uint32_t firstCallerTokenId); int Enable(const Key &key, std::shared_ptr context); - void Emit(const std::string &uri, int64_t subscriberId, std::shared_ptr context); + void Emit(const std::string &uri, int64_t subscriberId, const std::string &bundleName, + std::shared_ptr context); void Emit(const std::string &uri, std::shared_ptr context); void Emit(const std::string &uri, int32_t userId, DistributedData::StoreMetaData &metaData); void EmitByKey(const Key &key, int32_t userId, const std::string &rdbPath, int version); diff --git a/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp b/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp index b26413388..45061da68 100644 --- a/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp +++ b/services/distributeddataservice/service/test/data_share_subscriber_managers_test.cpp @@ -178,7 +178,7 @@ HWTEST_F(DataShareSubscriberManagersTest, Emit, TestSize.Level1) { auto context = std::make_shared(DATA_SHARE_URI_TEST); RdbSubscriberManager::GetInstance().Emit(DATA_SHARE_URI_TEST, context); - RdbSubscriberManager::GetInstance().Emit(DATA_SHARE_URI_TEST, TEST_SUB_ID, context); + RdbSubscriberManager::GetInstance().Emit(DATA_SHARE_URI_TEST, TEST_SUB_ID, BUNDLE_NAME_TEST, context); TemplateId tpltId; tpltId.subscriberId_ = TEST_SUB_ID; tpltId.bundleName_ = BUNDLE_NAME_TEST; From d61669a8769ee7143fa192262fb027a54d89a419 Mon Sep 17 00:00:00 2001 From: shenpeixing Date: Fri, 15 Nov 2024 11:39:56 +0800 Subject: [PATCH 20/25] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: shenpeixing --- .../distributeddataservice/service/cloud/cloud_service_impl.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index 2be9b5104..cbd0125b3 100644 --- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -196,6 +196,7 @@ int32_t CloudServiceImpl::DoClean(const CloudInfo &cloudInfo, const std::map Date: Sat, 16 Nov 2024 15:06:40 +0800 Subject: [PATCH 21/25] codecheck Signed-off-by: louzhihao Change-Id: I2cb5756d6ac36b6f1d9da9efd6144d9371b6d634 --- .../data_share/subscriber_managers/rdb_subscriber_manager.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp index 5b22fbce2..026648d82 100644 --- a/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp +++ b/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.cpp @@ -359,7 +359,8 @@ void RdbSubscriberManager::Clear() rdbCache_.Clear(); } -void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId, const std::string &bundleName, std::shared_ptr context) +void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId, + const std::string &bundleName, std::shared_ptr context) { if (!URIUtils::IsDataProxyURI(uri)) { return; From 5c34ed7584913cbb0d3ac739bd25506cd8e163d3 Mon Sep 17 00:00:00 2001 From: WangJiangtong Date: Mon, 4 Nov 2024 17:33:57 +0800 Subject: [PATCH 22/25] =?UTF-8?q?=E5=AF=B9=E4=BA=8E=E8=B6=85=E8=BF=87=2020?= =?UTF-8?q?0k=20=E7=9A=84=20RdbChangeNode=20=E6=95=B0=E6=8D=AE=EF=BC=8C?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E4=BD=BF=E7=94=A8=E5=85=B1=E4=BA=AB=E5=86=85?= =?UTF-8?q?=E5=AD=98=E4=BC=A0=E8=BE=93=EF=BC=8C=E9=81=BF=E5=85=8D=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=20IPC=20=E4=BC=A0=E8=BE=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: WangJiangtong --- .../data_share/data_share_obs_proxy.cpp | 116 +++++++ .../service/data_share/data_share_obs_proxy.h | 4 + .../data_share/data_share_types_util.cpp | 16 +- .../service/test/BUILD.gn | 1 + .../test/data_share_obs_proxy_test.cpp | 318 ++++++++++++++++++ 5 files changed, 454 insertions(+), 1 deletion(-) create mode 100644 services/distributeddataservice/service/test/data_share_obs_proxy_test.cpp diff --git a/services/distributeddataservice/service/data_share/data_share_obs_proxy.cpp b/services/distributeddataservice/service/data_share/data_share_obs_proxy.cpp index ce6440327..769ea0b3e 100644 --- a/services/distributeddataservice/service/data_share/data_share_obs_proxy.cpp +++ b/services/distributeddataservice/service/data_share/data_share_obs_proxy.cpp @@ -15,13 +15,124 @@ #define LOG_TAG "ObserverProxy" #include "data_share_obs_proxy.h" +#include "datashare_errno.h" #include "itypes_util.h" +#include "datashare_itypes_utils.h" #include "log_print.h" namespace OHOS { namespace DataShare { static constexpr int REQUEST_CODE = 0; +int RdbObserverProxy::CreateAshmem(RdbChangeNode &changeNode) +{ + OHOS::sptr memory = Ashmem::CreateAshmem(ASHMEM_NAME, DATA_SIZE_ASHMEM_TRANSFER_LIMIT); + if (memory == nullptr) { + ZLOGE("failed to create Ashmem instance."); + return E_ERROR; + } + bool mapRet = memory->MapReadAndWriteAshmem(); + if (!mapRet) { + ZLOGE("failed to map read and write ashmem, ret=%{public}d", mapRet); + memory->CloseAshmem(); + return E_ERROR; + } + if (changeNode.memory_ != nullptr) { + ZLOGE( + "Unknown error: changeNode.memory_ should be null, but something is there %{public}p", + (void *)changeNode.memory_ + ); + return E_ERROR; + } + changeNode.memory_ = memory; + return E_OK; +} + +int RdbObserverProxy::WriteAshmem(RdbChangeNode &changeNode, void *data, int len, int &offset) +{ + if (changeNode.memory_ == nullptr) { + ZLOGE("changeNode memory is nullptr."); + return E_ERROR; + } + bool writeRet = changeNode.memory_->WriteToAshmem(data, len, offset); + if (!writeRet) { + ZLOGE("failed to write into ashmem, ret=%{public}d", writeRet); + changeNode.memory_->UnmapAshmem(); + changeNode.memory_->CloseAshmem(); + changeNode.memory_ = nullptr; + return E_ERROR; + } + offset += len; + return E_OK; +} + +int RdbObserverProxy::SerializeDataIntoAshmem(RdbChangeNode &changeNode) +{ + if (changeNode.memory_ == nullptr) { + ZLOGE("changeNode.memory_ is nullptr"); + return E_ERROR; + } + // move data + // simple serialization: [vec_size(int32); str1_len(int32), str1; str2_len(int32), str2; ...], + // total byte size is recorded in changeNode.size + int offset = 0; + // 4 byte for length int + int intLen = 4; + int dataSize = changeNode.data_.size(); + if (WriteAshmem(changeNode, (void *)&dataSize, intLen, offset) != E_OK) { + ZLOGE("failed to write data with len %{public}d, offset %{public}d.", intLen, offset); + return E_ERROR; + } + for (int i = 0; i < dataSize; i++) { + const char *str = changeNode.data_[i].c_str(); + int strLen = changeNode.data_[i].length(); + // write length int + if (WriteAshmem(changeNode, (void *)&strLen, intLen, offset) != E_OK) { + ZLOGE("failed to write data with index %{public}d, len %{public}d, offset %{public}d.", i, intLen, offset); + return E_ERROR; + } + // write str + if (WriteAshmem(changeNode, (void *)str, strLen, offset) != E_OK) { + ZLOGE("failed to write data with index %{public}d, len %{public}d, offset %{public}d.", i, strLen, offset); + return E_ERROR; + } + } + changeNode.size_ = offset; + return E_OK; +} + +int RdbObserverProxy::PrepareRdbChangeNodeData(RdbChangeNode &changeNode) +{ + // If data size is bigger than the limit, move it to the shared memory + // 4 byte for length int + int intByteLen = 4; + int size = intByteLen; + for (int i = 0; i < changeNode.data_.size(); i++) { + size += intByteLen; + size += changeNode.data_[i].length(); + } + if (size > DATA_SIZE_ASHMEM_TRANSFER_LIMIT) { + ZLOGE("Data to write into ashmem is %{public}d bytes, over 10M.", size); + return E_ERROR; + } + if (size > DATA_SIZE_IPC_TRANSFER_LIMIT) { + ZLOGD("Data size is over 200k, transfer it by the shared memory"); + if (RdbObserverProxy::CreateAshmem(changeNode) != E_OK) { + ZLOGE("failed to create ashmem."); + return E_ERROR; + } + if (RdbObserverProxy::SerializeDataIntoAshmem(changeNode) != E_OK) { + ZLOGE("failed to serialize data into ashmem."); + return E_ERROR; + } + // clear original data spot + changeNode.data_.clear(); + changeNode.isSharedMemory_ = true; + ZLOGD("Preparation done. Data size: %{public}d", changeNode.size_); + } + return E_OK; +} + void RdbObserverProxy::OnChangeFromRdb(RdbChangeNode &changeNode) { MessageParcel parcel; @@ -29,6 +140,11 @@ void RdbObserverProxy::OnChangeFromRdb(RdbChangeNode &changeNode) return; } + if (RdbObserverProxy::PrepareRdbChangeNodeData(changeNode) != E_OK) { + ZLOGE("failed to prepare RdbChangeNode data."); + return; + } + if (!ITypesUtil::Marshal(parcel, changeNode)) { ZLOGE("failed to WriteParcelable changeNode "); return; diff --git a/services/distributeddataservice/service/data_share/data_share_obs_proxy.h b/services/distributeddataservice/service/data_share/data_share_obs_proxy.h index b54e0b0ce..42a3f1065 100644 --- a/services/distributeddataservice/service/data_share/data_share_obs_proxy.h +++ b/services/distributeddataservice/service/data_share/data_share_obs_proxy.h @@ -28,6 +28,10 @@ public: void OnChangeFromRdb(RdbChangeNode &changeNode) override; private: + int PrepareRdbChangeNodeData(RdbChangeNode &changeNode); + int CreateAshmem(RdbChangeNode &changeNode); + int WriteAshmem(RdbChangeNode &changeNode, void *data, int len, int &offset); + int SerializeDataIntoAshmem(RdbChangeNode &changeNode); static inline BrokerDelegator delegator_; }; diff --git a/services/distributeddataservice/service/data_share/data_share_types_util.cpp b/services/distributeddataservice/service/data_share/data_share_types_util.cpp index 804a6f76d..32f850f1d 100644 --- a/services/distributeddataservice/service/data_share/data_share_types_util.cpp +++ b/services/distributeddataservice/service/data_share/data_share_types_util.cpp @@ -85,7 +85,21 @@ bool Unmarshalling(PredicateTemplateNode &predicateTemplateNode, MessageParcel & template<> bool Marshalling(const RdbChangeNode &changeNode, MessageParcel &parcel) { - return ITypesUtil::Marshal(parcel, changeNode.uri_, changeNode.templateId_, changeNode.data_); + bool firstPart = ITypesUtil::Marshal( + parcel, changeNode.uri_, changeNode.templateId_, changeNode.data_, changeNode.isSharedMemory_); + if (!firstPart) { + return false; + } + if (changeNode.isSharedMemory_) { + if (changeNode.memory_ == nullptr) { + ZLOGE("Used shared memory but ashmem is nullptr."); + return false; + } + if (!parcel.WriteAshmem(changeNode.memory_)) { + return false; + } + } + return ITypesUtil::Marshal(parcel, changeNode.size_); } template<> diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index f2afadabb..2f4203b32 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -970,6 +970,7 @@ ohos_unittest("DataShareServiceImplTest") { "${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_share_obs_proxy_test.cpp", "data_share_profile_config_test.cpp", "data_share_service_impl_test.cpp", "data_share_service_stub_test.cpp", diff --git a/services/distributeddataservice/service/test/data_share_obs_proxy_test.cpp b/services/distributeddataservice/service/test/data_share_obs_proxy_test.cpp new file mode 100644 index 000000000..ec335f6ee --- /dev/null +++ b/services/distributeddataservice/service/test/data_share_obs_proxy_test.cpp @@ -0,0 +1,318 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +#define LOG_TAG "DataShareObsProxyTest" + +#include +#include + +#include "data_share_obs_proxy.h" +#include "datashare_errno.h" +#include "log_print.h" + +namespace OHOS::Test { +using namespace testing::ext; +using namespace OHOS::DataShare; +std::string BUNDLE_NAME = "ohos.datasharetest.demo"; +constexpr int64_t TEST_SUB_ID = 100; + +class DataShareObsProxyTest : public testing::Test { +public: + static void SetUpTestCase(void){}; + static void TearDownTestCase(void){}; + void SetUp(){}; + void TearDown(){}; +}; + +RdbChangeNode SampleRdbChangeNode() +{ + TemplateId tplId; + tplId.subscriberId_ = TEST_SUB_ID; + tplId.bundleName_ = BUNDLE_NAME; + + RdbChangeNode node; + node.uri_ = std::string(""); + node.templateId_ = tplId; + node.data_ = std::vector(); + node.isSharedMemory_ = false; + node.memory_ = nullptr; + node.size_ = 0; + + return node; +} + +/** +* @tc.name: CreateAshmem +* @tc.desc: test CreateAshmem function +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DataShareObsProxyTest, CreateAshmem, TestSize.Level1) +{ + ZLOGI("CreateAshmem starts"); + RdbChangeNode node = SampleRdbChangeNode(); + + OHOS::sptr fake = nullptr; + RdbObserverProxy proxy(fake); + int ret = proxy.CreateAshmem(node); + EXPECT_EQ(ret, DataShare::E_OK); + EXPECT_NE(node.memory_, nullptr); + ZLOGI("CreateAshmem ends"); +} + +/** +* @tc.name: WriteAshmem001 +* @tc.desc: test WriteAshmem function. Write an int +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DataShareObsProxyTest, WriteAshmem001, TestSize.Level1) +{ + ZLOGI("WriteAshmem001 starts"); + RdbChangeNode node = SampleRdbChangeNode(); + OHOS::sptr fake = nullptr; + RdbObserverProxy proxy(fake); + int retCreate = proxy.CreateAshmem(node); + EXPECT_EQ(retCreate, DataShare::E_OK); + + int len = 10; + int intLen = 4; + int offset = 0; + int ret = proxy.WriteAshmem(node, (void *)&len, intLen, offset); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(offset, intLen); + + // read from the start + const void *read = node.memory_->ReadFromAshmem(intLen, 0); + EXPECT_NE(read, nullptr); + int lenRead = *reinterpret_cast(read); + EXPECT_EQ(len, lenRead); + ZLOGI("WriteAshmem001 ends"); +} + +/** +* @tc.name: WriteAshmem002 +* @tc.desc: test WriteAshmem function. Write a str +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DataShareObsProxyTest, WriteAshmem002, TestSize.Level1) +{ + ZLOGI("WriteAshmem002 starts"); + RdbChangeNode node = SampleRdbChangeNode(); + OHOS::sptr fake = nullptr; + RdbObserverProxy proxy(fake); + int retCreate = proxy.CreateAshmem(node); + EXPECT_EQ(retCreate, DataShare::E_OK); + + std::string string("Hello World"); + const char *str = string.c_str(); + int len = string.length(); + int offset = 0; + int ret = proxy.WriteAshmem(node, (void *)str, len, offset); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(offset, len); + + // read from the start + const void *read = node.memory_->ReadFromAshmem(len, 0); + EXPECT_NE(read, nullptr); + const char *strRead = reinterpret_cast(read); + std::string stringRead(strRead, len); + EXPECT_EQ(stringRead, string); + ZLOGI("WriteAshmem002 ends"); +} + +/** +* @tc.name: WriteAshmem003 +* @tc.desc: test WriteAshmem function with error +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DataShareObsProxyTest, WriteAshmem003, TestSize.Level1) +{ + ZLOGI("WriteAshmem003 starts"); + RdbChangeNode node = SampleRdbChangeNode(); + OHOS::sptr fake = nullptr; + RdbObserverProxy proxy(fake); + + OHOS::sptr memory = Ashmem::CreateAshmem("WriteAshmem003", 2); + EXPECT_NE(memory, nullptr); + bool mapRet = memory->MapReadAndWriteAshmem(); + ASSERT_TRUE(mapRet); + node.memory_ = memory; + + int len = 10; + int offset = 0; + int ret = proxy.WriteAshmem(node, (void *)&len, 4, offset); + EXPECT_EQ(ret, E_ERROR); + ZLOGI("WriteAshmem003 ends"); +} + +/** +* @tc.name: SerializeDataIntoAshmem +* @tc.desc: test SerializeDataIntoAshmem function +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DataShareObsProxyTest, SerializeDataIntoAshmem, TestSize.Level1) +{ + ZLOGI("SerializeDataIntoAshmem starts"); + RdbChangeNode node = SampleRdbChangeNode(); + + OHOS::sptr fake = nullptr; + RdbObserverProxy proxy(fake); + + int retCreate = proxy.CreateAshmem(node); + EXPECT_EQ(retCreate, E_OK); + + // Push three times + node.data_.push_back(BUNDLE_NAME); + node.data_.push_back(BUNDLE_NAME); + node.data_.push_back(BUNDLE_NAME); + + int intLen = 4; + // item length size + (str length size + str length) * 3 + int offset = intLen + (intLen + strlen(BUNDLE_NAME.c_str())) * 3; + int retSe = proxy.SerializeDataIntoAshmem(node); + EXPECT_EQ(retSe, E_OK); + EXPECT_EQ(node.size_, offset); + + offset = 0; + const void *vecLenRead = node.memory_->ReadFromAshmem(intLen, offset); + EXPECT_NE(vecLenRead, nullptr); + int vecLen = *reinterpret_cast(vecLenRead); + EXPECT_EQ(vecLen, 3); + offset += intLen; + + // 3 strings in the vec + for (int i = 0; i < 3; i++) { + const void *strLenRead = node.memory_->ReadFromAshmem(intLen, offset); + EXPECT_NE(strLenRead, nullptr); + int strLen = *reinterpret_cast(strLenRead); + EXPECT_EQ(strLen, BUNDLE_NAME.length()); + offset += intLen; + + const void *strRead = node.memory_->ReadFromAshmem(strLen, offset); + EXPECT_NE(strRead, nullptr); + const char *str = reinterpret_cast(strRead); + std::string stringRead(str, strLen); + EXPECT_EQ(stringRead, BUNDLE_NAME); + offset += strLen; + } + ZLOGI("SerializeDataIntoAshmem ends"); +} + +/** +* @tc.name: SerializeDataIntoAshmem002 +* @tc.desc: test SerializeDataIntoAshmem function +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DataShareObsProxyTest, SerializeDataIntoAshmem002, TestSize.Level1) +{ + ZLOGI("SerializeDataIntoAshmem starts"); + RdbChangeNode node = SampleRdbChangeNode(); + + OHOS::sptr fake = nullptr; + RdbObserverProxy proxy(fake); + + // Push three times + node.data_.push_back(BUNDLE_NAME); + node.data_.push_back(BUNDLE_NAME); + node.data_.push_back(BUNDLE_NAME); + + // memory too small for vec length + OHOS::sptr memory = Ashmem::CreateAshmem("SerializeDataIntoAshmem002", 2); + EXPECT_NE(memory, nullptr); + bool mapRet = memory->MapReadAndWriteAshmem(); + ASSERT_TRUE(mapRet); + node.memory_ = memory; + + int retSe = proxy.SerializeDataIntoAshmem(node); + EXPECT_EQ(retSe, E_ERROR); + EXPECT_EQ(node.size_, 0); + EXPECT_EQ(node.data_.size(), 3); + ASSERT_FALSE(node.isSharedMemory_); + + // memory too small for string length + OHOS::sptr memory2 = Ashmem::CreateAshmem("SerializeDataIntoAshmem002", 6); + EXPECT_NE(memory2, nullptr); + mapRet = memory2->MapReadAndWriteAshmem(); + ASSERT_TRUE(mapRet); + node.memory_ = memory2; + + retSe = proxy.SerializeDataIntoAshmem(node); + EXPECT_EQ(retSe, E_ERROR); + EXPECT_EQ(node.size_, 0); + EXPECT_EQ(node.data_.size(), 3); + ASSERT_FALSE(node.isSharedMemory_); + + // memory too small for string + OHOS::sptr memory3 = Ashmem::CreateAshmem("SerializeDataIntoAshmem002", 10); + EXPECT_NE(memory3, nullptr); + mapRet = memory3->MapReadAndWriteAshmem(); + ASSERT_TRUE(mapRet); + node.memory_ = memory3; + + retSe = proxy.SerializeDataIntoAshmem(node); + EXPECT_EQ(retSe, E_ERROR); + EXPECT_EQ(node.size_, 0); + EXPECT_EQ(node.data_.size(), 3); + ASSERT_FALSE(node.isSharedMemory_); + + ZLOGI("SerializeDataIntoAshmem002 ends"); +} + +/** +* @tc.name: PreparationData +* @tc.desc: test PrepareRdbChangeNodeData function +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DataShareObsProxyTest, PreparationData, TestSize.Level1) +{ + ZLOGI("PreparationData starts"); + RdbChangeNode node = SampleRdbChangeNode(); + OHOS::sptr fake = nullptr; + RdbObserverProxy proxy(fake); + + // Push three times, less than 200k + node.data_.push_back(BUNDLE_NAME); + node.data_.push_back(BUNDLE_NAME); + node.data_.push_back(BUNDLE_NAME); + + int ret = proxy.PrepareRdbChangeNodeData(node); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(node.data_.size(), 3); + EXPECT_FALSE(node.isSharedMemory_); + + // Try to fake a 200k data. BUNDLE_NAME is 23 byte long and 7587 BUNDLE_NAMEs is over 200k. + for (int i = 0; i < 7587; i++) { + node.data_.push_back(BUNDLE_NAME); + } + ret = proxy.PrepareRdbChangeNodeData(node); + EXPECT_EQ(ret, E_OK); + EXPECT_EQ(node.data_.size(), 0); + EXPECT_TRUE(node.isSharedMemory_); + + // Try to fake data over 10M. Write data of such size should fail because it exceeds the limit. + for (int i = 0; i < 388362; i++) { + node.data_.push_back(BUNDLE_NAME); + } + ret = proxy.PrepareRdbChangeNodeData(node); + EXPECT_EQ(ret, E_ERROR); + + ZLOGI("PreparationData ends"); +} +} // namespace OHOS::Test \ No newline at end of file From 150fd03a5700172a5669a187505c66bc523f6d38 Mon Sep 17 00:00:00 2001 From: yangliu Date: Sun, 17 Nov 2024 20:12:57 +0800 Subject: [PATCH 23/25] update Signed-off-by: yangliu --- .../app/src/session_manager/session_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index cc3258017..8322720d4 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -66,6 +66,7 @@ Session SessionManager::GetSession(const SessionPoint &from, const std::string & return session; } for (const auto &user : users) { + aclParams.accCallee.userId = user.id; auto [isPermitted, isSameAccount] = AuthDelegate::GetInstance()->CheckAccess(from.userId, user.id, targetDeviceId, aclParams); if (isPermitted) { From 3ad3614bf7a04a4391271d2d0eff51afdfbcf390 Mon Sep 17 00:00:00 2001 From: yangliu Date: Mon, 18 Nov 2024 10:56:46 +0800 Subject: [PATCH 24/25] update Signed-off-by: yangliu --- .../app/src/session_manager/session_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index 8322720d4..15ff12854 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -79,7 +79,7 @@ Session SessionManager::GetSession(const SessionPoint &from, const std::string & } } } - ZLOGD("access to peer user:%{public}d", session.targetUserIds[0]); + ZLOGD("access to peer user count:%{public}zu", session.targetUserIds.size()); return session; } From 7ee52257f9f77c501a095df7769f41f771d53718 Mon Sep 17 00:00:00 2001 From: yangliu Date: Mon, 18 Nov 2024 15:37:34 +0800 Subject: [PATCH 25/25] update Signed-off-by: yangliu --- .../app/src/session_manager/session_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp index 15ff12854..3fd3f6a52 100644 --- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp +++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp @@ -79,7 +79,7 @@ Session SessionManager::GetSession(const SessionPoint &from, const std::string & } } } - ZLOGD("access to peer user count:%{public}zu", session.targetUserIds.size()); + ZLOGD("access to peer users:%{public}s", DistributedData::Serializable::Marshall(session.targetUserIds).c_str()); return session; }