From c64005644a4be928312b814bec31e7cb4099c65e Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Mon, 8 Nov 2021 10:43:33 +0800 Subject: [PATCH 1/8] fix the uninstaller, backup, Encrypt, broadcast function. Signed-off-by: zuojiangjiang --- .../src/client_permission_validator.cpp | 16 + .../src/client_permission_validator.h | 22 +- .../app/src/backup_handler.cpp | 114 ++-- .../app/src/backup_handler.h | 9 + .../app/src/kvstore_data_service.cpp | 527 +++++++++--------- .../app/src/kvstore_data_service.h | 45 +- .../app/src/kvstore_impl.cpp | 3 +- .../app/src/kvstore_meta_manager.cpp | 41 +- .../app/src/kvstore_meta_manager.h | 6 +- .../app/src/single_kvstore_impl.cpp | 2 +- .../app/src/uninstaller/uninstaller_impl.cpp | 5 +- .../app/src/uninstaller/uninstaller_impl.h | 7 +- .../app/test/unittest/kvstore_backup_test.cpp | 246 +++++++- .../test/unittest/kvstore_data_service.cpp | 514 +++++++++-------- 14 files changed, 969 insertions(+), 588 deletions(-) diff --git a/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp b/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp index 0c8390ef2..b004c9376 100755 --- a/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp +++ b/services/distributeddataservice/adapter/permission/src/client_permission_validator.cpp @@ -22,6 +22,22 @@ namespace OHOS { namespace DistributedKv { +ClientPermissionChangedCallback::ClientPermissionChangedCallback(std::int32_t pid, std::int32_t uid) +{ + this->pid_ = pid; + this->uid_ = uid; +} + +std::int32_t ClientPermissionChangedCallback::GetPid() +{ + return this->pid_; +} + +void ClientPermissionChangedCallback::OnChanged(const int32_t uid) +{ + +} + void ClientPermissionValidator::UpdatePermissionStatus( int32_t uid, const std::string &permissionType, bool permissionStatus) { diff --git a/services/distributeddataservice/adapter/permission/src/client_permission_validator.h b/services/distributeddataservice/adapter/permission/src/client_permission_validator.h index eaece3cd6..b31bcc902 100755 --- a/services/distributeddataservice/adapter/permission/src/client_permission_validator.h +++ b/services/distributeddataservice/adapter/permission/src/client_permission_validator.h @@ -16,16 +16,36 @@ #ifndef CLIENT_PERMISSION_VALIDATOR_H #define CLIENT_PERMISSION_VALIDATOR_H -#include "permission_validator.h" #include #include #include +#include "bundlemgr/on_permission_changed_callback_host.h" +#include "permission_validator.h" namespace OHOS { namespace DistributedKv { const std::string DISTRIBUTED_DATASYNC = "ohos.permission.DISTRIBUTED_DATASYNC"; +// Callback registered with BMS to listen App permission changes. +class ClientPermissionChangedCallback : public AppExecFwk::OnPermissionChangedCallbackHost { +public: + ClientPermissionChangedCallback(std::int32_t pid, std::int32_t uid); + + ~ClientPermissionChangedCallback() override = default; + + std::int32_t GetPid(); + + void OnChanged(const int32_t uid) override; +private: + std::int32_t pid_; + std::int32_t uid_; +}; + +struct AppPermissionInfo : AppThreadInfo { + sptr callback; +}; + class ClientPermissionValidator { public: static ClientPermissionValidator &GetInstance() diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index 85962c626..d07657207 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -58,7 +58,7 @@ void BackupHandler::BackSchedule() } std::map results; ZLOGI("BackupHandler Schedule Every start."); - if (KvStoreMetaManager::GetInstance().GetFullMetaData(results)) { + if (!KvStoreMetaManager::GetInstance().GetFullMetaData(results)) { ZLOGE("GetFullMetaData failed."); return; } @@ -82,24 +82,16 @@ void BackupHandler::BackSchedule() void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) { ZLOGI("SingleKvStoreBackup start."); - auto pathType = KvStoreAppManager::ConvertPathType( - metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); - if (!ForceCreateDirectory(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { - ZLOGE("SingleKvStoreBackup backup create directory failed."); - return; - } - - DistributedDB::CipherPassword password; - const std::vector &secretKey = metaData.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { - ZLOGE("Set secret key failed."); + BackupPara backupPara; + auto initPara = InitBackupPara(metaData, backupPara); + if (!initPara) { return; } DistributedDB::KvStoreNbDelegate::Option dbOption; dbOption.createIfNecessary = false; - dbOption.isEncryptedDb = password.GetSize() > 0; - dbOption.passwd = password; + dbOption.isEncryptedDb = backupPara.password.GetSize() > 0; + dbOption.passwd = backupPara.password; dbOption.createDirByStoreIdOnly = true; dbOption.secOption = KvStoreAppManager::ConvertSecurity(metaData.kvStoreMetaData.securityLevel); @@ -107,10 +99,10 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(metaData.kvStoreMetaData.bundleName)); std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, - metaData.kvStoreMetaData.bundleName, pathType); - delegateMgr->SetKvStoreConfig( - { Constant::Concatenate({appDataStoragePath, "/", metaData.kvStoreMetaData.bundleName })}); - + metaData.kvStoreMetaData.bundleName, backupPara.pathType); + DistributedDB::KvStoreConfig kvStoreConfig; + kvStoreConfig.dataDir = appDataStoragePath; + delegateMgr->SetKvStoreConfig(kvStoreConfig); std::function fun = [&](DistributedDB::DBStatus status, DistributedDB::KvStoreNbDelegate *delegate) { auto del = std::shared_ptr(delegateMgr); @@ -129,14 +121,8 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) ZLOGW("SingleKvStoreBackup export"); if (status == DistributedDB::DBStatus::OK) { - std::string backupName = Constant::Concatenate( - { metaData.kvStoreMetaData.userId, "_", metaData.kvStoreMetaData.appId, "_", - metaData.kvStoreMetaData.storeId }); - auto backupFullName = Constant::Concatenate({ - BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", - GetHashedBackupName(backupName) - }); - auto backupBackFullName = Constant::Concatenate({ backupFullName, ".", "backup" }); + auto backupFullName = backupPara.backupFullName; + auto backupBackFullName = backupPara.backupBackFullName; RenameFile(backupFullName, backupBackFullName); status = delegate->Export(backupFullName, dbOption.passwd); if (status == DistributedDB::DBStatus::OK) { @@ -154,33 +140,26 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) { - auto pathType = KvStoreAppManager::ConvertPathType(metaData.kvStoreMetaData.bundleName, - metaData.kvStoreMetaData.securityLevel); - if (!ForceCreateDirectory(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { - ZLOGE("MultiKvStoreBackup backup create directory failed."); - return; - } ZLOGI("MultiKvStoreBackup start."); - - DistributedDB::CipherPassword password; - const std::vector &secretKey = metaData.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { - ZLOGE("Set secret key value failed. len is (%d)", int32_t(secretKey.size())); + BackupPara backupPara; + auto initPara = InitBackupPara(metaData, backupPara); + if (!initPara) { return; } DistributedDB::KvStoreDelegate::Option option; option.createIfNecessary = false; - option.isEncryptedDb = password.GetSize() > 0; - option.passwd = password; + option.isEncryptedDb = backupPara.password.GetSize() > 0; + option.passwd = backupPara.password; option.createDirByStoreIdOnly = true; auto *delegateMgr = new DistributedDB::KvStoreDelegateManager(metaData.kvStoreMetaData.appId, AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(metaData.kvStoreMetaData.bundleName)); std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, - metaData.kvStoreMetaData.bundleName, pathType); - delegateMgr->SetKvStoreConfig( - {Constant::Concatenate({appDataStoragePath, "/", metaData.kvStoreMetaData.bundleName})}); + metaData.kvStoreMetaData.bundleName, backupPara.pathType); + DistributedDB::KvStoreConfig kvStoreConfig; + kvStoreConfig.dataDir = appDataStoragePath; + delegateMgr->SetKvStoreConfig(kvStoreConfig); std::function fun = [&](DistributedDB::DBStatus status, DistributedDB::KvStoreDelegate *delegate) { auto del = std::shared_ptr(delegateMgr); @@ -190,14 +169,9 @@ void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) } ZLOGW("MultiKvStoreBackup export"); if (status == DistributedDB::DBStatus::OK) { - std::string backupName = - Constant::Concatenate({metaData.kvStoreMetaData.userId, "_", - metaData.kvStoreMetaData.appId, "_", metaData.kvStoreMetaData.storeId}); - auto backupFullName = Constant::Concatenate({ - BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", - GetHashedBackupName(backupName) - }); - auto backupBackFullName = Constant::Concatenate({backupFullName, ".", "backup"}); + auto backupFullName = backupPara.backupFullName; + auto backupBackFullName = backupPara.backupBackFullName; + RenameFile(backupFullName, backupBackFullName); status = delegate->Export(backupFullName, option.passwd); if (status == DistributedDB::DBStatus::OK) { @@ -214,6 +188,42 @@ void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) delegateMgr->GetKvStore(metaData.kvStoreMetaData.storeId, option, fun); } +bool BackupHandler::InitBackupPara(const MetaData &metaData, BackupPara &backupPara) +{ + BackupPara backupParameter; + auto pathType = KvStoreAppManager::ConvertPathType( + metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); + if (!ForceCreateDirectory(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { + ZLOGE("MultiKvStoreBackup backup create directory failed."); + return false; + } + + DistributedDB::CipherPassword password; + const std::vector &secretKey = metaData.secretKeyMetaData.secretKey; + if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { + ZLOGE("Set secret key value failed. len is (%d)", int32_t(secretKey.size())); + return false; + } + + std::initializer_list backList = {metaData.kvStoreMetaData.userId, "_", + metaData.kvStoreMetaData.appId, "_", metaData.kvStoreMetaData.storeId}; + std::string backupName = Constant::Concatenate(backList); + std::initializer_list backFullList = { + BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType), "/", + GetHashedBackupName(backupName)}; + auto backupFullName = Constant::Concatenate(backFullList); + std::initializer_list backNameList = {backupFullName, ".", "backup"}; + auto backupBackFullName = Constant::Concatenate(backNameList); + + backupParameter.pathType = pathType; + backupParameter.password = password; + backupParameter.backupFullName = backupFullName; + backupParameter.backupBackFullName = backupBackFullName; + backupPara = backupParameter; + + return true; +} + bool BackupHandler::SingleKvStoreRecover(MetaData &metaData, DistributedDB::KvStoreNbDelegate *delegate) { ZLOGI("start."); @@ -292,9 +302,9 @@ bool BackupHandler::MultiKvStoreRecover(MetaData &metaData, std::string BackupHandler::backupDirCe_; std::string BackupHandler::backupDirDe_; -const std::string &BackupHandler::GetBackupPath(const std::string &deviceAccountId, int type) +const std::string &BackupHandler::GetBackupPath(const std::string &deviceAccountId, int pathType) { - if (type == KvStoreAppManager::PATH_DE) { + if (pathType == KvStoreAppManager::PATH_DE) { if (backupDirDe_.empty()) { backupDirDe_ = Constant::Concatenate({ Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), diff --git a/services/distributeddataservice/app/src/backup_handler.h b/services/distributeddataservice/app/src/backup_handler.h index 39485c91a..a8f71aec5 100755 --- a/services/distributeddataservice/app/src/backup_handler.h +++ b/services/distributeddataservice/app/src/backup_handler.h @@ -22,6 +22,7 @@ #include "kv_scheduler.h" #include "kvstore_meta_manager.h" #include "ikvstore_data_service.h" +#include "kvstore_app_manager.h" namespace OHOS::DistributedKv { class BackupHandler { @@ -40,8 +41,16 @@ public: static bool RemoveFile(const std::string &path); static bool FileExists(const std::string &path); static std::string GetHashedBackupName(const std::string &bundleName); + + struct BackupPara { + KvStoreAppManager::PathType pathType; + DistributedDB::CipherPassword password; + std::string backupFullName; + std::string backupBackFullName; + }; private: bool CheckNeedBackup(); + bool InitBackupPara(const MetaData &metaData, BackupPara &backupPara); static std::string backupDirCe_; static std::string backupDirDe_; diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index d0d01d151..5b58f04e9 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -151,90 +151,28 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId ZLOGW("callback is nullptr"); return Status::ERROR; } - if (appId.appId.empty() || storeId.storeId.empty()) { - ZLOGW("appid or storeid empty"); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION && - kvStoreType != KvStoreType::MULTI_VERSION) { - ZLOGE("invalid kvStore type."); + GetKvStorePara getKvStorePara; + getKvStorePara.funType = KvStoreType::MULTI_VERSION; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, getKvStorePara); + if (checkParaStatus != Status::SUCCESS) { callback(nullptr); - return Status::INVALID_ARGUMENT; + return checkParaStatus; } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); - std::string bundleName = Constant::TrimCopy(appId.appId); - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); + SecretKeyPara secretKeyParas; + Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, getKvStorePara, secretKeyParas); + if (getSecretKeyStatus != Status::SUCCESS) { callback(nullptr); - return Status::INVALID_ARGUMENT; + return getSecretKeyStatus; } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGW("appId empty(permission issues?)"); - callback(nullptr); - return Status::PERMISSION_DENIED; - } + auto deviceAccountId = getKvStorePara.deviceAccountId; + auto bundleName = getKvStorePara.bundleName; + auto storeIdTmp = getKvStorePara.storeId; - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } - std::lock_guard lg(accountMutex_); - auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); - if (!CheckOptions(options, metaKey)) { - callback(nullptr); - ZLOGE("encrypt type or kvStore type is not the same"); - return Status::INVALID_ARGUMENT; - } - std::vector secretKey; - std::unique_ptr, void (*)(std::vector *)> cleanGuard( - &secretKey, [](std::vector *ptr) { ptr->assign(ptr->size(), 0); }); - - bool outdated = false; - auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile(deviceAccountId, bundleName, storeIdTmp); - Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); - if (options.encrypt) { - ZLOGI("Getting secret key"); - if (alreadyCreated != Status::SUCCESS) { - ZLOGI("new secret key"); - CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length - KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); - KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); - } else { - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); - if (secretKey.empty()) { - ZLOGW("get secret key from meta failed, try to recover"); - KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - } - if (secretKey.empty()) { - ZLOGW("recover failed"); - callback(nullptr); - return Status::CRYPT_ERROR; - } - } - } else { - if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { - ZLOGW("try to get an encrypted store with false option encrypt parameter"); - callback(nullptr); - return Status::CRYPT_ERROR; - } - } + auto secretKey = secretKeyParas.secretKey; + bool outdated = secretKeyParas.outdated; auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { @@ -249,8 +187,7 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId } it = result.first; } - Status statusTmp = (it->second).GetKvStore( - options, bundleName, storeIdTmp, secretKey, + Status statusTmp = (it->second).GetKvStore(options, bundleName, storeIdTmp, secretKey, [&](sptr store) { if (outdated) { KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); @@ -261,71 +198,10 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId ZLOGD("get kvstore return status:%d, deviceAccountId:[%s], bundleName:[%s].", statusTmp, KvStoreUtils::ToBeAnonymous(deviceAccountId).c_str(), bundleName.c_str()); if (statusTmp == Status::SUCCESS) { - struct KvStoreMetaData metaData { - .appId = trueAppId, - .appType = "harmony", - .bundleName = bundleName, - .dataDir = "default", - .deviceAccountId = deviceAccountId, - .deviceId = DeviceKvStoreImpl::GetLocalDeviceId(), - .isAutoSync = options.autoSync, - .isBackup = options.backup, - .isEncrypt = options.encrypt, - .kvStoreType = options.kvStoreType, - .schema = options.schema, - .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, - .uid = IPCSkeleton::GetCallingUid(), - .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, - }; - std::string jsonStr = metaData.Marshal(); - std::vector jsonVec(jsonStr.begin(), jsonStr.end()); - - return KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, UPDATE, jsonVec); - } - Status getKvStoreStatus = statusTmp; - ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); - if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { - if (alreadyCreated != Status::SUCCESS) { - // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(deviceAccountId, bundleName, storeIdTmp); - return Status::ERROR; - } - // get existing encrypted store failed, retry with key stored in file - Status status = KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - if (status != Status::SUCCESS) { - callback(nullptr); - return Status::CRYPT_ERROR; - } - // here callback is called twice - statusTmp = (it->second).GetKvStore( - options, bundleName, storeIdTmp, secretKey, - [&](sptr store) { - if (outdated) { - KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); - } - callback(store); - }); - } - - // if kvstore damaged and no backup file, then return DB_ERROR - if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { - // if backup file not exist, dont need recover - if (!CheckBackupFileExist(deviceAccountId, bundleName, storeId.storeId, options.securityLevel)) { - return Status::CRYPT_ERROR; - } - // remove damaged database - if (DeleteKvStoreOnly(storeIdTmp, deviceAccountId, bundleName) != Status::SUCCESS) { - ZLOGE("DeleteKvStoreOnly failed."); - return Status::DB_ERROR; - } - // recover database - return RecoverMultiKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return UpdateMetaData(options, getKvStorePara, secretKeyParas.metaKey, it->second); } - - return statusTmp; + getKvStorePara.getKvStoreStatus = statusTmp; + return GetKvStoreFailDo(options, getKvStorePara, secretKeyParas, it->second, callback); } Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, @@ -337,16 +213,65 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId ZLOGW("callback is nullptr"); return Status::ERROR; } + + GetKvStorePara getKvStorePara; + getKvStorePara.funType = KvStoreType::SINGLE_VERSION; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::SINGLE_VERSION, getKvStorePara); + if (checkParaStatus != Status::SUCCESS) { + callback(nullptr); + return checkParaStatus; + } + + SecretKeyPara secretKeyParas; + Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, getKvStorePara, secretKeyParas); + if (getSecretKeyStatus != Status::SUCCESS) { + callback(nullptr); + return getSecretKeyStatus; + } + + auto deviceAccountId = getKvStorePara.deviceAccountId; + auto bundleName = getKvStorePara.bundleName; + auto storeIdTmp = getKvStorePara.storeId; + + auto secretKey = secretKeyParas.secretKey; + bool outdated = secretKeyParas.outdated; + + auto it = deviceAccountMap_.find(deviceAccountId); + if (it == deviceAccountMap_.end()) { + auto result = deviceAccountMap_.emplace(std::piecewise_construct, + std::forward_as_tuple(deviceAccountId), std::forward_as_tuple(deviceAccountId)); + if (!result.second) { + ZLOGE("emplace failed."); + callback(nullptr); + return Status::ERROR; + } + it = result.first; + } + auto newCallback = [&callback, outdated, deviceAccountId, bundleName, storeIdTmp](sptr store) { + if (outdated) { + KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); + } + callback(store); + }; + Status statusTmp = (it->second).GetSingleKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); + if (statusTmp == Status::SUCCESS) { + return UpdateMetaData(options, getKvStorePara, secretKeyParas.metaKey, it->second); + } + getKvStorePara.getKvStoreStatus = statusTmp; + return GetSingleKvStoreFailDo(options, getKvStorePara, secretKeyParas, it->second, callback); +} + +Status KvStoreDataService::CheckParameters(const Options &options, const AppId &appId, + const StoreId &storeId, const KvStoreType &kvStoreType, GetKvStorePara &getKvStorePara) +{ if (appId.appId.empty() || storeId.storeId.empty()) { ZLOGW("appid or storeid empty"); - callback(nullptr); return Status::INVALID_ARGUMENT; } - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION) { + KvStoreType kvStoreTypeInOptions = options.kvStoreType; + if (kvStoreTypeInOptions != KvStoreType::DEVICE_COLLABORATION && kvStoreTypeInOptions != kvStoreType) { ZLOGE("invalid kvStore type."); - callback(nullptr); return Status::INVALID_ARGUMENT; } KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); @@ -354,18 +279,15 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); if (!CheckBundleName(bundleName)) { ZLOGE("invalid bundleName."); - callback(nullptr); return Status::INVALID_ARGUMENT; } if (!CheckStoreId(storeIdTmp)) { ZLOGE("invalid storeIdTmp."); - callback(nullptr); return Status::INVALID_ARGUMENT; } std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); if (trueAppId.empty()) { - callback(nullptr); ZLOGW("appId empty(permission issues?)"); return Status::PERMISSION_DENIED; } @@ -373,14 +295,30 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId const int32_t uid = IPCSkeleton::GetCallingUid(); const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); ZLOGE("not support sub account"); return Status::NOT_SUPPORT; } + + GetKvStorePara KvStorePara; + KvStorePara.bundleName = bundleName; + KvStorePara.storeId = storeIdTmp; + KvStorePara.trueAppId = trueAppId; + KvStorePara.deviceAccountId = deviceAccountId; + getKvStorePara = KvStorePara; + + return Status::SUCCESS; +} + +Status KvStoreDataService::GetSecretKey(const Options &options, const GetKvStorePara &kvParas, + SecretKeyPara &secretKeyParas) +{ + std::string bundleName = kvParas.bundleName; + std::string storeIdTmp = kvParas.storeId; + std::string deviceAccountId = kvParas.deviceAccountId; + std::lock_guard lg(accountMutex_); auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { - callback(nullptr); ZLOGE("encrypt type or kvStore type is not the same"); return Status::INVALID_ARGUMENT; } @@ -388,113 +326,191 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId std::unique_ptr, void (*)(std::vector *)> cleanGuard( &secretKey, [](std::vector *ptr) { ptr->assign(ptr->size(), 0); }); + std::vector metaSecretKey; + if (kvParas.funType == KvStoreType::MULTI_VERSION) { + metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); + } else { + metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); + } + + auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( + deviceAccountId, bundleName, storeIdTmp, options.securityLevel); bool outdated = false; - auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, - "SINGLE_KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile(deviceAccountId, bundleName, storeIdTmp); Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); if (options.encrypt) { ZLOGI("Getting secret key"); - if (alreadyCreated != Status::SUCCESS) { + Status recStatus = RecoverSecretKey(alreadyCreated, outdated, metaSecretKey, secretKey, secretKeyFile); + if (recStatus != Status::SUCCESS) { + return recStatus; + } + } else { + if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { + ZLOGW("try to get an encrypted store with false option encrypt parameter"); + return Status::CRYPT_ERROR; + } + } + + SecretKeyPara kvStoreSecretKey; + kvStoreSecretKey.metaKey = metaKey; + kvStoreSecretKey.secretKey = secretKey; + kvStoreSecretKey.metaSecretKey = metaSecretKey; + kvStoreSecretKey.secretKeyFile = secretKeyFile; + kvStoreSecretKey.alreadyCreated = alreadyCreated; + kvStoreSecretKey.outdated = outdated; + secretKeyParas = kvStoreSecretKey; + + return Status::SUCCESS; +} + +Status KvStoreDataService::RecoverSecretKey(const Status &alreadyCreated, bool &outdated, + const std::vector &metaSecretKey, std::vector &secretKey, const std::string &secretKeyFile) +{ + if (alreadyCreated != Status::SUCCESS) { + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { ZLOGI("new secret key"); CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); - } else { - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); - if (secretKey.empty()) { - ZLOGW("get secret key from meta failed, try to recover"); - KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - } - if (secretKey.empty()) { - ZLOGW("recover failed"); - callback(nullptr); - return Status::CRYPT_ERROR; - } } } else { - if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { - ZLOGW("try to get an encrypted store with false option encrypt parameter"); - callback(nullptr); + KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { + ZLOGW("get secret key from meta failed, try to recover"); + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + } + if (secretKey.empty()) { + ZLOGW("recover failed"); return Status::CRYPT_ERROR; } + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); } + return Status::SUCCESS; +} - auto it = deviceAccountMap_.find(deviceAccountId); - if (it == deviceAccountMap_.end()) { - auto result = deviceAccountMap_.emplace(std::piecewise_construct, - std::forward_as_tuple(deviceAccountId), std::forward_as_tuple(deviceAccountId)); - if (!result.second) { - ZLOGE("emplace failed."); - callback(nullptr); +Status KvStoreDataService::UpdateMetaData(const Options &options, const GetKvStorePara &kvParas, + const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager) +{ + KvStoreMetaData metaData; + metaData.appId = kvParas.trueAppId; + metaData.appType = "harmony"; + metaData.bundleName = kvParas.bundleName; + metaData.deviceAccountId = kvParas.deviceAccountId; + metaData.deviceId = DeviceKvStoreImpl::GetLocalDeviceId(); + metaData.isAutoSync = options.autoSync; + metaData.isBackup = options.backup; + metaData.isEncrypt = options.encrypt; + metaData.kvStoreType = options.kvStoreType; + metaData.schema = options.schema; + metaData.storeId = kvParas.storeId; + metaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(kvParas.bundleName); + metaData.uid = IPCSkeleton::GetCallingUid(); + metaData.version = KVSTORE_META_VERSION; + metaData.securityLevel = options.securityLevel; + if (kvParas.funType == KvStoreType::MULTI_VERSION) { + metaData.dataDir = "default"; + } else { + metaData.dataDir = kvStoreUserManager.GetDbDir(kvParas.bundleName, options); + } + + std::string jsonStr = metaData.Marshal(); + std::vector jsonVec(jsonStr.begin(), jsonStr.end()); + + return KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, UPDATE, jsonVec); +} + +Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, std::function)> callback) +{ + Status statusTmp = kvParas.getKvStoreStatus; + Status getKvStoreStatus = statusTmp; + ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); + if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { + if (secKeyParas.alreadyCreated != Status::SUCCESS) { + // create encrypted store failed, remove secret key + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); return Status::ERROR; } - it = result.first; - } - auto newCallback = [&callback, outdated, deviceAccountId, bundleName, storeIdTmp](sptr store) { - if (outdated) { - KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); + // get existing encrypted store failed, retry with key stored in file + Status status = KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secKeyParas.secretKeyFile, secKeyParas.metaSecretKey, secKeyParas.secretKey, secKeyParas.outdated); + if (status != Status::SUCCESS) { + callback(nullptr); + return Status::CRYPT_ERROR; } - callback(store); - }; - Status statusTmp = (it->second).GetSingleKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); - if (statusTmp == Status::SUCCESS) { - KvStoreMetaData metaData { - .appId = trueAppId, - .appType = "harmony", - .bundleName = bundleName, - .dataDir = (it->second).GetDbDir(bundleName, options), - .deviceAccountId = deviceAccountId, - .deviceId = DeviceKvStoreImpl::GetLocalDeviceId(), - .isAutoSync = options.autoSync, - .isBackup = options.backup, - .isEncrypt = options.encrypt, - .kvStoreType = options.kvStoreType, - .schema = options.schema, - .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, - .uid = IPCSkeleton::GetCallingUid(), - .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, - }; - std::string jsonStr = metaData.Marshal(); - std::vector jsonVec(jsonStr.begin(), jsonStr.end()); + // here callback is called twice + statusTmp = kvUserManager.GetKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, + [&](sptr store) { + if (secKeyParas.outdated) { + KvStoreMetaManager::GetInstance().ReKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId, store); + } + callback(store); + }); + } - return KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, UPDATE, jsonVec); + // if kvstore damaged and no backup file, then return DB_ERROR + if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { + // if backup file not exist, dont need recover + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { + return Status::CRYPT_ERROR; + } + // remove damaged database + if (DeleteKvStoreOnly(kvParas.storeId, kvParas.deviceAccountId, kvParas.bundleName) != Status::SUCCESS) { + ZLOGE("DeleteKvStoreOnly failed."); + return Status::DB_ERROR; + } + // recover database + return RecoverMultiKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, callback); } - ZLOGW("getKvStore failed with status %d", static_cast(statusTmp)); + return statusTmp; +} + +Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, + KvStoreUserManager &kvUserManager, std::function)> callback) +{ + Status statusTmp = kvParas.getKvStoreStatus; Status getKvStoreStatus = statusTmp; + ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { - if (alreadyCreated != Status::SUCCESS) { + if (secKeyParas.alreadyCreated != Status::SUCCESS) { // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(deviceAccountId, bundleName, storeIdTmp); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); return Status::ERROR; } // get existing encrypted store failed, retry with key stored in file Status status = KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); + secKeyParas.secretKeyFile, secKeyParas.metaSecretKey, secKeyParas.secretKey, secKeyParas.outdated); if (status != Status::SUCCESS) { callback(nullptr); return Status::CRYPT_ERROR; } // here callback is called twice - statusTmp = (it->second).GetSingleKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); + statusTmp = kvUserManager.GetSingleKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, + [&](sptr store) { + if (secKeyParas.outdated) { + KvStoreMetaManager::GetInstance().ReKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId, store); + } + callback(store); + }); } // if kvstore damaged and no backup file, then return DB_ERROR if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { // if backup file not exist, dont need recover - if (!CheckBackupFileExist(deviceAccountId, bundleName, storeId.storeId, options.securityLevel)) { + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { return Status::CRYPT_ERROR; } // remove damaged database - if (DeleteKvStoreOnly(storeIdTmp, deviceAccountId, bundleName) != Status::SUCCESS) { + if (DeleteKvStoreOnly(kvParas.storeId, kvParas.deviceAccountId, kvParas.bundleName) != Status::SUCCESS) { ZLOGE("DeleteKvStoreOnly failed."); return Status::DB_ERROR; } // recover database - return RecoverSingleKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return RecoverSingleKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, callback); } return statusTmp; } @@ -534,8 +550,9 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId { auto pathType = KvStoreAppManager::ConvertPathType(bundleName, securityLevel); auto backupFileName = Constant::Concatenate({ Constant::DEFAULT_GROUP_ID, "_", bundleName, "_", storeId }); - auto backFilePath = Constant::Concatenate({ BackupHandler::GetBackupPath(deviceAccountId, pathType), - "/", BackupHandler::GetHashedBackupName(backupFileName) }); + std::initializer_list backFileList = {BackupHandler::GetBackupPath(deviceAccountId, pathType), + "/", BackupHandler::GetHashedBackupName(backupFileName)}; + auto backFilePath = Constant::Concatenate(backFileList); if (!BackupHandler::FileExists(backFilePath)) { ZLOGE("BackupHandler file is not exist."); return false; @@ -544,18 +561,19 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId } Status KvStoreDataService::RecoverSingleKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, - const StoreId &storeId, + const std::string &storeId, const std::vector &secretKey, std::function)> callback) { // restore database - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + std::string storeIdTmp = storeId; std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -584,18 +602,19 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, } Status KvStoreDataService::RecoverMultiKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, - const StoreId &storeId, + const std::string &storeId, const std::vector &secretKey, std::function)> callback) { // restore database - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + std::string storeIdTmp = storeId; std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -779,9 +798,9 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor return Status::PERMISSION_DENIED; } // delete the backup file - auto backupFileName = Constant::Concatenate({ - AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), "_", bundleName, "_", storeId.storeId - }); + std::initializer_list backFileList = { + AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), "_", bundleName, "_", storeId.storeId}; + auto backupFileName = Constant::Concatenate(backFileList); const int32_t uid = IPCSkeleton::GetCallingUid(); const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); @@ -790,17 +809,15 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor return Status::NOT_SUPPORT; } - auto backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", - BackupHandler::GetHashedBackupName(backupFileName) - }); + std::initializer_list backPathListDE = {BackupHandler::GetBackupPath(deviceAccountId, + KvStoreAppManager::PATH_DE), "/", BackupHandler::GetHashedBackupName(backupFileName)}; + auto backFilePath = Constant::Concatenate(backPathListDE); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } - backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), "/", - BackupHandler::GetHashedBackupName(backupFileName) - }); + std::initializer_list backPathListCE = {BackupHandler::GetBackupPath(deviceAccountId, + KvStoreAppManager::PATH_CE), "/", BackupHandler::GetHashedBackupName(backupFileName)}; + backFilePath = Constant::Concatenate(backPathListCE); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } @@ -962,7 +979,11 @@ void KvStoreDataService::OnStart() return; } } + StartService(); +} +void KvStoreDataService::StartService() +{ // register this to ServiceManager. bool ret = SystemAbility::Publish(this); if (!ret) { @@ -974,14 +995,24 @@ void KvStoreDataService::OnStart() // add softbus permission. AddPermission(); + std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, + KvStoreAppManager::PATH_DE); + ZLOGI("backupPath is : %s ", backupPath.c_str()); + if (!ForceCreateDirectory(backupPath)) { + ZLOGE("backup create directory failed"); + } // Initialize meta db delegate manager. KvStoreMetaManager::GetInstance().InitMetaListener([this](const KvStoreMetaData &metaData) { if (!metaData.isDirty) { return; } - CloseKvStore({metaData.bundleName}, {metaData.storeId}); - DeleteKvStore({metaData.bundleName}, {metaData.storeId}); + AppId appId; + appId.appId = metaData.bundleName; + StoreId storeId; + storeId.storeId = metaData.storeId; + CloseKvStore(appId, storeId); + DeleteKvStore(appId, storeId); }); // subscribe account event listener to EventNotificationMgr @@ -1006,13 +1037,8 @@ void KvStoreDataService::OnStart() DistributedDB::KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); backup_ = std::make_unique(this); - std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, - KvStoreAppManager::PATH_CE); - ZLOGI("backupPath is : %s ", backupPath.c_str()); - if (!ForceCreateDirectory(backupPath)) { - ZLOGE("backup create directory failed."); - } backup_->BackSchedule(); + std::thread th = std::thread([]() { sleep(TEN_SEC); KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(); @@ -1230,13 +1256,12 @@ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) if (it != deviceAccountMap_.end()) { deviceAccountMap_.erase(eventInfo.deviceAccountId); } - std::string deviceAccountKvStoreDataDir = - Constant::Concatenate({Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, - "/", eventInfo.deviceAccountId}); + std::initializer_list dirList = {Constant::ROOT_PATH_DE, "/", + Constant::SERVICE_NAME, "/", eventInfo.deviceAccountId}; + std::string deviceAccountKvStoreDataDir = Constant::Concatenate(dirList); ForceRemoveDirectory(deviceAccountKvStoreDataDir); - deviceAccountKvStoreDataDir = - Constant::Concatenate({Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, - "/", eventInfo.deviceAccountId}); + dirList = {Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", eventInfo.deviceAccountId}; + deviceAccountKvStoreDataDir = Constant::Concatenate(dirList); ForceRemoveDirectory(deviceAccountKvStoreDataDir); g_kvStoreAccountEventStatus = 0; break; @@ -1258,8 +1283,8 @@ Status KvStoreDataService::GetLocalDevice(DeviceInfo &device) Status KvStoreDataService::GetDeviceList(std::vector &deviceInfoList, DeviceFilterStrategy strategy) { auto devices = KvStoreUtils::GetProviderInstance().GetRemoteNodesBasicInfo(); - for(auto const &device : devices) { - deviceInfoList.push_back({device.deviceId, device.deviceName, device.deviceType}); + for (auto const &device : devices) { + deviceInfoList.push_back({ device.deviceId, device.deviceName, device.deviceType }); } ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; @@ -1278,7 +1303,7 @@ Status KvStoreDataService::StartWatchDeviceChange(sptrAsObject().GetRefPtr(); - deviceListeners_.insert({objectPtr, observer}); + deviceListeners_.insert({ objectPtr, observer }); ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; } diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index fcec10db5..be24df9f9 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -87,15 +87,29 @@ public: bool CheckBackupFileExist(const std::string &deviceAccountId, const std::string &bundleName, const std::string &storeId, int securityLevel); - Status RecoverSingleKvStore(const Options &options, const std::string &deviceAccountId, - const std::string &bundleName, const StoreId &storeId, - const std::vector &secretKey, + Status RecoverSingleKvStore(const Options &options, const std::string &bundleName, + const std::string &storeId, const std::vector &secretKey, std::function)> callback); - Status RecoverMultiKvStore(const Options &options, const std::string &deviceAccountId, - const std::string &bundleName, const StoreId &storeId, - const std::vector &secretKey, + Status RecoverMultiKvStore(const Options &options, const std::string &bundleName, + const std::string &storeId, const std::vector &secretKey, std::function)> callback); + struct GetKvStorePara { + std::string bundleName; + std::string storeId; + std::string trueAppId; + std::string deviceAccountId; + Status getKvStoreStatus = Status::SUCCESS; + KvStoreType funType = KvStoreType::DEVICE_COLLABORATION; + }; + struct SecretKeyPara { + std::vector metaKey; + std::vector secretKey; + std::vector metaSecretKey; + std::string secretKeyFile; + Status alreadyCreated = Status::SUCCESS; + bool outdated = false; + }; private: class KvStoreClientDeathObserverImpl { public: @@ -124,6 +138,25 @@ private: void Initialize(); + void StartService(); + + Status CheckParameters(const Options &options, const AppId &appId, const StoreId &storeId, + const KvStoreType &kvStoreType, GetKvStorePara &getKvStorePara); + + Status GetSecretKey(const Options &options, const GetKvStorePara &KvParas, SecretKeyPara &secretKeyParas); + + Status RecoverSecretKey(const Status &alreadyCreated, bool &outdated, const std::vector &metaSecretKey, + std::vector &secretKey, const std::string &secretKeyFile); + + Status UpdateMetaData(const Options &options, const GetKvStorePara &kvParas, + const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager); + + Status GetKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, + KvStoreUserManager &kvUserManager, std::function)> callback); + + Status GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, + KvStoreUserManager &kvUserManager, std::function)> callback); + Status AppExit(const AppId &appId); bool CheckBundleName(const std::string &bundleName) const; diff --git a/services/distributeddataservice/app/src/kvstore_impl.cpp b/services/distributeddataservice/app/src/kvstore_impl.cpp index 6ea4f718d..6b8acbafc 100755 --- a/services/distributeddataservice/app/src/kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/kvstore_impl.cpp @@ -780,7 +780,7 @@ bool KvStoreImpl::Import(const std::string &bundleName) const ZLOGI("KvStoreImpl Import start"); const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId_, harmonyAccountId, bundleName, storeId_, - "SINGLE_KEY"); + "KEY"); std::vector secretKey; bool outdated = false; auto trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); @@ -792,6 +792,7 @@ bool KvStoreImpl::Import(const std::string &bundleName) const metaData.kvStoreMetaData.bundleName = bundleName; metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.storeId = storeId_; + metaData.kvStoreMetaData.securityLevel = options_.securityLevel; metaData.secretKeyMetaData.secretKey = secretKey; std::shared_lock lock(storeDelegateMutex_); return std::make_unique()->MultiKvStoreRecover(metaData, kvStoreDelegate_); diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index 54417a641..4eb7f5354 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -32,6 +32,7 @@ #include "log_print.h" #include "reporter.h" #include "directory_utils.h" +#include "kvstore_app_manager.h" namespace OHOS { namespace DistributedKv { @@ -202,7 +203,7 @@ std::vector KvStoreMetaManager::GetMetaKey(const std::string &deviceAcc } std::string KvStoreMetaManager::GetSecretKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId) + const std::string &storeId, int securityLevel) { std::string hashedStoreId; DistributedDB::DBStatus result = DistributedDB::KvStoreDelegateManager::GetDatabaseDir(storeId, hashedStoreId); @@ -210,13 +211,15 @@ std::string KvStoreMetaManager::GetSecretKeyFile(const std::string &deviceAccoun ZLOGE("get data base directory by kvstore store id failed, result = %d.", result); return ""; } - return Constant::ROOT_PATH_DE + "/" + Constant::SERVICE_NAME + "/" + + auto pathType = KvStoreAppManager::ConvertPathType(appId, securityLevel); + std::string miscPath = (pathType == KvStoreAppManager::PATH_DE) ? Constant::ROOT_PATH_DE : Constant::ROOT_PATH_CE; + return miscPath + "/" + Constant::SERVICE_NAME + "/" + deviceAccountId + "/" + Constant::GetDefaultHarmonyAccountName() + "/" + appId + "/" + hashedStoreId + ".mul.key"; } std::string KvStoreMetaManager::GetSecretSingleKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId) + const std::string &storeId, int securityLevel) { std::string hashedStoreId; DistributedDB::DBStatus result = DistributedDB::KvStoreDelegateManager::GetDatabaseDir(storeId, hashedStoreId); @@ -224,7 +227,9 @@ std::string KvStoreMetaManager::GetSecretSingleKeyFile(const std::string &device ZLOGE("get data base directory by kvstore store id failed, result = %d.", result); return ""; } - return Constant::ROOT_PATH_DE + "/" + Constant::SERVICE_NAME + "/" + + auto pathType = KvStoreAppManager::ConvertPathType(appId, securityLevel); + std::string miscPath = (pathType == KvStoreAppManager::PATH_DE) ? Constant::ROOT_PATH_DE : Constant::ROOT_PATH_CE; + return miscPath + "/" + Constant::SERVICE_NAME + "/" + deviceAccountId + "/" + Constant::GetDefaultHarmonyAccountName() + "/" + appId + "/" + hashedStoreId + ".sig.key"; } @@ -239,7 +244,7 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me return Status::DB_ERROR; } - KvStoreAppManager::PathType pathType = KvStoreAppManager::PATH_CE; + KvStoreAppManager::PathType pathType = KvStoreAppManager::PATH_DE; DistributedDB::Key dbKey = metaKey; DistributedDB::Value dbValue = val; DistributedDB::DBStatus dbStatus; @@ -533,13 +538,15 @@ Status KvStoreMetaManager::RemoveSecretKey(const std::string &deviceAccountId, c status = Status::DB_ERROR; } - std::string secretKeyFile = GetSecretKeyFile(deviceAccountId, bundleName, storeId); + int securityLevel; + GetSecurityLevelByBundleName(bundleName, securityLevel); + std::string secretKeyFile = GetSecretKeyFile(deviceAccountId, bundleName, storeId, securityLevel); bool rmFile = RemoveFile(secretKeyFile); if (!rmFile) { ZLOGW("remove secretKeyFile fail."); status = Status::DB_ERROR; } - secretKeyFile = GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId); + secretKeyFile = GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId, securityLevel); rmFile = RemoveFile(secretKeyFile); if (!rmFile) { ZLOGW("remove secretKeyFile Single fail."); @@ -632,7 +639,9 @@ void KvStoreMetaManager::ReKey(const std::string &deviceAccountId, const std::st WriteSecretKeyToMeta(GetMetaKey(deviceAccountId, "default", bundleName, storeId, "KEY"), key); Status status = kvStoreimpl->ReKey(key); if (status == Status::SUCCESS) { - WriteSecretKeyToFile(GetSecretKeyFile(deviceAccountId, bundleName, storeId), key); + int securityLevel; + GetSecurityLevelByBundleName(bundleName, securityLevel); + WriteSecretKeyToFile(GetSecretKeyFile(deviceAccountId, bundleName, storeId, securityLevel), key); } key.assign(key.size(), 0); } @@ -649,7 +658,9 @@ void KvStoreMetaManager::ReKey(const std::string &deviceAccountId, const std::st WriteSecretKeyToMeta(GetMetaKey(deviceAccountId, "default", bundleName, storeId, "SINGLE_KEY"), key); Status status = kvStoreImpl->ReKey(key); if (status == Status::SUCCESS) { - WriteSecretKeyToFile(GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId), key); + int securityLevel; + GetSecurityLevelByBundleName(bundleName, securityLevel); + WriteSecretKeyToFile(GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId, securityLevel), key); } key.assign(key.size(), 0); } @@ -1222,6 +1233,18 @@ bool KvStoreMetaManager::GetFullMetaData(std::map &entrie return true; } +bool KvStoreMetaManager::GetSecurityLevelByBundleName(const std::string &bundleName, int &securityLevel) +{ + KvStoreMetaData kvStoreMetaData; + auto getKvStoreMetaBMeta = GetKvStoreMetaByType(KvStoreMetaData::BUNDLE_NAME, bundleName, kvStoreMetaData); + if (!getKvStoreMetaBMeta) { + ZLOGE("getkvstore meta by type failed"); + return false; + } + securityLevel = kvStoreMetaData.securityLevel; + return true; +} + bool KvStoreMetaManager::GetKvStoreMetaByType(const std::string &name, const std::string &val, KvStoreMetaData &metaData) { diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 05aa7bdf7..d54c3e01c 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -198,10 +198,10 @@ public: const std::string &storeId, const std::string &key = ""); static std::string GetSecretKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId); + const std::string &storeId, int securityLevel); static std::string GetSecretSingleKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId); + const std::string &storeId, int securityLevel); Status GetSecretKeyFromMeta(const std::vector &metaSecretKey, std::vector &key, bool &outdated); @@ -269,6 +269,8 @@ private: Status GetStategyMeta(const std::string &key, std::map> &strategies); + bool GetSecurityLevelByBundleName(const std::string &bundleName, int &securityLevel); + bool GetKvStoreMetaByType(const std::string &name, const std::string &val, KvStoreMetaData &metaData); class KvStoreMetaObserver : public DistributedDB::KvStoreObserver { diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.cpp b/services/distributeddataservice/app/src/single_kvstore_impl.cpp index c67beddd1..3d8143330 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/single_kvstore_impl.cpp @@ -1391,6 +1391,7 @@ bool SingleKvStoreImpl::Import(const std::string &bundleName) const metaData.kvStoreMetaData.bundleName = bundleName; metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.storeId = storeId_; + metaData.kvStoreMetaData.securityLevel = options_.securityLevel; metaData.secretKeyMetaData.secretKey = secretKey; std::shared_lock lock(storeNbDelegateMutex_); return std::make_unique()->SingleKvStoreRecover(metaData, kvStoreNbDelegate_); @@ -1481,7 +1482,6 @@ Status SingleKvStoreImpl::GetSecurityLevel(SecurityLevel &securityLevel) } return Status::SUCCESS; } - void SingleKvStoreImpl::OnDump(int fd) const { const std::string prefix(12, ' '); diff --git a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp index 60104ce49..21af99766 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp @@ -91,16 +91,15 @@ Status UninstallerImpl::Init(KvStoreDataService *kvStoreDataService) matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); CommonEventSubscribeInfo info(matchingSkills); auto callback = [kvStoreDataService](const std::string &bundleName, int userId) { - ZLOGI("uninstalled bundleName:%s, userId:%d", bundleName.c_str(), userId); KvStoreMetaData kvStoreMetaData; if (!KvStoreMetaManager::GetInstance().GetKvStoreMetaDataByBundleName(bundleName, kvStoreMetaData)) { return; } if (!kvStoreMetaData.appId.empty() && !kvStoreMetaData.storeId.empty()) { ZLOGI("Has been uninstalled bundleName:%s", bundleName.c_str()); - AppId appid = {kvStoreMetaData.bundleName}; + AppId appId = {kvStoreMetaData.bundleName}; StoreId storeId = {kvStoreMetaData.storeId}; - kvStoreDataService->DeleteKvStore(appid, storeId, kvStoreMetaData.appId); + kvStoreDataService->DeleteKvStore(appId, storeId); } }; subscriber_ = std::make_shared(info, callback); diff --git a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h index a3c8bf064..b433152b1 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h @@ -20,16 +20,15 @@ #include "uninstaller.h" namespace OHOS::DistributedKv { -using namespace OHOS::EventFwk; using UninstallEventCallback = std::function; -class UninstallEventSubscriber : public CommonEventSubscriber { +class UninstallEventSubscriber : public EventFwk::CommonEventSubscriber { public: - UninstallEventSubscriber(const CommonEventSubscribeInfo &info, + UninstallEventSubscriber(const EventFwk::CommonEventSubscribeInfo &info, UninstallEventCallback callback); ~UninstallEventSubscriber() {}; - void OnReceiveEvent(const CommonEventData &event) override; + void OnReceiveEvent(const EventFwk::CommonEventData &event) override; private: static const std::string USER_ID; UninstallEventCallback callback_; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp index 01e88e6d2..8f8056541 100755 --- a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp @@ -49,10 +49,13 @@ void KvStoreBackupTest::TearDownTestCase(void) void KvStoreBackupTest::SetUp(void) { - const std::string backupDir = "/data/misc_ce/0/mdds/0/default/backup"; + const std::string backupDirCe = "/data/misc_ce/0/mdds/0/default/backup"; + unlink(backupDirCe.c_str()); + mkdir(backupDirCe.c_str(), KvStoreBackupTest::DEFAULT_DIR_MODE); - unlink(backupDir.c_str()); - mkdir(backupDir.c_str(), KvStoreBackupTest::DEFAULT_DIR_MODE); + const std::string backupDirDe = "/data/misc_de/0/mdds/0/default/backup"; + unlink(backupDirDe.c_str()); + mkdir(backupDirDe.c_str(), KvStoreBackupTest::DEFAULT_DIR_MODE); } void KvStoreBackupTest::TearDown(void) @@ -75,7 +78,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest001, TestSize.Level1) kvDataService.DeleteKvStore(appId, storeId); sptr kvStorePtr; Status status = kvDataService.GetSingleKvStore(options, appId, storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); + [&](sptr kvStore) { kvStorePtr = std::move(kvStore); }); EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest001 set backup true failed"; kvDataService.CloseKvStore(appId, storeId); } @@ -101,7 +104,6 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest002 set backup true failed"; - Key key1("test1_key"); Value value1("test1_value"); kvStorePtr->Put(key1, value1); @@ -115,8 +117,9 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; - metaData.kvStoreMetaData.isBackup = false; + metaData.kvStoreMetaData.isBackup = true; metaData.kvStoreType = KvStoreType::SINGLE_VERSION; backupHandler->SingleKvStoreBackup(metaData); @@ -124,14 +127,14 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) kvStorePtr->Delete(key2); Value value22; kvStorePtr->Get(key2, value22); - auto kptr = static_cast(kvStorePtr.GetRefPtr()); - kptr->Import(appId.appId); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest002 NO_LABEL single kvstore import failed"; kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest002 single kvstore backup failed"; kvDataService.CloseKvStore(appId, storeId); } - /** * @tc.name: KvStoreBackupTest003 * @tc.desc: kvstore backup test for multi db @@ -142,7 +145,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) { Options options = { .createIfMissing = true, .encrypt = false, .autoSync = true, .backup = true, - .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + .kvStoreType = KvStoreType::MULTI_VERSION, .dataOwnership = true }; AppId appId = { "backup3" }; StoreId storeId = { "store3" }; @@ -150,7 +153,7 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) kvDataService.DeleteKvStore(appId, storeId); sptr kvStorePtr; Status status = kvDataService.GetKvStore(options, appId, storeId, - [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest003 set backup true failed"; @@ -168,8 +171,9 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) metaData.kvStoreMetaData.deviceAccountId = "0"; metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; - metaData.kvStoreMetaData.isBackup = false; + metaData.kvStoreMetaData.isBackup = true; metaData.kvStoreType = KvStoreType::MULTI_VERSION; backupHandler->MultiKvStoreBackup(metaData); @@ -189,7 +193,225 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) Value value22; kvStoreSnapshotPtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest003 muti kvstore backup failed"; kvStorePtr->ReleaseKvStoreSnapshot(std::move(kvStoreSnapshotPtr)); kvDataService.CloseKvStore(appId, storeId); } +/** +* @tc.name: KvStoreBackupTest004 +* @tc.desc: kvstore backup delete test +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest004, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .autoSync = true, .backup = true, + .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup4" }; + StoreId storeId = { "store4" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest004 set backup true failed"; + + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + auto currentAccountId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + std::initializer_list fileList = {currentAccountId, "_", trueAppId, "_", storeId.storeId}; + auto backupFileName = Constant::Concatenate(fileList); + auto backupFileNameHashed = BackupHandler::GetHashedBackupName(backupFileName); + auto pathType = KvStoreAppManager::ConvertPathType(appId.appId, metaData.kvStoreMetaData.securityLevel); + std::initializer_list backFileList = {BackupHandler::GetBackupPath("0", pathType), + "/", backupFileNameHashed}; + auto backFilePath = Constant::Concatenate(backFileList); + bool ret = BackupHandler::FileExists(backFilePath); + EXPECT_EQ(ret, true) << "KvStoreBackupTest004 backup file failed"; + + kvDataService.CloseKvStore(appId, storeId); + kvDataService.DeleteKvStore(appId, storeId); + ret = BackupHandler::FileExists(backFilePath); + EXPECT_EQ(ret, false) << "KvStoreBackupTest004 delete backup file failed"; +} +/** +* @tc.name: KvStoreBackupTest005 +* @tc.desc: S0 kvstore backup test for single db +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest005, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .backup = true, .autoSync = true, + .securityLevel = SecurityLevel::S0, .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup5" }; + StoreId storeId = { "store5" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest005 set backup true failed"; + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreMetaData.securityLevel = SecurityLevel::S0; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + kvStorePtr->Delete(key2); + Value value22; + kvStorePtr->Get(key2, value22); + auto kptr = static_cast(kvStorePtr.GetRefPtr()); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest005 S0 single kvstore import failed"; + kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest005 S0 single kvstore backup failed"; + + kvDataService.CloseKvStore(appId, storeId); +} +/** +* @tc.name: KvStoreBackupTest006 +* @tc.desc: S2 kvstore backup test for single db +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest006, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .backup = true, .autoSync = true, + .securityLevel = SecurityLevel::S2, .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup6" }; + StoreId storeId = { "store6" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest006 set backup true failed"; + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreMetaData.securityLevel = SecurityLevel::S2; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + kvStorePtr->Delete(key2); + Value value22; + kvStorePtr->Get(key2, value22); + auto kptr = static_cast(kvStorePtr.GetRefPtr()); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest006 S2 single kvstore import failed"; + kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest006 S2 single kvstore backup failed"; + + kvDataService.CloseKvStore(appId, storeId); +} +/** +* @tc.name: KvStoreBackupTest007 +* @tc.desc: S4 kvstore backup test for single db +* @tc.type: FUNC +* @tc.require:AR000G2VNB +* @tc.author:zuojiangjiang +*/ +HWTEST_F(KvStoreBackupTest, KvStoreBackupTest007, TestSize.Level1) +{ + Options options = { .createIfMissing = true, .encrypt = false, .backup = true, .autoSync = true, + .securityLevel = SecurityLevel::S4, .kvStoreType = KvStoreType::SINGLE_VERSION, .dataOwnership = true }; + AppId appId = { "backup7" }; + StoreId storeId = { "store7" }; + + KvStoreDataService kvDataService; + kvDataService.DeleteKvStore(appId, storeId); + sptr kvStorePtr; + Status status = kvDataService.GetSingleKvStore(options, appId, storeId, + [&](sptr kvStore) { kvStorePtr = std::move(kvStore);}); + + EXPECT_EQ(status, Status::SUCCESS) << "KvStoreBackupTest007 set backup true failed"; + Key key1("test1_key"); + Value value1("test1_value"); + kvStorePtr->Put(key1, value1); + Key key2("test2_key"); + Value value2("test2_value"); + kvStorePtr->Put(key2, value2); + + auto backupHandler = std::make_unique(); + auto trueAppId = KvStoreUtils::GetAppIdByBundleName(appId.appId); + MetaData metaData{0}; + metaData.kvStoreMetaData.deviceAccountId = "0"; + metaData.kvStoreMetaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.bundleName = appId.appId; + metaData.kvStoreMetaData.storeId = storeId.storeId; + metaData.kvStoreMetaData.isBackup = true; + metaData.kvStoreMetaData.securityLevel = SecurityLevel::S4; + metaData.kvStoreType = KvStoreType::SINGLE_VERSION; + + backupHandler->SingleKvStoreBackup(metaData); + + kvStorePtr->Delete(key2); + Value value22; + kvStorePtr->Get(key2, value22); + auto kptr = static_cast(kvStorePtr.GetRefPtr()); + bool importRes = kptr->Import(appId.appId); + EXPECT_EQ(importRes, true) << "KvStoreBackupTest007 S4 single kvstore import failed"; + kvStorePtr->Get(key2, value22); + EXPECT_EQ(value22.ToString(), value2.ToString()) << "KvStoreBackupTest007 S0 single kvstore backup failed"; + + kvDataService.CloseKvStore(appId, storeId); +} \ No newline at end of file diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp index c5ee3beea..9985e88ae 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp @@ -142,95 +142,32 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId { ZLOGI("begin."); DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (callback == nullptr) { ZLOGW("callback is nullptr"); return Status::ERROR; } - if (appId.appId.empty() || storeId.storeId.empty()) { - ZLOGW("appid or storeid empty"); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION && - kvStoreType != KvStoreType::MULTI_VERSION) { - ZLOGE("invalid kvStore type."); - callback(nullptr); - return Status::INVALID_ARGUMENT; - } - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); - std::string bundleName = Constant::TrimCopy(appId.appId); - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); + GetKvStorePara getKvStorePara; + getKvStorePara.funType = KvStoreType::MULTI_VERSION; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, getKvStorePara); + if (checkParaStatus != Status::SUCCESS) { callback(nullptr); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - callback(nullptr); - return Status::INVALID_ARGUMENT; + return checkParaStatus; } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGW("appId empty(permission issues?)"); + SecretKeyPara secretKeyParas; + Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, getKvStorePara, secretKeyParas); + if (getSecretKeyStatus != Status::SUCCESS) { callback(nullptr); - return Status::PERMISSION_DENIED; + return getSecretKeyStatus; } - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } - std::lock_guard lg(accountMutex_); - auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); - if (!CheckOptions(options, metaKey)) { - callback(nullptr); - ZLOGE("encrypt type or kvStore type is not the same"); - return Status::INVALID_ARGUMENT; - } - std::vector secretKey; - std::unique_ptr, void (*)(std::vector *)> cleanGuard( - &secretKey, [](std::vector *ptr) { ptr->assign(ptr->size(), 0); }); + auto deviceAccountId = getKvStorePara.deviceAccountId; + auto bundleName = getKvStorePara.bundleName; + auto storeIdTmp = getKvStorePara.storeId; - bool outdated = false; - auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile(deviceAccountId, bundleName, storeIdTmp); - Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); - if (options.encrypt) { - ZLOGI("Getting secret key"); - if (alreadyCreated != Status::SUCCESS) { - ZLOGI("new secret key"); - CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length - KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); - KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); - } else { - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); - if (secretKey.empty()) { - ZLOGW("get secret key from meta failed, try to recover"); - KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - } - if (secretKey.empty()) { - ZLOGW("recover failed"); - callback(nullptr); - return Status::CRYPT_ERROR; - } - } - } else { - if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { - ZLOGW("try to get an encrypted store with false option encrypt parameter"); - callback(nullptr); - return Status::CRYPT_ERROR; - } - } + auto secretKey = secretKeyParas.secretKey; + bool outdated = secretKeyParas.outdated; auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { @@ -245,8 +182,7 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId } it = result.first; } - Status statusTmp = (it->second).GetKvStore( - options, bundleName, storeIdTmp, secretKey, + Status statusTmp = (it->second).GetKvStore(options, bundleName, storeIdTmp, secretKey, [&](sptr store) { if (outdated) { KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); @@ -257,93 +193,80 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId ZLOGD("get kvstore return status:%d, deviceAccountId:[%s], bundleName:[%s].", statusTmp, KvStoreUtils::ToBeAnonymous(deviceAccountId).c_str(), bundleName.c_str()); if (statusTmp == Status::SUCCESS) { - struct KvStoreMetaData metaData { - .appId = trueAppId, - .appType = "harmony", - .bundleName = bundleName, - .dataDir = "default", - .deviceAccountId = deviceAccountId, - .deviceId = DeviceKvStoreImpl::GetLocalDeviceId(), - .isAutoSync = options.autoSync, - .isBackup = options.backup, - .isEncrypt = options.encrypt, - .kvStoreType = options.kvStoreType, - .schema = options.schema, - .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, - .uid = IPCSkeleton::GetCallingUid(), - .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, - }; - std::string jsonStr = metaData.Marshal(); - std::vector jsonVec(jsonStr.begin(), jsonStr.end()); - - return KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, UPDATE, jsonVec); - } - Status getKvStoreStatus = statusTmp; - ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); - if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { - if (alreadyCreated != Status::SUCCESS) { - // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(deviceAccountId, bundleName, storeIdTmp); - return Status::ERROR; - } - // get existing encrypted store failed, retry with key stored in file - Status status = KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - if (status != Status::SUCCESS) { - callback(nullptr); - return Status::CRYPT_ERROR; - } - // here callback is called twice - statusTmp = (it->second).GetKvStore( - options, bundleName, storeIdTmp, secretKey, - [&](sptr store) { - if (outdated) { - KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); - } - callback(store); - }); - } - - // if kvstore damaged and no backup file, then return DB_ERROR - if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { - // if backup file not exist, dont need recover - if (!CheckBackupFileExist(deviceAccountId, bundleName, storeId.storeId, options.securityLevel)) { - return Status::CRYPT_ERROR; - } - // remove damaged database - if (DeleteKvStoreOnly(storeIdTmp, deviceAccountId, bundleName) != Status::SUCCESS) { - ZLOGE("DeleteKvStoreOnly failed."); - return Status::DB_ERROR; - } - // recover database - return RecoverMultiKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return UpdateMetaData(options, getKvStorePara, secretKeyParas.metaKey, it->second); } - - return statusTmp; + getKvStorePara.getKvStoreStatus = statusTmp; + return GetKvStoreFailDo(options, getKvStorePara, secretKeyParas, it->second, callback); } Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, std::function)> callback) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGI("begin."); if (callback == nullptr) { ZLOGW("callback is nullptr"); return Status::ERROR; } + + GetKvStorePara getKvStorePara; + getKvStorePara.funType = KvStoreType::SINGLE_VERSION; + Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::SINGLE_VERSION, getKvStorePara); + if (checkParaStatus != Status::SUCCESS) { + callback(nullptr); + return checkParaStatus; + } + + SecretKeyPara secretKeyParas; + Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, getKvStorePara, secretKeyParas); + if (getSecretKeyStatus != Status::SUCCESS) { + callback(nullptr); + return getSecretKeyStatus; + } + + auto deviceAccountId = getKvStorePara.deviceAccountId; + auto bundleName = getKvStorePara.bundleName; + auto storeIdTmp = getKvStorePara.storeId; + + auto secretKey = secretKeyParas.secretKey; + bool outdated = secretKeyParas.outdated; + + auto it = deviceAccountMap_.find(deviceAccountId); + if (it == deviceAccountMap_.end()) { + auto result = deviceAccountMap_.emplace(std::piecewise_construct, + std::forward_as_tuple(deviceAccountId), std::forward_as_tuple(deviceAccountId)); + if (!result.second) { + ZLOGE("emplace failed."); + callback(nullptr); + return Status::ERROR; + } + it = result.first; + } + auto newCallback = [&callback, outdated, deviceAccountId, bundleName, storeIdTmp](sptr store) { + if (outdated) { + KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); + } + callback(store); + }; + Status statusTmp = (it->second).GetSingleKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); + if (statusTmp == Status::SUCCESS) { + return UpdateMetaData(options, getKvStorePara, secretKeyParas.metaKey, it->second); + } + getKvStorePara.getKvStoreStatus = statusTmp; + return GetSingleKvStoreFailDo(options, getKvStorePara, secretKeyParas, it->second, callback); +} + +Status KvStoreDataService::CheckParameters(const Options &options, const AppId &appId, + const StoreId &storeId, const KvStoreType &kvStoreType, GetKvStorePara &getKvStorePara) +{ if (appId.appId.empty() || storeId.storeId.empty()) { ZLOGW("appid or storeid empty"); - callback(nullptr); return Status::INVALID_ARGUMENT; } - KvStoreType kvStoreType = options.kvStoreType; - if (kvStoreType != KvStoreType::DEVICE_COLLABORATION && kvStoreType != KvStoreType::SINGLE_VERSION) { + KvStoreType kvStoreTypeInOptions = options.kvStoreType; + if (kvStoreTypeInOptions != KvStoreType::DEVICE_COLLABORATION && kvStoreTypeInOptions != kvStoreType) { ZLOGE("invalid kvStore type."); - callback(nullptr); return Status::INVALID_ARGUMENT; } KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); @@ -351,18 +274,15 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); if (!CheckBundleName(bundleName)) { ZLOGE("invalid bundleName."); - callback(nullptr); return Status::INVALID_ARGUMENT; } if (!CheckStoreId(storeIdTmp)) { ZLOGE("invalid storeIdTmp."); - callback(nullptr); return Status::INVALID_ARGUMENT; } std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); if (trueAppId.empty()) { - callback(nullptr); ZLOGW("appId empty(permission issues?)"); return Status::PERMISSION_DENIED; } @@ -370,14 +290,30 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId const int32_t uid = IPCSkeleton::GetCallingUid(); const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - callback(nullptr); ZLOGE("not support sub account"); return Status::NOT_SUPPORT; } + + GetKvStorePara KvStorePara; + KvStorePara.bundleName = bundleName; + KvStorePara.storeId = storeIdTmp; + KvStorePara.trueAppId = trueAppId; + KvStorePara.deviceAccountId = deviceAccountId; + getKvStorePara = KvStorePara; + + return Status::SUCCESS; +} + +Status KvStoreDataService::GetSecretKey(const Options &options, const GetKvStorePara &kvParas, + SecretKeyPara &secretKeyParas) +{ + std::string bundleName = kvParas.bundleName; + std::string storeIdTmp = kvParas.storeId; + std::string deviceAccountId = kvParas.deviceAccountId; + std::lock_guard lg(accountMutex_); auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { - callback(nullptr); ZLOGE("encrypt type or kvStore type is not the same"); return Status::INVALID_ARGUMENT; } @@ -385,113 +321,191 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId std::unique_ptr, void (*)(std::vector *)> cleanGuard( &secretKey, [](std::vector *ptr) { ptr->assign(ptr->size(), 0); }); + std::vector metaSecretKey; + if (kvParas.funType == KvStoreType::MULTI_VERSION) { + metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); + } else { + metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); + } + + auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( + deviceAccountId, bundleName, storeIdTmp, options.securityLevel); bool outdated = false; - auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, - "SINGLE_KEY"); - auto secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile(deviceAccountId, bundleName, storeIdTmp); Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); if (options.encrypt) { ZLOGI("Getting secret key"); - if (alreadyCreated != Status::SUCCESS) { + Status recStatus = RecoverSecretKey(alreadyCreated, outdated, metaSecretKey, secretKey, secretKeyFile); + if (recStatus != Status::SUCCESS) { + return recStatus; + } + } else { + if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { + ZLOGW("try to get an encrypted store with false option encrypt parameter"); + return Status::CRYPT_ERROR; + } + } + + SecretKeyPara kvStoreSecretKey; + kvStoreSecretKey.metaKey = metaKey; + kvStoreSecretKey.secretKey = secretKey; + kvStoreSecretKey.metaSecretKey = metaSecretKey; + kvStoreSecretKey.secretKeyFile = secretKeyFile; + kvStoreSecretKey.alreadyCreated = alreadyCreated; + kvStoreSecretKey.outdated = outdated; + secretKeyParas = kvStoreSecretKey; + + return Status::SUCCESS; +} + +Status KvStoreDataService::RecoverSecretKey(const Status &alreadyCreated, bool &outdated, + const std::vector &metaSecretKey, std::vector &secretKey, const std::string &secretKeyFile) +{ + if (alreadyCreated != Status::SUCCESS) { + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { ZLOGI("new secret key"); CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); - } else { - KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); - if (secretKey.empty()) { - ZLOGW("get secret key from meta failed, try to recover"); - KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); - } - if (secretKey.empty()) { - ZLOGW("recover failed"); - callback(nullptr); - return Status::CRYPT_ERROR; - } } } else { - if (alreadyCreated == Status::SUCCESS || FileExists(secretKeyFile)) { - ZLOGW("try to get an encrypted store with false option encrypt parameter"); - callback(nullptr); + KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); + if (secretKey.empty()) { + ZLOGW("get secret key from meta failed, try to recover"); + KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secretKeyFile, metaSecretKey, secretKey, outdated); + } + if (secretKey.empty()) { + ZLOGW("recover failed"); return Status::CRYPT_ERROR; } + KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); } + return Status::SUCCESS; +} - auto it = deviceAccountMap_.find(deviceAccountId); - if (it == deviceAccountMap_.end()) { - auto result = deviceAccountMap_.emplace(std::piecewise_construct, - std::forward_as_tuple(deviceAccountId), std::forward_as_tuple(deviceAccountId)); - if (!result.second) { - ZLOGE("emplace failed."); - callback(nullptr); +Status KvStoreDataService::UpdateMetaData(const Options &options, const GetKvStorePara &kvParas, + const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager) +{ + KvStoreMetaData metaData; + metaData.appId = kvParas.trueAppId; + metaData.appType = "harmony"; + metaData.bundleName = kvParas.bundleName; + metaData.deviceAccountId = kvParas.deviceAccountId; + metaData.deviceId = DeviceKvStoreImpl::GetLocalDeviceId(); + metaData.isAutoSync = options.autoSync; + metaData.isBackup = options.backup; + metaData.isEncrypt = options.encrypt; + metaData.kvStoreType = options.kvStoreType; + metaData.schema = options.schema; + metaData.storeId = kvParas.storeId; + metaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(kvParas.bundleName); + metaData.uid = IPCSkeleton::GetCallingUid(); + metaData.version = KVSTORE_META_VERSION; + metaData.securityLevel = options.securityLevel; + if (kvParas.funType == KvStoreType::MULTI_VERSION) { + metaData.dataDir = "default"; + } else { + metaData.dataDir = kvStoreUserManager.GetDbDir(kvParas.bundleName, options); + } + + std::string jsonStr = metaData.Marshal(); + std::vector jsonVec(jsonStr.begin(), jsonStr.end()); + + return KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, UPDATE, jsonVec); +} + +Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, std::function)> callback) +{ + Status statusTmp = kvParas.getKvStoreStatus; + Status getKvStoreStatus = statusTmp; + ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); + if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { + if (secKeyParas.alreadyCreated != Status::SUCCESS) { + // create encrypted store failed, remove secret key + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); return Status::ERROR; } - it = result.first; - } - auto newCallback = [&callback, outdated, deviceAccountId, bundleName, storeIdTmp](sptr store) { - if (outdated) { - KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); + // get existing encrypted store failed, retry with key stored in file + Status status = KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( + secKeyParas.secretKeyFile, secKeyParas.metaSecretKey, secKeyParas.secretKey, secKeyParas.outdated); + if (status != Status::SUCCESS) { + callback(nullptr); + return Status::CRYPT_ERROR; } - callback(store); - }; - Status statusTmp = (it->second).GetSingleKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); - if (statusTmp == Status::SUCCESS) { - KvStoreMetaData metaData { - .appId = trueAppId, - .appType = "harmony", - .bundleName = bundleName, - .dataDir = (it->second).GetDbDir(bundleName, options), - .deviceAccountId = deviceAccountId, - .deviceId = DeviceKvStoreImpl::GetLocalDeviceId(), - .isAutoSync = options.autoSync, - .isBackup = options.backup, - .isEncrypt = options.encrypt, - .kvStoreType = options.kvStoreType, - .schema = options.schema, - .storeId = storeIdTmp, - .userId = Constant::DEFAULT_GROUP_ID, - .uid = IPCSkeleton::GetCallingUid(), - .version = KVSTORE_META_VERSION, - .securityLevel = SecurityLevel::NO_LABEL, - }; - std::string jsonStr = metaData.Marshal(); - std::vector jsonVec(jsonStr.begin(), jsonStr.end()); + // here callback is called twice + statusTmp = kvUserManager.GetKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, + [&](sptr store) { + if (secKeyParas.outdated) { + KvStoreMetaManager::GetInstance().ReKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId, store); + } + callback(store); + }); + } - return KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, UPDATE, jsonVec); + // if kvstore damaged and no backup file, then return DB_ERROR + if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { + // if backup file not exist, dont need recover + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { + return Status::CRYPT_ERROR; + } + // remove damaged database + if (DeleteKvStoreOnly(kvParas.storeId, kvParas.deviceAccountId, kvParas.bundleName) != Status::SUCCESS) { + ZLOGE("DeleteKvStoreOnly failed."); + return Status::DB_ERROR; + } + // recover database + return RecoverMultiKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, callback); } - ZLOGW("getKvStore failed with status %d", static_cast(statusTmp)); + return statusTmp; +} + +Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, + KvStoreUserManager &kvUserManager, std::function)> callback) +{ + Status statusTmp = kvParas.getKvStoreStatus; Status getKvStoreStatus = statusTmp; + ZLOGW("getKvStore failed with status %d", static_cast(getKvStoreStatus)); if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { - if (alreadyCreated != Status::SUCCESS) { + if (secKeyParas.alreadyCreated != Status::SUCCESS) { // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(deviceAccountId, bundleName, storeIdTmp); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); return Status::ERROR; } // get existing encrypted store failed, retry with key stored in file Status status = KvStoreMetaManager::GetInstance().RecoverSecretKeyFromFile( - secretKeyFile, metaSecretKey, secretKey, outdated); + secKeyParas.secretKeyFile, secKeyParas.metaSecretKey, secKeyParas.secretKey, secKeyParas.outdated); if (status != Status::SUCCESS) { callback(nullptr); return Status::CRYPT_ERROR; } // here callback is called twice - statusTmp = (it->second).GetSingleKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); + statusTmp = kvUserManager.GetSingleKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, + [&](sptr store) { + if (secKeyParas.outdated) { + KvStoreMetaManager::GetInstance().ReKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId, store); + } + callback(store); + }); } // if kvstore damaged and no backup file, then return DB_ERROR if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { // if backup file not exist, dont need recover - if (!CheckBackupFileExist(deviceAccountId, bundleName, storeId.storeId, options.securityLevel)) { + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { return Status::CRYPT_ERROR; } // remove damaged database - if (DeleteKvStoreOnly(storeIdTmp, deviceAccountId, bundleName) != Status::SUCCESS) { + if (DeleteKvStoreOnly(kvParas.storeId, kvParas.deviceAccountId, kvParas.bundleName) != Status::SUCCESS) { ZLOGE("DeleteKvStoreOnly failed."); return Status::DB_ERROR; } // recover database - return RecoverSingleKvStore(options, deviceAccountId, bundleName, storeId, secretKey, callback); + return RecoverSingleKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, callback); } return statusTmp; } @@ -531,8 +545,9 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId { auto pathType = KvStoreAppManager::ConvertPathType(bundleName, securityLevel); auto backupFileName = Constant::Concatenate({ Constant::DEFAULT_GROUP_ID, "_", bundleName, "_", storeId }); - auto backFilePath = Constant::Concatenate({ BackupHandler::GetBackupPath(deviceAccountId, pathType), - "/", BackupHandler::GetHashedBackupName(backupFileName) }); + std::initializer_list backFileList = {BackupHandler::GetBackupPath(deviceAccountId, pathType), + "/", BackupHandler::GetHashedBackupName(backupFileName)}; + auto backFilePath = Constant::Concatenate(backFileList); if (!BackupHandler::FileExists(backFilePath)) { ZLOGE("BackupHandler file is not exist."); return false; @@ -541,18 +556,19 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId } Status KvStoreDataService::RecoverSingleKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, - const StoreId &storeId, + const std::string &storeId, const std::vector &secretKey, std::function)> callback) { // restore database - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + std::string storeIdTmp = storeId; std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -581,18 +597,19 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, } Status KvStoreDataService::RecoverMultiKvStore(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, - const StoreId &storeId, + const std::string &storeId, const std::vector &secretKey, std::function)> callback) { // restore database - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + std::string storeIdTmp = storeId; std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); Options optionsTmp = options; optionsTmp.createIfMissing = true; + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { ZLOGD("deviceAccountId not found"); @@ -768,7 +785,6 @@ Status KvStoreDataService::CloseAllKvStore(const AppId &appId) Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &storeId) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - std::string bundleName = appId.appId; if (!CheckBundleName(bundleName)) { ZLOGE("invalid bundleName."); @@ -780,9 +796,9 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor return Status::PERMISSION_DENIED; } // delete the backup file - auto backupFileName = Constant::Concatenate({ - AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), "_", bundleName, "_", storeId.storeId - }); + std::initializer_list backFileList = { + AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), "_", bundleName, "_", storeId.storeId}; + auto backupFileName = Constant::Concatenate(backFileList); const int32_t uid = IPCSkeleton::GetCallingUid(); const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); @@ -791,17 +807,15 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor return Status::NOT_SUPPORT; } - auto backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_DE), "/", - BackupHandler::GetHashedBackupName(backupFileName) - }); + std::initializer_list backPathListDE = {BackupHandler::GetBackupPath(deviceAccountId, + KvStoreAppManager::PATH_DE), "/", BackupHandler::GetHashedBackupName(backupFileName)}; + auto backFilePath = Constant::Concatenate(backPathListDE); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } - backFilePath = Constant::Concatenate({ - BackupHandler::GetBackupPath(deviceAccountId, KvStoreAppManager::PATH_CE), "/", - BackupHandler::GetHashedBackupName(backupFileName) - }); + std::initializer_list backPathListCE = {BackupHandler::GetBackupPath(deviceAccountId, + KvStoreAppManager::PATH_CE), "/", BackupHandler::GetHashedBackupName(backupFileName)}; + backFilePath = Constant::Concatenate(backPathListCE); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } @@ -940,24 +954,37 @@ void KvStoreDataService::OnStart() return; } } + StartService(); +} +void KvStoreDataService::StartService() +{ // register this to ServiceManager. bool ret = SystemAbility::Publish(this); if (!ret) { FaultMsg msg = {FaultType::SERVICE_FAULT, "service", __FUNCTION__, Fault::SF_SERVICE_PUBLISH}; Reporter::GetInstance()->ServiceFault()->Report(msg); } - Uninstaller::GetInstance().Init(this); + std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, + KvStoreAppManager::PATH_DE); + ZLOGI("backupPath is : %s ", backupPath.c_str()); + if (!ForceCreateDirectory(backupPath)) { + ZLOGE("backup create directory failed"); + } // Initialize meta db delegate manager. KvStoreMetaManager::GetInstance().InitMetaListener([this](const KvStoreMetaData &metaData) { if (!metaData.isDirty) { return; } - CloseKvStore({metaData.bundleName}, {metaData.storeId}); - DeleteKvStore({metaData.bundleName}, {metaData.storeId}); + AppId appId; + appId.appId = metaData.bundleName; + StoreId storeId; + storeId.storeId = metaData.storeId; + CloseKvStore(appId, storeId); + DeleteKvStore(appId, storeId); }); // subscribe account event listener to EventNotificationMgr @@ -983,13 +1010,8 @@ void KvStoreDataService::OnStart() DistributedDB::KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); backup_ = std::make_unique(this); - std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, - KvStoreAppManager::PATH_CE); - ZLOGI("backupPath is : %s ", backupPath.c_str()); - if (!ForceCreateDirectory(backupPath)) { - ZLOGE("backup create directory failed."); - } backup_->BackSchedule(); + std::thread th = std::thread([]() { sleep(TEN_SEC); KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(); -- Gitee From 19c46d12afb07cde2215a40ad6426a40ac7ee59a Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Mon, 8 Nov 2021 11:48:54 +0800 Subject: [PATCH 2/8] fix some code style Signed-off-by: zuojiangjiang --- .../app/src/backup_handler.cpp | 1 - .../app/src/kvstore_data_service.cpp | 25 +++++++++++-------- .../test/unittest/kvstore_data_service.cpp | 21 ++++++++++------ 3 files changed, 28 insertions(+), 19 deletions(-) diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index d07657207..87ce1e8ca 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -118,7 +118,6 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) ZLOGE("pragmaStatus: %d", static_cast(pragmaStatus)); } } - ZLOGW("SingleKvStoreBackup export"); if (status == DistributedDB::DBStatus::OK) { auto backupFullName = backupPara.backupFullName; diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 5b58f04e9..5c74e8087 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -170,7 +170,6 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId auto deviceAccountId = getKvStorePara.deviceAccountId; auto bundleName = getKvStorePara.bundleName; auto storeIdTmp = getKvStorePara.storeId; - auto secretKey = secretKeyParas.secretKey; bool outdated = secretKeyParas.outdated; @@ -330,7 +329,8 @@ Status KvStoreDataService::GetSecretKey(const Options &options, const GetKvStore if (kvParas.funType == KvStoreType::MULTI_VERSION) { metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); } else { - metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); + metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, + storeIdTmp, "SINGLE_KEY"); } auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( @@ -430,7 +430,8 @@ Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvS if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { if (secKeyParas.alreadyCreated != Status::SUCCESS) { // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId); return Status::ERROR; } // get existing encrypted store failed, retry with key stored in file @@ -454,7 +455,8 @@ Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvS // if kvstore damaged and no backup file, then return DB_ERROR if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { // if backup file not exist, dont need recover - if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, + options.securityLevel)) { return Status::CRYPT_ERROR; } // remove damaged database @@ -468,8 +470,9 @@ Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvS return statusTmp; } -Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, std::function)> callback) +Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, + std::function)> callback) { Status statusTmp = kvParas.getKvStoreStatus; Status getKvStoreStatus = statusTmp; @@ -477,7 +480,8 @@ Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { if (secKeyParas.alreadyCreated != Status::SUCCESS) { // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId); return Status::ERROR; } // get existing encrypted store failed, retry with key stored in file @@ -501,7 +505,8 @@ Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const // if kvstore damaged and no backup file, then return DB_ERROR if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { // if backup file not exist, dont need recover - if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, + options.securityLevel)) { return Status::CRYPT_ERROR; } // remove damaged database @@ -1284,7 +1289,7 @@ Status KvStoreDataService::GetDeviceList(std::vector &deviceInfoList { auto devices = KvStoreUtils::GetProviderInstance().GetRemoteNodesBasicInfo(); for (auto const &device : devices) { - deviceInfoList.push_back({ device.deviceId, device.deviceName, device.deviceType }); + deviceInfoList.push_back({device.deviceId, device.deviceName, device.deviceType}); } ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; @@ -1303,7 +1308,7 @@ Status KvStoreDataService::StartWatchDeviceChange(sptrAsObject().GetRefPtr(); - deviceListeners_.insert({ objectPtr, observer }); + deviceListeners_.insert({objectPtr, observer}); ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; } diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp index 9985e88ae..132f304a8 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp @@ -165,7 +165,6 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId auto deviceAccountId = getKvStorePara.deviceAccountId; auto bundleName = getKvStorePara.bundleName; auto storeIdTmp = getKvStorePara.storeId; - auto secretKey = secretKeyParas.secretKey; bool outdated = secretKeyParas.outdated; @@ -325,7 +324,8 @@ Status KvStoreDataService::GetSecretKey(const Options &options, const GetKvStore if (kvParas.funType == KvStoreType::MULTI_VERSION) { metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); } else { - metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); + metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, + storeIdTmp, "SINGLE_KEY"); } auto secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( @@ -425,7 +425,8 @@ Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvS if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { if (secKeyParas.alreadyCreated != Status::SUCCESS) { // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId); return Status::ERROR; } // get existing encrypted store failed, retry with key stored in file @@ -449,7 +450,8 @@ Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvS // if kvstore damaged and no backup file, then return DB_ERROR if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { // if backup file not exist, dont need recover - if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, + options.securityLevel)) { return Status::CRYPT_ERROR; } // remove damaged database @@ -463,8 +465,9 @@ Status KvStoreDataService::GetKvStoreFailDo(const Options &options, const GetKvS return statusTmp; } -Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, std::function)> callback) +Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, + std::function)> callback) { Status statusTmp = kvParas.getKvStoreStatus; Status getKvStoreStatus = statusTmp; @@ -472,7 +475,8 @@ Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const if (getKvStoreStatus == Status::CRYPT_ERROR && options.encrypt) { if (secKeyParas.alreadyCreated != Status::SUCCESS) { // create encrypted store failed, remove secret key - KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.deviceAccountId, kvParas.bundleName, + kvParas.storeId); return Status::ERROR; } // get existing encrypted store failed, retry with key stored in file @@ -496,7 +500,8 @@ Status KvStoreDataService::GetSingleKvStoreFailDo(const Options &options, const // if kvstore damaged and no backup file, then return DB_ERROR if (statusTmp != Status::SUCCESS && getKvStoreStatus == Status::CRYPT_ERROR) { // if backup file not exist, dont need recover - if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { + if (!CheckBackupFileExist(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, + options.securityLevel)) { return Status::CRYPT_ERROR; } // remove damaged database -- Gitee From 3635e14d54be0751ec06c00ae8636e81984f0399 Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Mon, 8 Nov 2021 14:34:14 +0800 Subject: [PATCH 3/8] fix some code style Signed-off-by: zuojiangjiang --- .../app/src/backup_handler.cpp | 3 +-- .../app/src/kvstore_data_service.cpp | 20 ++++++++++--------- .../test/unittest/kvstore_data_service.cpp | 20 +++++++++---------- 3 files changed, 22 insertions(+), 21 deletions(-) diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index 87ce1e8ca..b3c7b5263 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -100,8 +100,7 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, metaData.kvStoreMetaData.bundleName, backupPara.pathType); - DistributedDB::KvStoreConfig kvStoreConfig; - kvStoreConfig.dataDir = appDataStoragePath; + DistributedDB::KvStoreConfig kvStoreConfig = {appDataStoragePath}; delegateMgr->SetKvStoreConfig(kvStoreConfig); std::function fun = [&](DistributedDB::DBStatus status, DistributedDB::KvStoreNbDelegate *delegate) { diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 5c74e8087..375b516d6 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -186,13 +186,14 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId } it = result.first; } - Status statusTmp = (it->second).GetKvStore(options, bundleName, storeIdTmp, secretKey, - [&](sptr store) { - if (outdated) { - KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); - } - callback(store); - }); + + auto newCallback = [&callback, outdated, deviceAccountId, bundleName, storeIdTmp](sptr store) { + if (outdated) { + KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); + } + callback(store); + }; + Status statusTmp = (it->second).GetKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); ZLOGD("get kvstore return status:%d, deviceAccountId:[%s], bundleName:[%s].", statusTmp, KvStoreUtils::ToBeAnonymous(deviceAccountId).c_str(), bundleName.c_str()); @@ -1289,7 +1290,8 @@ Status KvStoreDataService::GetDeviceList(std::vector &deviceInfoList { auto devices = KvStoreUtils::GetProviderInstance().GetRemoteNodesBasicInfo(); for (auto const &device : devices) { - deviceInfoList.push_back({device.deviceId, device.deviceName, device.deviceType}); + DeviceInfo deviceInfo = {device.deviceId, device.deviceName, device.deviceType}; + deviceInfoList.push_back(deviceInfo); } ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; @@ -1308,7 +1310,7 @@ Status KvStoreDataService::StartWatchDeviceChange(sptrAsObject().GetRefPtr(); - deviceListeners_.insert({objectPtr, observer}); + deviceListeners_.insert({ objectPtr, observer }); ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; } diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp index 132f304a8..b3f5eaf96 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp @@ -181,13 +181,13 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId } it = result.first; } - Status statusTmp = (it->second).GetKvStore(options, bundleName, storeIdTmp, secretKey, - [&](sptr store) { - if (outdated) { - KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); - } - callback(store); - }); + auto newCallback = [&callback, outdated, deviceAccountId, bundleName, storeIdTmp](sptr store) { + if (outdated) { + KvStoreMetaManager::GetInstance().ReKey(deviceAccountId, bundleName, storeIdTmp, store); + } + callback(store); + }; + Status statusTmp = (it->second).GetKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); ZLOGD("get kvstore return status:%d, deviceAccountId:[%s], bundleName:[%s].", statusTmp, KvStoreUtils::ToBeAnonymous(deviceAccountId).c_str(), bundleName.c_str()); @@ -1236,9 +1236,9 @@ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) if (it != deviceAccountMap_.end()) { deviceAccountMap_.erase(eventInfo.deviceAccountId); } - std::string deviceAccountKvStoreDataDir = - Constant::Concatenate({Constant::ROOT_PATH_DE, "/", Constant::SERVICE_NAME, - "/", eventInfo.deviceAccountId}); + std::initializer_list dataDirList = {Constant::ROOT_PATH_DE, "/", + Constant::SERVICE_NAME, "/", eventInfo.deviceAccountId}; + std::string deviceAccountKvStoreDataDir = Constant::Concatenate(dataDirList); ForceRemoveDirectory(deviceAccountKvStoreDataDir); deviceAccountKvStoreDataDir = Constant::Concatenate({Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, -- Gitee From 7b755721e0846ca1aa97b53b39e1833b0731edd6 Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Mon, 8 Nov 2021 15:46:29 +0800 Subject: [PATCH 4/8] fix some code style Signed-off-by: zuojiangjiang --- .../app/src/kvstore_data_service.cpp | 103 +++++++++--------- .../app/src/kvstore_data_service.h | 2 +- .../test/unittest/kvstore_data_service.cpp | 1 - 3 files changed, 51 insertions(+), 55 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 375b516d6..cacba646b 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -153,7 +153,6 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId } GetKvStorePara getKvStorePara; - getKvStorePara.funType = KvStoreType::MULTI_VERSION; Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, getKvStorePara); if (checkParaStatus != Status::SUCCESS) { callback(nullptr); @@ -555,7 +554,8 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId const std::string &storeId, int securityLevel) { auto pathType = KvStoreAppManager::ConvertPathType(bundleName, securityLevel); - auto backupFileName = Constant::Concatenate({ Constant::DEFAULT_GROUP_ID, "_", bundleName, "_", storeId }); + std::initializer_list backupFileNameList = {Constant::DEFAULT_GROUP_ID, "_", bundleName, "_", storeId}; + auto backupFileName = Constant::Concatenate(backupFileNameList); std::initializer_list backFileList = {BackupHandler::GetBackupPath(deviceAccountId, pathType), "/", BackupHandler::GetHashedBackupName(backupFileName)}; auto backFilePath = Constant::Concatenate(backFileList); @@ -650,6 +650,47 @@ Status KvStoreDataService::RecoverMultiKvStore(const Options &options, return Status::RECOVER_SUCCESS; } +Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &storeId) +{ + DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); + ZLOGI("begin."); + std::string bundleName = Constant::TrimCopy(appId.appId); + std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + if (!CheckBundleName(bundleName)) { + ZLOGE("invalid bundleName."); + return Status::INVALID_ARGUMENT; + } + if (!CheckStoreId(storeIdTmp)) { + ZLOGE("invalid storeIdTmp."); + return Status::INVALID_ARGUMENT; + } + + std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); + if (trueAppId.empty()) { + ZLOGE("get appId failed."); + return Status::PERMISSION_DENIED; + } + + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { + ZLOGE("not support sub account"); + return Status::NOT_SUPPORT; + } + std::lock_guard lg(accountMutex_); + auto it = deviceAccountMap_.find(deviceAccountId); + if (it != deviceAccountMap_.end()) { + Status status = (it->second).CloseKvStore(bundleName, storeIdTmp); + if (status != Status::STORE_NOT_OPEN) { + return status; + } + } + FaultMsg msg = {FaultType::RUNTIME_FAULT, "user", __FUNCTION__, Fault::RF_CLOSE_DB}; + Reporter::GetInstance()->ServiceFault()->Report(msg); + ZLOGE("return STORE_NOT_OPEN."); + return Status::STORE_NOT_OPEN; +} + void KvStoreDataService::GetAllKvStoreId( const AppId &appId, std::function &)> callback) { @@ -685,15 +726,11 @@ void KvStoreDataService::GetAllKvStoreId( } std::vector dbEntries; DistributedDB::DBStatus dbStatus; - DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor( - DeviceKvStoreImpl::GetLocalDeviceId() + Constant::KEY_SEPARATOR + - deviceAccountId + Constant::KEY_SEPARATOR + - "default" + Constant::KEY_SEPARATOR + - bundleName + Constant::KEY_SEPARATOR); - { - DdsTrace trace(std::string(LOG_TAG "Delegate::") + std::string(__FUNCTION__)); - dbStatus = metaKvStoreDelegate->GetEntries(dbKey, dbEntries); - } + DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor(DeviceKvStoreImpl::GetLocalDeviceId() + + Constant::KEY_SEPARATOR + deviceAccountId + Constant::KEY_SEPARATOR + + "default" + Constant::KEY_SEPARATOR + bundleName + Constant::KEY_SEPARATOR); + DdsTrace trace(std::string(LOG_TAG "Delegate::") + std::string(__FUNCTION__)); + dbStatus = metaKvStoreDelegate->GetEntries(dbKey, dbEntries); if (dbStatus != DistributedDB::DBStatus::OK) { ZLOGE("GetEntries delegate return error: %d.", static_cast(dbStatus)); if (dbEntries.empty()) { @@ -717,47 +754,6 @@ void KvStoreDataService::GetAllKvStoreId( callback(Status::SUCCESS, storeIdList); } -Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &storeId) -{ - DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGI("begin."); - std::string bundleName = Constant::TrimCopy(appId.appId); - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - return Status::INVALID_ARGUMENT; - } - - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGE("get appId failed."); - return Status::PERMISSION_DENIED; - } - - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } - std::lock_guard lg(accountMutex_); - auto it = deviceAccountMap_.find(deviceAccountId); - if (it != deviceAccountMap_.end()) { - Status status = (it->second).CloseKvStore(bundleName, storeIdTmp); - if (status != Status::STORE_NOT_OPEN) { - return status; - } - } - FaultMsg msg = {FaultType::RUNTIME_FAULT, "user", __FUNCTION__, Fault::RF_CLOSE_DB}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - ZLOGE("return STORE_NOT_OPEN."); - return Status::STORE_NOT_OPEN; -} - /* close all opened kvstore */ Status KvStoreDataService::CloseAllKvStore(const AppId &appId) { @@ -1310,7 +1306,8 @@ Status KvStoreDataService::StartWatchDeviceChange(sptrAsObject().GetRefPtr(); - deviceListeners_.insert({ objectPtr, observer }); + auto listenerPair = std::make_pair(objectPtr, observer); + deviceListeners_.insert(listenerPair); ZLOGD("strategy is %d.", strategy); return Status::SUCCESS; } diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index be24df9f9..01d75536a 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -100,7 +100,7 @@ public: std::string trueAppId; std::string deviceAccountId; Status getKvStoreStatus = Status::SUCCESS; - KvStoreType funType = KvStoreType::DEVICE_COLLABORATION; + KvStoreType funType = KvStoreType::MULTI_VERSION; }; struct SecretKeyPara { std::vector metaKey; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp index b3f5eaf96..2f4aacf3f 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp @@ -148,7 +148,6 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId } GetKvStorePara getKvStorePara; - getKvStorePara.funType = KvStoreType::MULTI_VERSION; Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, getKvStorePara); if (checkParaStatus != Status::SUCCESS) { callback(nullptr); -- Gitee From a73152bd19ff0066913af67885558b1aa4528bfa Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Mon, 8 Nov 2021 16:18:47 +0800 Subject: [PATCH 5/8] fix some code style Signed-off-by: zuojiangjiang --- .../app/src/kvstore_data_service.cpp | 92 +++++++++---------- 1 file changed, 43 insertions(+), 49 deletions(-) diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index cacba646b..3ec35f2e2 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -554,7 +554,8 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId const std::string &storeId, int securityLevel) { auto pathType = KvStoreAppManager::ConvertPathType(bundleName, securityLevel); - std::initializer_list backupFileNameList = {Constant::DEFAULT_GROUP_ID, "_", bundleName, "_", storeId}; + std::initializer_list backupFileNameList = {Constant::DEFAULT_GROUP_ID, "_", + bundleName, "_", storeId}; auto backupFileName = Constant::Concatenate(backupFileNameList); std::initializer_list backFileList = {BackupHandler::GetBackupPath(deviceAccountId, pathType), "/", BackupHandler::GetHashedBackupName(backupFileName)}; @@ -650,47 +651,6 @@ Status KvStoreDataService::RecoverMultiKvStore(const Options &options, return Status::RECOVER_SUCCESS; } -Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &storeId) -{ - DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGI("begin."); - std::string bundleName = Constant::TrimCopy(appId.appId); - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - return Status::INVALID_ARGUMENT; - } - - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGE("get appId failed."); - return Status::PERMISSION_DENIED; - } - - const int32_t uid = IPCSkeleton::GetCallingUid(); - const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } - std::lock_guard lg(accountMutex_); - auto it = deviceAccountMap_.find(deviceAccountId); - if (it != deviceAccountMap_.end()) { - Status status = (it->second).CloseKvStore(bundleName, storeIdTmp); - if (status != Status::STORE_NOT_OPEN) { - return status; - } - } - FaultMsg msg = {FaultType::RUNTIME_FAULT, "user", __FUNCTION__, Fault::RF_CLOSE_DB}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - ZLOGE("return STORE_NOT_OPEN."); - return Status::STORE_NOT_OPEN; -} - void KvStoreDataService::GetAllKvStoreId( const AppId &appId, std::function &)> callback) { @@ -704,13 +664,6 @@ void KvStoreDataService::GetAllKvStoreId( return; } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGE("get appId failed."); - callback(Status::PERMISSION_DENIED, storeIdList); - return; - } - auto &metaKvStoreDelegate = KvStoreMetaManager::GetInstance().GetMetaKvStore(); if (metaKvStoreDelegate == nullptr) { ZLOGE("metaKvStoreDelegate is null"); @@ -754,6 +707,47 @@ void KvStoreDataService::GetAllKvStoreId( callback(Status::SUCCESS, storeIdList); } +Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &storeId) +{ + DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); + ZLOGI("begin."); + std::string bundleName = Constant::TrimCopy(appId.appId); + std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); + if (!CheckBundleName(bundleName)) { + ZLOGE("invalid bundleName."); + return Status::INVALID_ARGUMENT; + } + if (!CheckStoreId(storeIdTmp)) { + ZLOGE("invalid storeIdTmp."); + return Status::INVALID_ARGUMENT; + } + + std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); + if (trueAppId.empty()) { + ZLOGE("get appId failed."); + return Status::PERMISSION_DENIED; + } + + const int32_t uid = IPCSkeleton::GetCallingUid(); + const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { + ZLOGE("not support sub account"); + return Status::NOT_SUPPORT; + } + std::lock_guard lg(accountMutex_); + auto it = deviceAccountMap_.find(deviceAccountId); + if (it != deviceAccountMap_.end()) { + Status status = (it->second).CloseKvStore(bundleName, storeIdTmp); + if (status != Status::STORE_NOT_OPEN) { + return status; + } + } + FaultMsg msg = {FaultType::RUNTIME_FAULT, "user", __FUNCTION__, Fault::RF_CLOSE_DB}; + Reporter::GetInstance()->ServiceFault()->Report(msg); + ZLOGE("return STORE_NOT_OPEN."); + return Status::STORE_NOT_OPEN; +} + /* close all opened kvstore */ Status KvStoreDataService::CloseAllKvStore(const AppId &appId) { -- Gitee From a11ad0b8f4d91322c9b3baa82b9d879481ee5d36 Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Mon, 8 Nov 2021 16:39:50 +0800 Subject: [PATCH 6/8] fix Debug ERROR Signed-off-by: zuojiangjiang --- .../distributeddataservice/app/src/kvstore_data_service.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 3ec35f2e2..70a3feaed 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -682,7 +682,7 @@ void KvStoreDataService::GetAllKvStoreId( DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor(DeviceKvStoreImpl::GetLocalDeviceId() + Constant::KEY_SEPARATOR + deviceAccountId + Constant::KEY_SEPARATOR + "default" + Constant::KEY_SEPARATOR + bundleName + Constant::KEY_SEPARATOR); - DdsTrace trace(std::string(LOG_TAG "Delegate::") + std::string(__FUNCTION__)); + DdsTrace traceDelegate(std::string(LOG_TAG "Delegate::") + std::string(__FUNCTION__)); dbStatus = metaKvStoreDelegate->GetEntries(dbKey, dbEntries); if (dbStatus != DistributedDB::DBStatus::OK) { ZLOGE("GetEntries delegate return error: %d.", static_cast(dbStatus)); -- Gitee From 09f9dda80e5e2551a2ccbfcd1eaa17fc371eb219 Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Wed, 10 Nov 2021 10:27:32 +0800 Subject: [PATCH 7/8] fix the SecretKeyMetaData Signed-off-by: zuojiangjiang --- services/distributeddataservice/app/src/kvstore_meta_manager.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index d54c3e01c..e99bd3d0d 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -61,6 +61,9 @@ struct SecretKeyMetaData { std::vector secretKey {}; KvStoreType kvStoreType = KvStoreType::INVALID_TYPE; SecretKeyMetaData() {} + ~SecretKeyMetaData() { + secretKey.assign(secretKey.size(), 0); + } explicit SecretKeyMetaData(const nlohmann::json &jObject) { Unmarshal(jObject); -- Gitee From 992b3b2564408445240381d84fd0d57cbfc4564b Mon Sep 17 00:00:00 2001 From: zuojiangjiang Date: Wed, 10 Nov 2021 11:04:53 +0800 Subject: [PATCH 8/8] fix SecretKeyMetaData Signed-off-by: zuojiangjiang --- services/distributeddataservice/app/src/kvstore_meta_manager.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index e99bd3d0d..0d05b68ee 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -61,7 +61,8 @@ struct SecretKeyMetaData { std::vector secretKey {}; KvStoreType kvStoreType = KvStoreType::INVALID_TYPE; SecretKeyMetaData() {} - ~SecretKeyMetaData() { + ~SecretKeyMetaData() + { secretKey.assign(secretKey.size(), 0); } explicit SecretKeyMetaData(const nlohmann::json &jObject) -- Gitee