diff --git a/conf/config.json b/conf/config.json index 5a311cee7a95c0b2f496a925ad3063c48046ef42..3648e364d3d744cab0dd6d3147af7502fc17ebbf 100644 --- a/conf/config.json +++ b/conf/config.json @@ -30,16 +30,6 @@ "bundleName": "bundle_manager_service", "appId": "bundle_manager_service", "checker": "SystemChecker" - }, - { - "bundleName": "form_storage", - "appId": "form_storage", - "checker": "SystemChecker" - }, - { - "bundleName": "ivi_config_manager", - "appId": "ivi_config_manager", - "checker": "SystemChecker" } ] }, diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h index 2821dee8e5e81a81017d165ddf6bcb9462368feb..5b79c239d93928e2fc3633e6383d32dc5bab5192 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h @@ -93,7 +93,6 @@ public: private: static inline BrokerDelegator delegator_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h b/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h index ee3e8f61983188baabed94067dc554ec7d81f394..d55c2b534295d489fc45a3f0314e9bbe10187492 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h @@ -27,31 +27,31 @@ class ITypesUtil final { public: static bool Marshalling(const Blob &blob, MessageParcel &data); static bool Unmarshalling(MessageParcel &data, Blob &output); - + static bool Marshalling(const std::vector &blobs, MessageParcel &data); static bool Unmarshalling(MessageParcel &data, std::vector &output); - + static bool Marshalling(const Entry &entry, MessageParcel &data); static bool Unmarshalling(MessageParcel &data, Entry &output); - + static bool Marshalling(const std::vector &entry, MessageParcel &data); static bool Unmarshalling(MessageParcel &data, std::vector &output); - + static bool Marshalling(const DeviceInfo &entry, MessageParcel &data); static bool Unmarshalling(MessageParcel &data, DeviceInfo &output); - + static bool Marshalling(const std::vector &input, MessageParcel &data); static bool Unmarshalling(MessageParcel &data, std::vector &output); - + static bool Marshalling(const ChangeNotification ¬ification, MessageParcel &parcel); static bool Unmarshalling(MessageParcel &parcel, ChangeNotification &output); - + static bool Marshalling(const DistributedRdb::RdbSyncerParam& param, MessageParcel& parcel); static bool UnMarshalling(MessageParcel& parcel, DistributedRdb::RdbSyncerParam& param); - + static int64_t GetTotalSize(const std::vector &entries); static int64_t GetTotalSize(const std::vector &entries); - + template static Status MarshalToBuffer(const T &input, int size, MessageParcel &data) { @@ -68,7 +68,7 @@ public: } return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR; } - + template static Status MarshalToBuffer(const std::vector &input, int size, MessageParcel &data) { @@ -90,7 +90,7 @@ public: } return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR; } - + template static Status UnmarshalFromBuffer(MessageParcel &data, int size, T &output) { @@ -106,7 +106,7 @@ public: } return output.ReadFromBuffer(buffer, size) ? Status::SUCCESS : Status::IPC_ERROR; } - + template static Status UnmarshalFromBuffer(MessageParcel &data, int size, std::vector &output) { @@ -121,7 +121,7 @@ public: if (count < 0 || buffer == nullptr) { return Status::INVALID_ARGUMENT; } - + output.resize(count); for (auto &entry : output) { if (!entry.ReadFromBuffer(buffer, size)) { @@ -139,7 +139,7 @@ private: bool Writer(const T &entry) { return ITypesUtil::Marshalling(entry, *this); } bool Reader(T &entry) { return ITypesUtil::Unmarshalling(*this, entry); } }; - + template static bool ReadVector(Parcel &parcel, std::vector &val, bool (Parcel::*read)(T &)); template diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp index 1ffeafd8c995e6f8d526e9d42f97d1c7bbb68047..a464c22eec65ac3998f7382df0da657833974d79 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.cpp @@ -63,7 +63,7 @@ std::shared_ptr AppDistributedKvDataManagerImpl::Ge return nullptr; } - std::string appId = KvStoreUtils::GetAppIdByBundleName(bundleName); + std::string appId = bundleName; if (appId.empty()) { appId = bundleName; } @@ -98,7 +98,7 @@ std::shared_ptr AppDistributedKvDataManagerImpl::Ge return nullptr; } - auto temp = std::make_shared(delegateManager, appId); + auto temp = std::make_shared(delegateManager, appId, userId); if (temp == nullptr) { delete delegateManager; delegateManager = nullptr; @@ -112,8 +112,8 @@ std::shared_ptr AppDistributedKvDataManagerImpl::Ge } AppDistributedKvDataManagerImpl::AppDistributedKvDataManagerImpl( - DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId) - : kvStoreDelegateManager_(delegateManager), appId_(appId) + DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId, const std::string &accountId) + : kvStoreDelegateManager_(delegateManager), appId_(appId), accountId_(accountId) { ZLOGI("construct"); } @@ -152,8 +152,7 @@ Status AppDistributedKvDataManagerImpl::GetKvStore( ZLOGI("succeed."); auto statDelegateMgr = std::make_shared(kvStoreDelegateManager_); auto statDelegate = std::static_pointer_cast(statDelegateMgr); - Reporter::GetInstance()->DatabaseStatistic()->Report( - {AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), appId_, storeId, 0, statDelegate}); + Reporter::GetInstance()->DatabaseStatistic()->Report({accountId_, appId_, storeId, 0, statDelegate}); return; } diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h index 9032b7a85f0276ede2b491c3e7727e4fc0f08a3f..7fa56c8300e0b750603d33175cb7fc0d889c3807 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/app_distributed_kv_data_manager_impl.h @@ -30,7 +30,8 @@ namespace AppDistributedKv { // This class provides open, close, delete AppKvStore and manage remote device functions. class AppDistributedKvDataManagerImpl final : public AppDistributedKvDataManager { public: - AppDistributedKvDataManagerImpl(DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId); + AppDistributedKvDataManagerImpl(DistributedDB::KvStoreDelegateManager *delegateManager, const std::string &appId, + const std::string &accountId); static std::shared_ptr GetInstance(const std::string &bundleName, const std::string &dataDir, @@ -57,7 +58,7 @@ private: // pointer of class DistributedDB::KvStoreDelegateManager. defined as void* to avoid exposing inside implementions. DistributedDB::KvStoreDelegateManager *kvStoreDelegateManager_; std::string appId_; - + std::string accountId_; std::shared_ptr corruptionObserver_; }; // class AppDistributedKvDataManagerImpl } // namespace AppDistributedKv diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/idevice_status_change_listener_impl.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/idevice_status_change_listener_impl.cpp index 3900444fb24b2741cbe694bcfcbb286d7595ca63..2bb53ec31a6692590b3a3e25222156b7192f7acb 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/idevice_status_change_listener_impl.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/idevice_status_change_listener_impl.cpp @@ -49,7 +49,7 @@ void DeviceStatusChangeListenerProxy::OnChange(const DeviceInfo &results, const int DeviceStatusChangeListenerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - ZLOGD("%d", code); + ZLOGD("%{public}d", code); std::u16string descriptor = DeviceStatusChangeListenerStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore.cpp index 823907b15cddfb30a8827d7265c8f74ead90eea8..64500b51c0368a30794c8fbf512007a7e7ff2b49 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore.cpp @@ -675,7 +675,7 @@ int32_t KvStoreImplStub::UnSubscribeKvStoreOnRemote(MessageParcel &data, Message int32_t KvStoreImplStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - ZLOGD("%d", code); + ZLOGD("%{public}d", code); std::u16string descriptor = KvStoreImplStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp index 56e0a24089766c977217fefc09a659457e267cc5..426b784cbe83fa39012909d65fc5f95ed655e772 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp @@ -410,10 +410,6 @@ sptr KvStoreDataServiceProxy::GetRdbService() int32_t KvStoreDataServiceStub::GetKvStoreOnRemote(MessageParcel &data, MessageParcel &reply) { - OptionsIpc optionsIpc; - AppId appId; - StoreId storeId; - const OptionsIpc *optionIpcPtr = reinterpret_cast(data.ReadBuffer(sizeof(OptionsIpc))); if (optionIpcPtr == nullptr) { ZLOGW("optionPtr is nullptr"); @@ -422,7 +418,7 @@ int32_t KvStoreDataServiceStub::GetKvStoreOnRemote(MessageParcel &data, MessageP } return 0; } - optionsIpc = *optionIpcPtr; + OptionsIpc optionsIpc = *optionIpcPtr; Options options; options.createIfMissing = optionsIpc.createIfMissing; options.encrypt = optionsIpc.encrypt; @@ -434,8 +430,8 @@ int32_t KvStoreDataServiceStub::GetKvStoreOnRemote(MessageParcel &data, MessageP options.kvStoreType = optionsIpc.kvStoreType; options.syncable = optionsIpc.syncable; options.dataOwnership = optionsIpc.dataOwnership; - appId.appId = data.ReadString(); - storeId.storeId = data.ReadString(); + AppId appId = { Constant::TrimCopy(data.ReadString())}; + StoreId storeId = { Constant::TrimCopy(data.ReadString())}; sptr proxyTmp; Status status = GetKvStore(options, appId, storeId, [&proxyTmp](sptr proxy) { proxyTmp = std::move(proxy); }); @@ -454,8 +450,7 @@ int32_t KvStoreDataServiceStub::GetKvStoreOnRemote(MessageParcel &data, MessageP } int32_t KvStoreDataServiceStub::GetAllKvStoreIdOnRemote(MessageParcel &data, MessageParcel &reply) { - AppId appId; - appId.appId = data.ReadString(); + AppId appId = { Constant::TrimCopy(data.ReadString())}; std::vector storeIdList; Status statusTmp; GetAllKvStoreId(appId, [&](Status status, std::vector &storeIds) { @@ -532,9 +527,6 @@ int32_t KvStoreDataServiceStub::StopWatchDeviceChangeOnRemote(MessageParcel &dat } int32_t KvStoreDataServiceStub::GetSingleKvStoreOnRemote(MessageParcel &data, MessageParcel &reply) { - OptionsIpc optionsIpc; - AppId appId; - StoreId storeId; const OptionsIpc *optionIpcPtr = reinterpret_cast(data.ReadBuffer(sizeof(OptionsIpc))); if (optionIpcPtr == nullptr) { ZLOGW("optionPtr is nullptr"); @@ -543,9 +535,9 @@ int32_t KvStoreDataServiceStub::GetSingleKvStoreOnRemote(MessageParcel &data, Me } return 0; } - optionsIpc = *optionIpcPtr; - appId.appId = data.ReadString(); - storeId.storeId = data.ReadString(); + OptionsIpc optionsIpc = *optionIpcPtr; + AppId appId = { Constant::TrimCopy(data.ReadString())}; + StoreId storeId = { Constant::TrimCopy(data.ReadString())}; Options options; options.createIfMissing = optionsIpc.createIfMissing; options.encrypt = optionsIpc.encrypt; @@ -574,10 +566,8 @@ int32_t KvStoreDataServiceStub::GetSingleKvStoreOnRemote(MessageParcel &data, Me int32_t KvStoreDataServiceStub::CloseKvStoreOnRemote(MessageParcel &data, MessageParcel &reply) { - AppId appId; - StoreId storeId; - appId.appId = data.ReadString(); - storeId.storeId = data.ReadString(); + AppId appId = { Constant::TrimCopy(data.ReadString())}; + StoreId storeId = { Constant::TrimCopy(data.ReadString())}; Status status = CloseKvStore(appId, storeId); if (!reply.WriteInt32(static_cast(status))) { return -1; @@ -587,8 +577,7 @@ int32_t KvStoreDataServiceStub::CloseKvStoreOnRemote(MessageParcel &data, Messag int32_t KvStoreDataServiceStub::CloseAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply) { - AppId appId; - appId.appId = data.ReadString(); + AppId appId = { Constant::TrimCopy(data.ReadString())}; Status status = CloseAllKvStore(appId); if (!reply.WriteInt32(static_cast(status))) { return -1; @@ -598,10 +587,8 @@ int32_t KvStoreDataServiceStub::CloseAllKvStoreOnRemote(MessageParcel &data, Mes int32_t KvStoreDataServiceStub::DeleteKvStoreOnRemote(MessageParcel &data, MessageParcel &reply) { - AppId appId; - StoreId storeId; - appId.appId = data.ReadString(); - storeId.storeId = data.ReadString(); + AppId appId = { Constant::TrimCopy(data.ReadString())}; + StoreId storeId = { Constant::TrimCopy(data.ReadString())}; Status status = DeleteKvStore(appId, storeId); if (!reply.WriteInt32(static_cast(status))) { return -1; @@ -611,8 +598,7 @@ int32_t KvStoreDataServiceStub::DeleteKvStoreOnRemote(MessageParcel &data, Messa int32_t KvStoreDataServiceStub::DeleteAllKvStoreOnRemote(MessageParcel &data, MessageParcel &reply) { - AppId appId; - appId.appId = data.ReadString(); + AppId appId = { Constant::TrimCopy(data.ReadString())}; Status status = DeleteAllKvStore(appId); if (!reply.WriteInt32(static_cast(status))) { return -1; @@ -622,8 +608,7 @@ int32_t KvStoreDataServiceStub::DeleteAllKvStoreOnRemote(MessageParcel &data, Me int32_t KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply) { - AppId appId; - appId.appId = data.ReadString(); + AppId appId = { Constant::TrimCopy(data.ReadString())}; sptr kvStoreClientDeathObserverProxy = data.ReadRemoteObject(); if (kvStoreClientDeathObserverProxy == nullptr) { return -1; @@ -656,7 +641,7 @@ int32_t KvStoreDataServiceStub::GetRdbServiceOnRemote(MessageParcel &data, Messa int32_t KvStoreDataServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - ZLOGD("%d", code); + ZLOGD("%{public}d", code); std::u16string descriptor = KvStoreDataServiceStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_observer.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_observer.cpp index 8455773a21a30fdbad99c7a8fbc1c92de485d19a..1ed10b7cc89e5e3b49ce406cea8d15539dd78b3f 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_observer.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_observer.cpp @@ -171,7 +171,7 @@ bool ReadListFromBuf(MessageParcel &data, std::vector &entries) int32_t KvStoreObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - ZLOGD("%d", code); + ZLOGD("%{public}d", code); std::u16string descriptor = KvStoreObserverStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_resultset.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_resultset.cpp index eb4946ee75ca5ec039b74bafcd73b8c6459bf886..72dd7171eca6f767828fc15c584cdf9a82eaa0de 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_resultset.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_resultset.cpp @@ -207,7 +207,7 @@ int KvStoreResultSetStub::GetEntryOnRemote(MessageParcel &reply) int KvStoreResultSetStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - ZLOGD("%u", code); + ZLOGD("%{public}u", code); std::u16string descriptor = KvStoreResultSetStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp index 6482d72bc543312e16c9977f948ed1ecaf251982..a2fd8e0f555a912aca260af1f7d26c9f3200efe4 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp @@ -1604,7 +1604,7 @@ int SingleKvStoreStub::OnSyncRequest(MessageParcel &data, MessageParcel &reply) int SingleKvStoreStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - ZLOGD("%d", code); + ZLOGD("%{public}d", code); std::u16string descriptor = SingleKvStoreStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp index ed6745386b52f30cc344dfd9e758bf8da8609670..8b8c4aaa48731cb1b2f719864bc1bdc51e97e7f9 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp @@ -513,7 +513,7 @@ int32_t KvStoreSnapshotImplStub::GetRemote(MessageParcel &data, MessageParcel &r int32_t KvStoreSnapshotImplStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { - ZLOGD("%d", code); + ZLOGD("%{public}d", code); std::u16string descriptor = KvStoreSnapshotImplStub::GetDescriptor(); std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp index ff654c7e25c700377ae3a46655f4c51c82fa019a..f7801e5fd0f3b71d5cd9a13e10f27f45c29b08ba 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp @@ -106,11 +106,11 @@ bool ITypesUtil::Marshalling(const ChangeNotification ¬ification, MessageParc if (!Marshalling(notification.GetInsertEntries(), parcel)) { return false; } - + if (!Marshalling(notification.GetUpdateEntries(), parcel)) { return false; } - + if (!Marshalling(notification.GetDeleteEntries(), parcel)) { return false; } @@ -118,7 +118,7 @@ bool ITypesUtil::Marshalling(const ChangeNotification ¬ification, MessageParc ZLOGE("WriteString deviceId_ failed."); return false; } - + return parcel.WriteBool(notification.IsClear()); } @@ -250,7 +250,7 @@ bool ITypesUtil::ReadVector(Parcel &parcel, std::vector &val, bool (Parcel::* if (len < 0) { return false; } - + size_t readAbleSize = parcel.GetReadableBytes(); size_t size = static_cast(len); if ((size > readAbleSize) || (size > val.max_size())) { @@ -260,13 +260,13 @@ bool ITypesUtil::ReadVector(Parcel &parcel, std::vector &val, bool (Parcel::* if (val.size() < size) { return false; } - + for (auto &v : val) { if (!(parcel.*read)(v)) { return false; } } - + return true; } @@ -276,11 +276,11 @@ bool ITypesUtil::WriteVector(Parcel &parcel, const std::vector &val, bool (Pa if (val.size() > INT_MAX) { return false; } - + if (!parcel.WriteInt32(static_cast(val.size()))) { return false; } - + for (auto &v : val) { if (!(parcel.*writer)(v)) { return false; diff --git a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp index 866b28f83a0817062e9d3211315f10f39ae677bc..3e4f83c94affe05dc0be92d841c8ac4608c2b722 100755 --- a/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp @@ -15,7 +15,6 @@ #define LOG_TAG "SingleKvStoreClientQueryTest" -#include #include #include #include @@ -23,7 +22,7 @@ #include "distributed_kv_data_manager.h" #include "types.h" #include "log_print.h" - +#include "gtest/gtest.h" using namespace testing::ext; using namespace OHOS::DistributedKv; diff --git a/frameworks/jskitsimpl/distributeddata/include/js_field_node.h b/frameworks/jskitsimpl/distributeddata/include/js_field_node.h index a861306eca72ff4d191696b2d979e7c87c50e4ea..2845c94b07f13117e67218c74256ada7e5efdf76 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_field_node.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_field_node.h @@ -14,16 +14,15 @@ */ #ifndef OHOS_FIELD_NODE_H #define OHOS_FIELD_NODE_H -#include #include - +#include #include "js_util.h" #include "napi_queue.h" namespace OHOS::DistributedData { -using json = nlohmann::json; class JsFieldNode { public: + using json = nlohmann::json; JsFieldNode(const std::string& fName); ~JsFieldNode() = default; diff --git a/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h b/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h index 678250f6c157db7ab532bdda57847d68a62ce7d0..15fc2795a9671c072bb7c1b1120f83d9ccc09301 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h @@ -14,6 +14,7 @@ */ #ifndef OHOS_KV_MANAGER_H #define OHOS_KV_MANAGER_H +#include #include "distributed_kv_data_manager.h" #include "kvstore_death_recipient.h" #include "napi_queue.h" diff --git a/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h b/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h index 8f2afd14459c854df4c09b7c4ab796ea9ba395f2..5ad046038d3a2a55d55ab12497d0b8c302445745 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_kv_store.h @@ -14,6 +14,7 @@ */ #ifndef OHOS_KV_STORE_H #define OHOS_KV_STORE_H +#include #include "napi_queue.h" #include "single_kvstore.h" #include "uv_queue.h" diff --git a/frameworks/jskitsimpl/distributeddata/include/js_util.h b/frameworks/jskitsimpl/distributeddata/include/js_util.h index a601b35410a19327e05a6da41abf01a718940a37..10a25b9aafd44163002f52e055fc6f7734a5b72f 100644 --- a/frameworks/jskitsimpl/distributeddata/include/js_util.h +++ b/frameworks/jskitsimpl/distributeddata/include/js_util.h @@ -22,11 +22,8 @@ #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" -#include "log_print.h" namespace OHOS::DistributedData { -using namespace OHOS::DistributedKv; - class JSUtil final { public: enum { @@ -39,7 +36,12 @@ public: DOUBLE = 5, INVALID = 255 }; - + using Blob = OHOS::DistributedKv::Blob; + using ChangeNotification = OHOS::DistributedKv::ChangeNotification; + using Options = OHOS::DistributedKv::Options; + using Entry = OHOS::DistributedKv::Entry; + using StoreId = OHOS::DistributedKv::StoreId; + using Status = OHOS::DistributedKv::Status; /* for kvStore Put/Get : boolean|string|number|Uint8Array */ using KvStoreVariant = std::variant, bool, double>; static KvStoreVariant Blob2VariantValue(const Blob& blob); diff --git a/frameworks/jskitsimpl/distributeddata/include/napi_queue.h b/frameworks/jskitsimpl/distributeddata/include/napi_queue.h index 66270b1071a669f8bdbad9a349e50016b0cf741a..afb65f967eaf26cffef7697213c01c69c1720867 100644 --- a/frameworks/jskitsimpl/distributeddata/include/napi_queue.h +++ b/frameworks/jskitsimpl/distributeddata/include/napi_queue.h @@ -15,6 +15,8 @@ #ifndef OHOS_NAPI_QUEUE_H #define OHOS_NAPI_QUEUE_H #include +#include +#include #include "log_print.h" #include "napi/native_api.h" @@ -22,9 +24,7 @@ #include "napi/native_node_api.h" namespace OHOS::DistributedData { -using namespace OHOS::DistributedKv; // for ZLOGD/ZLOGE constexpr size_t ARGC_MAX = 6; - using NapiCbInfoParser = std::function; using NapiAsyncExecute = std::function; using NapiAsyncComplete = std::function; diff --git a/frameworks/jskitsimpl/distributeddata/include/uv_queue.h b/frameworks/jskitsimpl/distributeddata/include/uv_queue.h index 58a5b29159eddef5bc02a13ebc82e00c86b523e8..afb6158330dbad501e1225e97b6b3b8f609dbab5 100644 --- a/frameworks/jskitsimpl/distributeddata/include/uv_queue.h +++ b/frameworks/jskitsimpl/distributeddata/include/uv_queue.h @@ -34,9 +34,13 @@ public: void CallFunction(NapiArgsGenerator genArgs = NapiArgsGenerator()); private: + struct UvEntry { + napi_env env; + napi_ref callback; + NapiArgsGenerator args; + }; napi_env env_ = nullptr; napi_ref callback_ = nullptr; - NapiArgsGenerator args; uv_loop_s* loop_ = nullptr; }; } diff --git a/frameworks/jskitsimpl/distributeddata/src/entry_point.cpp b/frameworks/jskitsimpl/distributeddata/src/entry_point.cpp index 9726531763dd9d010422b6dda73e757c8ab5f20e..d3f105d41207b0240099f4f9ae08b5960c9e7f1d 100644 --- a/frameworks/jskitsimpl/distributeddata/src/entry_point.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/entry_point.cpp @@ -22,7 +22,6 @@ #include "log_print.h" using namespace OHOS::DistributedData; -using namespace OHOS::DistributedKv; static napi_value Init(napi_env env, napi_value exports) { diff --git a/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp b/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp index 70ae140be79f0d137f28179b3d31bbb3ec881182..cbf2c5798aba4b2b4aa6b88283556d16c5a552db 100644 --- a/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/js_field_node.cpp @@ -14,15 +14,12 @@ */ #define LOG_TAG "JS_FieldNode" #include "js_field_node.h" -#include - #include "js_util.h" #include "log_print.h" #include "napi_queue.h" #include "uv_queue.h" using namespace OHOS::DistributedKv; -using json = nlohmann::json; namespace OHOS::DistributedData { static std::string FIELDNAME = "FIELDNAME"; @@ -42,7 +39,7 @@ std::string JsFieldNode::GetFieldName() return fieldName; } -json JsFieldNode::GetValueForJson() +JsFieldNode::json JsFieldNode::GetValueForJson() { if (!fields.empty()) { /* example: diff --git a/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp b/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp index 32fe0bd8d68b7d4ff3fdf20a1dd1904ef91e15ab..0af33d9ff84f26cf7c3b794121ac5c135cd09360 100644 --- a/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp +++ b/frameworks/jskitsimpl/distributeddata/src/uv_queue.cpp @@ -48,29 +48,29 @@ void UvQueue::CallFunction(NapiArgsGenerator genArgs) ZLOGE("no memory for uv_work_t"); return; } - work->data = this; - this->args = std::move(genArgs); - + work->data = new UvEntry{env_, callback_, std::move(genArgs)}; uv_queue_work( loop_, work, [](uv_work_t* work) {}, [](uv_work_t* work, int uvstatus) { - auto queue = static_cast(work->data); + auto *entry = static_cast(work->data); int argc = 0; napi_value argv[ARGC_MAX] = { nullptr }; - if (queue->args) { - queue->args(queue->env_, argc, argv); + if (entry->args) { + argc = ARGC_MAX; + entry->args(entry->env, argc, argv); } ZLOGD("queue uv_after_work_cb"); napi_value callback = nullptr; - napi_get_reference_value(queue->env_, queue->callback_, &callback); + napi_get_reference_value(entry->env, entry->callback, &callback); napi_value global = nullptr; - napi_get_global(queue->env_, &global); + napi_get_global(entry->env, &global); napi_value result; - napi_status status = napi_call_function(queue->env_, global, callback, argc, argv, &result); + napi_status status = napi_call_function(entry->env, global, callback, argc, argv, &result); if (status != napi_ok) { ZLOGE("notify data change failed status:%{public}d callback:%{public}p", status, callback); } + delete entry; delete work; work = nullptr; }); diff --git a/interfaces/innerkits/app_distributeddata/BUILD.gn b/interfaces/innerkits/app_distributeddata/BUILD.gn index e40e82144f570bc61445715af081377257692b5b..0c204c35132bbce57164c12f84efe68f6d32f6fa 100755 --- a/interfaces/innerkits/app_distributeddata/BUILD.gn +++ b/interfaces/innerkits/app_distributeddata/BUILD.gn @@ -67,12 +67,9 @@ ohos_shared_library("app_distributeddata") { ] configs = [ ":distributeddatafwk_config" ] - ldflags = [ "-Wl,--exclude-libs,libcrypto_static.a" ] deps = [ - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/account:distributeddata_account_static", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/distributeddata/include/types.h b/interfaces/innerkits/distributeddata/include/types.h index d94c3b0d0ced7137505a0fedbac91c3ccdb30f24..3fd669735a36195953fce8187a1853b6c0f4fe70 100755 --- a/interfaces/innerkits/distributeddata/include/types.h +++ b/interfaces/innerkits/distributeddata/include/types.h @@ -277,8 +277,8 @@ struct Options { inline bool IsValidType() const { - return kvStoreType == KvStoreType::DEVICE_COLLABORATION || kvStoreType == KvStoreType::SINGLE_VERSION || - kvStoreType == KvStoreType::DEVICE_COLLABORATION; + return kvStoreType == KvStoreType::DEVICE_COLLABORATION || kvStoreType == KvStoreType::SINGLE_VERSION + || kvStoreType == KvStoreType::MULTI_VERSION; } }; diff --git a/services/distributeddataservice/adapter/BUILD.gn b/services/distributeddataservice/adapter/BUILD.gn index 7c630e73fbd602291250aa5af240f862ca422b69..99ed4c66222d61b122bd140b8afc671413f9bb96 100755 --- a/services/distributeddataservice/adapter/BUILD.gn +++ b/services/distributeddataservice/adapter/BUILD.gn @@ -35,6 +35,7 @@ config("distributeddata_adapter_public_config") { "include/security", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", ] } diff --git a/services/distributeddataservice/adapter/account/BUILD.gn b/services/distributeddataservice/adapter/account/BUILD.gn index a7f4895d0b630eaada28d05fbdd5d6d352178310..fb10a29d4a13e7163970cc05d6a76e36001380a4 100755 --- a/services/distributeddataservice/adapter/account/BUILD.gn +++ b/services/distributeddataservice/adapter/account/BUILD.gn @@ -26,13 +26,18 @@ ohos_static_library("distributeddata_account_static") { "//utils/native/base/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", ] cflags_cc = [ "-fvisibility=hidden" ] + remove_configs = [ "//build/config/compiler:no_exceptions" ] + + configs = [ "//build/config/compiler:exceptions" ] + deps = [ - "../utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/adapter/account/src/account_delegate.cpp b/services/distributeddataservice/adapter/account/src/account_delegate.cpp index e2734df68fac7e8bc3dc79fb40262296be5c808c..17737f1e5bee6c5aa9a25d7a689ef2424013f90a 100755 --- a/services/distributeddataservice/adapter/account/src/account_delegate.cpp +++ b/services/distributeddataservice/adapter/account/src/account_delegate.cpp @@ -17,8 +17,6 @@ namespace OHOS { namespace DistributedKv { -const std::string AccountDelegate::MAIN_DEVICE_ACCOUNT_ID = "0"; - AccountDelegate *AccountDelegate::GetInstance() { if (getInstance_ == nullptr) { diff --git a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp index 9c5d8e58d505b4ad9997a7873f01bca482f1195f..4c0dab823571ad38c4ecc0338aae6a7dc0293936 100755 --- a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp +++ b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp @@ -16,17 +16,23 @@ #define LOG_TAG "EVENT_HANDLER" #include "account_delegate_impl.h" -#include +#include +#include +#include #include +#include +#include #include "constant.h" -#include "crypto_utils.h" #include "ohos_account_kits.h" #include "permission_validator.h" +#include "utils/crypto.h" namespace OHOS { namespace DistributedKv { using namespace OHOS::EventFwk; using namespace OHOS::AAFwk; +using namespace OHOS::DistributedData; + EventSubscriber::EventSubscriber(const CommonEventSubscribeInfo &info) : CommonEventSubscriber(info) {} void EventSubscriber::OnReceiveEvent(const CommonEventData &event) @@ -94,7 +100,7 @@ void AccountDelegateImpl::SubscribeAccountEvent() CommonEventSubscribeInfo info(matchingSkills); eventSubscriber_ = std::make_shared(info); eventSubscriber_->SetEventCallback([&](AccountEventInfo &account) { - account.harmonyAccountId = GetCurrentHarmonyAccountId(); + account.harmonyAccountId = GetCurrentAccountId(); NotifyAccountChanged(account); }); @@ -122,7 +128,7 @@ void AccountDelegateImpl::SubscribeAccountEvent() th.detach(); } -std::string AccountDelegateImpl::GetCurrentHarmonyAccountId(const std::string &bundleName) const +std::string AccountDelegateImpl::GetCurrentAccountId(const std::string &bundleName) const { ZLOGD("start"); if (!bundleName.empty() && PermissionValidator::IsAutoLaunchEnabled(bundleName)) { @@ -138,7 +144,7 @@ std::string AccountDelegateImpl::GetCurrentHarmonyAccountId(const std::string &b return AccountSA::DEFAULT_OHOS_ACCOUNT_UID; } - return CryptoUtils::Sha256UserId(ohosAccountInfo.second.uid_); + return Sha256UserId(ohosAccountInfo.second.uid_); } std::string AccountDelegateImpl::GetDeviceAccountIdByUID(int32_t uid) const @@ -191,5 +197,37 @@ Status AccountDelegateImpl::Unsubscribe(std::shared_ptr observer) ZLOGD("fail"); return Status::ERROR; } + +std::string AccountDelegateImpl::Sha256UserId(const std::string &plainText) const +{ + std::regex pattern("^[0-9]+$"); + if (!std::regex_match(plainText, pattern)) { + return plainText; + } + + std::string::size_type sizeType; + int64_t plainVal; + std::string::size_type int64MaxLen(std::to_string(INT64_MAX).size()); + // plain text length must be less than INT64_MAX string. + try { + plainVal = static_cast(std::stoll(plainText, &sizeType)); + } catch (const std::out_of_range &) { + plainVal = static_cast(std::stoll( + plainText.substr(plainText.size() - int64MaxLen + 1, int64MaxLen - 1), &sizeType)); + } catch (const std::exception &) { + return plainText; + } + + union UnionLong { + int64_t val; + unsigned char byteLen[sizeof(int64_t)]; + }; + UnionLong unionLong {}; + unionLong.val = plainVal; + std::list unionList(std::begin(unionLong.byteLen), std::end(unionLong.byteLen)); + unionList.reverse(); + std::vector unionVec(unionList.begin(), unionList.end()); + return Crypto::Sha256(unionVec.data(), unionVec.size(), true); +} } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/adapter/account/src/account_delegate_impl.h b/services/distributeddataservice/adapter/account/src/account_delegate_impl.h index 0059bedab0e6bb5b9665f6754b490e0e55fa9d8c..fc0748b9c4585e145d986fc65e8a661cb87811c7 100755 --- a/services/distributeddataservice/adapter/account/src/account_delegate_impl.h +++ b/services/distributeddataservice/adapter/account/src/account_delegate_impl.h @@ -46,11 +46,12 @@ public: static AccountDelegate *GetBaseInstance(); Status Subscribe(std::shared_ptr observer) override; Status Unsubscribe(std::shared_ptr observer) override; - std::string GetCurrentHarmonyAccountId(const std::string &bundleName = "") const override; + std::string GetCurrentAccountId(const std::string &bundleName = "") const override; std::string GetDeviceAccountIdByUID(int32_t uid) const override; void SubscribeAccountEvent() override; private: ~AccountDelegateImpl(); + std::string Sha256UserId(const std::string &plainText) const; void NotifyAccountChanged(const AccountEventInfo &accountEventInfo); ConcurrentMap> observerMap_ {}; diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn index 6e089b0051d819c0ff7e59445efe08d06cfca2a3..f39be8a0ae7eb7b0f6031e6278b68a5cc3fc48d1 100755 --- a/services/distributeddataservice/adapter/account/test/BUILD.gn +++ b/services/distributeddataservice/adapter/account/test/BUILD.gn @@ -26,6 +26,7 @@ ohos_unittest("DistributeddataAccountTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/utils", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", ] deps = [ diff --git a/services/distributeddataservice/adapter/account/test/account_delegate_test.cpp b/services/distributeddataservice/adapter/account/test/account_delegate_test.cpp index 21e8f4e767ffc8fc762b2282e7e595c53b7bbf58..0655433455b601952bb85448890db7cb5cd0440d 100755 --- a/services/distributeddataservice/adapter/account/test/account_delegate_test.cpp +++ b/services/distributeddataservice/adapter/account/test/account_delegate_test.cpp @@ -64,8 +64,7 @@ HWTEST_F(AccountDelegateTest, Test001, TestSize.Level0) */ HWTEST_F(AccountDelegateTest, Test002, TestSize.Level0) { - auto account = AccountDelegate::GetInstance(); - auto id = account->MAIN_DEVICE_ACCOUNT_ID; + auto id = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(getuid()); ZLOGD("observer subscribed %s", id.c_str()); ASSERT_TRUE(!id.empty()); } diff --git a/services/distributeddataservice/adapter/autils/src/constant.cpp b/services/distributeddataservice/adapter/autils/src/constant.cpp index 475f1ba730e7362fcfdb36c8fa88332482a8eba6..f393d354c1666d9eb528a76c6f95a0e5898dcef4 100755 --- a/services/distributeddataservice/adapter/autils/src/constant.cpp +++ b/services/distributeddataservice/adapter/autils/src/constant.cpp @@ -83,8 +83,6 @@ const std::string Constant::SERVICE_META_DB_NAME = "service_meta"; const std::string Constant::KEY_SEPARATOR = "###"; -const std::string Constant::PROCESS_LABEL = "distributeddata"; - const std::string Constant::ROOT_KEY_GENERATED = "RootKeyGenerated"; std::vector KvStoreMetaRow::GetKeyFor(const std::string &key) diff --git a/services/distributeddataservice/adapter/include/account/account_delegate.h b/services/distributeddataservice/adapter/include/account/account_delegate.h index d25a21db1ac31e48dad1de0e901b7c40081d942d..617e56f56dd4eb7263eb12daa47fbb36a40f0a88 100755 --- a/services/distributeddataservice/adapter/include/account/account_delegate.h +++ b/services/distributeddataservice/adapter/include/account/account_delegate.h @@ -49,11 +49,10 @@ public: KVSTORE_API virtual ~AccountDelegate() = default; KVSTORE_API virtual Status Subscribe(std::shared_ptr observer) = 0; KVSTORE_API virtual Status Unsubscribe(std::shared_ptr observer) = 0; - KVSTORE_API virtual std::string GetCurrentHarmonyAccountId(const std::string &bundleName = "") const = 0; + KVSTORE_API virtual std::string GetCurrentAccountId(const std::string &bundleName = "") const = 0; KVSTORE_API virtual std::string GetDeviceAccountIdByUID(int32_t uid) const = 0; KVSTORE_API virtual void SubscribeAccountEvent() = 0; KVSTORE_API static AccountDelegate *GetInstance(); - const static std::string MAIN_DEVICE_ACCOUNT_ID; private: using BaseInstance = AccountDelegate *(*)(); static BaseInstance getInstance_; diff --git a/services/distributeddataservice/adapter/include/autils/constant.h b/services/distributeddataservice/adapter/include/autils/constant.h index 75d4c0e7278bd696126a90070e83e7d5c0cacd52..efeaa381d839f920b9fd57d616afb0af7258e79f 100644 --- a/services/distributeddataservice/adapter/include/autils/constant.h +++ b/services/distributeddataservice/adapter/include/autils/constant.h @@ -131,7 +131,6 @@ public: KVSTORE_API static const int MAX_OPEN_KVSTORES; // name for process label (bus name for communication). compatible with HwDDMP - KVSTORE_API static const std::string PROCESS_LABEL; KVSTORE_API static const std::string ROOT_KEY_GENERATED; }; diff --git a/services/distributeddataservice/adapter/include/autils/serializable.h b/services/distributeddataservice/adapter/include/autils/serializable.h deleted file mode 100755 index cdefafe3b94cd33fb287fa1f055d90e4e89702b8..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/include/autils/serializable.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_SERIALIZABLE_H -#define OHOS_SERIALIZABLE_H - -#include - -namespace OHOS::DistributedKv { -struct Serializable { - static inline std::string GetVal(const Json::Value &value, const std::string &def) - { - if (value.isNull()) { - return def; - } - return value.asString(); - } - - static inline uint32_t GetVal(const Json::Value &value, const uint32_t def) - { - if (value.isNull()) { - return def; - } - return value.asUInt(); - } - -#ifndef GET_NAME -#define GET_NAME(value) #value -#endif -}; -} - -#endif // OHOS_SERIALIZABLE_H diff --git a/services/distributeddataservice/adapter/include/log/log_print.h b/services/distributeddataservice/adapter/include/log/log_print.h index 0824f6387dd639c9ad3f43d15e35a258b1c22f58..ccaa6c91ef5acbeba3b5baccc2d8810a30a23534 100755 --- a/services/distributeddataservice/adapter/include/log/log_print.h +++ b/services/distributeddataservice/adapter/include/log/log_print.h @@ -16,42 +16,51 @@ #ifndef DISTRIBUTEDDATA_LOG_PRINT_H #define DISTRIBUTEDDATA_LOG_PRINT_H -#ifndef KVSTORE_API -#define KVSTORE_API __attribute__ ((visibility ("default"))) -#endif #define OS_OHOS #if defined OS_OHOS // log for OHOS #include "hilog/log.h" namespace OHOS { namespace DistributedKv { - -KVSTORE_API static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0xD001610, "ZDDS" }; - +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001610, "ZDDS" }; +} } // end namespace DistributesdKv -namespace AppDistributedKv { - -KVSTORE_API static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0xD001620, "ZDDC" }; +namespace DistributedData { +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001611, "ZDD" }; +} +} // end namespace DistributedData -} // end namespace AppDistributesdKv +namespace AppDistributedKv { +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001620, "ZDDC" }; +} +} // namespace AppDistributedKv namespace DistributedRdb { -KVSTORE_API static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = { LOG_CORE, 0xD001630, "ZDDR" }; +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001655, "DRDB" }; } +} // end namespace DistributedRdb } // end namespace OHOS #define ZLOGD(fmt, ...) \ - OHOS::HiviewDFX::HiLog::Debug(LOG_LABEL, LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) + OHOS::HiviewDFX::HiLog::Debug(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) #define ZLOGI(fmt, ...) \ - OHOS::HiviewDFX::HiLog::Info(LOG_LABEL, LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) + OHOS::HiviewDFX::HiLog::Info(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) #define ZLOGW(fmt, ...) \ - OHOS::HiviewDFX::HiLog::Warn(LOG_LABEL, LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) + OHOS::HiviewDFX::HiLog::Warn(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) #define ZLOGE(fmt, ...) \ - OHOS::HiviewDFX::HiLog::Error(LOG_LABEL, LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) + OHOS::HiviewDFX::HiLog::Error(LogLabel(), LOG_TAG "::%{public}s: " fmt, __FUNCTION__, ##__VA_ARGS__) #else #error // unknown system diff --git a/services/distributeddataservice/adapter/include/utils/crypto_utils.h b/services/distributeddataservice/adapter/include/utils/crypto_utils.h deleted file mode 100644 index 1595115b46b7b7dc5c86bdce40c103bde203b28c..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/include/utils/crypto_utils.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef CRYPTO_UTILS_H -#define CRYPTO_UTILS_H - -#include -#include -#include "visibility.h" - -namespace OHOS { -namespace DistributedKv { -class CryptoUtils { -public: -// get sha256 hash -// plainText: string to be hashed -// sha256 hash of the input string -KVSTORE_API static std::string Sha256(const std::string &plainText); - -// get appId from bundle name -// bundleName: client declared bundleName -// userId: id of current user -// hashed id of this app. each char in returned string minus 'A' is the sha512 value of origin appId. -KVSTORE_API static std::string Sha256AppId(const std::string &bundleName, int userId = 0); - -// get sha256 hash -// plainText: string to be hashed -// sha256 hash of the input string -KVSTORE_API static std::string Sha256UserId(const std::string &plainText); - -// Use system entropy pool to generate true random number. note that it will run quiet slowly on system entropy -// pool running out. -// keyLen: returned vector length. -// true random 8-bit sequence. -KVSTORE_API static void GetRandomKey(int keyLen, std::vector &key); -}; -} // namespace DistributedKv -} // namespace OHOS -#endif // CRYPTO_UTILS_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/include/utils/json_utils.h b/services/distributeddataservice/adapter/include/utils/json_utils.h deleted file mode 100755 index cb706b565b5f83c810e59cf699f59e63052ccbbc..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/include/utils/json_utils.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef JSON_UTILS_H -#define JSON_UTILS_H - -#include -#include -#include "log_print.h" -#include "visibility.h" - -namespace OHOS { -namespace DistributedKv { -using json = nlohmann::json; - -class JsonUtils { -public: -template -static bool ParseJsonField(const std::string &jsonStr, const std::string &key, uint8_t valType, T &fieldVal) -{ - json jsonObj = json::parse(jsonStr, nullptr, false); - if (jsonObj.is_discarded()) { - ZLOGE("jsonObj is discarded, parse json[%s] failed.", key.c_str()); - return false; - } - if (jsonObj.find(key) == jsonObj.end()) { - return false; - } - if (static_cast(jsonObj[key].type()) != valType) { - ZLOGE("not match in jsonObj, parse json[%s] failed.", key.c_str()); - return false; - } - jsonObj[key].get_to(fieldVal); - return true; -} - -template -static bool ParseJsonField(const json &jsonObj, const std::string &key, uint8_t valType, T &fieldVal) -{ - if (jsonObj.is_discarded()) { - ZLOGE("jsonObj is discarded, parse json[%s] failed.", key.c_str()); - return false; - } - if (jsonObj.find(key) == jsonObj.end()) { - return false; - } - if (static_cast(jsonObj[key].type()) != valType) { - ZLOGE("not match in jsonObj, parse json[%s] failed.", key.c_str()); - return false; - } - jsonObj[key].get_to(fieldVal); - return true; -} -}; -} // namespace DistributedKv -} // namespace OHOS -#endif // JSON_UTILS_H \ No newline at end of file diff --git a/services/distributeddataservice/adapter/include/utils/kvstore_utils.h b/services/distributeddataservice/adapter/include/utils/kvstore_utils.h index 7a551215633136f227823d81728a944bf2a612d6..bfa9ab9a1e2e71ead8815eb0f86d85a0c00ce6d2 100755 --- a/services/distributeddataservice/adapter/include/utils/kvstore_utils.h +++ b/services/distributeddataservice/adapter/include/utils/kvstore_utils.h @@ -24,10 +24,6 @@ namespace OHOS { namespace DistributedKv { class KvStoreUtils { public: - // get app id; KvStore may use BundleName as appId, this function should run in IPC thread - // bundleName: string to be hashed - KVSTORE_API static std::string GetAppIdByBundleName(const std::string &bundleName); - // convert the name to the anonymous // the anonymous string is name[0,3]"***"name[end-3, end] // when the anonymous string is shorter than 9, the anonymous is "******" diff --git a/services/distributeddataservice/adapter/permission/BUILD.gn b/services/distributeddataservice/adapter/permission/BUILD.gn index d34a35da7f82dc820773fd6dbadc9d714b0e2f16..1e2df6263f9d263aef557f3436088385a694423d 100755 --- a/services/distributeddataservice/adapter/permission/BUILD.gn +++ b/services/distributeddataservice/adapter/permission/BUILD.gn @@ -26,7 +26,6 @@ ohos_static_library("distributeddata_permission_static") { "//utils/native/base/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", - "//third_party/openssl/include/", ] if (build_public_version) { @@ -36,7 +35,6 @@ ohos_static_library("distributeddata_permission_static") { deps = [ "../utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//third_party/openssl:libcrypto_static", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/adapter/permission/test/BUILD.gn b/services/distributeddataservice/adapter/permission/test/BUILD.gn index c91f7cfe95fc69c46655e784b0646a78ec99458b..4488f54fe064a8ec2a507f811b99d75a73f3e9c8 100755 --- a/services/distributeddataservice/adapter/permission/test/BUILD.gn +++ b/services/distributeddataservice/adapter/permission/test/BUILD.gn @@ -23,6 +23,8 @@ config("module_private_config") { "../../include/utils/", "//utils/native/base/include/", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", ] } @@ -36,12 +38,11 @@ ohos_unittest("PermissionValidatorTest") { deps = [ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/permission:distributeddata_permission_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//third_party/googletest:gtest_main", ] - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - ] + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] } group("unittest") { diff --git a/services/distributeddataservice/adapter/permission/test/unittest/permission_validator_test.cpp b/services/distributeddataservice/adapter/permission/test/unittest/permission_validator_test.cpp index 6fdfab00f0f396ff52361a819b7c8a025c00a7c9..97abd167d2ae8e3b840dfe16274e6415882cd626 100755 --- a/services/distributeddataservice/adapter/permission/test/unittest/permission_validator_test.cpp +++ b/services/distributeddataservice/adapter/permission/test/unittest/permission_validator_test.cpp @@ -15,11 +15,12 @@ #include -#include "crypto_utils.h" #include "permission_validator.h" +#include "utils/crypto.h" using namespace testing::ext; using namespace OHOS::DistributedKv; +using namespace OHOS::DistributedData; class PermissionValidatorTest : public testing::Test { public: @@ -79,5 +80,5 @@ HWTEST_F(PermissionValidatorTest, TestPermissionValidate002, TestSize.Level0) HWTEST_F(PermissionValidatorTest, TestPermissionValidate003, TestSize.Level0) { std::string userId = "ohos"; - EXPECT_NE(CryptoUtils::Sha256("ohos"), userId); + EXPECT_NE(Crypto::Sha256("ohos"), userId); } diff --git a/services/distributeddataservice/adapter/security/BUILD.gn b/services/distributeddataservice/adapter/security/BUILD.gn index ce3319b1ea119d4a7f2fe885c2d34b6d88490976..4ca34ef5ccda3ed239fe12fb3d1d749c5522a065 100755 --- a/services/distributeddataservice/adapter/security/BUILD.gn +++ b/services/distributeddataservice/adapter/security/BUILD.gn @@ -23,13 +23,6 @@ ohos_static_library("distributeddata_security_static") { cflags_cc = [ "-fvisibility=hidden" ] - remove_configs = [ "//build/config/compiler:no_exceptions" ] - - configs = [ - "//build/config/compiler:exceptions", - "//third_party/jsoncpp:jsoncpp_config", - ] - include_dirs = [ "../include/autils", "../include/log", @@ -40,7 +33,6 @@ ohos_static_library("distributeddata_security_static") { deps = [ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", - "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/adapter/security/src/sensitive.cpp b/services/distributeddataservice/adapter/security/src/sensitive.cpp index 96cd5a780555ad92ecc8086e792ce1aa972add5d..1d9e1834f24282797f6c239444eba156170bcc6c 100755 --- a/services/distributeddataservice/adapter/security/src/sensitive.cpp +++ b/services/distributeddataservice/adapter/security/src/sensitive.cpp @@ -17,7 +17,6 @@ #include #include "iprocess_system_api_adapter.h" #include "log_print.h" -#include "serializable.h" #undef LOG_TAG #define LOG_TAG "Sensitive" @@ -35,33 +34,11 @@ Sensitive::Sensitive(const std::vector &value) std::vector Sensitive::Marshal() const { - Json::Value root; - root[GET_NAME(securityLevel)] = securityLevel; - root[GET_NAME(deviceId)] = deviceId; - root[GET_NAME(dataBase64)] = dataBase64; - root[GET_NAME(deviceType)] = deviceType; - - Json::FastWriter writer; - auto jsonStr = writer.write(root); - ZLOGD("len:%d, value:%.20s!", int32_t(jsonStr.size()), jsonStr.c_str()); - return {jsonStr.begin(), jsonStr.end()}; + return {}; } void Sensitive::Unmarshal(const std::vector &value) { - std::string input(reinterpret_cast(value.data()), value.size()); - Json::Reader reader; - Json::Value root; - ZLOGD("len:%d, value:%.20s!", int32_t(value.size()), input.c_str()); - bool success = reader.parse(input, root); - if (!success) { - ZLOGE("reader.parse failed!"); - } - - securityLevel = Serializable::GetVal(root[GET_NAME(securityLevel)], securityLevel); - deviceId = Serializable::GetVal(root[GET_NAME(deviceId)], deviceId); - dataBase64 = Serializable::GetVal(root[GET_NAME(dataBase64)], dataBase64); - deviceType = Serializable::GetVal(root[GET_NAME(deviceType)], deviceType); } uint32_t Sensitive::GetSensitiveLevel() diff --git a/services/distributeddataservice/adapter/utils/BUILD.gn b/services/distributeddataservice/adapter/utils/BUILD.gn index 41ce269c5d09b47b36b22426410a3bbb85cf559b..fcf99e1b73562aa754b2e5aebdba32537b4d8dc1 100755 --- a/services/distributeddataservice/adapter/utils/BUILD.gn +++ b/services/distributeddataservice/adapter/utils/BUILD.gn @@ -13,10 +13,7 @@ import("//build/ohos.gni") ohos_static_library("distributeddata_utils_static") { - sources = [ - "src/crypto_utils.cpp", - "src/kvstore_utils.cpp", - ] + sources = [ "src/kvstore_utils.cpp" ] cflags_cc = [ "-fvisibility=hidden" ] @@ -24,10 +21,6 @@ ohos_static_library("distributeddata_utils_static") { cflags_cc += [ "-DCONFIG_PUBLIC_VERSION" ] } - remove_configs = [ "//build/config/compiler:no_exceptions" ] - - configs = [ "//build/config/compiler:exceptions" ] - include_dirs = [ "../include/permission", "../include/utils", @@ -36,12 +29,10 @@ ohos_static_library("distributeddata_utils_static") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", "//utils/native/base/include", "../include/dfx", - "//third_party/openssl/include/", ] ldflags = [ "-Wl,--exclude-libs,ALL" ] deps = [ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", - "//third_party/openssl:libcrypto_static", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/adapter/utils/src/crypto_utils.cpp b/services/distributeddataservice/adapter/utils/src/crypto_utils.cpp deleted file mode 100755 index 86f1831e3d3dce3c30d2ec69557afd259d745661..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/adapter/utils/src/crypto_utils.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "crypto_utils.h" - -#include -#include -#include -#include -#include "openssl/sha.h" - -namespace OHOS { -namespace DistributedKv { -std::string CryptoUtils::Sha256(const std::string &plainText) -{ - unsigned char hash[SHA256_DIGEST_LENGTH] = ""; - SHA256_CTX ctx; - SHA256_Init(&ctx); - SHA256_Update(&ctx, plainText.c_str(), plainText.size()); - SHA256_Final(hash, &ctx); - std::string hashToHex; - // here we translate sha256 hash to hexadecimal. each 8-bit char will be presented by two characters([0-9a-f]) - constexpr int CHAR_WIDTH = 8; - constexpr int HEX_WIDTH = 4; - constexpr unsigned char HEX_MASK = 0xf; - constexpr int HEX_A = 10; - hashToHex.reserve(SHA256_DIGEST_LENGTH * (CHAR_WIDTH / HEX_WIDTH)); - for (unsigned char i : hash) { - unsigned char hex = i >> HEX_WIDTH; - if (hex < HEX_A) { - hashToHex.push_back('0' + hex); - } else { - hashToHex.push_back('a' + hex - HEX_A); - } - hex = i & HEX_MASK; - if (hex < HEX_A) { - hashToHex.push_back('0' + hex); - } else { - hashToHex.push_back('a' + hex - HEX_A); - } - } - return hashToHex; -} - -std::string CryptoUtils::Sha256AppId(const std::string &bundleName, int userId) -{ - return bundleName; -} - -std::string CryptoUtils::Sha256UserId(const std::string &plainText) -{ - std::regex pattern("^[0-9]+$"); - if (!std::regex_match(plainText, pattern)) { - return plainText; - } - - std::string::size_type sizeType; - int64_t plainVal; - std::string::size_type int64MaxLen(std::to_string(INT64_MAX).size()); - // plain text length must be less than INT64_MAX string. - try { - plainVal = static_cast(std::stoll(plainText, &sizeType)); - } catch (const std::out_of_range &) { - plainVal = static_cast(std::stoll( - plainText.substr(plainText.size() - int64MaxLen + 1, int64MaxLen - 1), &sizeType)); - } catch (const std::exception &) { - return plainText; - } - - union UnionLong { - int64_t val; - unsigned char byteLen[sizeof(int64_t)]; - }; - UnionLong unionLong {}; - unionLong.val = plainVal; - std::list unionList(std::begin(unionLong.byteLen), std::end(unionLong.byteLen)); - unionList.reverse(); - std::vector unionVec(unionList.begin(), unionList.end()); - - unsigned char hash[SHA256_DIGEST_LENGTH]; - SHA256_CTX ctx; - SHA256_Init(&ctx); - SHA256_Update(&ctx, unionVec.data(), sizeof(int64_t)); - SHA256_Final(hash, &ctx); - - const char* hexArray = "0123456789ABCDEF"; - char* hexChars = new char[SHA256_DIGEST_LENGTH * 2 + 1]; - for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) { - unsigned int value = hash[i] & 0xFF; - hexChars[i * 2] = hexArray[value >> 4]; - hexChars[i * 2 + 1] = hexArray[value & 0x0F]; - } - hexChars[SHA256_DIGEST_LENGTH * 2] = '\0'; - std::string res(hexChars); - delete []hexChars; - return res; -} - -void CryptoUtils::GetRandomKey(int keyLen, std::vector &key) -{ - constexpr int UINT8_T_MAX = 255; - std::random_device randomDevice; - std::uniform_int_distribution distribution(0, UINT8_T_MAX); - key.clear(); - for (int i = 0; i < keyLen; i++) { - key.push_back(static_cast(distribution(randomDevice))); - } -} -} // namespace DistributedKv -} // namespace OHOS diff --git a/services/distributeddataservice/adapter/utils/src/kvstore_utils.cpp b/services/distributeddataservice/adapter/utils/src/kvstore_utils.cpp index aa495ba1e1b37eaefcbd1235f6ade6644c1f94e6..89dc7333e1d1b5bb9ad9279887060692dbc5c142 100755 --- a/services/distributeddataservice/adapter/utils/src/kvstore_utils.cpp +++ b/services/distributeddataservice/adapter/utils/src/kvstore_utils.cpp @@ -16,9 +16,6 @@ #define LOG_TAG "KvStoreUtils" #include "kvstore_utils.h" -#include "crypto_utils.h" -#include "ipc_skeleton.h" -#include "log_print.h" #include "permission_validator.h" namespace OHOS { @@ -28,11 +25,6 @@ constexpr int32_t END_SIZE = 3; constexpr int32_t MIN_SIZE = HEAD_SIZE + END_SIZE + 3; constexpr const char *REPLACE_CHAIN = "***"; constexpr const char *DEFAULT_ANONYMOUS = "******"; -std::string KvStoreUtils::GetAppIdByBundleName(const std::string &bundleName) -{ - return bundleName; -} - std::string KvStoreUtils::ToBeAnonymous(const std::string &name) { if (name.length() <= HEAD_SIZE) { diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 46aa789141f00a866ccac76894deb78601408695..ae7fbec18c38bd6530a19011b44a6a3c621a5d5d 100755 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -36,8 +36,13 @@ ohos_sa_profile("distributeddata_profile") { config("module_private_config") { visibility = [ ":*" ] include_dirs = [ - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/bootstrap/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/config/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/directory/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/rdb/src", "//foundation/distributeddatamgr/distributeddatamgr/services/rdb", @@ -107,7 +112,9 @@ ohos_shared_library("distributeddataservice") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/uninstaller:distributeddata_uninstaller_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index b3c7b5263f90be2674b1036c172fac3d40b2e881..80202b83e684f922f096c204f5a1ed9773d997b7 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -24,7 +24,6 @@ #include "battery_info.h" #include "battery_srv_client.h" #include "constant.h" -#include "crypto_utils.h" #include "kv_store_delegate_manager.h" #include "kv_scheduler.h" #include "kvstore_data_service.h" @@ -32,6 +31,7 @@ #include "kvstore_meta_manager.h" #include "power_mgr_client.h" #include "time_utils.h" +#include "utils/crypto.h" namespace OHOS::DistributedKv { using json = nlohmann::json; @@ -96,7 +96,7 @@ void BackupHandler::SingleKvStoreBackup(const MetaData &metaData) dbOption.secOption = KvStoreAppManager::ConvertSecurity(metaData.kvStoreMetaData.securityLevel); auto *delegateMgr = new DistributedDB::KvStoreDelegateManager(metaData.kvStoreMetaData.appId, - AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(metaData.kvStoreMetaData.bundleName)); + AccountDelegate::GetInstance()->GetCurrentAccountId(metaData.kvStoreMetaData.bundleName)); std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, metaData.kvStoreMetaData.bundleName, backupPara.pathType); @@ -152,7 +152,7 @@ void BackupHandler::MultiKvStoreBackup(const MetaData &metaData) option.createDirByStoreIdOnly = true; auto *delegateMgr = new DistributedDB::KvStoreDelegateManager(metaData.kvStoreMetaData.appId, - AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(metaData.kvStoreMetaData.bundleName)); + AccountDelegate::GetInstance()->GetCurrentAccountId(metaData.kvStoreMetaData.bundleName)); std::string appDataStoragePath = KvStoreAppManager::GetDataStoragePath(metaData.kvStoreMetaData.deviceAccountId, metaData.kvStoreMetaData.bundleName, backupPara.pathType); DistributedDB::KvStoreConfig kvStoreConfig; @@ -190,7 +190,7 @@ bool BackupHandler::InitBackupPara(const MetaData &metaData, BackupPara &backupP { BackupPara backupParameter; auto pathType = KvStoreAppManager::ConvertPathType( - metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); + metaData.kvStoreMetaData.uid, metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); if (!ForceCreateDirectory(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { ZLOGE("MultiKvStoreBackup backup create directory failed."); return false; @@ -229,8 +229,8 @@ bool BackupHandler::SingleKvStoreRecover(MetaData &metaData, DistributedDB::KvSt ZLOGE("SingleKvStoreRecover failed, delegate is null."); return false; } - auto pathType = KvStoreAppManager::ConvertPathType(metaData.kvStoreMetaData.bundleName, - metaData.kvStoreMetaData.securityLevel); + auto pathType = KvStoreAppManager::ConvertPathType( + metaData.kvStoreMetaData.uid, metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); if (!BackupHandler::FileExists(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { ZLOGE("SingleKvStoreRecover failed, backupDir_ file is not exist."); return false; @@ -267,8 +267,8 @@ bool BackupHandler::MultiKvStoreRecover(MetaData &metaData, ZLOGE("MultiKvStoreRecover failed, delegate is null."); return false; } - auto pathType = KvStoreAppManager::ConvertPathType(metaData.kvStoreMetaData.bundleName, - metaData.kvStoreMetaData.securityLevel); + auto pathType = KvStoreAppManager::ConvertPathType( + metaData.kvStoreMetaData.uid, metaData.kvStoreMetaData.bundleName, metaData.kvStoreMetaData.securityLevel); if (!BackupHandler::FileExists(BackupHandler::GetBackupPath(metaData.kvStoreMetaData.deviceAccountId, pathType))) { ZLOGE("MultiKvStoreRecover failed, backupDir_ file is not exist."); return false; @@ -399,6 +399,6 @@ std::string BackupHandler::GetHashedBackupName(const std::string &bundleName) if (bundleName.empty()) { return bundleName; } - return CryptoUtils::Sha256(bundleName); + return DistributedData::Crypto::Sha256(bundleName); } } // namespace OHOS::DistributedKv diff --git a/services/distributeddataservice/app/src/device_kvstore_impl.cpp b/services/distributeddataservice/app/src/device_kvstore_impl.cpp index 2594b6b9063ae6489d288c730885c9f7c4bc41c9..18440f667ad7b8fa280efdbeebb270f38058acfb 100644 --- a/services/distributeddataservice/app/src/device_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/device_kvstore_impl.cpp @@ -16,28 +16,29 @@ #define LOG_TAG "DeviceKvStoreImpl" #include "device_kvstore_impl.h" + #include -#include "kvstore_utils.h" + #include "constant.h" +#include "device_kvstore_observer_impl.h" +#include "device_kvstore_resultset_impl.h" +#include "kvstore_utils.h" #include "log_print.h" namespace OHOS::DistributedKv { using namespace AppDistributedKv; - -DeviceKvStoreImpl::DeviceKvStoreImpl(const KvStoreParams ¶ms, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate) - : SingleKvStoreImpl(params.options, params.deviceAccountId, params.appId, params.storeId, - params.appDirectory, kvStoreNbDelegate), params_(params) -{} +DeviceKvStoreImpl::DeviceKvStoreImpl(const Options &options, const std::string &userId, const std::string &bundleName, + const std::string &storeId, const std::string &appId, const std::string &directory, + DistributedDB::KvStoreNbDelegate *delegate) + : SingleKvStoreImpl(options, userId, bundleName, storeId, appId, directory, delegate) +{ +} DeviceKvStoreImpl::~DeviceKvStoreImpl() {} Status DeviceKvStoreImpl::Get(const Key &key, Value &value) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::Get(key, value); - } - std::vector tmpkey; Status status = DeleteKeyPrefix(key, tmpkey); if (status != Status::SUCCESS) { @@ -52,10 +53,6 @@ Status DeviceKvStoreImpl::Get(const Key &key, Value &value) Status DeviceKvStoreImpl::Put(const Key &key, const Value &value) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::Put(key, value); - } - std::vector tmpkey; AddKeyPrefixAndSuffix(key, tmpkey); Key decorateKey(tmpkey); @@ -64,10 +61,6 @@ Status DeviceKvStoreImpl::Put(const Key &key, const Value &value) Status DeviceKvStoreImpl::Delete(const Key &key) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::Delete(key); - } - std::vector tmpkey; AddKeyPrefixAndSuffix(key, tmpkey); Key decorateKey(tmpkey); @@ -76,10 +69,6 @@ Status DeviceKvStoreImpl::Delete(const Key &key) Status DeviceKvStoreImpl::GetEntries(const Key &prefixKey, std::vector &entries) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::GetEntries(prefixKey, entries); - } - std::vector tmpkey; Status status = DeleteKeyPrefix(prefixKey, tmpkey); if (status == Status::KEY_NOT_FOUND) { @@ -111,19 +100,9 @@ Status DeviceKvStoreImpl::GetEntries(const Key &prefixKey, std::vector &e return ret; } -Status DeviceKvStoreImpl::RemoveDeviceData(const std::string &device) -{ - return SingleKvStoreImpl::RemoveDeviceData(device); -} - void DeviceKvStoreImpl::GetResultSet(const Key &prefixKey, std::function)> callback) { - if (!params_.deviceCoordinate) { - SingleKvStoreImpl::GetResultSet(prefixKey, callback); - return; - } - std::vector tmpkey; Status status = DeleteKeyPrefix(prefixKey, tmpkey); if (status != Status::SUCCESS) { @@ -132,24 +111,11 @@ void DeviceKvStoreImpl::GetResultSet(const Key &prefixKey, return; } Key decorateKey(tmpkey); - SingleKvStoreImpl::GetResultSet(decorateKey, callback, true); -} - -Status DeviceKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sptr observer) -{ - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::SubscribeKvStore(subscribeType, observer); - } - - return SingleKvStoreImpl::SubscribeKvStore(subscribeType, observer, true); + SingleKvStoreImpl::GetResultSet(decorateKey, callback); } Status DeviceKvStoreImpl::PutBatch(const std::vector &entries) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::PutBatch(entries); - } - std::vector tmpEntries = entries; for (auto &entry : tmpEntries) { std::vector tmpkey; @@ -163,10 +129,6 @@ Status DeviceKvStoreImpl::PutBatch(const std::vector &entries) Status DeviceKvStoreImpl::DeleteBatch(const std::vector &keys) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::DeleteBatch(keys); - } - std::vector tmpKeys = keys; for (auto &key : tmpKeys) { std::vector tmpkey; @@ -179,10 +141,6 @@ Status DeviceKvStoreImpl::DeleteBatch(const std::vector &keys) Status DeviceKvStoreImpl::GetEntriesWithQuery(const std::string &query, std::vector &entries) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::GetEntriesWithQuery(query, entries); - } - Status ret = SingleKvStoreImpl::GetEntriesWithQuery(query, entries); if (ret != Status::SUCCESS) { return ret; @@ -197,17 +155,6 @@ Status DeviceKvStoreImpl::GetEntriesWithQuery(const std::string &query, std::vec return ret; } -void DeviceKvStoreImpl::GetResultSetWithQuery(const std::string &query, - std::function)> callback) -{ - if (!params_.deviceCoordinate) { - SingleKvStoreImpl::GetResultSetWithQuery(query, callback); - return; - } - - SingleKvStoreImpl::GetResultSetWithQuery(query, callback, true); -} - std::string DeviceKvStoreImpl::localDeviceId_; std::string DeviceKvStoreImpl::GetLocalDeviceId() { @@ -279,4 +226,16 @@ bool DeviceKvStoreImpl::AddKeyPrefixAndSuffix(const Key &in, std::vector observer) +{ + return new (std::nothrow) DeviceKvStoreObserverImpl(subscribeType, observer); +} + +KvStoreResultSetImpl *DeviceKvStoreImpl::CreateResultSet( + DistributedDB::KvStoreResultSet *resultSet, const DistributedDB::Key &prix) +{ + return new (std::nothrow) DeviceKvStoreResultSetImpl(resultSet, prix); +} } diff --git a/services/distributeddataservice/app/src/device_kvstore_impl.h b/services/distributeddataservice/app/src/device_kvstore_impl.h index c118b47cff78ec746ab82d7a0d0ee63efb543b8b..e00b3b5e5b28d08410536784eb2ddc48c2d27d17 100755 --- a/services/distributeddataservice/app/src/device_kvstore_impl.h +++ b/services/distributeddataservice/app/src/device_kvstore_impl.h @@ -16,7 +16,6 @@ #ifndef DEVICE_KVSTORE_IMPL_H #define DEVICE_KVSTORE_IMPL_H -#include "kvstore_common.h" #include "single_kvstore_impl.h" namespace OHOS::DistributedKv { @@ -27,27 +26,28 @@ union KeyEncap { class DeviceKvStoreImpl : public SingleKvStoreImpl { public: - DeviceKvStoreImpl(const KvStoreParams ¶ms, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate); + DeviceKvStoreImpl(const Options &options, const std::string &userId, + const std::string &bundleName, const std::string &storeId, const std::string &appId, + const std::string &directory, DistributedDB::KvStoreNbDelegate *delegate); ~DeviceKvStoreImpl(); Status Put(const Key &key, const Value &value) override; Status Delete(const Key &key) override; Status Get(const Key &key, Value &value) override; - Status SubscribeKvStore(const SubscribeType subscribeType, sptr observer) override; Status GetEntries(const Key &prefixKey, std::vector &entries) override; Status GetEntriesWithQuery(const std::string &query, std::vector &entries) override; void GetResultSet(const Key &prefixKey, std::function)> callback) override; - void GetResultSetWithQuery(const std::string &query, - std::function)> callback) override; - Status RemoveDeviceData(const std::string &device) override; Status PutBatch(const std::vector &entries) override; Status DeleteBatch(const std::vector &keys) override; static std::string GetLocalDeviceId(); +protected: + KvStoreObserverImpl *CreateObserver(const SubscribeType subscribeType, sptr observer) override; + KvStoreResultSetImpl *CreateResultSet( + DistributedDB::KvStoreResultSet *resultSet, const DistributedDB::Key &prix) override; private: bool AddKeyPrefixAndSuffix(const Key &in, std::vector &out); Status DeleteKeyPrefix(const Key &in, std::vector &out); void DeletePrefixAndSuffix(const Key &in, std::vector &out); static std::string localDeviceId_; - KvStoreParams params_; }; } #endif // DEVICE_KVSTORE_IMPL_H diff --git a/services/distributeddataservice/app/src/device_kvstore_observer_impl.cpp b/services/distributeddataservice/app/src/device_kvstore_observer_impl.cpp index 72e5788ce98b486d585a2b4c9295a1c9b2cddf0f..97934ea17e70cf8686f11b81b81edb049a7d3fc6 100644 --- a/services/distributeddataservice/app/src/device_kvstore_observer_impl.cpp +++ b/services/distributeddataservice/app/src/device_kvstore_observer_impl.cpp @@ -20,38 +20,33 @@ #include "log_print.h" using namespace OHOS::AppDistributedKv; namespace OHOS::DistributedKv { -DeviceKvStoreObserverImpl::DeviceKvStoreObserverImpl(SubscribeType subscribeType, sptr observerProxy, - bool deviceSync) : KvStoreObserverImpl(subscribeType, observerProxy), deviceSync_(deviceSync), - localDeviceId_{}, observerProxy_(observerProxy) -{} +DeviceKvStoreObserverImpl::DeviceKvStoreObserverImpl(SubscribeType subscribeType, sptr observerProxy) + : KvStoreObserverImpl(subscribeType, observerProxy), localDeviceId_{}, observerProxy_(observerProxy) +{ +} DeviceKvStoreObserverImpl::~DeviceKvStoreObserverImpl() {} void DeviceKvStoreObserverImpl::OnChange(const DistributedDB::KvStoreChangedData &data) { - if (deviceSync_) { - std::list insertList = data.GetEntriesInserted(); - std::list updateList = data.GetEntriesUpdated(); - std::list deletedList = data.GetEntriesDeleted(); + std::list insertList = data.GetEntriesInserted(); + std::list updateList = data.GetEntriesUpdated(); + std::list deletedList = data.GetEntriesDeleted(); - std::vector inserts; - std::vector updates; - std::vector deleteds; - std::string deviceId; - Transfer(insertList, inserts, deviceId); - Transfer(updateList, updates, deviceId); - Transfer(deletedList, deleteds, deviceId); - if (deviceId.empty()) { - ZLOGE("Did NOT find any valid deviceId"); - } - ChangeNotification change(std::move(inserts), std::move(updates), std::move(deleteds), deviceId, false); - if (observerProxy_ != nullptr) { - observerProxy_->OnChange(change, nullptr); - } - return; - } else { - KvStoreObserverImpl::OnChange(data); + std::vector inserts; + std::vector updates; + std::vector deleteds; + std::string deviceId; + Transfer(insertList, inserts, deviceId); + Transfer(updateList, updates, deviceId); + Transfer(deletedList, deleteds, deviceId); + if (deviceId.empty()) { + ZLOGE("Did NOT find any valid deviceId"); + } + ChangeNotification change(std::move(inserts), std::move(updates), std::move(deleteds), deviceId, false); + if (observerProxy_ != nullptr) { + observerProxy_->OnChange(change, nullptr); } } diff --git a/services/distributeddataservice/app/src/device_kvstore_observer_impl.h b/services/distributeddataservice/app/src/device_kvstore_observer_impl.h index bd9b1fd22a55f8c1d27cbf2d578429b57ca057a2..0147caf1c4309b0af52f364a9c23f2eb2cef4b9e 100644 --- a/services/distributeddataservice/app/src/device_kvstore_observer_impl.h +++ b/services/distributeddataservice/app/src/device_kvstore_observer_impl.h @@ -21,12 +21,11 @@ namespace OHOS::DistributedKv { class DeviceKvStoreObserverImpl : public KvStoreObserverImpl { public: - DeviceKvStoreObserverImpl(SubscribeType subscribeType, sptr observerProxy, bool deviceSync); + DeviceKvStoreObserverImpl(SubscribeType subscribeType, sptr observerProxy); ~DeviceKvStoreObserverImpl() override; void OnChange(const DistributedDB::KvStoreChangedData &data) override; private: void Transfer(const std::list &input, std::vector &output, std::string &deviceId); - bool deviceSync_; std::string localDeviceId_; sptr observerProxy_; }; diff --git a/services/distributeddataservice/app/src/device_kvstore_resultset_impl.cpp b/services/distributeddataservice/app/src/device_kvstore_resultset_impl.cpp index 465f14e43e35f195132acddcbb389b05458de84c..fac7e84b785e8d8f4a26ca93d13dbc124dedc4f4 100644 --- a/services/distributeddataservice/app/src/device_kvstore_resultset_impl.cpp +++ b/services/distributeddataservice/app/src/device_kvstore_resultset_impl.cpp @@ -21,27 +21,15 @@ namespace OHOS::DistributedKv { using namespace AppDistributedKv; - -DeviceKvStoreResultSetImpl::DeviceKvStoreResultSetImpl(DistributedDB::Key tmpKeyPrefix, - DistributedDB::KvStoreResultSet *kvStoreResultSet, bool deviceCoordinate) - : KvStoreResultSetImpl(tmpKeyPrefix, kvStoreResultSet), deviceCoordinate_(deviceCoordinate) -{} - -DeviceKvStoreResultSetImpl::DeviceKvStoreResultSetImpl(DistributedDB::KvStoreResultSet *kvStoreResultSet, - bool deviceCoordinate) : KvStoreResultSetImpl(kvStoreResultSet), deviceCoordinate_(deviceCoordinate) -{} - -DeviceKvStoreResultSetImpl::~DeviceKvStoreResultSetImpl() -{} +DeviceKvStoreResultSetImpl::DeviceKvStoreResultSetImpl( + DistributedDB::KvStoreResultSet *resultSet, DistributedDB::Key keyPrefix) + : KvStoreResultSetImpl(resultSet, keyPrefix) +{ +} Status DeviceKvStoreResultSetImpl::GetEntry(Entry &entry) { ZLOGD("RS:start"); - if (!deviceCoordinate_) { - ZLOGI("RS: normal"); - return KvStoreResultSetImpl::GetEntry(entry); - } - Entry tmpEntry; Status ret = KvStoreResultSetImpl::GetEntry(tmpEntry); if (ret != Status::SUCCESS) { diff --git a/services/distributeddataservice/app/src/device_kvstore_resultset_impl.h b/services/distributeddataservice/app/src/device_kvstore_resultset_impl.h index fc126a51cc6957ae9a079a37518359f8b28f8740..06e62c1688397ce50dd0cadc103c03a4f7b449bb 100755 --- a/services/distributeddataservice/app/src/device_kvstore_resultset_impl.h +++ b/services/distributeddataservice/app/src/device_kvstore_resultset_impl.h @@ -21,14 +21,8 @@ namespace OHOS::DistributedKv { class DeviceKvStoreResultSetImpl : public KvStoreResultSetImpl { public: - DeviceKvStoreResultSetImpl(DistributedDB::Key tmpKeyPrefix, - DistributedDB::KvStoreResultSet *kvStoreResultSet, bool deviceCoordinate); - DeviceKvStoreResultSetImpl(DistributedDB::KvStoreResultSet *kvStoreResultSet, - bool deviceCoordinate); - ~DeviceKvStoreResultSetImpl(); + explicit DeviceKvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet, DistributedDB::Key keyPrefix = {}); Status GetEntry(Entry &entry) override; -private: - bool deviceCoordinate_; }; } diff --git a/services/distributeddataservice/app/src/kvstore_app_accessor.cpp b/services/distributeddataservice/app/src/kvstore_app_accessor.cpp index 57f262340db81bcbc67956dcfc112bd87709d591..40af4e48db31be826efcf7df389e4d8ded74c300 100755 --- a/services/distributeddataservice/app/src/kvstore_app_accessor.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_accessor.cpp @@ -78,7 +78,8 @@ void KvStoreAppAccessor::EnableKvStoreAutoLaunch() ZLOGE("Get secret key failed."); return; } - auto pathType = KvStoreAppManager::ConvertPathType(metaData.bundleName, metaData.securityLevel); + auto pathType = + KvStoreAppManager::ConvertPathType(metaData.uid, metaData.bundleName, metaData.securityLevel); std::string appPath = KvStoreAppManager::GetDataStoragePath( metaData.deviceAccountId, metaData.bundleName, pathType); DistributedDB::AutoLaunchOption dbLaunchOption; diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.cpp b/services/distributeddataservice/app/src/kvstore_app_manager.cpp index 002ed44bc9b755afae937bd24479ed2efca4c26d..f5ba2b2b7a189efb920be04822ca776ac107f92a 100755 --- a/services/distributeddataservice/app/src/kvstore_app_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_manager.cpp @@ -23,6 +23,7 @@ #include #include "account_delegate.h" #include "broadcast_sender.h" +#include "checker/checker_manager.h" #include "constant.h" #include "directory_utils.h" #include "device_kvstore_impl.h" @@ -38,10 +39,12 @@ namespace OHOS { namespace DistributedKv { -KvStoreAppManager::KvStoreAppManager(const std::string &bundleName, const std::string &deviceAccountId) - : bundleName_(bundleName), deviceAccountId_(deviceAccountId), flowCtrlManager_(BURST_CAPACITY, SUSTAINED_CAPACITY) +using namespace OHOS::DistributedData; +KvStoreAppManager::KvStoreAppManager(const std::string &bundleName, pid_t uid) + : bundleName_(bundleName), uid_(uid), flowCtrl_(BURST_CAPACITY, SUSTAINED_CAPACITY) { ZLOGI("begin."); + deviceAccountId_ = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); GetDelegateManager(PATH_DE); GetDelegateManager(PATH_CE); } @@ -89,20 +92,19 @@ Status KvStoreAppManager::ConvertErrorStatus(DistributedDB::DBStatus dbStatus, b return Status::SUCCESS; } -Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &storeId, - const std::vector &cipherKey, - std::function)> callback) +Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, + const std::vector &cipherKey, sptr &kvStore) { ZLOGI("begin"); - PathType type = ConvertPathType(bundleName_, options.securityLevel); + kvStore = nullptr; + PathType type = ConvertPathType(uid_, bundleName_, options.securityLevel); auto *delegateManager = GetDelegateManager(type); if (delegateManager == nullptr) { ZLOGE("delegateManagers[%d] is nullptr.", type); - callback(nullptr); return Status::ILLEGAL_STATE; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -110,16 +112,14 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & std::lock_guard lg(storeMutex_); auto it = stores_[type].find(storeId); if (it != stores_[type].end()) { - sptr kvStoreImpl = it->second; - ZLOGI("find store in map refcount: %d.", kvStoreImpl->GetSptrRefCount()); - static_cast(kvStoreImpl.GetRefPtr())->IncreaseOpenCount(); - callback(std::move(kvStoreImpl)); + kvStore = it->second; + ZLOGI("find store in map refcount: %d.", kvStore->GetSptrRefCount()); + kvStore->IncreaseOpenCount(); return Status::SUCCESS; } if ((GetTotalKvStoreNum()) >= static_cast(Constant::MAX_OPEN_KVSTORES)) { ZLOGE("limit %d KvStores can be opened.", Constant::MAX_OPEN_KVSTORES); - callback(nullptr); return Status::ERROR; } @@ -127,7 +127,6 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & auto status = InitDbOption(options, cipherKey, dbOption); if (status != Status::SUCCESS) { ZLOGE("InitDbOption failed."); - callback(nullptr); return status; } @@ -141,62 +140,56 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & if (storeDelegate == nullptr) { ZLOGE("storeDelegate is nullptr, status:%d.", static_cast(dbStatusTmp)); - callback(nullptr); return ConvertErrorStatus(dbStatusTmp, options.createIfMissing); } ZLOGD("get delegate"); - sptr store = new (std::nothrow)KvStoreImpl(options, deviceAccountId_, bundleName_, - storeId, GetDbDir(options), storeDelegate); - if (store == nullptr) { - callback(nullptr); + kvStore = new (std::nothrow)KvStoreImpl(options, deviceAccountId_, bundleName_, + appId, storeId, GetDbDir(options), storeDelegate); + if (kvStore == nullptr) { delegateManager->CloseKvStore(storeDelegate); + kvStore = nullptr; return Status::ERROR; } - auto result = stores_[type].emplace(storeId, store); + auto result = stores_[type].emplace(storeId, kvStore); if (!result.second) { ZLOGE("emplace failed."); - callback(nullptr); delegateManager->CloseKvStore(storeDelegate); + kvStore = nullptr; return Status::ERROR; } - sptr kvStoreImpl = result.first->second; - ZLOGD("after emplace refcount: %d", kvStoreImpl->GetSptrRefCount()); - callback(std::move(kvStoreImpl)); + ZLOGD("after emplace refcount: %d", kvStore->GetSptrRefCount()); return Status::SUCCESS; } -Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &storeId, - const std::vector &cipherKey, - std::function)> callback) +Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, + const std::vector &cipherKey, sptr &kvStore) { ZLOGI("begin"); - PathType type = ConvertPathType(bundleName_, options.securityLevel); + kvStore = nullptr; + PathType type = ConvertPathType(uid_, bundleName_, options.securityLevel); auto *delegateManager = GetDelegateManager(type); if (delegateManager == nullptr) { ZLOGE("delegateManagers[%d] is nullptr.", type); - callback(nullptr); return Status::ILLEGAL_STATE; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } std::lock_guard lg(storeMutex_); auto it = singleStores_[type].find(storeId); if (it != singleStores_[type].end()) { - sptr singleKvStoreImpl = it->second; - ZLOGI("find store in map refcount: %d.", singleKvStoreImpl->GetSptrRefCount()); - static_cast(singleKvStoreImpl.GetRefPtr())->IncreaseOpenCount(); - callback(std::move(singleKvStoreImpl)); + kvStore = it->second; + ZLOGI("find store in map refcount: %d.", kvStore->GetSptrRefCount()); + kvStore->IncreaseOpenCount(); return Status::SUCCESS; } if ((GetTotalKvStoreNum()) >= static_cast(Constant::MAX_OPEN_KVSTORES)) { ZLOGE("limit %d KvStores can be opened.", Constant::MAX_OPEN_KVSTORES); - callback(nullptr); return Status::ERROR; } @@ -204,7 +197,6 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & auto status = InitNbDbOption(options, cipherKey, dbOption); if (status != Status::SUCCESS) { ZLOGE("InitNbDbOption failed."); - callback(nullptr); return status; } @@ -218,31 +210,34 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & if (storeDelegate == nullptr) { ZLOGE("storeDelegate is nullptr."); - callback(nullptr); return ConvertErrorStatus(dbStatusTmp, options.createIfMissing); } std::string kvStorePath = GetDbDir(options); - auto store = new (std::nothrow) DeviceKvStoreImpl({ - options, options.kvStoreType == KvStoreType::DEVICE_COLLABORATION, deviceAccountId_, bundleName_, storeId, - kvStorePath}, storeDelegate); - if (store == nullptr) { + switch (options.kvStoreType) { + case KvStoreType::DEVICE_COLLABORATION: + kvStore = new (std::nothrow) DeviceKvStoreImpl( + options, deviceAccountId_, bundleName_, storeId, trueAppId_, kvStorePath, storeDelegate); + break; + default: + kvStore = new (std::nothrow) SingleKvStoreImpl( + options, deviceAccountId_, bundleName_, storeId, trueAppId_, kvStorePath, storeDelegate); + break; + } + if (kvStore == nullptr) { ZLOGE("store is nullptr."); - callback(nullptr); delegateManager->CloseKvStore(storeDelegate); + kvStore = nullptr; return Status::ERROR; } - auto result = singleStores_[type].emplace(storeId, store); + auto result = singleStores_[type].emplace(storeId, kvStore); if (!result.second) { ZLOGE("emplace failed."); - callback(nullptr); delegateManager->CloseKvStore(storeDelegate); - delete store; + kvStore = nullptr; return Status::ERROR; } - sptr singleKvStoreImpl = result.first->second; - ZLOGI("after emplace refcount: %d autoSync: %d", - singleKvStoreImpl->GetSptrRefCount(), static_cast(options.autoSync)); + ZLOGI("after emplace refcount: %d autoSync: %d", kvStore->GetSptrRefCount(), static_cast(options.autoSync)); if (options.autoSync) { bool autoSync = true; DistributedDB::PragmaData data = static_cast(&autoSync); @@ -252,7 +247,6 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & } } - callback(std::move(singleKvStoreImpl)); DistributedDB::AutoLaunchOption launchOption = { options.createIfMissing, options.encrypt, dbOption.cipher, dbOption.passwd, dbOption.schema, dbOption.createDirByStoreIdOnly, kvStorePath, nullptr @@ -266,7 +260,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & Status KvStoreAppManager::CloseKvStore(const std::string &storeId) { ZLOGI("CloseKvStore"); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -308,7 +302,7 @@ Status KvStoreAppManager::CloseAllKvStore() Status KvStoreAppManager::DeleteKvStore(const std::string &storeId) { ZLOGI("%s", storeId.c_str()); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -419,18 +413,29 @@ Status KvStoreAppManager::InitNbDbOption(const Options &options, const std::vect std::string KvStoreAppManager::GetDbDir(const Options &options) const { - return GetDataStoragePath(deviceAccountId_, bundleName_, ConvertPathType(bundleName_, options.securityLevel)); + return GetDataStoragePath(deviceAccountId_, bundleName_, ConvertPathType(uid_, bundleName_, options.securityLevel)); } -KvStoreAppManager::PathType KvStoreAppManager::ConvertPathType(const std::string &bundleName, int securityLevel) +KvStoreAppManager::PathType KvStoreAppManager::ConvertPathType(int32_t uid, const std::string &bundleName, + int securityLevel) { - PathType type = PATH_CE; - if ((securityLevel == NO_LABEL && PermissionValidator::IsSystemService(bundleName)) || - securityLevel == S0 || - securityLevel == S1) { - type = PATH_DE; + switch (securityLevel) { + case S0: // fallthrough + case S1: + return PATH_DE; + case S2: // fallthrough + case S3_EX: // fallthrough + case S3: // fallthrough + case S4: // fallthrough + return PATH_CE; + default: + break; + } + auto *checker = CheckerManager::GetInstance().GetChecker("SystemChecker"); + if (checker == nullptr || !checker->IsValid(uid, bundleName)) { + return PATH_CE; } - return type; + return PATH_DE; } DistributedDB::KvStoreDelegateManager *KvStoreAppManager::GetDelegateManager(PathType type) @@ -450,14 +455,14 @@ DistributedDB::KvStoreDelegateManager *KvStoreAppManager::GetDelegateManager(Pat DirectoryUtils::ChangeModeDirOnly(directory, Constant::DEFAULT_MODE_DIR); DirectoryUtils::ChangeModeFileOnly(directory, Constant::DEFAULT_MODE_FILE); - trueAppId_ = KvStoreUtils::GetAppIdByBundleName(bundleName_); + trueAppId_ = CheckerManager::GetInstance().GetAppId(bundleName_, uid_); if (trueAppId_.empty()) { delegateManagers_[type] = nullptr; ZLOGW("trueAppId_ empty(permission issues?)"); return nullptr; } - userId_ = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(bundleName_); + userId_ = AccountDelegate::GetInstance()->GetCurrentAccountId(bundleName_); ZLOGD("accountId: %s bundleName: %s", KvStoreUtils::ToBeAnonymous(userId_).c_str(), bundleName_.c_str()); delegateManagers_[type] = new (std::nothrow) DistributedDB::KvStoreDelegateManager(trueAppId_, userId_); if (delegateManagers_[type] == nullptr) { @@ -468,7 +473,6 @@ DistributedDB::KvStoreDelegateManager *KvStoreAppManager::GetDelegateManager(Pat DistributedDB::KvStoreConfig kvStoreConfig; kvStoreConfig.dataDir = directory; delegateManagers_[type]->SetKvStoreConfig(kvStoreConfig); - DistributedDB::KvStoreDelegateManager::SetProcessLabel(Constant::PROCESS_LABEL, "default"); auto communicator = std::make_shared(); auto result = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator); ZLOGI("app set communicator result:%d.", static_cast(result)); @@ -686,12 +690,12 @@ size_t KvStoreAppManager::GetTotalKvStoreNum() const return int(total); }; -std::string KvStoreAppManager::GetDataStoragePath(const std::string &deviceAccountId, const std::string &bundleName, +std::string KvStoreAppManager::GetDataStoragePath(const std::string &userId, const std::string &bundleName, PathType type) { std::string miscPath = (type == PATH_DE) ? Constant::ROOT_PATH_DE : Constant::ROOT_PATH_CE; return Constant::Concatenate({ - miscPath, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), + miscPath, "/", Constant::SERVICE_NAME, "/", userId, "/", Constant::GetDefaultHarmonyAccountName(), "/", bundleName, "/" }); } diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.h b/services/distributeddataservice/app/src/kvstore_app_manager.h index 82d559c59f96f83f993a541bf5643a64b41f09e0..ca356d949f9d156a101b528ce56e5214cd1747b1 100755 --- a/services/distributeddataservice/app/src/kvstore_app_manager.h +++ b/services/distributeddataservice/app/src/kvstore_app_manager.h @@ -37,15 +37,15 @@ public: PATH_TYPE_MAX }; - KvStoreAppManager(const std::string &bundleName, const std::string &deviceAccountId); + KvStoreAppManager(const std::string &bundleName, pid_t uid); virtual ~KvStoreAppManager(); - Status GetKvStore(const Options &options, const std::string &storeId, const std::vector &cipherKey, - std::function)> callback); + Status GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, + const std::vector &cipherKey, sptr &kvStore); - Status GetKvStore(const Options &options, const std::string &storeId, const std::vector &cipherKey, - std::function)> callback); + Status GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, + const std::vector &cipherKey, sptr &kvStore); Status CloseKvStore(const std::string &storeId); @@ -63,10 +63,10 @@ public: static Status InitNbDbOption(const Options &options, const std::vector &cipherKey, DistributedDB::KvStoreNbDelegate::Option &dbOption); - static std::string GetDataStoragePath(const std::string &deviceAccountId, const std::string &bundleName, + static std::string GetDataStoragePath(const std::string &userId, const std::string &bundleName, PathType type); - static PathType ConvertPathType(const std::string &bundleName, int securityLevel); + static PathType ConvertPathType(int32_t uid, const std::string &bundleName, int securityLevel); std::string GetDbDir(const Options &options) const; @@ -93,9 +93,10 @@ private: std::string bundleName_ {}; std::string deviceAccountId_ {}; std::string trueAppId_ {}; + pid_t uid_; std::mutex delegateMutex_ {}; DistributedDB::KvStoreDelegateManager *delegateManagers_[PATH_TYPE_MAX] {nullptr, nullptr}; - KvStoreFlowCtrlManager flowCtrlManager_; + KvStoreFlowCtrlManager flowCtrl_; static inline const int BURST_CAPACITY = 50; static inline const int SUSTAINED_CAPACITY = 500; }; diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 545c4d5027de0d1e01e1007080ba772c7fb7078f..e04c555f952b550ef0db2e83730d10c7c497863c 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -17,20 +17,18 @@ #include "kvstore_data_service.h" #include -#include #include -#include #include #include -#include #include #include #include "auto_launch_export.h" +#include "bootstrap.h" +#include "checker/checker_manager.h" #include "communication_provider.h" +#include "config_factory.h" #include "constant.h" -#include "crypto_utils.h" #include "dds_trace.h" -#include "device_change_listener_impl.h" #include "device_kvstore_impl.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" @@ -47,11 +45,14 @@ #include "rdb_service_impl.h" #include "system_ability_definition.h" #include "uninstaller/uninstaller.h" +#include "utils/crypto.h" namespace OHOS::DistributedKv { using json = nlohmann::json; using namespace std::chrono; using namespace OHOS::Security::Permission; +using namespace OHOS::DistributedData; +using KvStoreDelegateManager = DistributedDB::KvStoreDelegateManager; REGISTER_SYSTEM_ABILITY_BY_ID(KvStoreDataService, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, true); @@ -65,7 +66,6 @@ KvStoreDataService::KvStoreDataService(bool runOnCreate) clientDeathObserverMap_() { ZLOGI("begin."); - Initialize(); } KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate) @@ -76,7 +76,6 @@ KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate clientDeathObserverMap_() { ZLOGI("begin"); - Initialize(); } KvStoreDataService::~KvStoreDataService() @@ -88,11 +87,13 @@ KvStoreDataService::~KvStoreDataService() void KvStoreDataService::Initialize() { ZLOGI("begin."); +#ifndef UT_TEST + KvStoreDelegateManager::SetProcessLabel(Bootstrap::GetInstance().GetProcessLabel(), "default"); +#endif KvStoreMetaManager::GetInstance().InitMetaParameter(); std::thread th = std::thread([]() { - DistributedDB::KvStoreDelegateManager::SetProcessLabel(Constant::PROCESS_LABEL, "default"); auto communicator = std::make_shared(); - auto ret = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator); + auto ret = KvStoreDelegateManager::SetProcessCommunicator(communicator); ZLOGI("set communicator ret:%d.", static_cast(ret)); if (KvStoreMetaManager::GetInstance().CheckRootKeyExist() == Status::SUCCESS) { return; @@ -147,35 +148,33 @@ 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.IsValid() || !storeId.IsValid() || options.kvStoreType != KvStoreType::MULTI_VERSION) { + ZLOGE("invalid argument type."); + return Status::INVALID_ARGUMENT; } - - GetKvStorePara getKvStorePara; - Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, getKvStorePara); - if (checkParaStatus != Status::SUCCESS) { - callback(nullptr); - return checkParaStatus; + KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); + KvStoreParam param; + param.bundleName = appId.appId; + param.storeId = storeId.storeId; + const int32_t uid = IPCSkeleton::GetCallingUid(); + param.trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); + if (param.trueAppId.empty()) { + ZLOGW("appId empty(permission issues?)"); + return Status::PERMISSION_DENIED; } - SecretKeyPara secretKeyParas; - Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, getKvStorePara, secretKeyParas); - if (getSecretKeyStatus != Status::SUCCESS) { + param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + SecretKeyPara keyPara; + Status status = KvStoreDataService::GetSecretKey(options, param, keyPara); + if (status != Status::SUCCESS) { callback(nullptr); - return getSecretKeyStatus; + return status; } - 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); + auto it = deviceAccountMap_.find(param.userId); if (it == deviceAccountMap_.end()) { auto result = deviceAccountMap_.emplace(std::piecewise_construct, - std::forward_as_tuple(deviceAccountId), std::forward_as_tuple(deviceAccountId)); + std::forward_as_tuple(param.userId), std::forward_as_tuple(param.userId)); if (!result.second) { ZLOGE("emplace failed."); FaultMsg msg = {FaultType::RUNTIME_FAULT, "user", __FUNCTION__, Fault::RF_GET_DB}; @@ -186,21 +185,20 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId 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).GetKvStore(options, bundleName, storeIdTmp, secretKey, newCallback); + sptr store; + param.status = (it->second).GetKvStore(options, param.bundleName, param.storeId, uid, keyPara.secretKey, store); + if (keyPara.outdated) { + KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, + KvStoreAppManager::ConvertPathType(param.uid, param.bundleName, options.securityLevel), store); + } - ZLOGD("get kvstore return status:%d, deviceAccountId:[%s], bundleName:[%s].", - statusTmp, KvStoreUtils::ToBeAnonymous(deviceAccountId).c_str(), bundleName.c_str()); - if (statusTmp == Status::SUCCESS) { - return UpdateMetaData(options, getKvStorePara, secretKeyParas.metaKey, it->second); + ZLOGD("get kvstore return status:%d, userId:[%s], bundleName:[%s].", + param.status, KvStoreUtils::ToBeAnonymous(param.userId).c_str(), appId.appId.c_str()); + if (param.status != Status::SUCCESS) { + param.status = GetKvStoreFailDo(options, param, keyPara, it->second, store); } - getKvStorePara.getKvStoreStatus = statusTmp; - return GetKvStoreFailDo(options, getKvStorePara, secretKeyParas, it->second, callback); + callback(std::move(store)); + return UpdateMetaData(options, param, keyPara.metaKey, it->second); } Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, @@ -208,37 +206,35 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGI("begin."); - if (callback == nullptr) { - ZLOGW("callback is nullptr"); - return Status::ERROR; + if (!appId.IsValid() || !storeId.IsValid() || !options.IsValidType() + || options.kvStoreType == KvStoreType::MULTI_VERSION) { + ZLOGE("invalid argument type."); + return Status::INVALID_ARGUMENT; } - 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; + KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); + KvStoreParam param; + param.bundleName = appId.appId; + param.storeId = storeId.storeId; + const int32_t uid = IPCSkeleton::GetCallingUid(); + param.trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); + if (param.trueAppId.empty()) { + ZLOGW("appId empty(permission issues?)"); + return Status::PERMISSION_DENIED; } - SecretKeyPara secretKeyParas; - Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, getKvStorePara, secretKeyParas); - if (getSecretKeyStatus != Status::SUCCESS) { + param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + SecretKeyPara keyPara; + Status status = KvStoreDataService::GetSecretKey(options, param, keyPara); + if (status != Status::SUCCESS) { callback(nullptr); - return getSecretKeyStatus; + return status; } - 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); + auto it = deviceAccountMap_.find(param.userId); if (it == deviceAccountMap_.end()) { auto result = deviceAccountMap_.emplace(std::piecewise_construct, - std::forward_as_tuple(deviceAccountId), std::forward_as_tuple(deviceAccountId)); + std::forward_as_tuple(param.userId), std::forward_as_tuple(param.userId)); if (!result.second) { ZLOGE("emplace failed."); callback(nullptr); @@ -246,77 +242,30 @@ Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId } 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"); - return Status::INVALID_ARGUMENT; - } - - KvStoreType kvStoreTypeInOptions = options.kvStoreType; - if (kvStoreTypeInOptions != KvStoreType::DEVICE_COLLABORATION && kvStoreTypeInOptions != kvStoreType) { - ZLOGE("invalid kvStore type."); - 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."); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - return Status::INVALID_ARGUMENT; - } - - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGW("appId empty(permission issues?)"); - return Status::PERMISSION_DENIED; + sptr store; + status = (it->second).GetKvStore(options, param.bundleName, param.storeId, uid, keyPara.secretKey, store); + if (keyPara.outdated) { + KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, + KvStoreAppManager::ConvertPathType(param.uid, param.bundleName, options.securityLevel), store); } - - 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; + if (status == Status::SUCCESS) { + callback(std::move(store)); + return UpdateMetaData(options, param, keyPara.metaKey, it->second); } - GetKvStorePara KvStorePara; - KvStorePara.bundleName = bundleName; - KvStorePara.storeId = storeIdTmp; - KvStorePara.trueAppId = trueAppId; - KvStorePara.deviceAccountId = deviceAccountId; - getKvStorePara = KvStorePara; - - return Status::SUCCESS; + param.status = status; + param.status = GetSingleKvStoreFailDo(options, param, keyPara, it->second, store); + callback(std::move(store)); + return param.status; } -Status KvStoreDataService::GetSecretKey(const Options &options, const GetKvStorePara &kvParas, +Status KvStoreDataService::GetSecretKey(const Options &options, const KvStoreParam &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); + auto metaKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp); if (!CheckOptions(options, metaKey)) { ZLOGE("encrypt type or kvStore type is not the same"); return Status::INVALID_ARGUMENT; @@ -327,15 +276,14 @@ Status KvStoreDataService::GetSecretKey(const Options &options, const GetKvStore std::vector metaSecretKey; std::string secretKeyFile; - if (kvParas.funType == KvStoreType::MULTI_VERSION) { - metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp, "KEY"); - secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( - deviceAccountId, bundleName, storeIdTmp, options.securityLevel); + if (options.kvStoreType == KvStoreType::MULTI_VERSION) { + metaSecretKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp, "KEY"); + secretKeyFile = KvStoreMetaManager::GetSecretKeyFile(kvParas.userId, bundleName, storeIdTmp, + KvStoreAppManager::ConvertPathType(kvParas.uid, bundleName, options.securityLevel)); } else { - metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, - storeIdTmp, "SINGLE_KEY"); - secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile( - deviceAccountId, bundleName, storeIdTmp, options.securityLevel); + metaSecretKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); + secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile(kvParas.userId, bundleName, storeIdTmp, + KvStoreAppManager::ConvertPathType(kvParas.uid, bundleName, options.securityLevel)); } bool outdated = false; @@ -373,7 +321,7 @@ Status KvStoreDataService::RecoverSecretKey(const Status &alreadyCreated, bool & secretKeyFile, metaSecretKey, secretKey, outdated); if (secretKey.empty()) { ZLOGI("new secret key"); - CryptoUtils::GetRandomKey(32, secretKey); // 32 is key length + secretKey = Crypto::Random(32); // 32 is key length KvStoreMetaManager::GetInstance().WriteSecretKeyToMeta(metaSecretKey, secretKey); KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); } @@ -393,14 +341,14 @@ Status KvStoreDataService::RecoverSecretKey(const Status &alreadyCreated, bool & return Status::SUCCESS; } -Status KvStoreDataService::UpdateMetaData(const Options &options, const GetKvStorePara &kvParas, +Status KvStoreDataService::UpdateMetaData(const Options &options, const KvStoreParam &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.deviceAccountId = kvParas.userId; metaData.deviceId = DeviceKvStoreImpl::GetLocalDeviceId(); metaData.isAutoSync = options.autoSync; metaData.isBackup = options.backup; @@ -408,117 +356,103 @@ Status KvStoreDataService::UpdateMetaData(const Options &options, const GetKvSto metaData.kvStoreType = options.kvStoreType; metaData.schema = options.schema; metaData.storeId = kvParas.storeId; - metaData.userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(kvParas.bundleName); + metaData.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(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); - } + 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 KvStoreDataService::GetKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &store) { - Status statusTmp = kvParas.getKvStoreStatus; + Status statusTmp = kvParas.status; Status getKvStoreStatus = statusTmp; + int32_t path = KvStoreAppManager::ConvertPathType(kvParas.uid, kvParas.bundleName, options.securityLevel); 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); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.uid, kvParas.bundleName, kvParas.storeId); return Status::ERROR; } // 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); + store = nullptr; return Status::CRYPT_ERROR; } // 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); - }); + statusTmp = kvUserManager.GetKvStore( + options, kvParas.bundleName, kvParas.storeId, kvParas.uid, secKeyParas.secretKey, store); + if (secKeyParas.outdated) { + KvStoreMetaManager::GetInstance().ReKey(kvParas.userId, kvParas.bundleName, kvParas.storeId, path, 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(kvParas.deviceAccountId, kvParas.bundleName, kvParas.storeId, - options.securityLevel)) { + if (!CheckBackupFileExist(kvParas.userId, kvParas.bundleName, kvParas.storeId, path)) { return Status::CRYPT_ERROR; } // remove damaged database - if (DeleteKvStoreOnly(kvParas.storeId, kvParas.deviceAccountId, kvParas.bundleName) != Status::SUCCESS) { + if (DeleteKvStoreOnly(kvParas.storeId, kvParas.userId, kvParas.bundleName) != Status::SUCCESS) { ZLOGE("DeleteKvStoreOnly failed."); return Status::DB_ERROR; } // recover database - return RecoverMultiKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, callback); + return RecoverKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, store); } 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 KvStoreParam &kvParas, + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &kvStore) { - Status statusTmp = kvParas.getKvStoreStatus; + Status statusTmp = kvParas.status; Status getKvStoreStatus = statusTmp; + int32_t path = KvStoreAppManager::ConvertPathType(kvParas.uid, kvParas.bundleName, options.securityLevel); 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); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.uid, kvParas.bundleName, kvParas.storeId); return Status::ERROR; } // 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); + kvStore = nullptr; return Status::CRYPT_ERROR; } // here callback is called twice - 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); - }); + statusTmp = kvUserManager.GetKvStore( + options, kvParas.bundleName, kvParas.storeId, kvParas.uid, secKeyParas.secretKey, kvStore); + if (secKeyParas.outdated) { + KvStoreMetaManager::GetInstance().ReKey(kvParas.userId, kvParas.bundleName, kvParas.storeId, path, kvStore); + } } // 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.userId, kvParas.bundleName, kvParas.storeId, path)) { return Status::CRYPT_ERROR; } // remove damaged database - if (DeleteKvStoreOnly(kvParas.storeId, kvParas.deviceAccountId, kvParas.bundleName) != Status::SUCCESS) { + if (DeleteKvStoreOnly(kvParas.storeId, kvParas.userId, kvParas.bundleName) != Status::SUCCESS) { ZLOGE("DeleteKvStoreOnly failed."); return Status::DB_ERROR; } // recover database - return RecoverSingleKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, callback); + return RecoverKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, kvStore); } return statusTmp; } @@ -553,14 +487,13 @@ bool KvStoreDataService::CheckOptions(const Options &options, const std::vector< return true; } -bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId, const std::string &bundleName, - const std::string &storeId, int securityLevel) +bool KvStoreDataService::CheckBackupFileExist(const std::string &userId, const std::string &bundleName, + const std::string &storeId, int pathType) { - auto pathType = KvStoreAppManager::ConvertPathType(bundleName, securityLevel); std::initializer_list backupFileNameList = {Constant::DEFAULT_GROUP_ID, "_", bundleName, "_", storeId}; auto backupFileName = Constant::Concatenate(backupFileNameList); - std::initializer_list backFileList = {BackupHandler::GetBackupPath(deviceAccountId, pathType), + std::initializer_list backFileList = {BackupHandler::GetBackupPath(userId, pathType), "/", BackupHandler::GetHashedBackupName(backupFileName)}; auto backFilePath = Constant::Concatenate(backFileList); if (!BackupHandler::FileExists(backFilePath)) { @@ -569,20 +502,16 @@ bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId } return true; } - -Status KvStoreDataService::RecoverSingleKvStore(const Options &options, - const std::string &bundleName, - const std::string &storeId, - const std::vector &secretKey, - std::function)> callback) +template +Status KvStoreDataService::RecoverKvStore(const Options &options, const std::string &bundleName, + const std::string &storeId, const std::vector &secretKey, sptr &kvStore) { // restore database std::string storeIdTmp = storeId; - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); Options optionsTmp = options; optionsTmp.createIfMissing = true; - const int32_t uid = IPCSkeleton::GetCallingUid(); + std::string trueAppId = CheckerManager::GetInstance().GetAppId(bundleName, uid); const std::string deviceAccountId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); auto it = deviceAccountMap_.find(deviceAccountId); if (it == deviceAccountMap_.end()) { @@ -590,19 +519,14 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, return Status::INVALID_ARGUMENT; } - sptr kvStorePtr; - Status statusTmp = (it->second).GetSingleKvStore( - optionsTmp, bundleName, storeIdTmp, secretKey, - [&kvStorePtr](sptr store) { kvStorePtr = store; }); + Status statusTmp = (it->second).GetKvStore(optionsTmp, bundleName, storeIdTmp, uid, secretKey, kvStore); // restore database failed - if (statusTmp != Status::SUCCESS || kvStorePtr == nullptr) { + if (statusTmp != Status::SUCCESS || kvStore == nullptr) { ZLOGE("RecoverSingleKvStore reget GetSingleKvStore failed."); return Status::DB_ERROR; } // recover database from backup file - auto kvStorePtrTmp = static_cast(kvStorePtr.GetRefPtr()); - bool importRet = kvStorePtrTmp->Import(bundleName); - callback(kvStorePtr); + bool importRet = kvStore->Import(bundleName); if (!importRet) { ZLOGE("RecoverSingleKvStore Import failed."); return Status::RECOVER_FAILED; @@ -611,49 +535,6 @@ Status KvStoreDataService::RecoverSingleKvStore(const Options &options, return Status::RECOVER_SUCCESS; } -Status KvStoreDataService::RecoverMultiKvStore(const Options &options, - const std::string &bundleName, - const std::string &storeId, - const std::vector &secretKey, - std::function)> callback) -{ - // restore database - 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"); - return Status::INVALID_ARGUMENT; - } - - sptr kvStorePtr; - Status statusTmp = (it->second).GetKvStore( - optionsTmp, bundleName, storeIdTmp, secretKey, - [&kvStorePtr](sptr store) { - kvStorePtr = store; - }); - // restore database failed - if (statusTmp != Status::SUCCESS || kvStorePtr == nullptr) { - ZLOGE("RecoverMultiKvStore reget GetSingleKvStore failed."); - return Status::DB_ERROR; - } - - // recover database from backup file - auto kvStorePtrTmp = static_cast(kvStorePtr.GetRefPtr()); - if (!kvStorePtrTmp->Import(bundleName)) { - ZLOGE("RecoverMultiKvStore Import failed."); - return Status::RECOVER_FAILED; - } - ZLOGD("RecoverMultiKvStore Import success."); - callback(kvStorePtr); - return Status::RECOVER_SUCCESS; -} - void KvStoreDataService::GetAllKvStoreId( const AppId &appId, std::function &)> callback) { @@ -675,15 +556,11 @@ void KvStoreDataService::GetAllKvStoreId( } 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; - } + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); std::vector dbEntries; DistributedDB::DBStatus dbStatus; DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor(DeviceKvStoreImpl::GetLocalDeviceId() + - Constant::KEY_SEPARATOR + deviceAccountId + Constant::KEY_SEPARATOR + + Constant::KEY_SEPARATOR + userId + Constant::KEY_SEPARATOR + "default" + Constant::KEY_SEPARATOR + bundleName + Constant::KEY_SEPARATOR); DdsTrace traceDelegate(std::string(LOG_TAG "Delegate::") + std::string(__FUNCTION__)); dbStatus = metaKvStoreDelegate->GetEntries(dbKey, dbEntries); @@ -714,33 +591,22 @@ Status KvStoreDataService::CloseKvStore(const AppId &appId, const StoreId &store { 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)) { + if (!appId.IsValid() || !storeId.IsValid()) { ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - return Status::INVALID_ARGUMENT; - } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); + const int32_t uid = IPCSkeleton::GetCallingUid(); + std::string trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); 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; - } + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); std::lock_guard lg(accountMutex_); - auto it = deviceAccountMap_.find(deviceAccountId); + auto it = deviceAccountMap_.find(userId); if (it != deviceAccountMap_.end()) { - Status status = (it->second).CloseKvStore(bundleName, storeIdTmp); + Status status = (it->second).CloseKvStore(appId.appId, storeId.storeId); if (status != Status::STORE_NOT_OPEN) { return status; } @@ -756,28 +622,22 @@ Status KvStoreDataService::CloseAllKvStore(const AppId &appId) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGD("begin."); - std::string bundleName = Constant::TrimCopy(appId.appId); - if (!CheckBundleName(bundleName)) { + if (!appId.IsValid()) { ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); + const int32_t uid = IPCSkeleton::GetCallingUid(); + std::string trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, uid); 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; - } + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); std::lock_guard lg(accountMutex_); - auto it = deviceAccountMap_.find(deviceAccountId); + auto it = deviceAccountMap_.find(userId); if (it != deviceAccountMap_.end()) { - return (it->second).CloseAllKvStore(bundleName); + return (it->second).CloseAllKvStore(appId.appId); } ZLOGE("store not open."); return Status::STORE_NOT_OPEN; @@ -786,58 +646,52 @@ 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)) { + if (!appId.IsValid()) { ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { + int32_t uid = IPCSkeleton::GetCallingUid(); + if (CheckerManager::GetInstance().IsValid(appId.appId, uid)) { ZLOGE("get appId failed."); return Status::PERMISSION_DENIED; } + // delete the backup file std::initializer_list backFileList = { - AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), "_", bundleName, "_", storeId.storeId}; + AccountDelegate::GetInstance()->GetCurrentAccountId(), "_", appId.appId, "_", storeId.storeId}; auto backupFileName = Constant::Concatenate(backFileList); - - 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::initializer_list backPathListDE = {BackupHandler::GetBackupPath(deviceAccountId, + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + std::initializer_list backPathListDE = {BackupHandler::GetBackupPath(userId, KvStoreAppManager::PATH_DE), "/", BackupHandler::GetHashedBackupName(backupFileName)}; auto backFilePath = Constant::Concatenate(backPathListDE); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } - std::initializer_list backPathListCE = {BackupHandler::GetBackupPath(deviceAccountId, + std::initializer_list backPathListCE = {BackupHandler::GetBackupPath(userId, KvStoreAppManager::PATH_CE), "/", BackupHandler::GetHashedBackupName(backupFileName)}; backFilePath = Constant::Concatenate(backPathListCE); if (!BackupHandler::RemoveFile(backFilePath)) { ZLOGE("DeleteKvStore RemoveFile backFilePath failed."); } - return DeleteKvStore(appId, storeId, bundleName); + return DeleteKvStore(appId.appId, storeId); } /* delete all kv store */ Status KvStoreDataService::DeleteAllKvStore(const AppId &appId) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - ZLOGI("%s", appId.appId.c_str()); - std::string bundleName = Constant::TrimCopy(appId.appId); - if (!CheckBundleName(bundleName)) { + if (!appId.IsValid()) { ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - if (KvStoreUtils::GetAppIdByBundleName(bundleName).empty()) { - ZLOGE("invalid appId."); + + int32_t uid = IPCSkeleton::GetCallingUid(); + if (CheckerManager::GetInstance().IsValid(appId.appId, uid)) { + ZLOGE("get appId failed."); return Status::PERMISSION_DENIED; } + Status statusTmp; std::vector existStoreIds; GetAllKvStoreId(appId, [&statusTmp, &existStoreIds](Status status, std::vector &storeIds) { @@ -846,14 +700,14 @@ Status KvStoreDataService::DeleteAllKvStore(const AppId &appId) }); if (statusTmp != Status::SUCCESS) { - ZLOGE("%s, error: %d ", bundleName.c_str(), static_cast(statusTmp)); + ZLOGE("%s, error: %d ", appId.appId.c_str(), static_cast(statusTmp)); return statusTmp; } for (const auto &storeId : existStoreIds) { statusTmp = DeleteKvStore(appId, storeId); if (statusTmp != Status::SUCCESS) { - ZLOGE("%s, error: %d ", bundleName.c_str(), static_cast(statusTmp)); + ZLOGE("%s, error: %d ", appId.appId.c_str(), static_cast(statusTmp)); return statusTmp; } } @@ -866,26 +720,28 @@ Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr< { ZLOGD("begin."); KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); - std::string bundleName = Constant::TrimCopy(appId.appId); - if (!CheckBundleName(bundleName)) { + if (!appId.IsValid()) { ZLOGE("invalid bundleName."); return Status::INVALID_ARGUMENT; } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { + + int32_t uid = IPCSkeleton::GetCallingUid(); + if (CheckerManager::GetInstance().IsValid(appId.appId, uid)) { + ZLOGE("no permission bundleName:%{public}s, uid:%{public}d.", appId.appId.c_str(), uid); return Status::PERMISSION_DENIED; } + std::lock_guard lg(clientDeathObserverMutex_); - auto it = clientDeathObserverMap_.emplace(std::piecewise_construct, std::forward_as_tuple(bundleName), + auto it = clientDeathObserverMap_.emplace(std::piecewise_construct, std::forward_as_tuple(appId.appId), std::forward_as_tuple(appId, *this, std::move(observer))); - ZLOGI("map size: %zu.", clientDeathObserverMap_.size()); + ZLOGI("map size: %{public}zu.", clientDeathObserverMap_.size()); if (!it.second) { ZLOGI("insert failed"); return Status::ERROR; } ZLOGI("insert success"); - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); - KvStoreTuple kvStoreTuple {userId, trueAppId}; + const std::string userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); + KvStoreTuple kvStoreTuple {userId, CheckerManager::GetInstance().GetAppId(appId.appId, uid)}; AppThreadInfo appThreadInfo {IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()}; PermissionValidator::RegisterPermissionChanged(kvStoreTuple, appThreadInfo); return Status::SUCCESS; @@ -903,12 +759,12 @@ Status KvStoreDataService::AppExit(const AppId &appId) ZLOGI("map size: %zu.", clientDeathObserverMap_.size()); } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(appIdTmp.appId); + std::string trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, CheckerManager::INVALID_UID); if (trueAppId.empty()) { ZLOGE("get appid for KvStore failed because of permission denied."); return Status::PERMISSION_DENIED; } - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appIdTmp.appId); + const std::string userId = AccountDelegate::GetInstance()->GetCurrentAccountId(appIdTmp.appId); KvStoreTuple kvStoreTuple {userId, trueAppId}; PermissionValidator::UnregisterPermissionChanged(kvStoreTuple); @@ -931,43 +787,40 @@ int KvStoreDataService::Dump(int fd, const std::vector &args) dprintf(fd, "------------------------------------------------------------------\n"); dprintf(fd, "DeviceAccount count : %u\n", static_cast(deviceAccountMap_.size())); for (const auto &pair : deviceAccountMap_) { - dprintf(fd, "DeviceAccountID : %s\n", KvStoreUtils::GetAppIdByBundleName(pair.first).c_str()); + dprintf(fd, "DeviceAccountID : %s\n", pair.first.c_str()); pair.second.Dump(fd); } return 0; } -const std::string PKGNAME = "ohos.distributeddata"; -const std::string APP_DATASYNC_PERMISSION = "ohos.permission.DISTRIBUTED_DATASYNC"; -const std::string LABEL = "distributeddata"; -const std::string DESCRIPTION = "distributeddata service"; -const int LABEL_ID = 9527; -const int DESCRIPTION_ID = 9528; - void KvStoreDataService::AddPermission() const { - std::vector permissionDefs { - { - .permissionName = APP_DATASYNC_PERMISSION, - .bundleName = PKGNAME, - .grantMode = GrantMode::SYSTEM_GRANT, - .availableScope = AVAILABLE_SCOPE_ALL, - .label = LABEL, - .labelId = LABEL_ID, - .description = DESCRIPTION, - .descriptionId = DESCRIPTION_ID - } + const PermissionDef permission { + .permissionName = "ohos.permission.DISTRIBUTED_DATASYNC", + .bundleName = "ohos.distributeddata", + .grantMode = GrantMode::SYSTEM_GRANT, + .availableScope = AVAILABLE_SCOPE_ALL, + .label = "distributeddata", + .labelId = 9527, + .description = "distributeddata service", + .descriptionId = 9528 }; - PermissionKit::AddDefPermissions(permissionDefs); + const std::vector permissionDefs{ permission }; + PermissionKit::AddDefPermissions({ permission }); std::vector permissions; - permissions.push_back(APP_DATASYNC_PERMISSION); - PermissionKit::AddSystemGrantedReqPermissions(PKGNAME, permissions); - PermissionKit::GrantSystemGrantedPermission(PKGNAME, APP_DATASYNC_PERMISSION); + permissions.push_back(permission.permissionName); + PermissionKit::AddSystemGrantedReqPermissions(permission.bundleName, permissions); + PermissionKit::GrantSystemGrantedPermission(permission.bundleName, permission.permissionName); } void KvStoreDataService::OnStart() { ZLOGI("distributeddata service onStart"); + Initialize(); + Bootstrap::GetInstance().LoadComponents(); + Bootstrap::GetInstance().LoadDirectory(); + Bootstrap::GetInstance().LoadCheckers(); + Bootstrap::GetInstance().LoadNetworks(); auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (samgr != nullptr) { ZLOGI("samgr exist."); @@ -991,12 +844,12 @@ void KvStoreDataService::StartService() Reporter::GetInstance()->ServiceFault()->Report(msg); } Uninstaller::GetInstance().Init(this); - +#ifndef UT_TEST // add softbus permission. AddPermission(); - - std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, - KvStoreAppManager::PATH_DE); +#endif + std::string backupPath = BackupHandler::GetBackupPath( + AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(getuid()), KvStoreAppManager::PATH_DE); ZLOGI("backupPath is : %s ", backupPath.c_str()); if (!ForceCreateDirectory(backupPath)) { ZLOGE("backup create directory failed"); @@ -1024,7 +877,7 @@ void KvStoreDataService::StartService() ZLOGD("checking sync permission start appid:%s, stid:%s.", appId.c_str(), storeId.c_str()); return CheckPermissions(userId, appId, storeId, deviceId, flag); }; - auto dbStatus = DistributedDB::KvStoreDelegateManager::SetPermissionCheckCallback(permissionCheckCallback); + auto dbStatus = KvStoreDelegateManager::SetPermissionCheckCallback(permissionCheckCallback); if (dbStatus != DistributedDB::DBStatus::OK) { ZLOGE("SetPermissionCheck callback failed."); } @@ -1034,7 +887,7 @@ void KvStoreDataService::StartService() ResolveAutoLaunchParamByIdentifier(identifier, param); return true; }; - DistributedDB::KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); + KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); backup_ = std::make_unique(this); backup_->BackSchedule(); @@ -1054,9 +907,9 @@ void KvStoreDataService::ResolveAutoLaunchParamByIdentifier(const std::string &i std::map entries; if (KvStoreMetaManager::GetInstance().GetFullMetaData(entries)) { for (const auto &entry : entries) { - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId( + const std::string userId = AccountDelegate::GetInstance()->GetCurrentAccountId( entry.second.kvStoreMetaData.bundleName); - const std::string &curIdentifier = DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier(userId, + const std::string &curIdentifier = KvStoreDelegateManager::GetKvStoreIdentifier(userId, entry.second.kvStoreMetaData.appId, entry.second.kvStoreMetaData.storeId); if (identifier == curIdentifier) { ZLOGI("identifier find"); @@ -1180,58 +1033,49 @@ void KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient:: kvStoreClientDeathObserverImpl_.NotifyClientDie(); } -Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &storeId, const std::string &trueAppId) +Status KvStoreDataService::DeleteKvStore(const std::string &bundleName, const StoreId &storeId) { 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."); + if (!storeId.IsValid()) { + ZLOGE("invalid storeId."); return Status::INVALID_ARGUMENT; } + 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; - } + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); std::lock_guard lg(accountMutex_); Status status; - auto it = deviceAccountMap_.find(deviceAccountId); + auto it = deviceAccountMap_.find(userId); if (it != deviceAccountMap_.end()) { - status = (it->second).DeleteKvStore(trueAppId, storeIdTmp); + status = (it->second).DeleteKvStore(bundleName, storeId.storeId); } else { - KvStoreUserManager kvStoreUserManager(deviceAccountId); - status = kvStoreUserManager.DeleteKvStore(trueAppId, storeIdTmp); + KvStoreUserManager kvStoreUserManager(userId); + status = kvStoreUserManager.DeleteKvStore(bundleName, storeId.storeId); } if (status == Status::SUCCESS) { - auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); + auto metaKey = KvStoreMetaManager::GetMetaKey(userId, "default", bundleName, storeId.storeId); status = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, DELETE); if (status != Status::SUCCESS) { ZLOGW("Remove Kvstore Metakey failed."); } - KvStoreMetaManager::GetInstance().RemoveSecretKey(deviceAccountId, bundleName, storeIdTmp); - KvStoreMetaManager::GetInstance().DeleteStrategyMeta(bundleName, storeIdTmp); + KvStoreMetaManager::GetInstance().RemoveSecretKey(uid, bundleName, storeId.storeId); + KvStoreMetaManager::GetInstance().DeleteStrategyMeta(bundleName, storeId.storeId, userId); } return status; } -Status KvStoreDataService::DeleteKvStoreOnly(const std::string &storeIdTmp, const std::string &deviceAccountId, +Status KvStoreDataService::DeleteKvStoreOnly(const std::string &storeId, const std::string &userId, const std::string &bundleName) { ZLOGI("DeleteKvStoreOnly begin."); - auto it = deviceAccountMap_.find(deviceAccountId); + auto it = deviceAccountMap_.find(userId); if (it != deviceAccountMap_.end()) { - return (it->second).DeleteKvStore(bundleName, storeIdTmp); + return (it->second).DeleteKvStore(bundleName, storeId); } - KvStoreUserManager kvStoreUserManager(deviceAccountId); - return kvStoreUserManager.DeleteKvStore(bundleName, storeIdTmp); + KvStoreUserManager kvStoreUserManager(userId); + return kvStoreUserManager.DeleteKvStore(bundleName, storeId); } void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index 536fc2a6ea39e83c46fabd15427bdef28b7aebec..6d73fe6667ec4316f13372501f19c985a7226d9e 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -81,31 +81,20 @@ public: void OnStop() override; - Status DeleteKvStore(const AppId &appId, const StoreId &storeId, const std::string &trueAppId); - - Status DeleteKvStoreOnly(const std::string &storeIdTmp, const std::string &deviceAccountId, - const std::string &bundleName); + Status DeleteKvStoreOnly(const std::string &storeId, const std::string &userId, const std::string &bundleName); void AccountEventChanged(const AccountEventInfo &eventInfo); - bool CheckBackupFileExist(const std::string &deviceAccountId, const std::string &bundleName, - const std::string &storeId, int securityLevel); - - Status RecoverSingleKvStore(const Options &options, const std::string &bundleName, - const std::string &storeId, const std::vector &secretKey, - std::function)> callback); + bool CheckBackupFileExist(const std::string &userId, const std::string &bundleName, + const std::string &storeId, int pathType); - Status RecoverMultiKvStore(const Options &options, const std::string &bundleName, - const std::string &storeId, const std::vector &secretKey, - std::function)> callback); - - struct GetKvStorePara { + struct KvStoreParam { std::string bundleName; std::string storeId; std::string trueAppId; - std::string deviceAccountId; - Status getKvStoreStatus = Status::SUCCESS; - KvStoreType funType = KvStoreType::MULTI_VERSION; + std::string userId; + pid_t uid; + Status status = Status::SUCCESS; }; struct SecretKeyPara { std::vector metaKey; @@ -145,22 +134,24 @@ private: void StartService(); - Status CheckParameters(const Options &options, const AppId &appId, const StoreId &storeId, - const KvStoreType &kvStoreType, GetKvStorePara &getKvStorePara); + Status DeleteKvStore(const std::string &bundleName, const StoreId &storeId); - Status GetSecretKey(const Options &options, const GetKvStorePara &KvParas, SecretKeyPara &secretKeyParas); + template + Status RecoverKvStore(const Options &options, const std::string &bundleName, const std::string &storeId, + const std::vector &secretKey, sptr &kvStore); + Status GetSecretKey(const Options &options, const KvStoreParam &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, + Status UpdateMetaData(const Options &options, const KvStoreParam &kvParas, const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager); - Status GetKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, std::function)> callback); + Status GetKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, SecretKeyPara &secKeyParas, + KvStoreUserManager &kvUserManager, sptr &kvStore); - Status GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, std::function)> callback); + Status GetSingleKvStoreFailDo(const Options &options, const KvStoreParam &kvParas, SecretKeyPara &secKeyParas, + KvStoreUserManager &kvUserManager, sptr &kvStore); Status AppExit(const AppId &appId); diff --git a/services/distributeddataservice/app/src/kvstore_impl.cpp b/services/distributeddataservice/app/src/kvstore_impl.cpp index 6b8acbafc63fcd94df9a1b2f45e5118812b7be21..19a002fe4bf285add6a637b6d86c355af192b635 100755 --- a/services/distributeddataservice/app/src/kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/kvstore_impl.cpp @@ -20,6 +20,7 @@ #include #include #include "backup_handler.h" +#include "checker/checker_manager.h" #include "constant.h" #include "dds_trace.h" #include "kvstore_account_observer.h" @@ -32,22 +33,21 @@ namespace OHOS { namespace DistributedKv { -KvStoreImpl::KvStoreImpl(const Options &options, - const std::string &deviceAccountId, const std::string &bundleName, const std::string &storeId, - const std::string &appDirectory, DistributedDB::KvStoreDelegate *kvStoreDelegate) - : options_(options), - deviceAccountId_(deviceAccountId), - bundleName_(bundleName), - storeId_(storeId), - storePath_(Constant::Concatenate({ appDirectory, storeId })), - kvStoreDelegate_(kvStoreDelegate), - storeObserverMutex_(), - observerSet_(), - openCount_(1) +KvStoreImpl::KvStoreImpl(const Options &options, const std::string &userId, const std::string &bundleName, + const std::string &appId, const std::string &storeId, const std::string &directory, + DistributedDB::KvStoreDelegate *delegate) + : options_(options), deviceAccountId_(userId), bundleName_(bundleName), storeId_(storeId), appId_(appId), + storePath_(Constant::Concatenate({ directory, storeId })), kvStoreDelegate_(delegate), storeObserverMutex_(), + observerSet_(), openCount_(1) { ZLOGI("construct"); } +std::string KvStoreImpl::GetStoreId() +{ + return storeId_; +} + void KvStoreImpl::GetKvStoreSnapshot(sptr observer, std::function)> callback) { @@ -517,12 +517,11 @@ Status KvStoreImpl::MigrateKvStore(const std::string &harmonyAccountId, return status; } if (newDelegateMgr == nullptr) { - auto appId = KvStoreUtils::GetAppIdByBundleName(bundleName_); - if (appId.empty()) { + if (appId_.empty()) { ZLOGE("Get appId by bundle name failed."); return Status::MIGRATION_KVSTORE_FAILED; } - newDelegateMgr = new (std::nothrow) DistributedDB::KvStoreDelegateManager(appId, harmonyAccountId); + newDelegateMgr = new (std::nothrow) DistributedDB::KvStoreDelegateManager(appId_, harmonyAccountId); if (newDelegateMgr == nullptr) { ZLOGE("new KvStoreDelegateManager failed."); return Status::MIGRATION_KVSTORE_FAILED; @@ -778,19 +777,18 @@ KvStoreImpl::~KvStoreImpl() bool KvStoreImpl::Import(const std::string &bundleName) const { ZLOGI("KvStoreImpl Import start"); - const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); auto metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId_, harmonyAccountId, bundleName, storeId_, "KEY"); std::vector secretKey; bool outdated = false; - auto trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(metaSecretKey, secretKey, outdated); MetaData metaData{0}; metaData.kvStoreMetaData.deviceAccountId = deviceAccountId_; metaData.kvStoreMetaData.userId = harmonyAccountId; metaData.kvStoreMetaData.bundleName = bundleName; - metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.appId = appId_; metaData.kvStoreMetaData.storeId = storeId_; metaData.kvStoreMetaData.securityLevel = options_.securityLevel; metaData.secretKeyMetaData.secretKey = secretKey; diff --git a/services/distributeddataservice/app/src/kvstore_impl.h b/services/distributeddataservice/app/src/kvstore_impl.h index daf5eedb18e6f19844de7b3a90ae5dc9b54142e1..d399045e9a86404957222fc685522de012bd7069 100755 --- a/services/distributeddataservice/app/src/kvstore_impl.h +++ b/services/distributeddataservice/app/src/kvstore_impl.h @@ -50,9 +50,11 @@ struct KvStoreObserverImplPtrCompare { class KvStoreImpl : public KvStoreImplStub { public: - KvStoreImpl(const Options &options, const std::string &deviceAccountId, - const std::string &bundleName, const std::string &storeId, - const std::string &appDirectory, DistributedDB::KvStoreDelegate *kvStoreDelegate); + KvStoreImpl(const Options &options, const std::string &userId, const std::string &bundleName, + const std::string &appId, const std::string &storeId, const std::string &directory, + DistributedDB::KvStoreDelegate *delegate); + + std::string GetStoreId(); void GetKvStoreSnapshot(sptr observer, std::function)> callback) override; @@ -116,6 +118,8 @@ private: // kvstore name. const std::string storeId_; + const std::string appId_; + // kvstore absolute path in distributeddatamgr. const std::string storePath_; diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp index f23caee5782d3a1dc159d12e271c102140902885..9a41816b80726551f84bf9b806df53a5818e30ac 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -22,22 +22,24 @@ #include #include #include "security_adapter.h" - +#include "hks_api.h" +#include "hks_param.h" #include "account_delegate.h" #include "constant.h" #include "kvstore_utils.h" -#include "crypto_utils.h" #include "device_kvstore_impl.h" #include "kvstore_data_service.h" #include "log_print.h" #include "reporter.h" #include "directory_utils.h" #include "kvstore_app_manager.h" +#include "utils/crypto.h" namespace OHOS { namespace DistributedKv { using json = nlohmann::json; using namespace std::chrono; +using namespace OHOS::DistributedData; // APPID: distributeddata // USERID: default @@ -96,15 +98,15 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("get meta failed."); return; } - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); - auto metaKey = GetMetaKey(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, "default", META_DB_APP_ID, - Constant::SERVICE_META_DB_NAME); + const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(getuid()); + auto metaKey = GetMetaKey(userId, "default", META_DB_APP_ID, Constant::SERVICE_META_DB_NAME); struct KvStoreMetaData metaData { .appId = META_DB_APP_ID, .appType = "default", .bundleName = META_DB_APP_ID, .dataDir = "default", - .deviceAccountId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, + .deviceAccountId = userId, .deviceId = DeviceKvStoreImpl::GetLocalDeviceId(), .isAutoSync = false, .isBackup = false, @@ -112,7 +114,7 @@ void KvStoreMetaManager::InitMetaData() .kvStoreType = KvStoreType::SINGLE_VERSION, .schema = "", .storeId = Constant::SERVICE_META_DB_NAME, - .userId = userId, + .userId = accountId, .uid = -1, .version = KvStoreDataService::KVSTORE_META_VERSION, .securityLevel = SecurityLevel::NO_LABEL, @@ -128,7 +130,6 @@ void KvStoreMetaManager::InitMetaData() void KvStoreMetaManager::InitMetaParameter() { ZLOGI("start."); - bool ret = ForceCreateDirectory(metaDBDirectory_); if (!ret) { FaultMsg msg = {FaultType::SERVICE_FAULT, "user", __FUNCTION__, Fault::SF_CREATE_DIR}; @@ -218,8 +219,8 @@ std::vector KvStoreMetaManager::GetMetaKey(const std::string &deviceAcc return SecretMetaRow::GetKeyFor(originKey); } -std::string KvStoreMetaManager::GetSecretKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId, int securityLevel) +std::string KvStoreMetaManager::GetSecretKeyFile(const std::string &userId, const std::string &appId, + const std::string &storeId, int pathType) { std::string hashedStoreId; DistributedDB::DBStatus result = DistributedDB::KvStoreDelegateManager::GetDatabaseDir(storeId, hashedStoreId); @@ -227,15 +228,13 @@ std::string KvStoreMetaManager::GetSecretKeyFile(const std::string &deviceAccoun ZLOGE("get data base directory by kvstore store id failed, result = %d.", result); return ""; } - 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"; + return miscPath + "/" + Constant::SERVICE_NAME + "/" + userId + "/" + Constant::GetDefaultHarmonyAccountName() + + "/" + appId + "/" + hashedStoreId + ".mul.key"; } -std::string KvStoreMetaManager::GetSecretSingleKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId, int securityLevel) +std::string KvStoreMetaManager::GetSecretSingleKeyFile(const std::string &userId, const std::string &appId, + const std::string &storeId, int pathType) { std::string hashedStoreId; DistributedDB::DBStatus result = DistributedDB::KvStoreDelegateManager::GetDatabaseDir(storeId, hashedStoreId); @@ -243,11 +242,9 @@ std::string KvStoreMetaManager::GetSecretSingleKeyFile(const std::string &device ZLOGE("get data base directory by kvstore store id failed, result = %d.", result); return ""; } - 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"; + return miscPath + "/" + Constant::SERVICE_NAME + "/" + userId + "/" + Constant::GetDefaultHarmonyAccountName() + + "/" + appId + "/" + hashedStoreId + ".sig.key"; } Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &metaKey, FLAG flag, @@ -265,12 +262,11 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me DistributedDB::Value dbValue = val; DistributedDB::DBStatus dbStatus; DistributedDB::CipherPassword dbPassword; - const std::string deviceAccountId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; - - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); - std::initializer_list backList = {userId, "_", META_DB_APP_ID, "_", Constant::SERVICE_META_DB_NAME}; + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(getuid()); + const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); + std::initializer_list backList = {accountId, "_", META_DB_APP_ID, "_", Constant::SERVICE_META_DB_NAME}; std::string backupName = Constant::Concatenate(backList); - std::initializer_list backFullList = {BackupHandler::GetBackupPath(deviceAccountId, pathType), "/", + std::initializer_list backFullList = {BackupHandler::GetBackupPath(userId, pathType), "/", BackupHandler::GetHashedBackupName(backupName)}; auto backupFullName = Constant::Concatenate(backFullList); @@ -539,18 +535,17 @@ Status KvStoreMetaManager::WriteSecretKeyToFile(const std::string &secretKeyFile return Status::ERROR; } -Status KvStoreMetaManager::RemoveSecretKey(const std::string &deviceAccountId, const std::string &bundleName, - const std::string &storeId) +Status KvStoreMetaManager::RemoveSecretKey(pid_t uid, const std::string &bundleName, const std::string &storeId) { auto &metaDelegate = GetMetaKvStore(); if (metaDelegate == nullptr) { ZLOGE("GetMetaKvStore return nullptr."); return Status::DB_ERROR; } - + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); Status status = Status::SUCCESS; - DistributedDB::Key secretDbKey = GetMetaKey(deviceAccountId, "default", bundleName, storeId, "KEY"); - DistributedDB::Key secretSingleDbKey = GetMetaKey(deviceAccountId, "default", bundleName, storeId, "SINGLE_KEY"); + DistributedDB::Key secretDbKey = GetMetaKey(userId, "default", bundleName, storeId, "KEY"); + DistributedDB::Key secretSingleDbKey = GetMetaKey(userId, "default", bundleName, storeId, "SINGLE_KEY"); DistributedDB::DBStatus dbStatus = metaDelegate->DeleteLocal(secretDbKey); if (dbStatus != DistributedDB::DBStatus::OK) { ZLOGE("delete secretDbKey fail Status %d", static_cast(dbStatus)); @@ -562,18 +557,17 @@ Status KvStoreMetaManager::RemoveSecretKey(const std::string &deviceAccountId, c status = Status::DB_ERROR; } - int securityLevel = GetSecurityLevelByBundleName(bundleName); - 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, securityLevel); - rmFile = RemoveFile(secretKeyFile); - if (!rmFile) { - ZLOGW("remove secretKeyFile Single fail."); - status = Status::DB_ERROR; + for (int32_t pathType = KvStoreAppManager::PATH_DE; pathType < KvStoreAppManager::PATH_TYPE_MAX; ++pathType) { + std::string keyFile = GetSecretKeyFile(userId, bundleName, storeId, pathType); + if (!RemoveFile(keyFile)) { + ZLOGW("remove secret key file %{public}s fail.", keyFile.c_str()); + status = Status::DB_ERROR; + } + keyFile = GetSecretSingleKeyFile(userId, bundleName, storeId, pathType); + if (!RemoveFile(keyFile)) { + ZLOGW("remove secretKeyFile Single fail."); + status = Status::DB_ERROR; + } } return status; } @@ -650,38 +644,32 @@ Status KvStoreMetaManager::RecoverSecretKeyFromFile(const std::string &secretKey return Status::SUCCESS; } -void KvStoreMetaManager::ReKey(const std::string &deviceAccountId, const std::string &bundleName, - const std::string &storeId, sptr store) +void KvStoreMetaManager::ReKey(const std::string &userId, const std::string &bundleName, const std::string &storeId, + int32_t pathType, sptr store) { if (store == nullptr) { return; } - KvStoreImpl *kvStoreimpl = static_cast(store.GetRefPtr()); - std::vector key; - CryptoUtils::GetRandomKey(KEY_SIZE, key); - WriteSecretKeyToMeta(GetMetaKey(deviceAccountId, "default", bundleName, storeId, "KEY"), key); - Status status = kvStoreimpl->ReKey(key); + std::vector key = Crypto::Random(KEY_SIZE); + WriteSecretKeyToMeta(GetMetaKey(userId, "default", bundleName, storeId, "KEY"), key); + Status status = store->ReKey(key); if (status == Status::SUCCESS) { - int securityLevel = GetSecurityLevelByBundleName(bundleName); - WriteSecretKeyToFile(GetSecretKeyFile(deviceAccountId, bundleName, storeId, securityLevel), key); + WriteSecretKeyToFile(GetSecretKeyFile(userId, bundleName, storeId, pathType), key); } key.assign(key.size(), 0); } -void KvStoreMetaManager::ReKey(const std::string &deviceAccountId, const std::string &bundleName, - const std::string &storeId, sptr store) +void KvStoreMetaManager::ReKey(const std::string &userId, const std::string &bundleName, const std::string &storeId, + int32_t pathType, sptr store) { if (store == nullptr) { return; } - SingleKvStoreImpl *kvStoreImpl = static_cast(store.GetRefPtr()); - std::vector key; - CryptoUtils::GetRandomKey(KEY_SIZE, key); - WriteSecretKeyToMeta(GetMetaKey(deviceAccountId, "default", bundleName, storeId, "SINGLE_KEY"), key); - Status status = kvStoreImpl->ReKey(key); + std::vector key = Crypto::Random(KEY_SIZE); + WriteSecretKeyToMeta(GetMetaKey(userId, "default", bundleName, storeId, "SINGLE_KEY"), key); + Status status = store->ReKey(key); if (status == Status::SUCCESS) { - int securityLevel = GetSecurityLevelByBundleName(bundleName); - WriteSecretKeyToFile(GetSecretSingleKeyFile(deviceAccountId, bundleName, storeId, securityLevel), key); + WriteSecretKeyToFile(GetSecretSingleKeyFile(userId, bundleName, storeId, pathType), key); } key.assign(key.size(), 0); } @@ -787,7 +775,8 @@ Status KvStoreMetaManager::SaveStrategyMetaLabels(const std::string &key, return Status::SUCCESS; } -Status KvStoreMetaManager::DeleteStrategyMeta(const std::string &bundleName, const std::string &storeId) +Status KvStoreMetaManager::DeleteStrategyMeta(const std::string &bundleName, const std::string &storeId, + const std::string &userId) { ZLOGI("start"); std::string key; @@ -796,8 +785,7 @@ Status KvStoreMetaManager::DeleteStrategyMeta(const std::string &bundleName, con ZLOGE("get device id empty."); return Status::ERROR; } - std::string devAccId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; - StrategyMeta params = {devId, devAccId, Constant::DEFAULT_GROUP_ID, bundleName, storeId}; + StrategyMeta params = {devId, userId, Constant::DEFAULT_GROUP_ID, bundleName, storeId}; GetStrategyMetaKey(params, key); auto &metaDelegate = GetMetaKvStore(); @@ -858,22 +846,22 @@ void KvStoreMetaManager::SubscribeMetaKvStore() } Status KvStoreMetaManager::CheckSyncPermission(const std::string &userId, const std::string &appId, - const std::string &storeId, uint8_t flag, const std::string &deviceId) + const std::string &storeId, uint8_t flag, const std::string &remoteId) { - std::string devId = DeviceKvStoreImpl::GetLocalDeviceId(); - if (devId.empty()) { + std::string localId = DeviceKvStoreImpl::GetLocalDeviceId(); + if (localId.empty()) { ZLOGE("get device id empty."); return Status::ERROR; } - KvStoreMetaData val; - auto queryStatus = QueryKvStoreMetaDataByDeviceIdAndAppId(devId, appId, val); + KvStoreMetaData localMeta; + auto queryStatus = QueryKvStoreMetaDataByDeviceIdAndAppId(localId, appId, localMeta); if (queryStatus != Status::SUCCESS) { ZLOGE("get kvstore by deviceId and appId empty."); return Status::ERROR; } - std::string devAccId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; - StrategyMeta params = {devId, devAccId, Constant::DEFAULT_GROUP_ID, val.bundleName, storeId}; + StrategyMeta params = {localId, localMeta.deviceAccountId, Constant::DEFAULT_GROUP_ID, localMeta.bundleName, + storeId}; std::string localKey; GetStrategyMetaKey(params, localKey); if (localKey.empty()) { @@ -882,7 +870,7 @@ Status KvStoreMetaManager::CheckSyncPermission(const std::string &userId, const } std::string remoteKey; - params.devId = deviceId; + params.devId = remoteId; GetStrategyMetaKey(params, remoteKey); if (remoteKey.empty()) { ZLOGE("get key empty."); diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index 5457b814389e7c6aca2b784e80fe14c880ec2eef..a3fc0307fc11e5570bb282d5f4eedcccdf05ac2d 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -19,8 +19,6 @@ #include #include "app_device_status_change_listener.h" -#include "hks_api.h" -#include "hks_param.h" #include "types.h" #include "system_ability.h" #include "kv_store_delegate.h" @@ -138,7 +136,6 @@ private: static constexpr const char *DIRTY_KEY = "isDirty"; }; - struct MetaData { std::int32_t kvStoreType; KvStoreMetaData kvStoreMetaData; @@ -201,11 +198,11 @@ public: const std::string &deviceAccountId, const std::string &groupId, const std::string &bundleName, const std::string &storeId, const std::string &key = ""); - static std::string GetSecretKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId, int securityLevel); + static std::string GetSecretKeyFile(const std::string &userId, const std::string &appId, + const std::string &storeId, int pathType); - static std::string GetSecretSingleKeyFile(const std::string &deviceAccountId, const std::string &appId, - const std::string &storeId, int securityLevel); + static std::string GetSecretSingleKeyFile(const std::string &userId, const std::string &appId, + const std::string &storeId, int pathType); Status GetSecretKeyFromMeta(const std::vector &metaSecretKey, std::vector &key, bool &outdated); @@ -219,21 +216,21 @@ public: Status WriteSecretKeyToFile(const std::string &secretKeyFile, const std::vector &key); Status - RemoveSecretKey(const std::string &deviceAccountId, const std::string &bundleName, const std::string &storeId); + RemoveSecretKey(pid_t uid, const std::string &bundleName, const std::string &storeId); Status RecoverSecretKeyFromFile(const std::string &secretKeyFile, const std::vector &metaSecretKey, std::vector &key, bool &outdated); - void ReKey(const std::string &deviceAccountId, const std::string &bundleName, const std::string &storeId, - sptr store); + void ReKey(const std::string &userId, const std::string &bundleName, const std::string &storeId, int32_t pathType, + sptr store); - void ReKey(const std::string &deviceAccountId, const std::string &bundleName, const std::string &storeId, - sptr store); + void ReKey(const std::string &userId, const std::string &bundleName, const std::string &storeId, int32_t pathType, + sptr store); void GetStrategyMetaKey(const StrategyMeta ¶ms, std::string &retVal); - Status DeleteStrategyMeta(const std::string &bundleName, const std::string &storeId); + Status DeleteStrategyMeta(const std::string &bundleName, const std::string &storeId, const std::string &userId); Status SaveStrategyMetaEnable(const std::string &key, bool enable); @@ -242,7 +239,7 @@ public: const std::vector &remoteSupportLabels); Status CheckSyncPermission(const std::string &userId, const std::string &appId, const std::string &storeId, - uint8_t flag, const std::string &deviceId); + uint8_t flag, const std::string &remoteId); Status QueryKvStoreMetaDataByDeviceIdAndAppId(const std::string &devId, const std::string &appId, KvStoreMetaData &val); diff --git a/services/distributeddataservice/app/src/kvstore_resultset_impl.cpp b/services/distributeddataservice/app/src/kvstore_resultset_impl.cpp index 36e0bb4598c174e974d4fd7500394dfc96f7ecb6..6d474a40470f7085b452048eddc57f78550ae475 100755 --- a/services/distributeddataservice/app/src/kvstore_resultset_impl.cpp +++ b/services/distributeddataservice/app/src/kvstore_resultset_impl.cpp @@ -26,12 +26,7 @@ KvStoreResultSetImpl::~KvStoreResultSetImpl() { } -KvStoreResultSetImpl::KvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet) - : kvStoreResultSet_(resultSet) -{ -} - -KvStoreResultSetImpl::KvStoreResultSetImpl(DistributedDB::Key keyPrefix, DistributedDB::KvStoreResultSet *resultSet) +KvStoreResultSetImpl::KvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet, DistributedDB::Key keyPrefix) : keyPrefix_(std::move(keyPrefix)), kvStoreResultSet_(resultSet) { } diff --git a/services/distributeddataservice/app/src/kvstore_resultset_impl.h b/services/distributeddataservice/app/src/kvstore_resultset_impl.h index b0880f9327f545a8960680645d59ca672b7b8dc8..c0b4d101e21e424d88de3098085b7b2e8adfdbcd 100755 --- a/services/distributeddataservice/app/src/kvstore_resultset_impl.h +++ b/services/distributeddataservice/app/src/kvstore_resultset_impl.h @@ -26,8 +26,7 @@ namespace OHOS::DistributedKv { class KvStoreResultSetImpl : public KvStoreResultSetStub { public: - explicit KvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet); - KvStoreResultSetImpl(DistributedDB::Key keyPrefix, DistributedDB::KvStoreResultSet *resultSet); + explicit KvStoreResultSetImpl(DistributedDB::KvStoreResultSet *resultSet, DistributedDB::Key keyPrefix = {}); ~KvStoreResultSetImpl() override; int GetCount() override; diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.cpp b/services/distributeddataservice/app/src/kvstore_user_manager.cpp index 2374311856983798d8b8558333d7121463f49a3b..7e61eaf673e619821e4b98bd611fbaada23afec2 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_user_manager.cpp @@ -17,6 +17,7 @@ #include "kvstore_user_manager.h" #include "account_delegate.h" +#include "checker/checker_manager.h" #include "constant.h" #include "kvstore_utils.h" #include "log_print.h" @@ -24,6 +25,7 @@ namespace OHOS { namespace DistributedKv { +using namespace DistributedData; KvStoreUserManager::KvStoreUserManager(const std::string &deviceAccountId) : appMutex_(), appMap_(), @@ -38,49 +40,6 @@ KvStoreUserManager::~KvStoreUserManager() appMap_.clear(); } -Status KvStoreUserManager::GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, - const std::vector &cipherKey, - std::function)> callback) -{ - ZLOGI("begin."); - std::lock_guard lg(appMutex_); - auto it = appMap_.find(appId); - if (it != appMap_.end()) { - return (it->second).GetKvStore(options, storeId, cipherKey, callback); - } - - auto result = appMap_.emplace(std::piecewise_construct, std::forward_as_tuple(appId), - std::forward_as_tuple(appId, deviceAccountId_)); - if (result.second && result.first != appMap_.end()) { - return (result.first->second).GetKvStore(options, storeId, cipherKey, callback); - } else { - ZLOGE("emplace failed."); - callback(nullptr); - return Status::ERROR; - } -} - -Status KvStoreUserManager::GetSingleKvStore(const Options &options, const std::string &appId, - const std::string &storeId, const std::vector &cipherKey, - std::function)> callback) -{ - ZLOGI("begin."); - std::lock_guard lg(appMutex_); - auto it = appMap_.find(appId); - if (it != appMap_.end()) { - return (it->second).GetKvStore(options, storeId, cipherKey, callback); - } - auto result = appMap_.emplace(std::piecewise_construct, std::forward_as_tuple(appId), - std::forward_as_tuple(appId, deviceAccountId_)); - if (result.second && result.first != appMap_.end()) { - return (result.first->second).GetKvStore(options, storeId, cipherKey, callback); - } else { - ZLOGE("emplace failed."); - callback(nullptr); - return Status::ERROR; - } -} - Status KvStoreUserManager::CloseKvStore(const std::string &appId, const std::string &storeId) { ZLOGI("begin."); @@ -129,7 +88,7 @@ Status KvStoreUserManager::DeleteKvStore(const std::string &bundleName, const st } return status; } - KvStoreAppManager kvStoreAppManager(bundleName, deviceAccountId_); + KvStoreAppManager kvStoreAppManager(bundleName, CheckerManager::INVALID_UID); return kvStoreAppManager.DeleteKvStore(storeId); } @@ -163,6 +122,9 @@ Status KvStoreUserManager::MigrateAllKvStore(const std::string &harmonyAccountId std::string KvStoreUserManager::GetDbDir(const std::string &bundleName, const Options &options) { ZLOGI("begin."); + if (options.kvStoreType == KvStoreType::MULTI_VERSION) { + return "default"; + } std::lock_guard lg(appMutex_); auto it = appMap_.find(bundleName); if (it != appMap_.end()) { @@ -175,7 +137,7 @@ void KvStoreUserManager::Dump(int fd) const { const std::string prefix(4, ' '); dprintf(fd, "%s--------------------------------------------------------------\n", prefix.c_str()); - dprintf(fd, "%sUserID : %s\n", prefix.c_str(), KvStoreUtils::GetAppIdByBundleName(userId_).c_str()); + dprintf(fd, "%sUserID : %s\n", prefix.c_str(), userId_.c_str()); dprintf(fd, "%sApp count : %u\n", prefix.c_str(), static_cast(appMap_.size())); for (const auto &pair : appMap_) { pair.second.Dump(fd); diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.h b/services/distributeddataservice/app/src/kvstore_user_manager.h index 5ef3a1d41bd2e2508613764c12a6b63084d61d55..af22549e1f06a8c672c67b74de6e98bf6dbd7326 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.h +++ b/services/distributeddataservice/app/src/kvstore_user_manager.h @@ -24,18 +24,31 @@ namespace OHOS { namespace DistributedKv { - class KvStoreUserManager { public: explicit KvStoreUserManager(const std::string &deviceAccountId); virtual ~KvStoreUserManager(); - Status GetKvStore(const Options &options, const std::string &appId, const std::string &storeId, - const std::vector &cipherKey, std::function)> callback); - - Status GetSingleKvStore(const Options &options, const std::string &appId, const std::string &storeId, - const std::vector &cipherKey, std::function)> callback); + template + Status GetKvStore(const Options &options, const std::string &bundleName, const std::string &storeId, pid_t uid, + const std::vector &cipherKey, sptr &kvStore) + { + std::lock_guard lg(appMutex_); + auto it = appMap_.find(bundleName); + if (it == appMap_.end()) { + auto result = appMap_.emplace( + std::piecewise_construct, std::forward_as_tuple(bundleName), std::forward_as_tuple(bundleName, uid)); + if (result.second) { + it = result.first; + } + } + if (it == appMap_.end()) { + kvStore = nullptr; + return Status::ERROR; + } + return (it->second).GetKvStore(options, bundleName, storeId, cipherKey, kvStore); + } Status CloseKvStore(const std::string &appId, const std::string &storeId); @@ -59,7 +72,6 @@ private: std::string deviceAccountId_; std::string userId_; }; - } // namespace DistributedKv } // namespace OHOS diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.cpp b/services/distributeddataservice/app/src/single_kvstore_impl.cpp index c9ba96be8593aac1875e61c971aff04d56324997..4389691c4443081d60434059f36ca6b03bf57e52 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/single_kvstore_impl.cpp @@ -19,15 +19,11 @@ #include #include "account_delegate.h" #include "backup_handler.h" +#include "checker/checker_manager.h" #include "constant.h" #include "dds_trace.h" -#include "device_kvstore_resultset_impl.h" #include "device_kvstore_impl.h" -#include "device_kvstore_observer_impl.h" -#include "kvstore_app_manager.h" #include "kvstore_data_service.h" -#include "kvstore_meta_manager.h" -#include "kvstore_sync_manager.h" #include "kvstore_utils.h" #include "ipc_skeleton.h" #include "log_print.h" @@ -36,6 +32,7 @@ #include "reporter.h" namespace OHOS::DistributedKv { +using namespace OHOS::DistributedData; static bool TaskIsBackground(pid_t pid) { std::ifstream ifs("/proc/" + std::to_string(pid) + "/cgroup", std::ios::in); @@ -66,27 +63,19 @@ SingleKvStoreImpl::~SingleKvStoreImpl() ZLOGI("destructor"); } -SingleKvStoreImpl::SingleKvStoreImpl(const Options &options, const std::string &deviceAccountId, - const std::string &bundleName, const std::string &storeId, - const std::string &appDirectory, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate) - : options_(options), - deviceAccountId_(deviceAccountId), - bundleName_(bundleName), - storeId_(storeId), - storePath_(Constant::Concatenate({ appDirectory, storeId })), - kvStoreNbDelegate_(kvStoreNbDelegate), - observerMapMutex_(), - observerMap_(), - storeResultSetMutex_(), - storeResultSetMap_(), - openCount_(1), - flowCtrlManager_(BURST_CAPACITY, SUSTAINED_CAPACITY) +SingleKvStoreImpl::SingleKvStoreImpl(const Options &options, const std::string &userId, const std::string &bundleName, + const std::string &storeId, const std::string &appId, const std::string &directory, + DistributedDB::KvStoreNbDelegate *delegate) + : options_(options), deviceAccountId_(userId), bundleName_(bundleName), storeId_(storeId), appId_(appId), + storePath_(Constant::Concatenate({ directory, storeId })), kvStoreNbDelegate_(delegate), observerMapMutex_(), + observerMap_(), storeResultSetMutex_(), storeResultSetMap_(), openCount_(1), + flowCtrl_(BURST_CAPACITY, SUSTAINED_CAPACITY) { } Status SingleKvStoreImpl::Put(const Key &key, const Value &value) { - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -128,6 +117,9 @@ Status SingleKvStoreImpl::Put(const Key &key, const Value &value) Status SingleKvStoreImpl::ConvertDbStatus(DistributedDB::DBStatus status) { switch (status) { + case DistributedDB::DBStatus::BUSY: // fallthrough + case DistributedDB::DBStatus::DB_ERROR: + return Status::DB_ERROR; case DistributedDB::DBStatus::OK: return Status::SUCCESS; case DistributedDB::DBStatus::INVALID_ARGS: @@ -164,7 +156,7 @@ Status SingleKvStoreImpl::ConvertDbStatus(DistributedDB::DBStatus status) Status SingleKvStoreImpl::Delete(const Key &key) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -199,7 +191,7 @@ Status SingleKvStoreImpl::Delete(const Key &key) Status SingleKvStoreImpl::Get(const Key &key, Value &value) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -237,14 +229,8 @@ Status SingleKvStoreImpl::Get(const Key &key, Value &value) Status SingleKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sptr observer) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - return SubscribeKvStore(subscribeType, observer, false); -} - -Status SingleKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sptr observer, - bool deviceCoordinate) -{ ZLOGD("start."); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -256,8 +242,7 @@ Status SingleKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sp ZLOGE("kvstore is not open"); return Status::ILLEGAL_STATE; } - KvStoreObserverImpl *nbObserver = new (std::nothrow) DeviceKvStoreObserverImpl(subscribeType, observer, - deviceCoordinate); + KvStoreObserverImpl *nbObserver = CreateObserver(subscribeType, observer); if (nbObserver == nullptr) { ZLOGW("new KvStoreObserverNbImpl failed"); return Status::ERROR; @@ -293,6 +278,11 @@ Status SingleKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sp return Status::ERROR; } +KvStoreObserverImpl *SingleKvStoreImpl::CreateObserver( + const SubscribeType subscribeType, sptr observer) +{ + return new (std::nothrow) KvStoreObserverImpl(subscribeType, observer); +} // Convert KvStore subscribe type to DistributeDB observer mode. int SingleKvStoreImpl::ConvertToDbObserverMode(const SubscribeType subscribeType) const { @@ -324,7 +314,7 @@ int SingleKvStoreImpl::ConvertToDbObserverMode(const SubscribeType subscribeType Status SingleKvStoreImpl::UnSubscribeKvStore(const SubscribeType subscribeType, sptr observer) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -371,7 +361,7 @@ Status SingleKvStoreImpl::UnSubscribeKvStore(const SubscribeType subscribeType, Status SingleKvStoreImpl::GetEntries(const Key &prefixKey, std::vector &entries) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -429,7 +419,7 @@ Status SingleKvStoreImpl::GetEntries(const Key &prefixKey, std::vector &e Status SingleKvStoreImpl::GetEntriesWithQuery(const std::string &query, std::vector &entries) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -498,11 +488,10 @@ Status SingleKvStoreImpl::GetEntriesWithQuery(const std::string &query, std::vec } void SingleKvStoreImpl::GetResultSet(const Key &prefixKey, - std::function)> callback, - bool deviceCoordinate) + std::function)> callback) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); callback(Status::EXCEED_MAX_ACCESS_RATE, nullptr); return; @@ -529,58 +518,24 @@ void SingleKvStoreImpl::GetResultSet(const Key &prefixKey, ZLOGI("result DBStatus: %d", static_cast(status)); if (status == DistributedDB::DBStatus::OK) { std::lock_guard lg(storeResultSetMutex_); - KvStoreResultSetImpl *storeResultSetImpl = new DeviceKvStoreResultSetImpl(tmpKeyPrefix, dbResultSet, - deviceCoordinate); - sptr storeResultSet = storeResultSetImpl; + sptr storeResultSet = CreateResultSet(dbResultSet, tmpKeyPrefix); callback(Status::SUCCESS, storeResultSet); - storeResultSetMap_.emplace(storeResultSetImpl, storeResultSet); + storeResultSetMap_.emplace(storeResultSet.GetRefPtr(), storeResultSet); return; } - switch (status) { - case DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB: { - ZLOGE("GetResultSet failed, distributeddb need recover."); - bool success = Import(bundleName_); - callback(success ? Status::RECOVER_SUCCESS : Status::RECOVER_FAILED, nullptr); - break; - } - case DistributedDB::DBStatus::BUSY: // fallthrough - case DistributedDB::DBStatus::DB_ERROR: - callback(Status::DB_ERROR, nullptr); - break; - case DistributedDB::DBStatus::NOT_FOUND: - callback(Status::KEY_NOT_FOUND, nullptr); - break; - case DistributedDB::DBStatus::INVALID_ARGS: - callback(Status::INVALID_ARGUMENT, nullptr); - break; - case DistributedDB::DBStatus::EKEYREVOKED_ERROR: - case DistributedDB::DBStatus::SECURITY_OPTION_CHECK_ERROR: - callback(Status::SECURITY_LEVEL_ERROR, nullptr); - break; - default: - callback(Status::ERROR, nullptr); - break; + if (status == DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB) { + bool success = Import(bundleName_); + callback(success ? Status::RECOVER_SUCCESS : Status::RECOVER_FAILED, nullptr); + return; } -} - -void SingleKvStoreImpl::GetResultSet(const Key &prefixKey, - std::function)> callback) -{ - GetResultSet(prefixKey, callback, false); + callback(ConvertDbStatus(status), nullptr); } void SingleKvStoreImpl::GetResultSetWithQuery(const std::string &query, std::function)> callback) -{ - GetResultSetWithQuery(query, callback, false); -} - -void SingleKvStoreImpl::GetResultSetWithQuery(const std::string &query, - std::function)> callback, - bool deviceCoordinate) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); callback(Status::EXCEED_MAX_ACCESS_RATE, nullptr); return; @@ -608,10 +563,9 @@ void SingleKvStoreImpl::GetResultSetWithQuery(const std::string &query, ZLOGI("result DBStatus: %d", static_cast(status)); if (status == DistributedDB::DBStatus::OK) { std::lock_guard lg(storeResultSetMutex_); - KvStoreResultSetImpl *storeResultSetImpl = new DeviceKvStoreResultSetImpl(dbResultSet, deviceCoordinate); - sptr storeResultSet = storeResultSetImpl; + sptr storeResultSet = CreateResultSet(dbResultSet, {}); callback(Status::SUCCESS, storeResultSet); - storeResultSetMap_.emplace(storeResultSetImpl, storeResultSet); + storeResultSetMap_.emplace(storeResultSet.GetRefPtr(), storeResultSet); return; } switch (status) { @@ -647,10 +601,16 @@ void SingleKvStoreImpl::GetResultSetWithQuery(const std::string &query, } } +KvStoreResultSetImpl *SingleKvStoreImpl::CreateResultSet( + DistributedDB::KvStoreResultSet *resultSet, const DistributedDB::Key &prix) +{ + return new (std::nothrow) KvStoreResultSetImpl(resultSet, prix); +} + Status SingleKvStoreImpl::GetCountWithQuery(const std::string &query, int &result) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -714,22 +674,21 @@ Status SingleKvStoreImpl::CloseResultSet(sptr resultSet) if (resultSet == nullptr) { return Status::INVALID_ARGUMENT; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } std::shared_lock lock(storeNbDelegateMutex_); std::lock_guard lg(storeResultSetMutex_); - KvStoreResultSetImpl *kvStoreResultSetImpl = static_cast(resultSet.GetRefPtr()); Status status; - auto it = storeResultSetMap_.find(kvStoreResultSetImpl); + auto it = storeResultSetMap_.find(resultSet.GetRefPtr()); if (it == storeResultSetMap_.end()) { ZLOGE("ResultSet not found in this store."); return Status::INVALID_ARGUMENT; } { DdsTrace trace(std::string(LOG_TAG "Delegate::") + std::string(__FUNCTION__)); - status = kvStoreResultSetImpl->CloseResultSet(kvStoreNbDelegate_); + status = it->second->CloseResultSet(kvStoreNbDelegate_); } if (status == Status::SUCCESS) { storeResultSetMap_.erase(it); @@ -742,7 +701,7 @@ Status SingleKvStoreImpl::CloseResultSet(sptr resultSet) Status SingleKvStoreImpl::RemoveDeviceData(const std::string &device) { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -780,7 +739,7 @@ Status SingleKvStoreImpl::Sync(const std::vector &deviceIds, SyncMo { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGD("start."); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -802,7 +761,7 @@ Status SingleKvStoreImpl::Sync(const std::vector &deviceIds, SyncMo { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGD("start."); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1050,7 +1009,7 @@ Status SingleKvStoreImpl::SubscribeWithQuery(const std::vector &dev { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGD("start."); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1063,7 +1022,7 @@ Status SingleKvStoreImpl::UnSubscribeWithQuery(const std::vector &d { DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); ZLOGD("start."); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1113,7 +1072,7 @@ Status SingleKvStoreImpl::ForceClose(DistributedDB::KvStoreDelegateManager *kvSt ZLOGI("start to clean resultset"); std::lock_guard lg(storeResultSetMutex_); for (auto resultSetPair = storeResultSetMap_.begin(); resultSetPair != storeResultSetMap_.end();) { - Status status = (resultSetPair->first)->CloseResultSet(kvStoreNbDelegate_); + Status status = (resultSetPair->second)->CloseResultSet(kvStoreNbDelegate_); if (status != Status::SUCCESS) { ZLOGW("CloseResultSet failed during ForceClose, errCode %d", status); return status; @@ -1166,12 +1125,11 @@ Status SingleKvStoreImpl::MigrateKvStore(const std::string &harmonyAccountId, } if (newDelegateMgr == nullptr) { - auto appId = KvStoreUtils::GetAppIdByBundleName(bundleName_); - if (appId.empty()) { + if (appId_.empty()) { ZLOGE("Get appId by bundle name failed."); return Status::MIGRATION_KVSTORE_FAILED; } - newDelegateMgr = new (std::nothrow) DistributedDB::KvStoreDelegateManager(appId, harmonyAccountId); + newDelegateMgr = new (std::nothrow) DistributedDB::KvStoreDelegateManager(appId_, harmonyAccountId); if (newDelegateMgr == nullptr) { ZLOGE("new KvStoreDelegateManager failed."); return Status::MIGRATION_KVSTORE_FAILED; @@ -1265,7 +1223,7 @@ Status SingleKvStoreImpl::RebuildKvStoreResultSet() std::lock_guard lg(storeResultSetMutex_); Status retStatus = Status::SUCCESS; for (const auto &resultSetPair : storeResultSetMap_) { - Status status = (resultSetPair.first)->MigrateKvStore(kvStoreNbDelegate_); + Status status = (resultSetPair.second)->MigrateKvStore(kvStoreNbDelegate_); if (status != Status::SUCCESS) { retStatus = status; ZLOGW("rebuild resultset failed, errCode %d", static_cast(status)); @@ -1322,7 +1280,7 @@ Status SingleKvStoreImpl::PutBatch(const std::vector &entries) ZLOGE("delegate is null."); return Status::DB_ERROR; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1376,7 +1334,7 @@ Status SingleKvStoreImpl::DeleteBatch(const std::vector &keys) ZLOGE("delegate is null."); return Status::DB_ERROR; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1427,7 +1385,7 @@ Status SingleKvStoreImpl::StartTransaction() ZLOGE("delegate is null."); return Status::DB_ERROR; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1457,7 +1415,7 @@ Status SingleKvStoreImpl::Commit() ZLOGE("delegate is null."); return Status::DB_ERROR; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1488,7 +1446,7 @@ Status SingleKvStoreImpl::Rollback() ZLOGE("delegate is null."); return Status::DB_ERROR; } - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1550,17 +1508,16 @@ void SingleKvStoreImpl::IncreaseOpenCount() bool SingleKvStoreImpl::Import(const std::string &bundleName) const { ZLOGI("Single KvStoreImpl Import start"); - const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + const std::string harmonyAccountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); auto sKey = KvStoreMetaManager::GetMetaKey(deviceAccountId_, harmonyAccountId, bundleName, storeId_, "SINGLE_KEY"); std::vector secretKey; bool outdated = false; - auto trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); KvStoreMetaManager::GetInstance().GetSecretKeyFromMeta(sKey, secretKey, outdated); MetaData metaData{0}; metaData.kvStoreMetaData.deviceAccountId = deviceAccountId_; metaData.kvStoreMetaData.userId = harmonyAccountId; metaData.kvStoreMetaData.bundleName = bundleName; - metaData.kvStoreMetaData.appId = trueAppId; + metaData.kvStoreMetaData.appId = appId_; metaData.kvStoreMetaData.storeId = storeId_; metaData.kvStoreMetaData.securityLevel = options_.securityLevel; metaData.secretKeyMetaData.secretKey = secretKey; @@ -1571,7 +1528,7 @@ bool SingleKvStoreImpl::Import(const std::string &bundleName) const Status SingleKvStoreImpl::SetCapabilityEnabled(bool enabled) { ZLOGD("begin."); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1596,7 +1553,7 @@ Status SingleKvStoreImpl::SetCapabilityEnabled(bool enabled) Status SingleKvStoreImpl::SetCapabilityRange(const std::vector &localLabels, const std::vector &remoteSupportLabels) { - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -1670,4 +1627,8 @@ void SingleKvStoreImpl::OnDump(int fd) const dprintf(fd, "%s createIfMissing : %d\n", prefix.c_str(), static_cast(options_.createIfMissing)); dprintf(fd, "%s schema : %s\n", prefix.c_str(), options_.schema.c_str()); } +std::string SingleKvStoreImpl::GetStoreId() +{ + return storeId_; +} } // namespace OHOS::DistributedKv diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.h b/services/distributeddataservice/app/src/single_kvstore_impl.h index 124bd7e9f74d51abc238f10bb38de237040a8f4b..2e2eaae5b8474d8a9ae51cc6c8104d3d9c71cc57 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.h +++ b/services/distributeddataservice/app/src/single_kvstore_impl.h @@ -34,10 +34,11 @@ namespace OHOS::DistributedKv { class SingleKvStoreImpl : public SingleKvStoreStub { public: - SingleKvStoreImpl(const Options &options, const std::string &deviceAccountId, - const std::string &bundleName, const std::string &storeId, - const std::string &appDirectory, DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate); + SingleKvStoreImpl(const Options &options, const std::string &userId, const std::string &bundleName, + const std::string &storeId, const std::string &appId, const std::string &directory, + DistributedDB::KvStoreNbDelegate *delegate); ~SingleKvStoreImpl(); + std::string GetStoreId(); Status Put(const Key &key, const Value &value) override; Status Delete(const Key &key) override; Status Get(const Key &key, Value &value) override; @@ -73,13 +74,13 @@ public: const std::vector &remoteSupportLabels) override; Status GetSecurityLevel(SecurityLevel &securityLevel) override; bool Import(const std::string &bundleName) const; - void GetResultSet(const Key &prefixKey, std::function)> callback, - bool deviceCoordinate); - Status SubscribeKvStore(const SubscribeType subscribeType, sptr observer, - bool deviceCoordinate); - void GetResultSetWithQuery(const std::string &query, - std::function)> callback, bool deviceCoordinate); void OnDump(int fd) const; + +protected: + virtual KvStoreObserverImpl *CreateObserver(const SubscribeType subscribeType, sptr observer); + virtual KvStoreResultSetImpl *CreateResultSet( + DistributedDB::KvStoreResultSet *resultSet, const DistributedDB::Key &prix); + private: Status ConvertDbStatus(DistributedDB::DBStatus dbStatus); uint32_t GetSyncDelayTime(uint32_t allowedDelayMs) const; @@ -121,6 +122,9 @@ private: const std::string bundleName_; // kvstore name. const std::string storeId_; + + const std::string appId_; + // kvstore absolute path in distributeddatamgr. const std::string storePath_; // for top-app, 0 means synchronization immediately. for others, 0 means 1000ms. @@ -140,12 +144,12 @@ private: std::mutex observerMapMutex_; std::map observerMap_; std::mutex storeResultSetMutex_; - std::map> storeResultSetMap_; + std::map> storeResultSetMap_; sptr syncCallback_; int openCount_; // flowControl - KvStoreFlowCtrlManager flowCtrlManager_; + KvStoreFlowCtrlManager flowCtrl_; static constexpr int BURST_CAPACITY = 1000; static constexpr int SUSTAINED_CAPACITY = 10000; }; diff --git a/services/distributeddataservice/app/src/uninstaller/uninstaller.h b/services/distributeddataservice/app/src/uninstaller/uninstaller.h index 92d2dfccdadf97e3c29251f0e935df98222397c4..693efe4f1dab478e6615ff1f636793da143fd416 100755 --- a/services/distributeddataservice/app/src/uninstaller/uninstaller.h +++ b/services/distributeddataservice/app/src/uninstaller/uninstaller.h @@ -16,7 +16,7 @@ #ifndef DISTRIBUTEDDATAMGR_UNINSTALLER_H #define DISTRIBUTEDDATAMGR_UNINSTALLER_H -#include +#include #include #include "visibility.h" diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index 1efe3cc355e4b6f4a6e2a5aec68ffb2682ca68d9..e4500ae8b83431fa3f0ae6b622942aa7dfe2d299 100755 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -18,6 +18,7 @@ module_output_path = "distributeddatamgr/distributeddataservice" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", @@ -26,7 +27,10 @@ config("module_private_config") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/broadcaster", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/utils", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/bootstrap/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/config/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service/directory/include", "//utils/native/base/include", "//utils/system/safwk/native/include", "../include", @@ -86,7 +90,9 @@ ohos_unittest("KvStoreImplLogicalIsolationTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/uninstaller:distributeddata_uninstaller_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] @@ -139,7 +145,9 @@ ohos_unittest("KvStoreImplPhysicalIsolationTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/uninstaller:distributeddata_uninstaller_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] @@ -192,7 +200,9 @@ ohos_unittest("KvStoreDataServiceTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/uninstaller:distributeddata_uninstaller_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] @@ -209,6 +219,8 @@ ohos_unittest("KvStoreBackupTest") { "../src/device_kvstore_resultset_impl.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_app_accessor.cpp", + "../src/kvstore_app_manager.cpp", + "../src/kvstore_data_service.cpp", "../src/kvstore_impl.cpp", "../src/kvstore_meta_manager.cpp", "../src/kvstore_observer_impl.cpp", @@ -218,11 +230,10 @@ ohos_unittest("KvStoreBackupTest") { "../src/kvstore_user_manager.cpp", "../src/query_helper.cpp", "../src/single_kvstore_impl.cpp", - "unittest/kvstore_app_manager.cpp", "unittest/kvstore_backup_test.cpp", - "unittest/kvstore_data_service.cpp", ] + cflags_cc = [ "-DUT_TEST" ] configs = [ ":module_private_config" ] external_deps = [ @@ -245,7 +256,9 @@ ohos_unittest("KvStoreBackupTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/uninstaller:distributeddata_uninstaller_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] @@ -275,6 +288,8 @@ ohos_unittest("KvStoreFlowCtrlManagerTest") { "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] @@ -326,7 +341,9 @@ ohos_unittest("KvStoreSyncManagerTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/uninstaller:distributeddata_uninstaller_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] @@ -368,7 +385,9 @@ ohos_unittest("KvStoreUninstallerTest") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/utils:distributeddata_utils_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app/src/uninstaller:distributeddata_uninstaller_static", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:distributeddb", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:distributeddatasvc", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp b/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp index dcb56f2cf0c0e6071bda88aa0d1ec18afcfca5ea..ef9bf94be7bef9ce8161b3bc3ac9c73798d53818 100644 --- a/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp +++ b/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp @@ -14,8 +14,6 @@ */ #include -#include - #include #include #include @@ -36,7 +34,7 @@ #include "common_event_manager.h" #include "ohos/aafwk/content/intent.h" #include "ohos_account_kits.h" - +#include "gtest/gtest.h" using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS; @@ -309,7 +307,7 @@ HWTEST_F(DistributedDataAccountEventTest, GetKvStore_DefaultDeviceAccount_003, T // Step2. Splice kvStore data storage expected path by distributedDB hash interface and clear directory. DistributedDB::DBStatus dbStatus = DistributedDB::KvStoreDelegateManager::GetDatabaseDir( - storeId.storeId, appId.appId, AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), hashedStoreId); + storeId.storeId, appId.appId, AccountDelegate::GetInstance()->GetCurrentAccountId(), hashedStoreId); EXPECT_EQ(dbStatus, DistributedDB::OK) << "Get data directory name from DB failed."; std::string appDataStoragePath; @@ -365,7 +363,7 @@ HWTEST_F(DistributedDataAccountEventTest, GetKvStore_DefaultDeviceAccount_004, T // Step2. Splice kvStore data storage expected path by distributedDB hash interface and clear directory. DistributedDB::DBStatus dbStatus = DistributedDB::KvStoreDelegateManager::GetDatabaseDir( - storeId.storeId, appId.appId, AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), hashedStoreId); + storeId.storeId, appId.appId, AccountDelegate::GetInstance()->GetCurrentAccountId(), hashedStoreId); EXPECT_EQ(dbStatus, DistributedDB::OK) << "Get data directory name from DB failed."; std::string appDataStoragePath; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_app_manager.cpp b/services/distributeddataservice/app/test/unittest/kvstore_app_manager.cpp deleted file mode 100755 index a5cdb6c9b01b580a9ea4b77bb00c5ad44c3f7554..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/app/test/unittest/kvstore_app_manager.cpp +++ /dev/null @@ -1,733 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "KvStoreAppManager" - -#include "kvstore_app_manager.h" -#include -#include -#include -#include -#include -#include "account_delegate.h" -#include "broadcast_sender.h" -#include "constant.h" -#include "directory_utils.h" -#include "device_kvstore_impl.h" -#include "ikvstore.h" -#include "kv_store_delegate.h" -#include "kvstore_app_accessor.h" -#include "kvstore_utils.h" -#include "log_print.h" -#include "process_communicator_impl.h" -#include "permission_validator.h" -#include "reporter.h" -#include "types.h" - -namespace OHOS { -namespace DistributedKv { -KvStoreAppManager::KvStoreAppManager(const std::string &bundleName, const std::string &deviceAccountId) - : bundleName_(bundleName), deviceAccountId_(deviceAccountId), flowCtrlManager_(BURST_CAPACITY, SUSTAINED_CAPACITY) -{ - ZLOGI("begin."); - GetDelegateManager(PATH_DE); - GetDelegateManager(PATH_CE); -} - -KvStoreAppManager::~KvStoreAppManager() -{ - ZLOGD("begin."); - stores_[PATH_DE].clear(); - stores_[PATH_CE].clear(); - - { - std::lock_guard guard(delegateMutex_); - delete delegateManagers_[PATH_DE]; - delete delegateManagers_[PATH_CE]; - delegateManagers_[PATH_DE] = nullptr; - delegateManagers_[PATH_CE] = nullptr; - } -} - -Status KvStoreAppManager::ConvertErrorStatus(DistributedDB::DBStatus dbStatus, bool createIfMissing) -{ - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("delegate return error: %d.", static_cast(dbStatus)); - switch (dbStatus) { - case DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB: - return Status::CRYPT_ERROR; - case DistributedDB::DBStatus::SCHEMA_MISMATCH: - return Status::SCHEMA_MISMATCH; - case DistributedDB::DBStatus::INVALID_SCHEMA: - return Status::INVALID_SCHEMA; - case DistributedDB::DBStatus::NOT_SUPPORT: - return Status::NOT_SUPPORT; - case DistributedDB::DBStatus::EKEYREVOKED_ERROR: // fallthrough - case DistributedDB::DBStatus::SECURITY_OPTION_CHECK_ERROR: - return Status::SECURITY_LEVEL_ERROR; - default: - break; - } - if (createIfMissing) { - return Status::DB_ERROR; - } else { - return Status::STORE_NOT_FOUND; - } - } - return Status::SUCCESS; -} - -Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &storeId, - const std::vector &cipherKey, - std::function)> callback) -{ - ZLOGI("begin"); - PathType type = ConvertPathType(bundleName_, options.securityLevel); - auto *delegateManager = GetDelegateManager(type); - if (delegateManager == nullptr) { - ZLOGE("delegateManagers[%d] is nullptr.", type); - callback(nullptr); - return Status::ILLEGAL_STATE; - } - - if (!flowCtrlManager_.IsTokenEnough()) { - ZLOGE("flow control denied"); - return Status::EXCEED_MAX_ACCESS_RATE; - } - - std::lock_guard lg(storeMutex_); - auto it = stores_[type].find(storeId); - if (it != stores_[type].end()) { - sptr kvStoreImpl = it->second; - ZLOGI("find store in map refcount: %d.", kvStoreImpl->GetSptrRefCount()); - static_cast(kvStoreImpl.GetRefPtr())->IncreaseOpenCount(); - callback(std::move(kvStoreImpl)); - return Status::SUCCESS; - } - - if ((GetTotalKvStoreNum()) >= static_cast(Constant::MAX_OPEN_KVSTORES)) { - ZLOGE("limit %d KvStores can be opened.", Constant::MAX_OPEN_KVSTORES); - callback(nullptr); - return Status::ERROR; - } - - DistributedDB::KvStoreDelegate::Option dbOption; - auto status = InitDbOption(options, cipherKey, dbOption); - if (status != Status::SUCCESS) { - ZLOGE("InitDbOption failed."); - callback(nullptr); - return status; - } - - DistributedDB::KvStoreDelegate *storeDelegate = nullptr; - DistributedDB::DBStatus dbStatusTmp; - delegateManager->GetKvStore(storeId, dbOption, - [&storeDelegate, &dbStatusTmp](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreDelegate *delegate) { - storeDelegate = delegate; - dbStatusTmp = dbStatus; - }); - - if (storeDelegate == nullptr) { - ZLOGE("storeDelegate is nullptr, status:%d.", static_cast(dbStatusTmp)); - callback(nullptr); - return ConvertErrorStatus(dbStatusTmp, options.createIfMissing); - } - - ZLOGD("get delegate"); - sptr store = new (std::nothrow)KvStoreImpl(options, deviceAccountId_, bundleName_, - storeId, GetDbDir(options), storeDelegate); - if (store == nullptr) { - callback(nullptr); - delegateManager->CloseKvStore(storeDelegate); - return Status::ERROR; - } - auto result = stores_[type].emplace(storeId, store); - if (!result.second) { - ZLOGE("emplace failed."); - callback(nullptr); - delegateManager->CloseKvStore(storeDelegate); - return Status::ERROR; - } - - sptr kvStoreImpl = result.first->second; - ZLOGD("after emplace refcount: %d", kvStoreImpl->GetSptrRefCount()); - callback(std::move(kvStoreImpl)); - return Status::SUCCESS; -} - -Status KvStoreAppManager::GetKvStore(const Options &options, const std::string &storeId, - const std::vector &cipherKey, - std::function)> callback) -{ - ZLOGI("begin"); - PathType type = ConvertPathType(bundleName_, options.securityLevel); - auto *delegateManager = GetDelegateManager(type); - if (delegateManager == nullptr) { - ZLOGE("delegateManagers[%d] is nullptr.", type); - callback(nullptr); - return Status::ILLEGAL_STATE; - } - - if (!flowCtrlManager_.IsTokenEnough()) { - ZLOGE("flow control denied"); - return Status::EXCEED_MAX_ACCESS_RATE; - } - std::lock_guard lg(storeMutex_); - auto it = singleStores_[type].find(storeId); - if (it != singleStores_[type].end()) { - sptr singleKvStoreImpl = it->second; - ZLOGI("find store in map refcount: %d.", singleKvStoreImpl->GetSptrRefCount()); - static_cast(singleKvStoreImpl.GetRefPtr())->IncreaseOpenCount(); - callback(std::move(singleKvStoreImpl)); - return Status::SUCCESS; - } - - if ((GetTotalKvStoreNum()) >= static_cast(Constant::MAX_OPEN_KVSTORES)) { - ZLOGE("limit %d KvStores can be opened.", Constant::MAX_OPEN_KVSTORES); - callback(nullptr); - return Status::ERROR; - } - - DistributedDB::KvStoreNbDelegate::Option dbOption; - auto status = InitNbDbOption(options, cipherKey, dbOption); - if (status != Status::SUCCESS) { - ZLOGE("InitNbDbOption failed."); - callback(nullptr); - return status; - } - - DistributedDB::KvStoreNbDelegate *storeDelegate = nullptr; - DistributedDB::DBStatus dbStatusTmp; - delegateManager->GetKvStore(storeId, dbOption, - [&](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreNbDelegate *kvStoreDelegate) { - storeDelegate = kvStoreDelegate; - dbStatusTmp = dbStatus; - }); - - if (storeDelegate == nullptr) { - ZLOGE("storeDelegate is nullptr."); - callback(nullptr); - return ConvertErrorStatus(dbStatusTmp, options.createIfMissing); - } - std::string kvStorePath = GetDbDir(options); - auto store = new (std::nothrow) DeviceKvStoreImpl({ - options, options.kvStoreType == KvStoreType::DEVICE_COLLABORATION, deviceAccountId_, bundleName_, storeId, - kvStorePath}, storeDelegate); - if (store == nullptr) { - ZLOGE("store is nullptr."); - callback(nullptr); - delegateManager->CloseKvStore(storeDelegate); - return Status::ERROR; - } - auto result = singleStores_[type].emplace(storeId, store); - if (!result.second) { - ZLOGE("emplace failed."); - callback(nullptr); - delegateManager->CloseKvStore(storeDelegate); - delete store; - return Status::ERROR; - } - - sptr singleKvStoreImpl = result.first->second; - ZLOGI("after emplace refcount: %d autoSync: %d", - singleKvStoreImpl->GetSptrRefCount(), static_cast(options.autoSync)); - if (options.autoSync) { - bool autoSync = true; - DistributedDB::PragmaData data = static_cast(&autoSync); - auto pragmaStatus = storeDelegate->Pragma(DistributedDB::PragmaCmd::AUTO_SYNC, data); - if (pragmaStatus != DistributedDB::DBStatus::OK) { - ZLOGE("pragmaStatus: %d", static_cast(pragmaStatus)); - } - } - - callback(std::move(singleKvStoreImpl)); - DistributedDB::AutoLaunchOption launchOption = { - options.createIfMissing, options.encrypt, dbOption.cipher, dbOption.passwd, dbOption.schema, - dbOption.createDirByStoreIdOnly, kvStorePath, nullptr - }; - launchOption.secOption = ConvertSecurity(options.securityLevel); - AppAccessorParam accessorParam = {Constant::DEFAULT_GROUP_ID, trueAppId_, storeId, launchOption}; - KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(accessorParam); - return Status::SUCCESS; -} - -Status KvStoreAppManager::CloseKvStore(const std::string &storeId) -{ - ZLOGI("CloseKvStore"); - if (!flowCtrlManager_.IsTokenEnough()) { - ZLOGE("flow control denied"); - return Status::EXCEED_MAX_ACCESS_RATE; - } - std::lock_guard lg(storeMutex_); - Status status = CloseKvStore(storeId, PATH_DE); - if (status != Status::STORE_NOT_OPEN) { - return status; - } - - status = CloseKvStore(storeId, PATH_CE); - if (status != Status::STORE_NOT_OPEN) { - return status; - } - - ZLOGW("store not open"); - return Status::STORE_NOT_OPEN; -} - -Status KvStoreAppManager::CloseAllKvStore() -{ - ZLOGI("begin."); - std::lock_guard lg(storeMutex_); - if (GetTotalKvStoreNum() == 0) { - return Status::STORE_NOT_OPEN; - } - - ZLOGI("close %zu KvStores.", GetTotalKvStoreNum()); - Status status = CloseAllKvStore(PATH_DE); - if (status == Status::DB_ERROR) { - return status; - } - status = CloseAllKvStore(PATH_CE); - if (status == Status::DB_ERROR) { - return status; - } - return Status::SUCCESS; -} - -Status KvStoreAppManager::DeleteKvStore(const std::string &storeId) -{ - ZLOGI("%s", storeId.c_str()); - if (!flowCtrlManager_.IsTokenEnough()) { - ZLOGE("flow control denied"); - return Status::EXCEED_MAX_ACCESS_RATE; - } - - Status statusDE = DeleteKvStore(storeId, PATH_DE); - Status statusCE = DeleteKvStore(storeId, PATH_CE); - if (statusDE == Status::SUCCESS || statusCE == Status::SUCCESS) { - return Status::SUCCESS; - } - - ZLOGE("delegate close error."); - return Status::DB_ERROR; -} - -Status KvStoreAppManager::DeleteAllKvStore() -{ - ZLOGI("begin."); - std::lock_guard lg(storeMutex_); - if (GetTotalKvStoreNum() == 0) { - return Status::STORE_NOT_OPEN; - } - ZLOGI("delete %d KvStores.", int32_t(GetTotalKvStoreNum())); - - Status status = DeleteAllKvStore(PATH_DE); - if (status != Status::SUCCESS) { - ZLOGE("path de delegate delete error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - status = DeleteAllKvStore(PATH_CE); - if (status != Status::SUCCESS) { - ZLOGE("path ce delegate delete error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - return Status::SUCCESS; -} - -Status KvStoreAppManager::MigrateAllKvStore(const std::string &harmonyAccountId) -{ - ZLOGI("begin"); - if (PermissionValidator::IsAutoLaunchEnabled(bundleName_)) { - return Status::SUCCESS; - } - - std::lock_guard lg(storeMutex_); - // update userid in kvstore tuple map of permission adapter. - KvStoreTuple srcKvStoreTuple {userId_, bundleName_}; - KvStoreTuple dstKvStoreTuple {harmonyAccountId, bundleName_}; - PermissionValidator::UpdateKvStoreTupleMap(srcKvStoreTuple, dstKvStoreTuple); - userId_ = harmonyAccountId; - ZLOGI("path de migration begin."); - Status statusDE = MigrateAllKvStore(harmonyAccountId, PATH_DE); - ZLOGI("path ce migration begin."); - Status statusCE = MigrateAllKvStore(harmonyAccountId, PATH_CE); - return (statusCE != Status::SUCCESS) ? statusCE : statusDE; -} - -Status KvStoreAppManager::InitDbOption(const Options &options, const std::vector &cipherKey, - DistributedDB::KvStoreDelegate::Option &dbOption) -{ - DistributedDB::CipherPassword password; - auto status = password.SetValue(cipherKey.data(), cipherKey.size()); - if (status != DistributedDB::CipherPassword::ErrorCode::OK) { - ZLOGE("Failed to set the passwd:%zu", cipherKey.size()); - return Status::DB_ERROR; - } - dbOption.createIfNecessary = options.createIfMissing; - dbOption.localOnly = false; - dbOption.isEncryptedDb = options.encrypt; - if (options.encrypt) { - dbOption.cipher = DistributedDB::CipherType::AES_256_GCM; - dbOption.passwd = password; - } - dbOption.createDirByStoreIdOnly = options.dataOwnership; - return Status::SUCCESS; -} - -Status KvStoreAppManager::InitNbDbOption(const Options &options, const std::vector &cipherKey, - DistributedDB::KvStoreNbDelegate::Option &dbOption) -{ - DistributedDB::CipherPassword password; - auto status = password.SetValue(cipherKey.data(), cipherKey.size()); - if (status != DistributedDB::CipherPassword::ErrorCode::OK) { - ZLOGE("Failed to set the passwd:%zu", cipherKey.size()); - return Status::DB_ERROR; - } - - dbOption.createIfNecessary = options.createIfMissing; - dbOption.isEncryptedDb = options.encrypt; - if (options.encrypt) { - dbOption.cipher = DistributedDB::CipherType::AES_256_GCM; - dbOption.passwd = password; - } - - if (options.kvStoreType == KvStoreType::SINGLE_VERSION) { - dbOption.conflictResolvePolicy = DistributedDB::LAST_WIN; - } else if (options.kvStoreType == KvStoreType::DEVICE_COLLABORATION) { - dbOption.conflictResolvePolicy = DistributedDB::DEVICE_COLLABORATION; - } else { - ZLOGE("kvStoreType is invalid"); - return Status::INVALID_ARGUMENT; - } - - dbOption.schema = options.schema; - dbOption.createDirByStoreIdOnly = options.dataOwnership; - dbOption.secOption = ConvertSecurity(options.securityLevel); - return Status::SUCCESS; -} - -std::string KvStoreAppManager::GetDbDir(const Options &options) const -{ - return GetDataStoragePath(deviceAccountId_, bundleName_, ConvertPathType(bundleName_, options.securityLevel)); -} - -KvStoreAppManager::PathType KvStoreAppManager::ConvertPathType(const std::string &bundleName, int securityLevel) -{ - PathType type = PATH_CE; - if ((securityLevel == NO_LABEL && PermissionValidator::IsSystemService(bundleName)) || - securityLevel == S0 || - securityLevel == S1) { - type = PATH_DE; - } - return type; -} - -DistributedDB::KvStoreDelegateManager *KvStoreAppManager::GetDelegateManager(PathType type) -{ - std::lock_guard guard(delegateMutex_); - if (delegateManagers_[type] != nullptr) { - return delegateManagers_[type]; - } - - std::string directory = GetDataStoragePath(deviceAccountId_, bundleName_, type); - bool ret = ForceCreateDirectory(directory); - if (!ret) { - ZLOGE("create directory[%s] failed, errstr=[%d].", directory.c_str(), errno); - return nullptr; - } - // change mode for directories to 0755, and for files to 0600. - DirectoryUtils::ChangeModeDirOnly(directory, Constant::DEFAULT_MODE_DIR); - DirectoryUtils::ChangeModeFileOnly(directory, Constant::DEFAULT_MODE_FILE); - - trueAppId_ = KvStoreUtils::GetAppIdByBundleName(bundleName_); - if (trueAppId_.empty()) { - delegateManagers_[type] = nullptr; - ZLOGW("trueAppId_ empty(permission issues?)"); - return nullptr; - } - - userId_ = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(bundleName_); - ZLOGD("accountId: %s bundleName: %s", KvStoreUtils::ToBeAnonymous(userId_).c_str(), bundleName_.c_str()); - delegateManagers_[type] = new (std::nothrow) DistributedDB::KvStoreDelegateManager(trueAppId_, userId_); - if (delegateManagers_[type] == nullptr) { - ZLOGE("delegateManagers_[%d] is nullptr.", type); - return nullptr; - } - - DistributedDB::KvStoreConfig kvStoreConfig; - kvStoreConfig.dataDir = directory; - delegateManagers_[type]->SetKvStoreConfig(kvStoreConfig); - DistributedDB::KvStoreDelegateManager::SetProcessLabel(Constant::PROCESS_LABEL, "default"); - auto communicator = std::make_shared(); - auto result = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator); - ZLOGI("app set communicator result:%d.", static_cast(result)); - return delegateManagers_[type]; -} - -DistributedDB::KvStoreDelegateManager *KvStoreAppManager::SwitchDelegateManager(PathType type, - DistributedDB::KvStoreDelegateManager *delegateManager) -{ - std::lock_guard guard(delegateMutex_); - DistributedDB::KvStoreDelegateManager *oldDelegateManager = delegateManagers_[type]; - delegateManagers_[type] = delegateManager; - return oldDelegateManager; -} - -Status KvStoreAppManager::CloseKvStore(const std::string &storeId, PathType type) -{ - auto *delegateManager = GetDelegateManager(type); - if (delegateManager == nullptr) { - ZLOGE("delegateManager[%d] is null.", type); - return Status::ILLEGAL_STATE; - } - - auto it = stores_[type].find(storeId); - if (it != stores_[type].end()) { - ZLOGD("find store and close delegate."); - InnerStatus status = it->second->Close(delegateManager); - if (status == InnerStatus::SUCCESS) { - stores_[type].erase(it); - return Status::SUCCESS; - } - if (status == InnerStatus::DECREASE_REFCOUNT) { - return Status::SUCCESS; - } - ZLOGE("delegate close error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - - auto itSingle = singleStores_[type].find(storeId); - if (itSingle != singleStores_[type].end()) { - ZLOGD("find single store and close delegate."); - InnerStatus status = itSingle->second->Close(delegateManager); - if (status == InnerStatus::SUCCESS) { - singleStores_[type].erase(itSingle); - return Status::SUCCESS; - } - if (status == InnerStatus::DECREASE_REFCOUNT) { - return Status::SUCCESS; - } - ZLOGE("delegate close error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - - return Status::STORE_NOT_OPEN; -} - -Status KvStoreAppManager::CloseAllKvStore(PathType type) -{ - auto *delegateManager = GetDelegateManager(type); - if (delegateManager == nullptr) { - ZLOGE("delegateManager[%d] is null.", type); - return Status::ILLEGAL_STATE; - } - - for (auto it = stores_[type].begin(); it != stores_[type].end(); it = stores_[type].erase(it)) { - KvStoreImpl *currentStore = it->second.GetRefPtr(); - ZLOGI("close kvstore, refcount %d.", it->second->GetSptrRefCount()); - Status status = currentStore->ForceClose(delegateManager); - if (status != Status::SUCCESS) { - ZLOGE("delegate close error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - } - stores_[type].clear(); - - for (auto it = singleStores_[type].begin(); it != singleStores_[type].end(); it = singleStores_[type].erase(it)) { - SingleKvStoreImpl *currentStore = it->second.GetRefPtr(); - ZLOGI("close kvstore, refcount %d.", it->second->GetSptrRefCount()); - Status status = currentStore->ForceClose(delegateManager); - if (status != Status::SUCCESS) { - ZLOGE("delegate close error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - } - singleStores_[type].clear(); - return Status::SUCCESS; -} - -Status KvStoreAppManager::DeleteKvStore(const std::string &storeId, PathType type) -{ - auto *delegateManager = GetDelegateManager(type); - if (delegateManager == nullptr) { - ZLOGE("delegateManager[%d] is null.", type); - return Status::ILLEGAL_STATE; - } - std::lock_guard lg(storeMutex_); - auto it = stores_[type].find(storeId); - if (it != stores_[type].end()) { - Status status = it->second->ForceClose(delegateManager); - if (status != Status::SUCCESS) { - return Status::DB_ERROR; - } - stores_[type].erase(it); - } - - auto itSingle = singleStores_[type].find(storeId); - if (itSingle != singleStores_[type].end()) { - Status status = itSingle->second->ForceClose(delegateManager); - if (status != Status::SUCCESS) { - return Status::DB_ERROR; - } - singleStores_[type].erase(itSingle); - } - - DistributedDB::DBStatus status = delegateManager->DeleteKvStore(storeId); - if (singleStores_[type].empty() && stores_[type].empty()) { - SwitchDelegateManager(type, nullptr); - delete delegateManager; - } - return (status != DistributedDB::DBStatus::OK) ? Status::DB_ERROR : Status::SUCCESS; -} - -Status KvStoreAppManager::DeleteAllKvStore(PathType type) -{ - auto *delegateManager = GetDelegateManager(type); - if (delegateManager == nullptr) { - ZLOGE("delegateManager[%d] is null.", type); - return Status::ILLEGAL_STATE; - } - - for (auto it = stores_[type].begin(); it != stores_[type].end(); it = stores_[type].erase(it)) { - std::string storeId = it->first; - KvStoreImpl *currentStore = it->second.GetRefPtr(); - Status status = currentStore->ForceClose(delegateManager); - if (status != Status::SUCCESS) { - ZLOGE("delegate delete close failed error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - - ZLOGI("delete kvstore, refcount %d.", it->second->GetSptrRefCount()); - DistributedDB::DBStatus dbStatus = delegateManager->DeleteKvStore(storeId); - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("delegate delete error: %d.", static_cast(dbStatus)); - return Status::DB_ERROR; - } - } - stores_[type].clear(); - - for (auto it = singleStores_[type].begin(); it != singleStores_[type].end(); it = singleStores_[type].erase(it)) { - std::string storeId = it->first; - SingleKvStoreImpl *currentStore = it->second.GetRefPtr(); - Status status = currentStore->ForceClose(delegateManager); - if (status != Status::SUCCESS) { - ZLOGE("delegate delete close failed error: %d.", static_cast(status)); - return Status::DB_ERROR; - } - - ZLOGI("close kvstore, refcount %d.", it->second->GetSptrRefCount()); - DistributedDB::DBStatus dbStatus = delegateManager->DeleteKvStore(storeId); - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("delegate delete error: %d.", static_cast(dbStatus)); - return Status::DB_ERROR; - } - } - singleStores_[type].clear(); - SwitchDelegateManager(type, nullptr); - delete delegateManager; - return Status::SUCCESS; -} - -Status KvStoreAppManager::MigrateAllKvStore(const std::string &harmonyAccountId, PathType type) -{ - auto *delegateManager = GetDelegateManager(type); - if (delegateManager == nullptr) { - ZLOGE("delegateManager is nullptr."); - return Status::ILLEGAL_STATE; - } - - std::string dirPath = GetDataStoragePath(deviceAccountId_, bundleName_, type); - DistributedDB::KvStoreDelegateManager *newDelegateManager = nullptr; - Status status = Status::SUCCESS; - ZLOGI("KvStore migration begin."); - for (auto &it : stores_[type]) { - sptr impl = it.second; - if (impl->MigrateKvStore(harmonyAccountId, dirPath, delegateManager, newDelegateManager) != Status::SUCCESS) { - status = Status::MIGRATION_KVSTORE_FAILED; - ZLOGE("migrate kvstore for appId-%s failed.", bundleName_.c_str()); - // skip this failed, continue to migrate other kvstore. - } - } - - ZLOGI("SingleKvStore migration begin."); - for (auto &it : singleStores_[type]) { - sptr impl = it.second; - if (impl->MigrateKvStore(harmonyAccountId, dirPath, delegateManager, newDelegateManager) != Status::SUCCESS) { - status = Status::MIGRATION_KVSTORE_FAILED; - ZLOGE("migrate single kvstore for appId-%s failed.", bundleName_.c_str()); - // skip this failed, continue to migrate other kvstore. - } - } - - if (newDelegateManager != nullptr) { - delegateManager = SwitchDelegateManager(type, newDelegateManager); - delete delegateManager; - } - return status; -} - -size_t KvStoreAppManager::GetTotalKvStoreNum() const -{ - size_t total = stores_[PATH_DE].size(); - total += stores_[PATH_CE].size(); - total += singleStores_[PATH_DE].size(); - total += singleStores_[PATH_CE].size(); - return int(total); -}; - -std::string KvStoreAppManager::GetDataStoragePath(const std::string &deviceAccountId, const std::string &bundleName, - PathType type) -{ - std::string miscPath = (type == PATH_DE) ? Constant::ROOT_PATH_DE : Constant::ROOT_PATH_CE; - return Constant::Concatenate({ - miscPath, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), - "/", bundleName, "/" - }); -} - -DistributedDB::SecurityOption KvStoreAppManager::ConvertSecurity(int securityLevel) -{ - if (securityLevel < SecurityLevel::NO_LABEL || securityLevel > SecurityLevel::S4) { - return {DistributedDB::NOT_SET, DistributedDB::ECE}; - } - switch (securityLevel) { - case SecurityLevel::S3: - return {DistributedDB::S3, DistributedDB::SECE}; - case SecurityLevel::S4: - return {DistributedDB::S4, DistributedDB::ECE}; - default: - return {securityLevel, DistributedDB::ECE}; - } -} - -void KvStoreAppManager::Dump(int fd) const -{ - const std::string prefix(8, ' '); - std::string dePath = GetDataStoragePath(deviceAccountId_, bundleName_, PATH_DE); - std::string cePath = GetDataStoragePath(deviceAccountId_, bundleName_, PATH_CE); - size_t singleStoreNum = singleStores_[PATH_DE].size() + singleStores_[PATH_CE].size(); - dprintf(fd, "%s----------------------------------------------------------\n", prefix.c_str()); - dprintf(fd, "%sAppID : %s\n", prefix.c_str(), trueAppId_.c_str()); - dprintf(fd, "%sBundleName : %s\n", prefix.c_str(), bundleName_.c_str()); - dprintf(fd, "%sAppDEDirectory: %s\n", prefix.c_str(), dePath.c_str()); - dprintf(fd, "%sAppCEDirectory: %s\n", prefix.c_str(), cePath.c_str()); - dprintf(fd, "%sStore count : %u\n", prefix.c_str(), static_cast(singleStoreNum)); - for (const auto &singleStoreMap : singleStores_) { - for (const auto &pair : singleStoreMap) { - pair.second->OnDump(fd); - } - } -} -} // namespace DistributedKv -} // namespace OHOS diff --git a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp index dead40eca2ba67697896abbdfd990c82489adfea..a02b3aaace41cbeb2c3ed606aa73ef4442053b04 100755 --- a/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_backup_test.cpp @@ -12,13 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include #include #include #include #include - +#include +#include "checker/checker_manager.h" #include "kvstore_impl.h" #include "backup_handler.h" #include "kv_scheduler.h" @@ -27,10 +26,11 @@ #include "kvstore_utils.h" #include "log_print.h" #include "single_kvstore_impl.h" - +#include "gtest/gtest.h" using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS; +using namespace OHOS::DistributedData; class KvStoreBackupTest : public testing::Test { public: @@ -111,11 +111,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest002, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); + auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, CheckerManager::INVALID_UID); 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.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; @@ -164,12 +164,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest003, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); + auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, CheckerManager::INVALID_UID); 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.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; @@ -227,11 +226,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest004, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); + auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, CheckerManager::INVALID_UID); 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.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; @@ -240,11 +239,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest004, TestSize.Level1) backupHandler->SingleKvStoreBackup(metaData); - auto currentAccountId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + auto currentAccountId = AccountDelegate::GetInstance()->GetCurrentAccountId(); 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); + auto pathType = KvStoreAppManager::ConvertPathType(1000, appId.appId, metaData.kvStoreMetaData.securityLevel); std::initializer_list backFileList = {BackupHandler::GetBackupPath("0", pathType), "/", backupFileNameHashed}; auto backFilePath = Constant::Concatenate(backFileList); @@ -284,11 +283,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest005, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); + auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, CheckerManager::INVALID_UID); 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.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; @@ -337,11 +336,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest006, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); + auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, CheckerManager::INVALID_UID); 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.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; @@ -390,11 +389,11 @@ HWTEST_F(KvStoreBackupTest, KvStoreBackupTest007, TestSize.Level1) Value value2("test2_value"); kvStorePtr->Put(key2, value2); + auto trueAppId = CheckerManager::GetInstance().GetAppId(appId.appId, CheckerManager::INVALID_UID); 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.userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.kvStoreMetaData.appId = trueAppId; metaData.kvStoreMetaData.bundleName = appId.appId; metaData.kvStoreMetaData.storeId = storeId.storeId; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp deleted file mode 100644 index fa255e7332c0573b987054b04184313d5257ea90..0000000000000000000000000000000000000000 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp +++ /dev/null @@ -1,1360 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "KvStoreDataService" - -#include "kvstore_data_service.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "auto_launch_export.h" -#include "communication_provider.h" -#include "constant.h" -#include "crypto_utils.h" -#include "dds_trace.h" -#include "device_change_listener_impl.h" -#include "device_kvstore_impl.h" -#include "iservice_registry.h" -#include "kvstore_account_observer.h" -#include "kvstore_app_accessor.h" -#include "kvstore_meta_manager.h" -#include "kvstore_utils.h" -#include "log_print.h" -#include "permission_validator.h" -#include "process_communicator_impl.h" -#include "reporter.h" -#include "rdb_service_impl.h" -#include "system_ability_definition.h" -#include "uninstaller/uninstaller.h" - -namespace OHOS { -namespace DistributedKv { -using json = nlohmann::json; -using namespace std::chrono; - -REGISTER_SYSTEM_ABILITY_BY_ID(KvStoreDataService, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, true); - -constexpr size_t MAX_APP_ID_LENGTH = 256; - -KvStoreDataService::KvStoreDataService(bool runOnCreate) - : SystemAbility(runOnCreate), - accountMutex_(), - deviceAccountMap_(), - clientDeathObserverMutex_(), - clientDeathObserverMap_() -{ - ZLOGI("begin."); - Initialize(); -} - -KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate) - : SystemAbility(systemAbilityId, runOnCreate), - accountMutex_(), - deviceAccountMap_(), - clientDeathObserverMutex_(), - clientDeathObserverMap_() -{ - ZLOGI("begin"); - Initialize(); -} - -KvStoreDataService::~KvStoreDataService() -{ - ZLOGI("begin."); - deviceAccountMap_.clear(); -} - -void KvStoreDataService::Initialize() -{ - ZLOGI("begin."); - KvStoreMetaManager::GetInstance().InitMetaParameter(); - std::thread th = std::thread([]() { - auto communicator = std::make_shared(); - auto ret = DistributedDB::KvStoreDelegateManager::SetProcessCommunicator(communicator); - ZLOGI("set communicator ret:%d.", static_cast(ret)); - if (KvStoreMetaManager::GetInstance().CheckRootKeyExist() == Status::SUCCESS) { - return; - } - constexpr int RETRY_MAX_TIMES = 100; - int retryCount = 0; - constexpr int RETRY_TIME_INTERVAL_MILLISECOND = 1 * 1000 * 1000; // retry after 1 second - while (retryCount < RETRY_MAX_TIMES) { - if (KvStoreMetaManager::GetInstance().GenerateRootKey() == Status::SUCCESS) { - ZLOGI("GenerateRootKey success."); - break; - } - retryCount++; - ZLOGE("GenerateRootKey failed."); - usleep(RETRY_TIME_INTERVAL_MILLISECOND); - } - }); - th.detach(); - - accountEventObserver_ = std::make_shared(*this); - AccountDelegate::GetInstance()->Subscribe(accountEventObserver_); -} - -bool KvStoreDataService::CheckBundleName(const std::string &bundleName) const -{ - if (bundleName.empty() || bundleName.size() > MAX_APP_ID_LENGTH || - bundleName.find(Constant::KEY_SEPARATOR) != std::string::npos) { - return false; - } - - auto iter = std::find_if_not(bundleName.begin(), bundleName.end(), - [](char c) { return (std::isprint(c) && c != '/'); }); - - return (iter == bundleName.end()); -} - -bool KvStoreDataService::CheckStoreId(const std::string &storeId) const -{ - if (storeId.empty() || storeId.size() > Constant::MAX_STORE_ID_LENGTH || - storeId.find(Constant::KEY_SEPARATOR) != std::string::npos) { - return false; - } - - auto iter = std::find_if_not(storeId.begin(), storeId.end(), - [](char c) { return (std::isdigit(c) || std::isalpha(c) || c == '_'); }); - - return (iter == storeId.end()); -} - -Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId, const StoreId &storeId, - std::function)> callback) -{ - ZLOGI("begin."); - DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - if (callback == nullptr) { - ZLOGW("callback is nullptr"); - return Status::ERROR; - } - - GetKvStorePara getKvStorePara; - Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_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."); - FaultMsg msg = {FaultType::RUNTIME_FAULT, "user", __FUNCTION__, Fault::RF_GET_DB}; - Reporter::GetInstance()->ServiceFault()->Report(msg); - 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).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()); - if (statusTmp == Status::SUCCESS) { - return UpdateMetaData(options, getKvStorePara, secretKeyParas.metaKey, it->second); - } - 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"); - return Status::INVALID_ARGUMENT; - } - - KvStoreType kvStoreTypeInOptions = options.kvStoreType; - if (kvStoreTypeInOptions != KvStoreType::DEVICE_COLLABORATION && kvStoreTypeInOptions != kvStoreType) { - ZLOGE("invalid kvStore type."); - 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."); - return Status::INVALID_ARGUMENT; - } - if (!CheckStoreId(storeIdTmp)) { - ZLOGE("invalid storeIdTmp."); - return Status::INVALID_ARGUMENT; - } - - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGW("appId empty(permission issues?)"); - 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; - } - - 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)) { - 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); }); - - 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; - Status alreadyCreated = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaSecretKey, CHECK_EXIST_LOCAL); - if (options.encrypt) { - ZLOGI("Getting secret key"); - 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"); - return Status::CRYPT_ERROR; - } - KvStoreMetaManager::GetInstance().WriteSecretKeyToFile(secretKeyFile, secretKey); - } - return Status::SUCCESS; -} - -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; - } - // 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; - } - // 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); - }); - } - - // 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); - } - 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 (secKeyParas.alreadyCreated != Status::SUCCESS) { - // create encrypted store failed, remove secret key - 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( - secKeyParas.secretKeyFile, secKeyParas.metaSecretKey, secKeyParas.secretKey, secKeyParas.outdated); - if (status != Status::SUCCESS) { - callback(nullptr); - return Status::CRYPT_ERROR; - } - // here callback is called twice - 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(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 RecoverSingleKvStore(options, kvParas.bundleName, kvParas.storeId, secKeyParas.secretKey, callback); - } - return statusTmp; -} - -bool KvStoreDataService::CheckOptions(const Options &options, const std::vector &metaKey) const -{ - ZLOGI("begin."); - KvStoreMetaData metaData; - metaData.version = 0; - Status statusTmp = KvStoreMetaManager::GetInstance().GetKvStoreMeta(metaKey, metaData); - if (statusTmp == Status::KEY_NOT_FOUND) { - ZLOGI("get metaKey not found."); - return true; - } - if (statusTmp != Status::SUCCESS) { - ZLOGE("get metaKey failed."); - return false; - } - ZLOGI("metaData encrypt is %d, kvStore type is %d, options encrypt is %d, kvStore type is %d", - static_cast(metaData.isEncrypt), static_cast(metaData.kvStoreType), - static_cast(options.encrypt), static_cast(options.kvStoreType)); - if (options.encrypt != metaData.isEncrypt) { - ZLOGE("checkOptions encrypt type is not the same."); - return false; - } - - if (options.kvStoreType != metaData.kvStoreType && metaData.version != 0) { - ZLOGE("checkOptions kvStoreType is not the same."); - return false; - } - ZLOGI("end."); - return true; -} - -bool KvStoreDataService::CheckBackupFileExist(const std::string &deviceAccountId, const std::string &bundleName, - 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 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; - } - return true; -} - -Status KvStoreDataService::RecoverSingleKvStore(const Options &options, - const std::string &bundleName, - const std::string &storeId, - const std::vector &secretKey, - std::function)> callback) -{ - // restore database - 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"); - return Status::INVALID_ARGUMENT; - } - - sptr kvStorePtr; - Status statusTmp = (it->second).GetSingleKvStore( - optionsTmp, bundleName, storeIdTmp, secretKey, - [&kvStorePtr](sptr store) { kvStorePtr = store; }); - // restore database failed - if (statusTmp != Status::SUCCESS || kvStorePtr == nullptr) { - ZLOGE("RecoverSingleKvStore reget GetSingleKvStore failed."); - return Status::DB_ERROR; - } - // recover database from backup file - auto kvStorePtrTmp = static_cast(kvStorePtr.GetRefPtr()); - bool importRet = kvStorePtrTmp->Import(bundleName); - callback(kvStorePtr); - if (!importRet) { - ZLOGE("RecoverSingleKvStore Import failed."); - return Status::RECOVER_FAILED; - } - ZLOGD("RecoverSingleKvStore Import success."); - return Status::RECOVER_SUCCESS; -} - -Status KvStoreDataService::RecoverMultiKvStore(const Options &options, - const std::string &bundleName, - const std::string &storeId, - const std::vector &secretKey, - std::function)> callback) -{ - // restore database - 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"); - return Status::INVALID_ARGUMENT; - } - - sptr kvStorePtr; - Status statusTmp = (it->second).GetKvStore( - optionsTmp, bundleName, storeIdTmp, secretKey, - [&kvStorePtr](sptr store) { - kvStorePtr = store; - }); - // restore database failed - if (statusTmp != Status::SUCCESS || kvStorePtr == nullptr) { - ZLOGE("RecoverMultiKvStore reget GetSingleKvStore failed."); - return Status::DB_ERROR; - } - - // recover database from backup file - auto kvStorePtrTmp = static_cast(kvStorePtr.GetRefPtr()); - if (!kvStorePtrTmp->Import(bundleName)) { - ZLOGE("RecoverMultiKvStore Import failed."); - return Status::RECOVER_FAILED; - } - ZLOGD("RecoverMultiKvStore Import success."); - callback(kvStorePtr); - return Status::RECOVER_SUCCESS; -} - -void KvStoreDataService::GetAllKvStoreId( - const AppId &appId, std::function &)> callback) -{ - DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - - ZLOGI("GetAllKvStoreId begin."); - std::string bundleName = Constant::TrimCopy(appId.appId); - std::vector storeIdList; - if (bundleName.empty() || bundleName.size() > MAX_APP_ID_LENGTH) { - ZLOGE("invalid appId."); - callback(Status::INVALID_ARGUMENT, storeIdList); - 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"); - callback(Status::DB_ERROR, storeIdList); - return; - } - - 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; - } - 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); - } - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("GetEntries delegate return error: %d.", static_cast(dbStatus)); - if (dbEntries.empty()) { - callback(Status::SUCCESS, storeIdList); - } else { - callback(Status::DB_ERROR, storeIdList); - } - return; - } - - for (const auto &entry : dbEntries) { - std::string keyStr = std::string(entry.key.begin(), entry.key.end()); - size_t pos = keyStr.find_last_of(Constant::KEY_SEPARATOR); - if (pos == std::string::npos) { - continue; - } - StoreId storeId; - storeId.storeId = keyStr.substr(pos + 1); - storeIdList.push_back(storeId); - } - 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) -{ - DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - - ZLOGD("begin."); - std::string bundleName = Constant::TrimCopy(appId.appId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - 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()) { - return (it->second).CloseAllKvStore(bundleName); - } - ZLOGE("store not open."); - return Status::STORE_NOT_OPEN; -} - -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."); - return Status::INVALID_ARGUMENT; - } - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - ZLOGE("get appId failed."); - return Status::PERMISSION_DENIED; - } - // delete the backup file - 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); - if (deviceAccountId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { - ZLOGE("not support sub account"); - return Status::NOT_SUPPORT; - } - - 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."); - } - 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."); - } - return DeleteKvStore(appId, storeId, bundleName); -} - -/* delete all kv store */ -Status KvStoreDataService::DeleteAllKvStore(const AppId &appId) -{ - DdsTrace trace(std::string(LOG_TAG "::") + std::string(__FUNCTION__)); - - ZLOGI("%s", appId.appId.c_str()); - std::string bundleName = Constant::TrimCopy(appId.appId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - return Status::INVALID_ARGUMENT; - } - - if (KvStoreUtils::GetAppIdByBundleName(bundleName).empty()) { - ZLOGE("invalid appId."); - return Status::PERMISSION_DENIED; - } - - Status statusTmp; - std::vector existStoreIds; - GetAllKvStoreId(appId, [&statusTmp, &existStoreIds](Status status, std::vector &storeIds) { - statusTmp = status; - existStoreIds = std::move(storeIds); - }); - - if (statusTmp != Status::SUCCESS) { - ZLOGE("%s, error: %d ", bundleName.c_str(), static_cast(statusTmp)); - return statusTmp; - } - - for (const auto &storeId : existStoreIds) { - statusTmp = DeleteKvStore(appId, storeId); - if (statusTmp != Status::SUCCESS) { - ZLOGE("%s, error: %d ", bundleName.c_str(), static_cast(statusTmp)); - return statusTmp; - } - } - - return statusTmp; -} - -/* RegisterClientDeathObserver */ -Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr observer) -{ - ZLOGD("begin."); - KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); - std::string bundleName = Constant::TrimCopy(appId.appId); - if (!CheckBundleName(bundleName)) { - ZLOGE("invalid bundleName."); - return Status::INVALID_ARGUMENT; - } - - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(bundleName); - if (trueAppId.empty()) { - return Status::PERMISSION_DENIED; - } - - std::lock_guard lg(clientDeathObserverMutex_); - auto it = clientDeathObserverMap_.emplace(std::piecewise_construct, std::forward_as_tuple(bundleName), - std::forward_as_tuple(appId, *this, std::move(observer))); - ZLOGI("map size: %zu.", clientDeathObserverMap_.size()); - if (!it.second) { - ZLOGI("insert failed"); - return Status::ERROR; - } - ZLOGI("insert success"); - - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); - KvStoreTuple kvStoreTuple {userId, trueAppId}; - AppThreadInfo appThreadInfo {IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid()}; - PermissionValidator::RegisterPermissionChanged(kvStoreTuple, appThreadInfo); - return Status::SUCCESS; -} - -Status KvStoreDataService::AppExit(const AppId &appId) -{ - ZLOGI("AppExit"); - // memory of parameter appId locates in a member of clientDeathObserverMap_ and will be freed after - // clientDeathObserverMap_ erase, so we have to take a copy if we want to use this parameter after erase operation. - AppId appIdTmp = appId; - { - std::lock_guard lg(clientDeathObserverMutex_); - clientDeathObserverMap_.erase(appIdTmp.appId); - ZLOGI("map size: %zu.", clientDeathObserverMap_.size()); - } - - std::string trueAppId = KvStoreUtils::GetAppIdByBundleName(appIdTmp.appId); - if (trueAppId.empty()) { - ZLOGE("get appid for KvStore failed because of permission denied."); - return Status::PERMISSION_DENIED; - } - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(appIdTmp.appId); - KvStoreTuple kvStoreTuple {userId, trueAppId}; - PermissionValidator::UnregisterPermissionChanged(kvStoreTuple); - - CloseAllKvStore(appIdTmp); - return Status::SUCCESS; -} - -void KvStoreDataService::OnDump() -{ - ZLOGD("begin."); -} - -int KvStoreDataService::Dump(int fd, const std::vector &args) -{ - int uid = static_cast(IPCSkeleton::GetCallingUid()); - const int maxUid = 10000; - if (uid > maxUid) { - return 0; - } - dprintf(fd, "------------------------------------------------------------------\n"); - dprintf(fd, "DeviceAccount count : %u\n", static_cast(deviceAccountMap_.size())); - for (const auto &pair : deviceAccountMap_) { - dprintf(fd, "DeviceAccountID : %s\n", pair.first.c_str()); - pair.second.Dump(fd); - } - return 0; -} - -void KvStoreDataService::OnStart() -{ - ZLOGI("distributeddata service onStart"); - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgr != nullptr) { - ZLOGI("samgr exist."); - auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); - auto kvDataServiceProxy = iface_cast(remote); - if (kvDataServiceProxy != nullptr) { - ZLOGI("service has been registered."); - 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; - } - - AppId appId; - appId.appId = metaData.bundleName; - StoreId storeId; - storeId.storeId = metaData.storeId; - CloseKvStore(appId, storeId); - DeleteKvStore(appId, storeId); - }); - - // subscribe account event listener to EventNotificationMgr - AccountDelegate::GetInstance()->SubscribeAccountEvent(); - auto permissionCheckCallback = - [this](const std::string &userId, const std::string &appId, const std::string - &storeId, const std::string &deviceId, uint8_t flag) -> bool { - // temp add permission whilelist for ddmp; this should be config in ddmp manifest. - ZLOGD("checking sync permission start appid:%s, stid:%s.", appId.c_str(), storeId.c_str()); - return CheckPermissions(userId, appId, storeId, deviceId, flag); - }; - auto dbStatus = DistributedDB::KvStoreDelegateManager::SetPermissionCheckCallback(permissionCheckCallback); - if (dbStatus != DistributedDB::DBStatus::OK) { - ZLOGE("SetPermissionCheck callback failed."); - } - - ZLOGI("autoLaunchRequestCallback start"); - auto autoLaunchRequestCallback = - [this](const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) -> bool { - ResolveAutoLaunchParamByIdentifier(identifier, param); - return true; - }; - DistributedDB::KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunchRequestCallback); - - backup_ = std::make_unique(this); - backup_->BackSchedule(); - - std::thread th = std::thread([]() { - sleep(TEN_SEC); - KvStoreAppAccessor::GetInstance().EnableKvStoreAutoLaunch(); - }); - th.detach(); - ZLOGI("Publish ret: %d", static_cast(ret)); -} - -void KvStoreDataService::ResolveAutoLaunchParamByIdentifier(const std::string &identifier, - DistributedDB::AutoLaunchParam ¶m) -{ - ZLOGI("start"); - std::map entries; - if (KvStoreMetaManager::GetInstance().GetFullMetaData(entries)) { - for (const auto &entry : entries) { - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId( - entry.second.kvStoreMetaData.bundleName); - const std::string &curIdentifier = DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier(userId, - entry.second.kvStoreMetaData.appId, entry.second.kvStoreMetaData.storeId); - if (identifier == curIdentifier) { - ZLOGI("identifier find"); - DistributedDB::AutoLaunchOption option; - option.createIfNecessary = false; - option.isEncryptedDb = entry.second.kvStoreMetaData.isEncrypt; - DistributedDB::CipherPassword password; - const std::vector &secretKey = entry.second.secretKeyMetaData.secretKey; - if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) { - ZLOGE("Get secret key failed."); - } - option.passwd = password; - option.schema = entry.second.kvStoreMetaData.schema; - option.createDirByStoreIdOnly = true; - option.dataDir = entry.second.kvStoreMetaData.dataDir; - option.secOption = KvStoreAppManager::ConvertSecurity(entry.second.kvStoreMetaData.securityLevel); - param.userId = userId; - param.appId = entry.second.kvStoreMetaData.appId; - param.storeId = entry.second.kvStoreMetaData.storeId; - param.option = option; - } - } - } -} - -bool KvStoreDataService::CheckPermissions(const std::string &userId, const std::string &appId, - const std::string &storeId, const std::string &deviceId, uint8_t flag) const -{ - auto &instance = KvStoreMetaManager::GetInstance(); - KvStoreMetaData metaData; - auto localDevId = DeviceKvStoreImpl::GetLocalDeviceId(); - auto qstatus = instance.QueryKvStoreMetaDataByDeviceIdAndAppId(localDevId, appId, metaData); - if (qstatus != Status::SUCCESS) { - qstatus = instance.QueryKvStoreMetaDataByDeviceIdAndAppId("", appId, metaData); // local device id maybe null - if (qstatus != Status::SUCCESS) { - ZLOGW("query appId failed."); - return false; - } - } - if (metaData.appType.compare("default") == 0) { - ZLOGD("default, dont check sync permission."); - return true; - } - - Status status = instance.CheckSyncPermission(userId, appId, storeId, flag, deviceId); - if (status != Status::SUCCESS) { - ZLOGW("PermissionCheck failed."); - return false; - } - - if (metaData.appType.compare("harmony") != 0) { - ZLOGD("it's A app, dont check sync permission."); - return true; - } - - if (PermissionValidator::IsAutoLaunchEnabled(appId)) { - return true; - } - bool ret = PermissionValidator::CheckSyncPermission(userId, appId, metaData.uid); - ZLOGD("checking sync permission ret:%d.", ret); - return ret; -} - -void KvStoreDataService::OnStop() -{ - ZLOGI("begin."); - if (backup_ != nullptr) { - backup_.reset(); - backup_ = nullptr; - } -} - -KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl( - const AppId &appId, KvStoreDataService &service, sptr observer) - : appId_(appId), dataService_(service), observerProxy_(std::move(observer)), - deathRecipient_(new KvStoreDeathRecipient(*this)) -{ - ZLOGI("KvStoreClientDeathObserverImpl"); - - if (observerProxy_ != nullptr) { - ZLOGI("add death recipient"); - observerProxy_->AddDeathRecipient(deathRecipient_); - } else { - ZLOGW("observerProxy_ is nullptr"); - } -} - -KvStoreDataService::KvStoreClientDeathObserverImpl::~KvStoreClientDeathObserverImpl() -{ - ZLOGI("~KvStoreClientDeathObserverImpl"); - if (deathRecipient_ != nullptr && observerProxy_ != nullptr) { - ZLOGI("remove death recipient"); - observerProxy_->RemoveDeathRecipient(deathRecipient_); - } -} - -void KvStoreDataService::KvStoreClientDeathObserverImpl::NotifyClientDie() -{ - ZLOGI("appId: %s", appId_.appId.c_str()); - dataService_.AppExit(appId_); -} - -KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::KvStoreDeathRecipient( - KvStoreClientDeathObserverImpl &kvStoreClientDeathObserverImpl) - : kvStoreClientDeathObserverImpl_(kvStoreClientDeathObserverImpl) -{ - ZLOGI("KvStore Client Death Observer"); -} - -KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::~KvStoreDeathRecipient() -{ - ZLOGI("KvStore Client Death Observer"); -} - -void KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::OnRemoteDied( - const wptr &remote) -{ - ZLOGI("begin"); - kvStoreClientDeathObserverImpl_.NotifyClientDie(); -} - -Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &storeId, const std::string &trueAppId) -{ - 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; - } - - 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_); - Status status; - auto it = deviceAccountMap_.find(deviceAccountId); - if (it != deviceAccountMap_.end()) { - status = (it->second).DeleteKvStore(trueAppId, storeIdTmp); - } else { - KvStoreUserManager kvStoreUserManager(deviceAccountId); - status = kvStoreUserManager.DeleteKvStore(trueAppId, storeIdTmp); - } - - if (status == Status::SUCCESS) { - auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); - status = KvStoreMetaManager::GetInstance().CheckUpdateServiceMeta(metaKey, DELETE); - if (status != Status::SUCCESS) { - ZLOGW("Remove Kvstore Metakey failed."); - } - KvStoreMetaManager::GetInstance().RemoveSecretKey(deviceAccountId, bundleName, storeIdTmp); - KvStoreMetaManager::GetInstance().DeleteStrategyMeta(bundleName, storeIdTmp); - } - return status; -} - - -Status KvStoreDataService::DeleteKvStoreOnly(const std::string &storeIdTmp, const std::string &deviceAccountId, - const std::string &bundleName) -{ - ZLOGI("DeleteKvStoreOnly begin."); - auto it = deviceAccountMap_.find(deviceAccountId); - if (it != deviceAccountMap_.end()) { - return (it->second).DeleteKvStore(bundleName, storeIdTmp); - } - KvStoreUserManager kvStoreUserManager(deviceAccountId); - return kvStoreUserManager.DeleteKvStore(bundleName, storeIdTmp); -} - -void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) -{ - ZLOGI("account event %d changed process, begin.", eventInfo.status); - std::lock_guard lg(accountMutex_); - switch (eventInfo.status) { - case AccountStatus::HARMONY_ACCOUNT_LOGIN: - case AccountStatus::HARMONY_ACCOUNT_LOGOUT: { - g_kvStoreAccountEventStatus = 1; - // migrate all kvstore belong to this device account - for (auto &it : deviceAccountMap_) { - (it.second).MigrateAllKvStore(eventInfo.harmonyAccountId); - } - g_kvStoreAccountEventStatus = 0; - break; - } - case AccountStatus::DEVICE_ACCOUNT_DELETE: { - g_kvStoreAccountEventStatus = 1; - // delete all kvstore belong to this device account - for (auto &it : deviceAccountMap_) { - (it.second).DeleteAllKvStore(); - } - auto it = deviceAccountMap_.find(eventInfo.deviceAccountId); - if (it != deviceAccountMap_.end()) { - deviceAccountMap_.erase(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, - "/", eventInfo.deviceAccountId}); - ForceRemoveDirectory(deviceAccountKvStoreDataDir); - g_kvStoreAccountEventStatus = 0; - break; - } - default: { - break; - } - } - ZLOGI("account event %d changed process, end.", eventInfo.status); -} - -Status KvStoreDataService::GetLocalDevice(DeviceInfo &device) -{ - auto tmpDevice = KvStoreUtils::GetProviderInstance().GetLocalBasicInfo(); - device = {tmpDevice.deviceId, tmpDevice.deviceName, tmpDevice.deviceType}; - return Status::SUCCESS; -} - -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 }); - } - ZLOGD("strategy is %d.", strategy); - return Status::SUCCESS; -} - -Status KvStoreDataService::StartWatchDeviceChange(sptr observer, - DeviceFilterStrategy strategy) -{ - if (observer == nullptr) { - ZLOGD("observer is null"); - return Status::INVALID_ARGUMENT; - } - std::lock_guard lck(deviceListenerMutex_); - if (deviceListener_ == nullptr) { - deviceListener_ = std::make_shared(deviceListeners_); - KvStoreUtils::GetProviderInstance().StartWatchDeviceChange(deviceListener_.get(), {"serviceWatcher"}); - } - IRemoteObject *objectPtr = observer->AsObject().GetRefPtr(); - deviceListeners_.insert({ objectPtr, observer }); - ZLOGD("strategy is %d.", strategy); - return Status::SUCCESS; -} - -Status KvStoreDataService::StopWatchDeviceChange(sptr observer) -{ - if (observer == nullptr) { - ZLOGD("observer is null"); - return Status::INVALID_ARGUMENT; - } - std::lock_guard lck(deviceListenerMutex_); - IRemoteObject *objectPtr = observer->AsObject().GetRefPtr(); - auto it = deviceListeners_.find(objectPtr); - if (it == deviceListeners_.end()) { - return Status::ILLEGAL_STATE; - } - deviceListeners_.erase(it->first); - return Status::SUCCESS; -} - -sptr KvStoreDataService::GetRdbService() -{ - return rdbService_; -} - -bool DbMetaCallbackDelegateMgr::GetKvStoreDiskSize(const std::string &storeId, uint64_t &size) -{ - if (IsDestruct()) { - return false; - } - DistributedDB::DBStatus ret = delegate_->GetKvStoreDiskSize(storeId, size); - return (ret == DistributedDB::DBStatus::OK); -} - -void DbMetaCallbackDelegateMgr::GetKvStoreKeys(std::vector &dbStats) -{ - if (IsDestruct()) { - return; - } - DistributedDB::DBStatus dbStatusTmp; - Option option {.createIfNecessary = true, .isMemoryDb = false, .isEncryptedDb = false}; - DistributedDB::KvStoreNbDelegate *kvStoreNbDelegatePtr = nullptr; - delegate_->GetKvStore( - Constant::SERVICE_META_DB_NAME, option, - [&kvStoreNbDelegatePtr, &dbStatusTmp](DistributedDB::DBStatus dbStatus, - DistributedDB::KvStoreNbDelegate *kvStoreNbDelegate) { - kvStoreNbDelegatePtr = kvStoreNbDelegate; - dbStatusTmp = dbStatus; - }); - - if (dbStatusTmp != DistributedDB::DBStatus::OK) { - return; - } - DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor(""); - std::vector entries; - kvStoreNbDelegatePtr->GetEntries(dbKey, entries); - if (entries.empty()) { - delegate_->CloseKvStore(kvStoreNbDelegatePtr); - return; - } - for (auto const &entry : entries) { - std::string key = std::string(entry.key.begin(), entry.key.end()); - std::vector out; - Split(key, Constant::KEY_SEPARATOR, out); - if (out.size() >= VECTOR_SIZE) { - StoreInfo storeInfo = {out[USER_ID], out[APP_ID], out[STORE_ID]}; - dbStats.push_back(std::move(storeInfo)); - } - } - delegate_->CloseKvStore(kvStoreNbDelegatePtr); -} -} // namespace DistributedKv -} // namespace OHOS diff --git a/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp index 358fa00bed5e020a70d01fc7c1232a03b75f0d5e..fbef76d6a62c3ba85ded6b84fee02157b6b085f3 100755 --- a/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_data_service_test.cpp @@ -13,13 +13,13 @@ * limitations under the License. */ -#include #include #include +#include #include #include "kvstore_client_death_observer.h" #include "kvstore_data_service.h" - +#include "gtest/gtest.h" using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp index 2a25bdaa55eb7d3be1804a76ccfa6c5875ad18c1..9b48b7633d3f01dbd778dd8ac315f90171cb3dfc 100755 --- a/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_impl_logical_isolation_test.cpp @@ -12,8 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include #include #include #include @@ -21,6 +19,7 @@ #include "kvstore_impl.h" #include "refbase.h" #include "types.h" +#include "gtest/gtest.h" using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS; diff --git a/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp index 2d737c9145b285a176fb0f8394d0aa89b1bdebf1..581083b1c3517b6f8b81275d3b628c4d0cee621f 100755 --- a/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_impl_physical_isolation_test.cpp @@ -12,8 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include #include #include #include @@ -22,6 +20,7 @@ #include "kvstore_impl.h" #include "refbase.h" #include "types.h" +#include "gtest/gtest.h" using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS; @@ -102,10 +101,9 @@ void KvStoreImplPhysicalIsolationTest::TearDown(void) */ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation001, TestSize.Level1) { - const std::string storePath = Constant::Concatenate({Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", - AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, "/", - Constant::GetDefaultHarmonyAccountName(), "/" }) + - std::string("phy0/store0"); + const std::string storePath = Constant::Concatenate( + {Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", "0", "/", Constant::GetDefaultHarmonyAccountName(), + "/"}) + std::string("phy0/store0"); sptr kvStorePtr; Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, @@ -124,7 +122,7 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation001, TestSize.Level1 */ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation002, TestSize.Level1) { - const std::string deviceAccountId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; + const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); @@ -154,7 +152,7 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation002, TestSize.Level1 */ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation003, TestSize.Level1) { - const std::string deviceAccountId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; + const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); @@ -184,7 +182,7 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation003, TestSize.Level1 */ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation004, TestSize.Level1) { - const std::string deviceAccountId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; + const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); @@ -215,9 +213,9 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation004, TestSize.Level1 */ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation005, TestSize.Level1) { - const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", - AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, "/", - Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); + const std::string storePath = Constant::Concatenate( + {Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", "0", "/", Constant::GetDefaultHarmonyAccountName(), + "/"}) + std::string("phy0/store0"); sptr kvStorePtr; Status status = g_kvStoreDataService->GetKvStore(g_defaultOptions, g_appId, g_storeId, @@ -243,9 +241,9 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation005, TestSize.Level1 */ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation006, TestSize.Level1) { - const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", - AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, "/", - Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); + const std::string storePath = Constant::Concatenate( + {Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", "0", "/", Constant::GetDefaultHarmonyAccountName(), + "/"}) + std::string("phy0/store0"); sptr kvStorePtr; sptr kvStorePtr1; sptr kvStorePtr2; @@ -283,7 +281,7 @@ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation006, TestSize.Level1 */ HWTEST_F(KvStoreImplPhysicalIsolationTest, PhysicalIsolation007, TestSize.Level1) { - const std::string deviceAccountId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; + const std::string deviceAccountId = "0"; const std::string storePath = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", deviceAccountId, "/", Constant::GetDefaultHarmonyAccountName(), "/" }) + std::string("phy0/store0"); const std::string storePath1 = Constant::Concatenate({ Constant::ROOT_PATH_CE, "/", Constant::SERVICE_NAME, "/", diff --git a/services/distributeddataservice/app/test/unittest/kvstore_sync_manager_test.cpp b/services/distributeddataservice/app/test/unittest/kvstore_sync_manager_test.cpp index e1ddbba8fc7eccc9c5eaa73e7f6349430ee5c87b..8f89a4b6cd71b4cb78822c23d1eb6e9de31a50d6 100644 --- a/services/distributeddataservice/app/test/unittest/kvstore_sync_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/kvstore_sync_manager_test.cpp @@ -12,16 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include #include #include #include #include +#include +#include "ut_kvstore_nb_delegate_impl.h" #include #include "kvstore_sync_manager.h" #include "log_print.h" -#include "ut_kvstore_nb_delegate_impl.h" +#include "gtest/gtest.h" using namespace testing::ext; using namespace OHOS::DistributedKv; @@ -69,8 +69,8 @@ void KvStoreSyncManagerTest::CreateKvStorePair(bool isAutoSync, const std::strin std::string userId = "syncManagerTest"; std::string appId = "syncTest"; std::string appDir = "syncTest"; - kvStore = std::make_unique(options, userId, appId, storeId, appDir, kvNb.get()); - kvStore2 = std::make_unique(options, userId, appId, storeId, appDir, kvNb2.get()); + kvStore = std::make_unique(options, userId, appId, storeId, appId, appDir, kvNb.get()); + kvStore2 = std::make_unique(options, userId, appId, storeId, appId, appDir, kvNb2.get()); return; } diff --git a/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp b/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp index 48972cc054d743dcae7c5eb180f53f3fda51ec48..dedd386d560e1b1c1075fe060fa627268ffb879e 100755 --- a/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp +++ b/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp @@ -14,7 +14,7 @@ */ #include -#include "uninstaller.h" +#include "uninstaller/uninstaller.h" using namespace testing::ext; using namespace OHOS::DistributedKv; diff --git a/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.cpp b/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.cpp index 193eca6cd0493060cc8f8892933938db5ba003f0..3fee2074e7d61b262d6ad67e816114833d6d221e 100755 --- a/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.cpp +++ b/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.cpp @@ -351,4 +351,19 @@ DBStatus UtKvStoreNbDelegateImpl::DeleteLocalBatch(const std::vector &keys) { return OK; } +DBStatus UtKvStoreNbDelegateImpl::Sync(const std::vector &devices, SyncMode mode, + const std::function &)> &onComplete, Query &query, bool wait) +{ + return ALREADY_SET; +} +DBStatus UtKvStoreNbDelegateImpl::SubscribeRemoteQuery(const std::vector &devices, + const std::function &)> &onComplete, Query &query, bool wait) +{ + return ALREADY_SET; +} +DBStatus UtKvStoreNbDelegateImpl::UnSubscribeRemoteQuery(const std::vector &devices, + const std::function &)> &onComplete, Query &query, bool wait) +{ + return ALREADY_SET; +} } // namespace DistributedDB diff --git a/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.h b/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.h index 19d80954e27fc7ce0f60f873d38dc36c6791f217..36a84567f8e9dfc12f8dbe51e1b729d0eb5edf56 100755 --- a/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.h +++ b/services/distributeddataservice/app/test/unittest/ut_kvstore_nb_delegate_impl.h @@ -101,6 +101,16 @@ public: { return DBStatus::NOT_SUPPORT; }; + DBStatus Sync(const std::vector &devices, SyncMode mode, + const std::function &)> &onComplete, Query &query, + bool wait) override; + DBStatus SubscribeRemoteQuery(const std::vector &devices, + const std::function &)> &onComplete, Query &query, + bool wait) override; + DBStatus UnSubscribeRemoteQuery(const std::vector &devices, + const std::function &)> &onComplete, Query &query, + bool wait) override; + private: static constexpr size_t MAX_KEY_SIZE = 1024; // 1KB static constexpr size_t MAX_VALUE_SIZE = 4 * 1024 * 1024; // 4MB diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 49ba332cf487c7bc2cfbb349757a43ab8d486863..80152824cc0bf68d3ce0104f33525ebbe99bec14 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -21,6 +21,7 @@ config("module_public_config") { include_dirs = [ "include", "//third_party/json/single_include", + "//third_party/openssl/include/", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", ] @@ -38,6 +39,7 @@ ohos_shared_library("distributeddatasvcfwk") { "metadata/store_meta_data.cpp", "serializable/serializable.cpp", "utils/constant.cpp", + "utils/crypto.cpp", ] cflags = [ "-Wno-multichar" ] @@ -45,9 +47,10 @@ ohos_shared_library("distributeddatasvcfwk") { configs = [ ":module_public_config" ] - # ldflags = [ "-Wl,--exclude-libs,libcrypto_static.a" ] + ldflags = [ "-Wl,--exclude-libs,libcrypto_static.a" ] deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//third_party/openssl:libcrypto_static", "//utils/native/base:utils", ] diff --git a/services/distributeddataservice/framework/checker/checker_manager.cpp b/services/distributeddataservice/framework/checker/checker_manager.cpp index e1c79200a0a433d5bc5ad54c9afce32395ace8f2..d6869475ce96552bbf546ac617a1b3dd16b78d31 100644 --- a/services/distributeddataservice/framework/checker/checker_manager.cpp +++ b/services/distributeddataservice/framework/checker/checker_manager.cpp @@ -63,7 +63,7 @@ std::string CheckerManager::GetAppId(const std::string &bundleName, pid_t uid) } return appId; } - return bundleName; + return ""; } bool CheckerManager::IsValid(const std::string &bundleName, pid_t uid) diff --git a/services/distributeddataservice/framework/checker/default/bundle_checker.cpp b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp index e6d301e6c8fe60805afdd2b7037ea8151e7ef4c3..48e9daa1ff5b42c333fb0de946487fade46c40d0 100644 --- a/services/distributeddataservice/framework/checker/default/bundle_checker.cpp +++ b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp @@ -12,10 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#define LOG_TAG "BundleChecker" #include "checker/default/bundle_checker.h" #include #include "bundlemgr/bundle_mgr_client.h" +#include "log/log_print.h" +#include "utils/crypto.h" namespace OHOS { namespace DistributedData { using namespace AppExecFwk; @@ -43,17 +46,21 @@ bool BundleChecker::SetTrustInfo(const CheckerManager::Trust &trust) std::string BundleChecker::GetAppId(pid_t uid, const std::string &bundleName) { + if (uid < SYSTEM_UID && uid != CheckerManager::INVALID_UID) { + return ""; + } + BundleMgrClient bmsClient; std::string bundle = bundleName; if (uid != CheckerManager::INVALID_UID) { auto success = bmsClient.GetBundleNameForUid(uid, bundle); - if (uid < SYSTEM_UID || !success || bundle != bundleName) { + if (!success || bundle != bundleName) { return ""; } } auto bundleInfo = std::make_unique(); - auto success = bmsClient.GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo); + auto success = bmsClient.GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo, Constants::ANY_USERID); if (!success) { return ""; } @@ -61,30 +68,26 @@ std::string BundleChecker::GetAppId(pid_t uid, const std::string &bundleName) if (it != trusts_.end() && (it->second == bundleInfo->appId)) { return bundleName; } - - return bundleInfo->appId; + ZLOGD("bundleName:%{public}s, uid:%{public}d, appId:%{public}s", bundleName.c_str(), uid, + bundleInfo->appId.c_str()); + return Crypto::Sha256(bundleInfo->appId); } bool BundleChecker::IsValid(pid_t uid, const std::string &bundleName) { + if (uid < SYSTEM_UID) { + return false; + } + BundleMgrClient bmsClient; std::string bundle = bundleName; auto success = bmsClient.GetBundleNameForUid(uid, bundle); - if (uid < SYSTEM_UID || !success || bundle != bundleName) { + if (!success || bundle != bundleName) { return false; } auto bundleInfo = std::make_unique(); - success = bmsClient.GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo); - if (!success) { - return false; - } - auto it = trusts_.find(bundleName); - if (it != trusts_.end() && (it->second == bundleInfo->appId)) { - return true; - } - - return true; + return bmsClient.GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo, Constants::ANY_USERID); } } } \ No newline at end of file diff --git a/services/distributeddataservice/framework/checker/default/system_checker.cpp b/services/distributeddataservice/framework/checker/default/system_checker.cpp index c497fb9518240ed6afc11fb5b8f8950b32cff89b..84ce58d0e8e3539ed6191fec2734d49edf92a5b5 100644 --- a/services/distributeddataservice/framework/checker/default/system_checker.cpp +++ b/services/distributeddataservice/framework/checker/default/system_checker.cpp @@ -12,8 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#define LOG_TAG "SystemChecker" #include "checker/default/system_checker.h" +#include "log/log_print.h" namespace OHOS { namespace DistributedData { SystemChecker SystemChecker::instance_; @@ -40,19 +41,17 @@ bool SystemChecker::SetTrustInfo(const CheckerManager::Trust &trust) std::string SystemChecker::GetAppId(pid_t uid, const std::string &bundleName) { - if (trusts_.find(bundleName) == trusts_.end() || uid >= SYSTEM_UID || uid == CheckerManager::INVALID_UID) { + if (uid >= SYSTEM_UID || uid == CheckerManager::INVALID_UID) { return ""; } - return trusts_[bundleName]; + std::string appId = (trusts_.find(bundleName) != trusts_.end()) ? trusts_[bundleName] : bundleName; + ZLOGD("bundleName:%{public}s, uid:%{public}d, appId:%{public}s", bundleName.c_str(), uid, appId.c_str()); + return appId; } bool SystemChecker::IsValid(pid_t uid, const std::string &bundleName) { - if (trusts_.find(bundleName) == trusts_.end() || uid >= SYSTEM_UID || uid == CheckerManager::INVALID_UID) { - return false; - } - // todo get appid - return true; + return (uid < SYSTEM_UID && uid != CheckerManager::INVALID_UID); } } } \ No newline at end of file diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h index 11402e7c3802479c240ebb8df2eb1f0fb135b481..244b1aecc616ba9bab162bb310e943a2ac995587 100644 --- a/services/distributeddataservice/framework/include/utils/constant.h +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -29,22 +29,22 @@ namespace OHOS { namespace DistributedKv { class KvStoreMetaRow { public: - KVSTORE_API static const std::string KEY_PREFIX; + API_EXPORT static const std::string KEY_PREFIX; - KVSTORE_API static std::vector GetKeyFor(const std::string &key); + API_EXPORT static std::vector GetKeyFor(const std::string &key); }; class SecretMetaRow { public: - KVSTORE_API static const std::string KEY_PREFIX; + API_EXPORT static const std::string KEY_PREFIX; - KVSTORE_API static std::vector GetKeyFor(const std::string &key); + API_EXPORT static std::vector GetKeyFor(const std::string &key); }; class Constant { public: // concatenate strings and return a composition string. - KVSTORE_API static std::string Concatenate(std::initializer_list stringList); + API_EXPORT static std::string Concatenate(std::initializer_list stringList); // delete left bland in s by reference. template @@ -71,68 +71,67 @@ public: static T TrimCopy(T s); // get default device account id. - KVSTORE_API static std::string GetDefaultDeviceAccountId(); + API_EXPORT static std::string GetDefaultDeviceAccountId(); // get default harmony account name. - KVSTORE_API static std::string GetDefaultHarmonyAccountName(); + API_EXPORT static std::string GetDefaultHarmonyAccountName(); // default group id for synchronization based on harmony account. - KVSTORE_API static const std::string DEFAULT_GROUP_ID; + API_EXPORT static const std::string DEFAULT_GROUP_ID; // Indicates whether only storeid are used as hash materials for the DistributedDB path generated. - KVSTORE_API static const bool STOREID_ONLY_FLAG; + API_EXPORT static const bool STOREID_ONLY_FLAG; // version for distributed kv data service. - KVSTORE_API static const std::string VERSION; + API_EXPORT static const std::string VERSION; // meta name for distributed kv data service. - KVSTORE_API static const std::string META_DIR_NAME; + API_EXPORT static const std::string META_DIR_NAME; // name for distributed kv data service. - KVSTORE_API static const std::string SERVICE_NAME; + API_EXPORT static const std::string SERVICE_NAME; // root path for distributed kv data service. - KVSTORE_API static const std::string ROOT_PATH; + API_EXPORT static const std::string ROOT_PATH; // root path for distributeddata service and system services. - KVSTORE_API static const std::string ROOT_PATH_DE; + API_EXPORT static const std::string ROOT_PATH_DE; // root path for self-developed and non-self-developed app. - KVSTORE_API static const std::string ROOT_PATH_CE; + API_EXPORT static const std::string ROOT_PATH_CE; // the max length for key is 256. - KVSTORE_API static const size_t MAX_KEY_LENGTH; + API_EXPORT static const size_t MAX_KEY_LENGTH; // the max length for value is 1M. - KVSTORE_API static const size_t MAX_VALUE_LENGTH; + API_EXPORT static const size_t MAX_VALUE_LENGTH; // the max length for StoreId is 64. - KVSTORE_API static const size_t MAX_STORE_ID_LENGTH; + API_EXPORT static const size_t MAX_STORE_ID_LENGTH; // the max batch for putBatch is 128. - KVSTORE_API static const size_t MAX_BATCH_SIZE; + API_EXPORT static const size_t MAX_BATCH_SIZE; // the max capacity for ipc is 800KB. - KVSTORE_API static const size_t MAX_IPC_CAPACITY; + API_EXPORT static const size_t MAX_IPC_CAPACITY; // service meta db name. - KVSTORE_API static const std::string SERVICE_META_DB_NAME; + API_EXPORT static const std::string SERVICE_META_DB_NAME; - KVSTORE_API static const std::string KEY_SEPARATOR; + API_EXPORT static const std::string KEY_SEPARATOR; - KVSTORE_API static const mode_t DEFAULT_MODE; + API_EXPORT static const mode_t DEFAULT_MODE; - KVSTORE_API static const mode_t DEFAULT_MODE_DIR; + API_EXPORT static const mode_t DEFAULT_MODE_DIR; - KVSTORE_API static const mode_t DEFAULT_MODE_FILE; + API_EXPORT static const mode_t DEFAULT_MODE_FILE; - KVSTORE_API static const int SWITCH_RAW_DATA_SIZE; + API_EXPORT static const int SWITCH_RAW_DATA_SIZE; - KVSTORE_API static const int MAX_OPEN_KVSTORES; + API_EXPORT static const int MAX_OPEN_KVSTORES; // name for process label (bus name for communication). compatible with HwDDMP - KVSTORE_API static const std::string PROCESS_LABEL; - KVSTORE_API static const std::string ROOT_KEY_GENERATED; + API_EXPORT static const std::string ROOT_KEY_GENERATED; }; // trim from start (in place) diff --git a/services/distributeddataservice/app/src/kvstore_common.h b/services/distributeddataservice/framework/include/utils/crypto.h old mode 100755 new mode 100644 similarity index 47% rename from services/distributeddataservice/app/src/kvstore_common.h rename to services/distributeddataservice/framework/include/utils/crypto.h index 41d4eb13927354336eb0fb4ac7a57ecd669d6172..d84266204eac6ce3400b519dcbdf475f52f06ccc --- a/services/distributeddataservice/app/src/kvstore_common.h +++ b/services/distributeddataservice/framework/include/utils/crypto.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,19 +13,19 @@ * limitations under the License. */ -#ifndef KVSTORE_COMMON_H -#define KVSTORE_COMMON_H - -#include "types.h" - -namespace OHOS::DistributedKv { -struct KvStoreParams { - Options options; - bool deviceCoordinate; - std::string deviceAccountId; - std::string appId; - std::string storeId; - std::string appDirectory; +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_UTILS_CRYPTO_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_UTILS_CRYPTO_H +#include +#include +#include "visibility.h" +namespace OHOS { +namespace DistributedData { +class Crypto { +public: + API_EXPORT static std::string Sha256(const std::string &text, bool isUpper = false); + API_EXPORT static std::string Sha256(const void *data, size_t size, bool isUpper = false); + API_EXPORT static std::vector Random(int32_t len); }; } -#endif // KVSTORE_COMMON_H +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_UTILS_CRYPTO_H diff --git a/services/distributeddataservice/framework/test/checker_manager_test.cpp b/services/distributeddataservice/framework/test/checker_manager_test.cpp index 31c292433073f5ab046c11eda340430be6f44ed0..b858eaabd041f5f4f38fb1751cd2bbee31eccde4 100644 --- a/services/distributeddataservice/framework/test/checker_manager_test.cpp +++ b/services/distributeddataservice/framework/test/checker_manager_test.cpp @@ -14,6 +14,7 @@ */ #include "checker/checker_manager.h" +#include "utils/crypto.h" #include using namespace testing::ext; using namespace OHOS::DistributedData; @@ -89,7 +90,7 @@ HWTEST_F(CheckerManagerTest, SystemCheckerIVI, TestSize.Level0) */ HWTEST_F(CheckerManagerTest, BundleChecker, TestSize.Level0) { - ASSERT_EQ("ohos.test.demo", + ASSERT_EQ(Crypto::Sha256("ohos.test.demo"), CheckerManager::GetInstance().GetAppId("ohos.test.demo", 100000)); ASSERT_TRUE(CheckerManager::GetInstance().IsValid("ohos.test.demo", 100000)); } \ No newline at end of file diff --git a/services/distributeddataservice/framework/utils/constant.cpp b/services/distributeddataservice/framework/utils/constant.cpp index 75b77bb9e2c5014a2fd788b4b4fb760f214e078c..910f564af3000e3b62909608f1702319cb2d93fa 100644 --- a/services/distributeddataservice/framework/utils/constant.cpp +++ b/services/distributeddataservice/framework/utils/constant.cpp @@ -83,8 +83,6 @@ const std::string Constant::SERVICE_META_DB_NAME = "service_meta"; const std::string Constant::KEY_SEPARATOR = "###"; -const std::string Constant::PROCESS_LABEL = "distributeddata"; - std::vector KvStoreMetaRow::GetKeyFor(const std::string &key) { std::string str = Constant::Concatenate({KvStoreMetaRow::KEY_PREFIX, Constant::KEY_SEPARATOR, key }); diff --git a/services/distributeddataservice/framework/utils/crypto.cpp b/services/distributeddataservice/framework/utils/crypto.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93be848591971be5a5653ccbfbd242d22b8ded4f --- /dev/null +++ b/services/distributeddataservice/framework/utils/crypto.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "utils/crypto.h" +#include +#include "openssl/sha.h" +namespace OHOS { +namespace DistributedData { +std::string Crypto::Sha256(const std::string &text, bool isUpper) +{ + return Sha256(text.data(), text.size(), isUpper); +} + +std::vector Crypto::Random(int32_t len) +{ + std::random_device randomDevice; + std::uniform_int_distribution distribution(0, std::numeric_limits::max()); + std::vector key(len); + for (int32_t i = 0; i < len; i++) { + key[i] = static_cast(distribution(randomDevice)); + } + return key; +} + +std::string Crypto::Sha256(const void *data, size_t size, bool isUpper) +{ + unsigned char hash[SHA256_DIGEST_LENGTH * 2 + 1] = ""; + SHA256_CTX ctx; + SHA256_Init(&ctx); + SHA256_Update(&ctx, data, size); + SHA256_Final(&hash[SHA256_DIGEST_LENGTH], &ctx); + // here we translate sha256 hash to hexadecimal. each 8-bit char will be presented by two characters([0-9a-f]) + constexpr int WIDTH = 4; + constexpr unsigned char MASK = 0x0F; + const char* hexCode = isUpper ? "0123456789ABCDEF" : "0123456789abcdef"; + for (int32_t i = 0; i < SHA256_DIGEST_LENGTH; ++i) { + unsigned char value = hash[SHA256_DIGEST_LENGTH + i]; + // uint8_t is 2 digits in hexadecimal. + hash[i * 2] = hexCode[(value >> WIDTH) & MASK]; + hash[i * 2 + 1] = hexCode[value & MASK]; + } + hash[SHA256_DIGEST_LENGTH * 2] = 0; + return reinterpret_cast(hash); +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/config_factory.cpp b/services/distributeddataservice/service/config/src/config_factory.cpp index c689aba36f27629fdcda4dcc36ddbaeb65c4d831..796b2cecb64f73dc6f38d42348fa81ee019a10e7 100644 --- a/services/distributeddataservice/service/config/src/config_factory.cpp +++ b/services/distributeddataservice/service/config/src/config_factory.cpp @@ -38,7 +38,7 @@ int32_t ConfigFactory::Initialize() { std::string jsonStr; std::ifstream fin(file_); - while (!fin.eof()) { + while (fin.good()) { std::string line; std::getline(fin, line); jsonStr += line; diff --git a/services/distributeddataservice/service/directory/src/directory_manager.cpp b/services/distributeddataservice/service/directory/src/directory_manager.cpp index feed7f7f3189326448b7c6760ba28bb9c13e47dc..f4e8f331c7c9cbe91b9743b18bc986ddd81577ef 100644 --- a/services/distributeddataservice/service/directory/src/directory_manager.cpp +++ b/services/distributeddataservice/service/directory/src/directory_manager.cpp @@ -18,7 +18,6 @@ #include #include "utils/constant.h" -#include "autils/directory_utils.h" #include "directory_ex.h" #include "kvstore_context.h" #include "log/log_print.h" @@ -44,17 +43,6 @@ bool ServerDirWorker::CreateDir(ClientContext clientContext, PathType type) ZLOGE("create directory[%s] failed, errstr=[%d].", directory.c_str(), errno); return false; } - // change mode for directories to 0755, and for files to 0600. - ret = DirectoryUtils::ChangeModeDirOnly(directory, Constant::DEFAULT_MODE_DIR); - if (!ret) { - ZLOGE("change directory[%s] mode failed, errstr=[%d].", directory.c_str(), errno); - return false; - } - ret = DirectoryUtils::ChangeModeFileOnly(directory, Constant::DEFAULT_MODE_FILE); - if (!ret) { - ZLOGE("change file[%s] mode failed, errstr=[%d].", directory.c_str(), errno); - return false; - } return true; } ServerDirWorker &ServerDirWorker::GetInstance() @@ -117,7 +105,6 @@ DirectoryManager &DirectoryManager::GetInstance() std::string DirectoryManager::GetStorePath(const StoreMetaData &metaData) { - // todo implement; return {}; } diff --git a/services/rdb/rdb_device_syncer.cpp b/services/rdb/rdb_device_syncer.cpp index a3fa2939e42543f388e8ff57538fa5a6688d2ae6..8a5da35db2198f498785c16456b9f6f3e2c68db8 100644 --- a/services/rdb/rdb_device_syncer.cpp +++ b/services/rdb/rdb_device_syncer.cpp @@ -22,8 +22,8 @@ #include "relational_store_delegate.h" namespace OHOS::DistributedRdb { -RdbDeviceSyncer::RdbDeviceSyncer(const RdbSyncerParam ¶m) - : RdbSyncerImpl(param), isInit_(false), manager_(nullptr), delegate_(nullptr) +RdbDeviceSyncer::RdbDeviceSyncer(const RdbSyncerParam ¶m, pid_t uid) + : RdbSyncerImpl(param, uid), isInit_(false), manager_(nullptr), delegate_(nullptr) { ZLOGI("construct %{public}s", param.storeName_.c_str()); } diff --git a/services/rdb/rdb_device_syncer.h b/services/rdb/rdb_device_syncer.h index 6ed93a5130690324150b398e397300616f6a273b..aa5f37eb4aad89ed8d818588a96538eae7aec74d 100644 --- a/services/rdb/rdb_device_syncer.h +++ b/services/rdb/rdb_device_syncer.h @@ -29,7 +29,7 @@ class RelationalStoreDelegate; namespace OHOS::DistributedRdb { class RdbDeviceSyncer : public RdbSyncerImpl { public: - explicit RdbDeviceSyncer(const RdbSyncerParam& param); + explicit RdbDeviceSyncer(const RdbSyncerParam& param, pid_t uid); ~RdbDeviceSyncer() override; diff --git a/services/rdb/rdb_service_impl.cpp b/services/rdb/rdb_service_impl.cpp index 20abd3c097076233200c87c5a62fa24eccb628d2..7cae2f86019cafaa86ce2cd5571a67d050cd505e 100644 --- a/services/rdb/rdb_service_impl.cpp +++ b/services/rdb/rdb_service_impl.cpp @@ -16,14 +16,16 @@ #define LOG_TAG "RdbServiceImpl" #include "rdb_service_impl.h" -#include "kvstore_utils.h" +#include "checker/checker_manager.h" +#include "ipc_skeleton.h" #include "log_print.h" #include "rdb_syncer_impl.h" #include "rdb_syncer_factory.h" namespace OHOS::DistributedRdb { -RdbServiceImpl::ClientDeathRecipient::ClientDeathRecipient(DeathCallback& callback) - : callback_(callback) +using namespace OHOS::DistributedData; +RdbServiceImpl::ClientDeathRecipient::ClientDeathRecipient(std::function&)> callback) + : callback_(std::move(callback)) { ZLOGI("construct"); } @@ -41,57 +43,56 @@ void RdbServiceImpl::ClientDeathRecipient::OnRemoteDied(const wptr& proxy) +void RdbServiceImpl::ClearClientRecipient(sptr& proxy) { - ZLOGI("remove %{public}s", bundleName.c_str()); recipients_.Erase(proxy); } -void RdbServiceImpl::ClearClientSyncers(const std::string& bundleName) +void RdbServiceImpl::ClearClientSyncers(pid_t pid) { ZLOGI("enter"); - std::string appId = DistributedKv::KvStoreUtils::GetAppIdByBundleName(bundleName); - auto count = syncers_.EraseIf([&appId](const std::string &key, sptr &value) -> bool { - return value->GetAppId() == appId; - }); + auto count = syncers_.Erase(pid); ZLOGI("remove %{public}d", static_cast(count)); } -void RdbServiceImpl::OnClientDied(const std::string &bundleName, sptr& proxy) -{ - ZLOGI("%{public}s died", bundleName.c_str()); - ClearClientRecipient(bundleName, proxy); - ClearClientSyncers(bundleName); -} - -bool RdbServiceImpl::CheckAccess(const RdbSyncerParam& param) const +void RdbServiceImpl::OnClientDied(pid_t pid, sptr& proxy) { - return !DistributedKv::KvStoreUtils::GetAppIdByBundleName(param.bundleName_).empty(); + ClearClientRecipient(proxy); + ClearClientSyncers(pid); } -sptr RdbServiceImpl::CreateSyncer(const RdbSyncerParam& param) +sptr RdbServiceImpl::CreateSyncer(const RdbSyncerParam& param, pid_t uid, pid_t pid) { - RdbSyncerImpl* syncerNew = RdbSyncerFactory::GetInstance().CreateSyncer(param); - syncers_.ComputeIfAbsent(syncerNew->GetIdentifier(), - [&syncerNew] (const auto& key) -> auto { - ZLOGI("create new syncer %{public}s", key.c_str()); - if (syncerNew != nullptr) { - syncerNew->Init(); - } - return sptr(syncerNew); - }); - return syncers_[syncerNew->GetIdentifier()]; + sptr syncer; + syncers_.Compute(pid, [¶m, uid, &syncer] (const auto &key, auto &syncers) -> bool { + ZLOGI("create new syncer %{public}d", key); + auto it = syncers.find(param.storeName_); + if (it != syncers.end()) { + syncer = it->second; + return true; + } + syncer = RdbSyncerFactory::GetInstance().CreateSyncer(param, uid); + if (syncer == nullptr) { + return false; + } + syncer->Init(); + syncers.insert({param.storeName_, syncer}); + return true; + }); + return syncer; } sptr RdbServiceImpl::GetRdbSyncerInner(const RdbSyncerParam& param) { + pid_t uid = IPCSkeleton::GetCallingUid(); + pid_t pid = IPCSkeleton::GetCallingPid(); ZLOGI("%{public}s %{public}s %{public}s", param.bundleName_.c_str(), param.path_.c_str(), param.storeName_.c_str()); - if (!CheckAccess(param)) { + if (!CheckerManager::GetInstance().IsValid(param.bundleName_, uid)) { ZLOGI("check access failed"); return nullptr; } - return CreateSyncer(param); + return CreateSyncer(param, uid, pid); } int RdbServiceImpl::RegisterClientDeathRecipient(const std::string& bundleName, sptr proxy) @@ -101,10 +102,11 @@ int RdbServiceImpl::RegisterClientDeathRecipient(const std::string& bundleName, return -1; } - ClientDeathRecipient::DeathCallback callback = [bundleName, this] (sptr& object) { - OnClientDied(bundleName, object); - }; - sptr recipient = new(std::nothrow) ClientDeathRecipient(callback); + pid_t pid = IPCSkeleton::GetCallingPid(); + sptr recipient = new(std::nothrow) ClientDeathRecipient( + [this, pid](sptr& object) { + OnClientDied(pid, object); + }); if (recipient == nullptr) { ZLOGE("malloc failed"); return -1; diff --git a/services/rdb/rdb_service_impl.h b/services/rdb/rdb_service_impl.h index 569def5a7159ef0209a966fed9d7f01a0a875f72..42b9bf1ef096746b374a99426b2dac0cf91ecbb2 100644 --- a/services/rdb/rdb_service_impl.h +++ b/services/rdb/rdb_service_impl.h @@ -31,28 +31,25 @@ public: int RegisterClientDeathRecipient(const std::string& bundleName, sptr proxy) override; - void OnClientDied(const std::string& bundleName, sptr& proxy); + void OnClientDied(pid_t pid, sptr& proxy); private: - bool CheckAccess(const RdbSyncerParam& param) const; + sptr CreateSyncer(const RdbSyncerParam& param, pid_t uid, pid_t pid); - sptr CreateSyncer(const RdbSyncerParam& param); + void ClearClientRecipient(sptr& proxy); - void ClearClientRecipient(const std::string& bundleName, sptr& proxy); - - void ClearClientSyncers(const std::string& bundleName); + void ClearClientSyncers(pid_t pid); class ClientDeathRecipient : public DeathRecipient { public: - using DeathCallback = std::function&)>; - explicit ClientDeathRecipient(DeathCallback& callback); + explicit ClientDeathRecipient(std::function&)> callback); ~ClientDeathRecipient() override; void OnRemoteDied(const wptr &object) override; private: - DeathCallback callback_; + std::function&)> callback_; }; - ConcurrentMap> syncers_; // identifier + ConcurrentMap>> syncers_; // identifier ConcurrentMap, sptr> recipients_; }; } diff --git a/services/rdb/rdb_syncer_factory.cpp b/services/rdb/rdb_syncer_factory.cpp index f073d69a543e5b101b9579c34fd314d01c9c731c..dd57b7d30539bc8bd065b2ca2cd3c7fedb73bb21 100644 --- a/services/rdb/rdb_syncer_factory.cpp +++ b/services/rdb/rdb_syncer_factory.cpp @@ -41,13 +41,13 @@ void RdbSyncerFactory::UnRegister(int type) creators_.erase(type); } -RdbSyncerImpl* RdbSyncerFactory::CreateSyncer(const RdbSyncerParam& param) +RdbSyncerImpl* RdbSyncerFactory::CreateSyncer(const RdbSyncerParam& param, pid_t uid) { auto it = creators_.find(param.type_); if (it == creators_.end()) { return nullptr; } - return it->second(param); + return it->second(param, uid); } } diff --git a/services/rdb/rdb_syncer_factory.h b/services/rdb/rdb_syncer_factory.h index 908308bebb13b0e4aab7d4bbdbe7a74eb5264e4e..ba47258ad755549b5c3a0c15c4191319fb197773 100644 --- a/services/rdb/rdb_syncer_factory.h +++ b/services/rdb/rdb_syncer_factory.h @@ -19,13 +19,13 @@ #include #include #include - +#include namespace OHOS::DistributedRdb { class RdbSyncerImpl; struct RdbSyncerParam; class RdbSyncerFactory { public: - using Creator = std::function; + using Creator = std::function; static RdbSyncerFactory& GetInstance(); @@ -33,7 +33,7 @@ public: void UnRegister(int type); - RdbSyncerImpl* CreateSyncer(const RdbSyncerParam& param); + RdbSyncerImpl* CreateSyncer(const RdbSyncerParam& param, pid_t uid); private: std::map creators_; @@ -42,9 +42,9 @@ private: template class RdbSyncerCreator { public: - RdbSyncerImpl* operator()(const RdbSyncerParam& param) + RdbSyncerImpl* operator()(const RdbSyncerParam& param, pid_t uid) { - return static_cast(new(std::nothrow) T(param)); + return static_cast(new(std::nothrow) T(param, uid)); } }; diff --git a/services/rdb/rdb_syncer_impl.cpp b/services/rdb/rdb_syncer_impl.cpp index fbd0c58b3eebbf424fcc7e5afff8f938c07868a0..062c4c1f8f4d0739b1952295117ad8e43447ed02 100644 --- a/services/rdb/rdb_syncer_impl.cpp +++ b/services/rdb/rdb_syncer_impl.cpp @@ -16,23 +16,21 @@ #define LOG_TAG "RdbSyncerImpl" #include "rdb_syncer_impl.h" -#include "kvstore_utils.h" +#include "account_delegate.h" +#include "checker/checker_manager.h" #include "log_print.h" namespace OHOS::DistributedRdb { -static std::string GetCurrentUserId() -{ - return "0"; -} - -RdbSyncerImpl::RdbSyncerImpl(const RdbSyncerParam ¶m) +using namespace OHOS::DistributedData; +using namespace OHOS::DistributedKv; +RdbSyncerImpl::RdbSyncerImpl(const RdbSyncerParam ¶m, pid_t uid) : type_(param.type_), bundleName_(param.bundleName_), path_(param.path_), storeId_(param.storeName_) { ZLOGI("construct %{public}s %{public}s %{public}s %{public}d", bundleName_.c_str(), userId_.c_str(), storeId_.c_str(), type_); - appId_ = DistributedKv::KvStoreUtils::GetAppIdByBundleName(bundleName_); - userId_ = GetCurrentUserId(); + appId_ = CheckerManager::GetInstance().GetAppId(param.bundleName_, uid); + userId_ = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); identifier_ = std::to_string(type_) + "-" + appId_ + "-" + userId_ + "-" + storeId_; } diff --git a/services/rdb/rdb_syncer_impl.h b/services/rdb/rdb_syncer_impl.h index cda4288e927a20d1d8454a49d788140284ee44b1..76ec6e7a44ab39a4eee2b1897591ce492664aa43 100644 --- a/services/rdb/rdb_syncer_impl.h +++ b/services/rdb/rdb_syncer_impl.h @@ -22,7 +22,7 @@ namespace OHOS::DistributedRdb { class RdbSyncerImpl : public RdbSyncerStub { public: - explicit RdbSyncerImpl(const RdbSyncerParam& param); + explicit RdbSyncerImpl(const RdbSyncerParam& param, pid_t uid); RdbSyncerImpl() = delete; RdbSyncerImpl(const RdbSyncerImpl&) = delete;