From 54fc322fa2e841a34184e23fe0518f306b19eb27 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Fri, 21 Jan 2022 20:58:01 +0800 Subject: [PATCH 1/5] add framework files Signed-off-by: Sven Wang --- bundle.json | 4 +- frameworks/common/concurrent_map.h | 223 +++ frameworks/common/visibility.h | 26 + .../distributeddatafwk/include/ikvstore.h | 1 - .../distributeddatafwk/include/itypes_util.h | 161 ++ .../app_distributed_kv_data_manager_impl.cpp | 5 +- .../src/ikvstore_data_service.cpp | 43 +- .../distributeddatafwk/src/itypes_util.cpp | 241 +++ .../single_kvstore_client_query_test.cpp | 1 + .../distributeddata/include/js_kv_manager.h | 1 + .../distributeddata/include/js_kv_store.h | 1 + .../distributeddata/include/napi_queue.h | 2 + interfaces/innerkits/distributeddata/BUILD.gn | 1 + .../innerkits/distributeddata/include/types.h | 4 +- .../distributeddata/include/visibility.h | 4 + .../distributeddataservice/adapter/BUILD.gn | 1 + .../adapter/account/BUILD.gn | 1 + .../account/src/account_delegate_impl.cpp | 15 +- .../account/src/account_delegate_impl.h | 2 +- .../adapter/account/test/BUILD.gn | 1 + .../adapter/autils/src/constant.cpp | 2 - .../include/account/account_delegate.h | 2 +- .../adapter/include/autils/concurrent_map.h | 101 -- .../adapter/include/autils/constant.h | 1 - .../adapter/include/utils/kvstore_utils.h | 4 - .../adapter/security/src/security.cpp | 3 +- .../adapter/security/src/sensitive.cpp | 25 +- .../adapter/utils/src/kvstore_utils.cpp | 5 - services/distributeddataservice/app/BUILD.gn | 1 + .../app/src/backup_handler.cpp | 4 +- .../app/src/device_kvstore_impl.cpp | 58 +- .../app/src/device_kvstore_impl.h | 7 +- .../app/src/kvstore_app_manager.cpp | 93 +- .../app/src/kvstore_app_manager.h | 13 +- .../app/src/kvstore_data_service.cpp | 478 +++--- .../app/src/kvstore_data_service.h | 24 +- .../app/src/kvstore_impl.cpp | 29 +- .../app/src/kvstore_impl.h | 10 +- .../app/src/kvstore_meta_manager.cpp | 27 +- .../app/src/kvstore_meta_manager.h | 8 +- .../app/src/kvstore_user_manager.cpp | 52 +- .../app/src/kvstore_user_manager.h | 28 +- .../app/src/single_kvstore_impl.cpp | 77 +- .../app/src/single_kvstore_impl.h | 12 +- .../app/src/uninstaller/uninstaller.h | 2 +- .../distributeddataservice/app/test/BUILD.gn | 5 +- .../distributeddata_account_event_test.cpp | 36 +- .../app/test/unittest/kvstore_app_manager.cpp | 733 --------- .../test/unittest/kvstore_data_service.cpp | 1360 ----------------- .../distributeddataservice/framework/BUILD.gn | 59 + .../framework/checker/checker_manager.cpp | 95 ++ .../checker/default/bundle_checker.cpp | 87 ++ .../checker/default/system_checker.cpp | 58 + .../eventcenter/event.cpp} | 29 +- .../framework/eventcenter/event_center.cpp | 146 ++ .../include/checker/checker_manager.h | 53 + .../include/checker/default/bundle_checker.h | 36 + .../include/checker/default/system_checker.h | 37 + .../framework/include/eventcenter/event.h | 40 + .../include/eventcenter/event_center.h | 67 + .../framework/include/metadata/meta_data.h | 32 + .../include/metadata/secret_key_meta_data.h} | 78 +- .../include/metadata/store_meta_data.h | 44 + .../include/serializable/serializable.h | 101 ++ .../framework/include/utils/constant.h | 187 +++ .../framework/metadata/meta_data.cpp | 34 + .../metadata/secret_key_meta_data.cpp | 33 + .../framework/metadata/store_meta_data.cpp | 60 + .../framework/serializable/serializable.cpp | 186 +++ .../framework/test/checker_manager_test.cpp | 94 ++ .../framework/test/event_center_test.cpp | 154 ++ .../framework/test/serializable_test.cpp | 162 ++ .../framework/utils/constant.cpp | 124 ++ .../distributeddataservice/service/BUILD.gn | 58 + .../service/bootstrap/CMakeLists.txt | 87 ++ .../service/bootstrap/include/bootstrap.h | 36 + .../service/bootstrap/src/bootstrap.cpp | 87 ++ .../service/config/CMakeLists.txt | 88 ++ .../service/config/include/config_factory.h | 42 + .../config/include/model/checker_config.h | 38 + .../config/include/model/component_config.h | 33 + .../config/include/model/directory_config.h | 38 + .../config/include/model/global_config.h | 40 + .../config/include/model/network_config.h | 33 + .../config/include/model/protocol_config.h | 31 + .../service/config/src/config_factory.cpp | 71 + .../config/src/model/checker_config.cpp | 53 + .../config/src/model/component_config.cpp | 44 + .../config/src/model/directory_config.cpp | 52 + .../config/src/model/global_config.cpp | 45 + .../config/src/model/network_config.cpp | 37 + .../config/src/model/protocol_config.cpp | 35 + .../service/directory/CMakeLists.txt | 86 ++ .../directory/include/directory_manager.h | 96 ++ .../directory/include/kvstore_context.h | 30 + .../directory/src/directory_manager.cpp | 151 ++ .../service/test/config_factory_test.cpp | 137 ++ .../service/test/directory_manager_test.cpp | 96 ++ 98 files changed, 4568 insertions(+), 2910 deletions(-) create mode 100644 frameworks/common/concurrent_map.h create mode 100644 frameworks/common/visibility.h create mode 100644 frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h create mode 100644 frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp delete mode 100644 services/distributeddataservice/adapter/include/autils/concurrent_map.h delete mode 100755 services/distributeddataservice/app/test/unittest/kvstore_app_manager.cpp delete mode 100644 services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp create mode 100644 services/distributeddataservice/framework/BUILD.gn create mode 100644 services/distributeddataservice/framework/checker/checker_manager.cpp create mode 100644 services/distributeddataservice/framework/checker/default/bundle_checker.cpp create mode 100644 services/distributeddataservice/framework/checker/default/system_checker.cpp rename services/distributeddataservice/{app/src/kvstore_common.h => framework/eventcenter/event.cpp} (65%) mode change 100755 => 100644 create mode 100644 services/distributeddataservice/framework/eventcenter/event_center.cpp create mode 100644 services/distributeddataservice/framework/include/checker/checker_manager.h create mode 100644 services/distributeddataservice/framework/include/checker/default/bundle_checker.h create mode 100644 services/distributeddataservice/framework/include/checker/default/system_checker.h create mode 100644 services/distributeddataservice/framework/include/eventcenter/event.h create mode 100644 services/distributeddataservice/framework/include/eventcenter/event_center.h create mode 100644 services/distributeddataservice/framework/include/metadata/meta_data.h rename services/distributeddataservice/{adapter/include/autils/serializable.h => framework/include/metadata/secret_key_meta_data.h} (49%) mode change 100755 => 100644 create mode 100644 services/distributeddataservice/framework/include/metadata/store_meta_data.h create mode 100644 services/distributeddataservice/framework/include/serializable/serializable.h create mode 100644 services/distributeddataservice/framework/include/utils/constant.h create mode 100644 services/distributeddataservice/framework/metadata/meta_data.cpp create mode 100644 services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp create mode 100644 services/distributeddataservice/framework/metadata/store_meta_data.cpp create mode 100644 services/distributeddataservice/framework/serializable/serializable.cpp create mode 100644 services/distributeddataservice/framework/test/checker_manager_test.cpp create mode 100644 services/distributeddataservice/framework/test/event_center_test.cpp create mode 100644 services/distributeddataservice/framework/test/serializable_test.cpp create mode 100644 services/distributeddataservice/framework/utils/constant.cpp create mode 100644 services/distributeddataservice/service/BUILD.gn create mode 100644 services/distributeddataservice/service/bootstrap/CMakeLists.txt create mode 100644 services/distributeddataservice/service/bootstrap/include/bootstrap.h create mode 100644 services/distributeddataservice/service/bootstrap/src/bootstrap.cpp create mode 100644 services/distributeddataservice/service/config/CMakeLists.txt create mode 100644 services/distributeddataservice/service/config/include/config_factory.h create mode 100644 services/distributeddataservice/service/config/include/model/checker_config.h create mode 100644 services/distributeddataservice/service/config/include/model/component_config.h create mode 100644 services/distributeddataservice/service/config/include/model/directory_config.h create mode 100644 services/distributeddataservice/service/config/include/model/global_config.h create mode 100644 services/distributeddataservice/service/config/include/model/network_config.h create mode 100644 services/distributeddataservice/service/config/include/model/protocol_config.h create mode 100644 services/distributeddataservice/service/config/src/config_factory.cpp create mode 100644 services/distributeddataservice/service/config/src/model/checker_config.cpp create mode 100644 services/distributeddataservice/service/config/src/model/component_config.cpp create mode 100644 services/distributeddataservice/service/config/src/model/directory_config.cpp create mode 100644 services/distributeddataservice/service/config/src/model/global_config.cpp create mode 100644 services/distributeddataservice/service/config/src/model/network_config.cpp create mode 100644 services/distributeddataservice/service/config/src/model/protocol_config.cpp create mode 100644 services/distributeddataservice/service/directory/CMakeLists.txt create mode 100644 services/distributeddataservice/service/directory/include/directory_manager.h create mode 100644 services/distributeddataservice/service/directory/include/kvstore_context.h create mode 100644 services/distributeddataservice/service/directory/src/directory_manager.cpp create mode 100644 services/distributeddataservice/service/test/config_factory_test.cpp create mode 100644 services/distributeddataservice/service/test/directory_manager_test.cpp diff --git a/bundle.json b/bundle.json index 143a62227..b994fbd68 100644 --- a/bundle.json +++ b/bundle.json @@ -85,7 +85,9 @@ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:build_module", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/jskits/distributeddata:build_module", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app:build_module", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:build_module" + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:build_module", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:build_module", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:build_module" ], "inner_kits": [ { diff --git a/frameworks/common/concurrent_map.h b/frameworks/common/concurrent_map.h new file mode 100644 index 000000000..954837808 --- /dev/null +++ b/frameworks/common/concurrent_map.h @@ -0,0 +1,223 @@ +/* + * 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_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H +#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H +#include +#include +#include +namespace OHOS { +template +class ConcurrentMap { +public: + using key_type = typename std::map<_Key, _Tp>::key_type; + using mapped_type = typename std::map<_Key, _Tp>::mapped_type; + using value_type = typename std::map<_Key, _Tp>::value_type; + using size_type = typename std::map<_Key, _Tp>::size_type; + using reference = typename std::map<_Key, _Tp>::reference; + using const_reference = typename std::map<_Key, _Tp>::const_reference; + + ConcurrentMap() = default; + ~ConcurrentMap() = default; + ConcurrentMap(const ConcurrentMap &other) + { + operator=(std::move(other)); + } + + ConcurrentMap &operator=(const ConcurrentMap &other) noexcept + { + if (this == &other) { + return *this; + } + auto tmp = other.Clone(); + std::lock_guard lock(mutex_); + entries_ = std::move(tmp); + return *this; + } + + ConcurrentMap(ConcurrentMap &&other) noexcept + { + operator=(std::move(other)); + } + + ConcurrentMap &operator=(ConcurrentMap &&other) noexcept + { + if (this == &other) { + return *this; + } + auto tmp = other.Steal(); + std::lock_guard lock(mutex_); + entries_ = std::move(tmp); + return *this; + } + + template + bool Emplace(_Args &&...__args) noexcept + { + std::lock_guard lock(mutex_); + auto it = entries_.emplace(std::forward<_Args>(__args)...); + return it->second; + } + + std::pair Find(const key_type &key) const noexcept + { + std::lock_guard lock(mutex_); + auto it = entries_.find(key); + if (it == entries_.end()) { + return std::pair{ false, mapped_type() }; + } + + return std::pair{ true, it->second }; + } + + bool Contains(const key_type& key) const noexcept + { + std::lock_guard lock(mutex_); + return (entries_.find(key) != entries_.end()); + } + + bool Insert(const key_type &key, const mapped_type &value) noexcept + { + std::lock_guard lock(mutex_); + auto it = entries_.insert(value_type{key, value}); + return it.second; + } + + size_type Erase(const key_type &key) noexcept + { + std::lock_guard lock(mutex_); + return entries_.erase(key); + } + + void Clear() noexcept + { + std::lock_guard lock(mutex_); + return entries_.clear(); + } + + bool Empty() const noexcept + { + std::lock_guard lock(mutex_); + return entries_.empty(); + } + + size_type Size() const noexcept + { + std::lock_guard lock(mutex_); + return entries_.size(); + } + + void ClearIf(std::function &action) noexcept + { + if (action == nullptr) { + return; + } + std::lock_guard lock(mutex_); + for (auto &[key, value] : entries_) { + if (action(key, value)) { + break; + } + } + return entries_.size(); + } + + mapped_type &operator[](const key_type &key) noexcept + { + std::lock_guard lock(mutex_); + return entries_[key]; + } + + const mapped_type &operator[](const key_type &key) const noexcept + { + std::lock_guard lock(mutex_); + return entries_[key]; + } + + void ForEach(const std::function &action) + { + if (action == nullptr) { + return; + } + std::lock_guard lock(mutex_); + for (auto &[key, value] : entries_) { + if (action(key, value)) { + break; + } + } + } + + bool Compute(const key_type &key, const std::function &action) + { + if (action == nullptr) { + return false; + } + std::lock_guard lock(mutex_); + auto it = entries_.find(key); + if (it == entries_.end()) { + auto result = entries_.emplace(key, mapped_type()); + it = result.second ? result.first : entries_.end(); + } + if (it == entries_.end()) { + return false; + } + action(it->first, it->second); + return true; + } + + bool ComputeIfPresent(const key_type &key, const std::function &action) + { + if (action == nullptr) { + return false; + } + std::lock_guard lock(mutex_); + auto it = entries_.find(key); + if (it == entries_.end()) { + return false; + } + action(key, it->second); + return true; + } + + bool ComputeIfAbsent(const key_type &key, std::function &action) + { + if (action == nullptr) { + return false; + } + std::lock_guard lock(mutex_); + auto it = entries_.find(key); + if (it != entries_.end()) { + return false; + } + entries_.insert(value_type{key, action(key)}); + return true; + } +private: + std::map<_Key, _Tp> Steal() noexcept + { + std::lock_guard lock(mutex_); + return std::move(entries_); + } + + std::map<_Key, _Tp> Clone() const noexcept + { + std::lock_guard lock(mutex_); + return entries_; + } +private: + mutable std::recursive_mutex mutex_; + std::map<_Key, _Tp> entries_; +}; +} +#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H diff --git a/frameworks/common/visibility.h b/frameworks/common/visibility.h new file mode 100644 index 000000000..7475300df --- /dev/null +++ b/frameworks/common/visibility.h @@ -0,0 +1,26 @@ +/* + * 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_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_VISIBILITY_H +#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_VISIBILITY_H + +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility ("default"))) +#endif +#ifndef KVSTORE_API +#define KVSTORE_API API_EXPORT +#endif + +#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_VISIBILITY_H diff --git a/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h b/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore.h index 2821dee8e..5b79c239d 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 new file mode 100644 index 000000000..1968a4d47 --- /dev/null +++ b/frameworks/innerkitsimpl/distributeddatafwk/include/itypes_util.h @@ -0,0 +1,161 @@ +/* + * 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 I_TYPES_UTIL_H +#define I_TYPES_UTIL_H + +#include "types.h" +#include "change_notification.h" +#include "message_parcel.h" + +namespace OHOS { +namespace DistributedKv { +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 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) + { + std::unique_ptr buffer = std::make_unique(size); + if (!data.WriteBool(buffer != nullptr)) { + return Status::IPC_ERROR; + } + if (buffer == nullptr) { + return Status::ILLEGAL_STATE; + } + uint8_t *cursor = buffer.get(); + if (!input.WriteToBuffer(cursor, size)) { + return Status::IPC_ERROR; + } + return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR; + } + + template + static Status MarshalToBuffer(const std::vector &input, int size, MessageParcel &data) + { + std::unique_ptr buffer = std::make_unique(size); + if (!data.WriteBool(buffer != nullptr)) { + return Status::IPC_ERROR; + } + if (buffer == nullptr) { + return Status::ILLEGAL_STATE; + } + uint8_t *cursor = buffer.get(); + for (const auto &entry : input) { + if (!entry.WriteToBuffer(cursor, size)) { + return Status::IPC_ERROR; + } + } + if (!data.WriteInt32(input.size())) { + return Status::IPC_ERROR; + } + return data.WriteRawData(buffer.get(), size) ? Status::SUCCESS : Status::IPC_ERROR; + } + + template + static Status UnmarshalFromBuffer(MessageParcel &data, int size, T &output) + { + if (size < 0) { + return Status::INVALID_ARGUMENT; + } + if (!data.ReadBool()) { + return Status::ILLEGAL_STATE; + } + const uint8_t *buffer = reinterpret_cast(data.ReadRawData(size)); + if (buffer == nullptr) { + return Status::INVALID_ARGUMENT; + } + return output.ReadFromBuffer(buffer, size) ? Status::SUCCESS : Status::IPC_ERROR; + } + + template + static Status UnmarshalFromBuffer(MessageParcel &data, int size, std::vector &output) + { + if (size < 0) { + return Status::INVALID_ARGUMENT; + } + if (!data.ReadBool()) { + return Status::ILLEGAL_STATE; + } + int count = data.ReadInt32(); + const uint8_t *buffer = reinterpret_cast(data.ReadRawData(size)); + if (count < 0 || buffer == nullptr) { + return Status::INVALID_ARGUMENT; + } + + output.resize(count); + for (auto &entry : output) { + if (!entry.ReadFromBuffer(buffer, size)) { + output.clear(); + return Status::IPC_ERROR; + } + } + return Status::SUCCESS; } +private: + template + class VectorParcel : public MessageParcel { + public: + 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 + static bool WriteVector(Parcel &parcel, const std::vector &val, bool (Parcel::*writer)(const T &)); + template using Reader = bool (Parcel::*)(T &); + template using Writer = bool (Parcel::*)(const T &); + template + static Writer GetParcelWriter() + { + return static_cast>(&VectorParcel::Writer); + } + template + static Reader GetParcelReader() + { + return static_cast>(&VectorParcel::Reader); + } + template + static std::vector Convert2Vector(const std::list &entries); + template + static std::list Convert2List(std::vector &&entries); +}; +} +} + +#endif // I_TYPES_UTIL_H 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 1ffeafd8c..f527965ae 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,8 @@ std::shared_ptr AppDistributedKvDataManagerImpl::Ge return nullptr; } - std::string appId = KvStoreUtils::GetAppIdByBundleName(bundleName); + // todo KvStoreUtils::GetAppIdByBundleName(bundleName); + std::string appId = bundleName; if (appId.empty()) { appId = bundleName; } @@ -153,7 +154,7 @@ Status AppDistributedKvDataManagerImpl::GetKvStore( auto statDelegateMgr = std::make_shared(kvStoreDelegateManager_); auto statDelegate = std::static_pointer_cast(statDelegateMgr); Reporter::GetInstance()->DatabaseStatistic()->Report( - {AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(), appId_, storeId, 0, statDelegate}); + {AccountDelegate::GetInstance()->GetCurrentAccountId(), appId_, storeId, 0, statDelegate}); return; } diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp index be7827b39..0dbfb0264 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; diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp new file mode 100644 index 000000000..200e2d3c7 --- /dev/null +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp @@ -0,0 +1,241 @@ +/* + * 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 "itypes_util.h" +#include +#include +#include + +namespace OHOS { +namespace DistributedKv { +bool ITypesUtil::Marshalling(const Blob &blob, MessageParcel &data) +{ + return data.WriteUInt8Vector(blob.Data()); +} + +bool ITypesUtil::Unmarshalling(MessageParcel &data, Blob &output) +{ + std::vector blob; + bool result = data.ReadUInt8Vector(&blob); + output = blob; + return result; +} + +bool ITypesUtil::Marshalling(const std::vector &blobs, MessageParcel &data) +{ + return WriteVector(data, blobs, ITypesUtil::GetParcelWriter()); +} + +bool ITypesUtil::Unmarshalling(MessageParcel &data, std::vector &output) +{ + return ReadVector(data, output, ITypesUtil::GetParcelReader()); +} + +bool ITypesUtil::Marshalling(const std::vector &entry, MessageParcel &data) +{ + return WriteVector(data, entry, ITypesUtil::GetParcelWriter()); +} + +bool ITypesUtil::Unmarshalling(MessageParcel &data, std::vector &output) +{ + return ReadVector(data, output, ITypesUtil::GetParcelReader()); +} + +bool ITypesUtil::Marshalling(const Entry &entry, MessageParcel &data) +{ + if (!Marshalling(entry.key, data)) { + return false; + } + return Marshalling(entry.value, data); +} + +bool ITypesUtil::Unmarshalling(MessageParcel &data, Entry &output) +{ + if (!Unmarshalling(data, output.key)) { + return false; + } + return Unmarshalling(data, output.value); +} + +bool ITypesUtil::Marshalling(const DeviceInfo &entry, MessageParcel &data) +{ + if (!data.WriteString(entry.deviceId)) { + return false; + } + if (!data.WriteString(entry.deviceName)) { + return false; + } + return data.WriteString(entry.deviceType); +} + +bool ITypesUtil::Unmarshalling(MessageParcel &data, DeviceInfo &output) +{ + if (!data.ReadString(output.deviceId)) { + return false; + } + if (!data.ReadString(output.deviceName)) { + return false; + } + return data.ReadString(output.deviceType); +} +bool ITypesUtil::Marshalling(const std::vector &input, MessageParcel &data) +{ + return WriteVector(data, input, ITypesUtil::GetParcelWriter()); +} + +bool ITypesUtil::Unmarshalling(MessageParcel &data, std::vector &output) +{ + return ReadVector(data, output, ITypesUtil::GetParcelReader()); +} + +bool ITypesUtil::Marshalling(const ChangeNotification ¬ification, MessageParcel &parcel) +{ + if (!Marshalling(notification.GetInsertEntries(), parcel)) { + return false; + } + + if (!Marshalling(notification.GetUpdateEntries(), parcel)) { + return false; + } + + if (!Marshalling(notification.GetDeleteEntries(), parcel)) { + return false; + } + if (!parcel.WriteString(notification.GetDeviceId())) { + ZLOGE("WriteString deviceId_ failed."); + return false; + } + + return parcel.WriteBool(notification.IsClear()); +} + +bool ITypesUtil::Unmarshalling(MessageParcel &parcel, ChangeNotification &output) +{ + std::vector insertEntries; + if (!Unmarshalling(parcel, insertEntries)) { + return false; + } + std::vector updateEntries; + if (!Unmarshalling(parcel, updateEntries)) { + return false; + } + std::vector deleteEntries; + if (!Unmarshalling(parcel, deleteEntries)) { + return false; + } + std::string deviceId; + if (!parcel.ReadString(deviceId)) { + ZLOGE("WriteString deviceId_ failed."); + return false; + } + bool isClear; + if (!parcel.ReadBool(isClear)) { + ZLOGE("WriteString deviceId_ failed."); + return false; + } + output = ChangeNotification(std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries), deviceId, + isClear); + return true; +} + +template +std::vector ITypesUtil::Convert2Vector(const std::list &entries) +{ + std::vector vector(entries.size()); + int i = 0; + for (const auto &entry : entries) { + vector[i++] = entry; + } + return vector; +} + +template +std::list ITypesUtil::Convert2List(std::vector &&entries) +{ + std::list result; + for (auto &entry : entries) { + result.push_back(std::move(entry)); + } + return result; +} +int64_t ITypesUtil::GetTotalSize(const std::vector &entries) +{ + int64_t bufferSize = 1; + for (const auto &item : entries) { + if (item.key.Size() > Constant::MAX_KEY_LENGTH || item.value.Size() > Constant::MAX_VALUE_LENGTH) { + return -bufferSize; + } + bufferSize += item.key.RawSize() + item.value.RawSize(); + } + return bufferSize - 1; +} +int64_t ITypesUtil::GetTotalSize(const std::vector &entries) +{ + int64_t bufferSize = 1; + for (const auto &item : entries) { + if (item.Size() > Constant::MAX_KEY_LENGTH) { + return -bufferSize; + } + bufferSize += item.RawSize(); + } + return bufferSize - 1; +} + +template +bool ITypesUtil::ReadVector(Parcel &parcel, std::vector &val, bool (Parcel::*read)(T &)) +{ + int32_t len = parcel.ReadInt32(); + if (len < 0) { + return false; + } + + size_t readAbleSize = parcel.GetReadableBytes(); + size_t size = static_cast(len); + if ((size > readAbleSize) || (size > val.max_size())) { + return false; + } + val.resize(size); + if (val.size() < size) { + return false; + } + + for (auto &v : val) { + if (!(parcel.*read)(v)) { + return false; + } + } + + return true; +} + +template +bool ITypesUtil::WriteVector(Parcel &parcel, const std::vector &val, bool (Parcel::*writer)(const T &)) +{ + 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; + } + } + return true; +} +} +} \ No newline at end of file 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 866b28f83..0feda8b97 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 @@ -21,6 +21,7 @@ #include #include #include "distributed_kv_data_manager.h" +#include "directory_manager.h" #include "types.h" #include "log_print.h" diff --git a/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h b/frameworks/jskitsimpl/distributeddata/include/js_kv_manager.h index 678250f6c..15fc2795a 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 8f2afd144..5ad046038 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/napi_queue.h b/frameworks/jskitsimpl/distributeddata/include/napi_queue.h index 66270b107..c402a9124 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" diff --git a/interfaces/innerkits/distributeddata/BUILD.gn b/interfaces/innerkits/distributeddata/BUILD.gn index 103a11c69..e41c87bf5 100755 --- a/interfaces/innerkits/distributeddata/BUILD.gn +++ b/interfaces/innerkits/distributeddata/BUILD.gn @@ -68,6 +68,7 @@ ohos_shared_library("distributeddata_inner") { "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_snapshot_client.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/single_kvstore_client.cpp", + "../../../frameworks/innerkitsimpl/distributeddatafwk/src/itypes_utils.cpp", "include/types.h", ] diff --git a/interfaces/innerkits/distributeddata/include/types.h b/interfaces/innerkits/distributeddata/include/types.h index d94c3b0d0..3fd669735 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/interfaces/innerkits/distributeddata/include/visibility.h b/interfaces/innerkits/distributeddata/include/visibility.h index af8fa9b3d..502eda59b 100644 --- a/interfaces/innerkits/distributeddata/include/visibility.h +++ b/interfaces/innerkits/distributeddata/include/visibility.h @@ -16,3 +16,7 @@ #ifndef KVSTORE_API #define KVSTORE_API __attribute__ ((visibility ("default"))) #endif + +#ifndef API_EXPORT +#define API_EXPORT __attribute__((visibility ("default"))) +#endif \ No newline at end of file diff --git a/services/distributeddataservice/adapter/BUILD.gn b/services/distributeddataservice/adapter/BUILD.gn index 7c630e73f..99ed4c662 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 5fdb1c580..ee6412cdb 100755 --- a/services/distributeddataservice/adapter/account/BUILD.gn +++ b/services/distributeddataservice/adapter/account/BUILD.gn @@ -25,6 +25,7 @@ ohos_static_library("distributeddata_account_static") { "./src", "//utils/native/base/include", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", ] cflags_cc = [ "-fvisibility=hidden" ] diff --git a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp index ae07da2bc..4a0092174 100755 --- a/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp +++ b/services/distributeddataservice/adapter/account/src/account_delegate_impl.cpp @@ -94,7 +94,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 +122,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)) { @@ -148,8 +148,9 @@ std::string AccountDelegateImpl::GetDeviceAccountIdByUID(int32_t uid) const void AccountDelegateImpl::NotifyAccountChanged(const AccountEventInfo &accountEventInfo) { - observerMap_.ForEach([&](std::string key, std::shared_ptr val) { + observerMap_.ForEach([&](const std::string &key, const std::shared_ptr &val) { val->OnAccountChanged(accountEventInfo); + return false; }); } @@ -159,11 +160,11 @@ Status AccountDelegateImpl::Subscribe(std::shared_ptr observer) if (observer == nullptr || observer->Name().empty()) { return Status::INVALID_ARGUMENT; } - if (observerMap_.ContainsKey(observer->Name())) { + if (observerMap_.Contains(observer->Name())) { return Status::INVALID_ARGUMENT; } - auto ret = observerMap_.Put(observer->Name(), observer); + auto ret = observerMap_.Insert(observer->Name(), observer); if (ret) { ZLOGD("end"); return Status::SUCCESS; @@ -178,11 +179,11 @@ Status AccountDelegateImpl::Unsubscribe(std::shared_ptr observer) if (observer == nullptr || observer->Name().empty()) { return Status::INVALID_ARGUMENT; } - if (!observerMap_.ContainsKey(observer->Name())) { + if (!observerMap_.Contains(observer->Name())) { return Status::INVALID_ARGUMENT; } - auto ret = observerMap_.Delete(observer->Name()); + auto ret = observerMap_.Erase(observer->Name()); if (ret) { ZLOGD("end"); return Status::SUCCESS; diff --git a/services/distributeddataservice/adapter/account/src/account_delegate_impl.h b/services/distributeddataservice/adapter/account/src/account_delegate_impl.h index 0059bedab..e8569218a 100755 --- a/services/distributeddataservice/adapter/account/src/account_delegate_impl.h +++ b/services/distributeddataservice/adapter/account/src/account_delegate_impl.h @@ -46,7 +46,7 @@ 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: diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn index 35646ebf1..366d42767 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/autils/src/constant.cpp b/services/distributeddataservice/adapter/autils/src/constant.cpp index 475f1ba73..f393d354c 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 d25a21db1..f9a9cdf42 100755 --- a/services/distributeddataservice/adapter/include/account/account_delegate.h +++ b/services/distributeddataservice/adapter/include/account/account_delegate.h @@ -49,7 +49,7 @@ 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(); diff --git a/services/distributeddataservice/adapter/include/autils/concurrent_map.h b/services/distributeddataservice/adapter/include/autils/concurrent_map.h deleted file mode 100644 index 5bd1b8637..000000000 --- a/services/distributeddataservice/adapter/include/autils/concurrent_map.h +++ /dev/null @@ -1,101 +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 DISTRIBUTEDDATAMGR_CURRENT_MAP_H -#define DISTRIBUTEDDATAMGR_CURRENT_MAP_H - -#include -#include -#include -#include "visibility.h" - -namespace OHOS { -namespace DistributedKv { -template -class ConcurrentMap { -public: - KVSTORE_API explicit ConcurrentMap() {}; - - KVSTORE_API ~ConcurrentMap() {}; - - KVSTORE_API bool Put(const K &key, const V &value) - { - std::unique_lock lock(mapMutex_); - auto ret = map_.insert(std::pair(key, value)); - return ret.second; - } - - KVSTORE_API bool PutValue(const K key, const V value) - { - std::unique_lock lock(mapMutex_); - auto ret = map_.insert(std::pair(key, value)); - return ret.second; - } - - KVSTORE_API bool Empty() - { - std::lock_guard lock(mapMutex_); - return map_.empty(); - } - - KVSTORE_API int Size() - { - std::lock_guard lock(mapMutex_); - return map_.size(); - } - - KVSTORE_API bool Delete(const K &key) - { - std::unique_lock lock(mapMutex_); - return map_.erase(key); - } - - KVSTORE_API bool Get(const K &key, V &v) - { - std::lock_guard lock(mapMutex_); - auto ret = map_.find(key); - if (ret != map_.end()) { - v = ret->second; - return true; - } - return false; - } - - KVSTORE_API bool ContainsKey(const K &key) - { - std::lock_guard lock(mapMutex_); - return map_.count(key); - } - - KVSTORE_API void Clear() - { - std::unique_lock lock(mapMutex_); - map_.clear(); - } - - KVSTORE_API void ForEach(std::function fun) - { - std::lock_guard lock(mapMutex_); - for (auto const &kvPair : map_) { - fun(kvPair.first, kvPair.second); - } - } -private: - std::mutex mapMutex_; - std::map map_; -}; -} // namespace DistributedKv -} // namespace OHOS -#endif // DISTRIBUTEDDATAMGR_CURRENT_MAP_H diff --git a/services/distributeddataservice/adapter/include/autils/constant.h b/services/distributeddataservice/adapter/include/autils/constant.h index 75d4c0e72..efeaa381d 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/utils/kvstore_utils.h b/services/distributeddataservice/adapter/include/utils/kvstore_utils.h index 7a5512156..bfa9ab9a1 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/security/src/security.cpp b/services/distributeddataservice/adapter/security/src/security.cpp index dd8ddf5ce..0c7b9bebf 100755 --- a/services/distributeddataservice/adapter/security/src/security.cpp +++ b/services/distributeddataservice/adapter/security/src/security.cpp @@ -83,8 +83,7 @@ DBStatus Security::RegOnAccessControlledEvent(const OnAccessControlledEvent &cal return OK; }; // retry after 10 second, 10 * 1000 * 1000 mains 1 second - BlockInteger retry(10 * 1000 * 1000); - for (; retry < RETRY_MAX_TIMES && !result; ++retry) { + for (BlockInteger retry(10 * 1000 * 1000); retry < RETRY_MAX_TIMES && !result; ++retry) { result = SubscribeUserStatus(observer); } diff --git a/services/distributeddataservice/adapter/security/src/sensitive.cpp b/services/distributeddataservice/adapter/security/src/sensitive.cpp index c0e408768..ffde5fb50 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" #include "1.0/dev_slinfo_mgr.h" #undef LOG_TAG #define LOG_TAG "Sensitive" @@ -36,33 +35,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/src/kvstore_utils.cpp b/services/distributeddataservice/adapter/utils/src/kvstore_utils.cpp index aa495ba1e..beb3566b8 100755 --- a/services/distributeddataservice/adapter/utils/src/kvstore_utils.cpp +++ b/services/distributeddataservice/adapter/utils/src/kvstore_utils.cpp @@ -28,11 +28,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 5de1fc99c..845a86314 100755 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -36,6 +36,7 @@ ohos_sa_profile("distributeddata_profile") { 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/include/rdb", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", diff --git a/services/distributeddataservice/app/src/backup_handler.cpp b/services/distributeddataservice/app/src/backup_handler.cpp index b3c7b5263..4e943a164 100755 --- a/services/distributeddataservice/app/src/backup_handler.cpp +++ b/services/distributeddataservice/app/src/backup_handler.cpp @@ -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; diff --git a/services/distributeddataservice/app/src/device_kvstore_impl.cpp b/services/distributeddataservice/app/src/device_kvstore_impl.cpp index 2594b6b90..e1d576f3b 100644 --- a/services/distributeddataservice/app/src/device_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/device_kvstore_impl.cpp @@ -23,21 +23,18 @@ 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 +49,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 +57,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 +65,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 +96,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) { @@ -137,19 +112,11 @@ void DeviceKvStoreImpl::GetResultSet(const Key &prefixKey, Status DeviceKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sptr observer) { - if (!params_.deviceCoordinate) { - return SingleKvStoreImpl::SubscribeKvStore(subscribeType, observer); - } - return SingleKvStoreImpl::SubscribeKvStore(subscribeType, observer, true); } 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 +130,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 +142,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; @@ -200,11 +159,6 @@ Status DeviceKvStoreImpl::GetEntriesWithQuery(const std::string &query, std::vec void DeviceKvStoreImpl::GetResultSetWithQuery(const std::string &query, std::function)> callback) { - if (!params_.deviceCoordinate) { - SingleKvStoreImpl::GetResultSetWithQuery(query, callback); - return; - } - SingleKvStoreImpl::GetResultSetWithQuery(query, callback, true); } diff --git a/services/distributeddataservice/app/src/device_kvstore_impl.h b/services/distributeddataservice/app/src/device_kvstore_impl.h index c118b47cf..02e499263 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,7 +26,9 @@ 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; @@ -38,7 +39,6 @@ public: 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(); @@ -47,7 +47,6 @@ private: 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/kvstore_app_manager.cpp b/services/distributeddataservice/app/src/kvstore_app_manager.cpp index 002ed44bc..c6c490ac3 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_ = CheckerManager::GetInstance().GetAppId(bundleName, 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"); + kvStore = nullptr; 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()) { + 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; + kvStore = it->second; ZLOGI("find store in map refcount: %d.", kvStoreImpl->GetSptrRefCount()); - static_cast(kvStoreImpl.GetRefPtr())->IncreaseOpenCount(); - callback(std::move(kvStoreImpl)); + 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"); + kvStore = nullptr; 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()) { + 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; + kvStore = it->second; ZLOGI("find store in map refcount: %d.", singleKvStoreImpl->GetSptrRefCount()); - static_cast(singleKvStoreImpl.GetRefPtr())->IncreaseOpenCount(); - callback(std::move(singleKvStoreImpl)); + 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,35 @@ 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)); + kvStore->GetSptrRefCount(), static_cast(options.autoSync)); if (options.autoSync) { bool autoSync = true; DistributedDB::PragmaData data = static_cast(&autoSync); @@ -252,7 +248,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 +261,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 +303,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; } @@ -450,14 +445,15 @@ 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_); + // trueAppId_ = KvStoreUtils::GetAppIdByBundleName(bundleName_); 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 +464,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)); diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.h b/services/distributeddataservice/app/src/kvstore_app_manager.h index 82d559c59..655330b57 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); @@ -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 47b1e7dc6..a3a0f0eec 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -26,7 +26,10 @@ #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" @@ -52,6 +55,8 @@ 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 +70,7 @@ KvStoreDataService::KvStoreDataService(bool runOnCreate) clientDeathObserverMap_() { ZLOGI("begin."); - Initialize(); + // Initialize(); } KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate) @@ -76,7 +81,7 @@ KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate clientDeathObserverMap_() { ZLOGI("begin"); - Initialize(); + // Initialize(); } KvStoreDataService::~KvStoreDataService() @@ -89,10 +94,12 @@ void KvStoreDataService::Initialize() { ZLOGI("begin."); KvStoreMetaManager::GetInstance().InitMetaParameter(); +#ifndef UT_TEST + KvStoreDelegateManager::SetProcessLabel(Bootstrap::GetInstance().GetProcessLabel(), "default"); +#endif 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 +154,39 @@ 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.IsValidType() + || options.kvStoreType != KvStoreType::MULTI_VERSION) { + ZLOGE("invalid argument type."); + return Status::INVALID_ARGUMENT; + } + KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING); + GetKvStorePara 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; } - GetKvStorePara getKvStorePara; - Status checkParaStatus = CheckParameters(options, appId, storeId, KvStoreType::MULTI_VERSION, getKvStorePara); - if (checkParaStatus != Status::SUCCESS) { - callback(nullptr); - return checkParaStatus; + param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (param.userId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { + ZLOGE("not support sub account"); + return Status::NOT_SUPPORT; } - SecretKeyPara secretKeyParas; - Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, getKvStorePara, secretKeyParas); - if (getSecretKeyStatus != Status::SUCCESS) { + 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 +197,18 @@ 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; + Status statusTmp = (it->second).GetKvStore(options, param.bundleName, param.storeId, uid, keyPara.secretKey, store); + if (keyPara.outdated) { + KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, 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); + return UpdateMetaData(options, param, keyPara.metaKey, it->second); } - getKvStorePara.getKvStoreStatus = statusTmp; - return GetKvStoreFailDo(options, getKvStorePara, secretKeyParas, it->second, callback); + return GetKvStoreFailDo(options, param, keyPara, it->second, store); } Status KvStoreDataService::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, @@ -208,37 +216,40 @@ 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); + GetKvStorePara 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); + param.userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (param.userId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { + ZLOGE("not support sub account"); + return Status::NOT_SUPPORT; + } + + SecretKeyPara keyPara; + Status getSecretKeyStatus = KvStoreDataService::GetSecretKey(options, param, keyPara); 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); + 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,66 +257,19 @@ 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); + sptr store; + Status statusTmp = (it->second).GetKvStore(options, param.bundleName, param.storeId, uid, keyPara.secretKey, store); + if (keyPara.outdated) { + KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, store); } - 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; + if (statusTmp == 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 = statusTmp; + 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, @@ -313,10 +277,8 @@ Status KvStoreDataService::GetSecretKey(const Options &options, const GetKvStore { 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 +289,15 @@ 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"); + if (options.kvStoreType == KvStoreType::MULTI_VERSION) { + metaSecretKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp, "KEY"); secretKeyFile = KvStoreMetaManager::GetSecretKeyFile( - deviceAccountId, bundleName, storeIdTmp, options.securityLevel); + kvParas.userId, bundleName, storeIdTmp, options.securityLevel); } else { - metaSecretKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, + metaSecretKey = KvStoreMetaManager::GetMetaKey(kvParas.userId, "default", bundleName, storeIdTmp, "SINGLE_KEY"); secretKeyFile = KvStoreMetaManager::GetSecretSingleKeyFile( - deviceAccountId, bundleName, storeIdTmp, options.securityLevel); + kvParas.userId, bundleName, storeIdTmp, options.securityLevel); } bool outdated = false; @@ -400,7 +362,7 @@ Status KvStoreDataService::UpdateMetaData(const Options &options, const GetKvSto 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 +370,102 @@ 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) + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &store) { - Status statusTmp = kvParas.getKvStoreStatus; + Status statusTmp = kvParas.status; 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); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.userId, 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, 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, + if (!CheckBackupFileExist(kvParas.userId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { 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) + SecretKeyPara &secKeyParas, KvStoreUserManager &kvUserManager, sptr &kvStore) { - Status statusTmp = kvParas.getKvStoreStatus; + Status statusTmp = kvParas.status; 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); + KvStoreMetaManager::GetInstance().RemoveSecretKey(kvParas.userId, 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, 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, + if (!CheckBackupFileExist(kvParas.userId, kvParas.bundleName, kvParas.storeId, options.securityLevel)) { 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; } @@ -569,20 +516,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 +533,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 +549,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) { @@ -714,33 +609,26 @@ 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) { + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (userId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { ZLOGE("not support sub account"); return Status::NOT_SUPPORT; } 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 +644,26 @@ 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) { + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (userId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { ZLOGE("not support sub account"); return Status::NOT_SUPPORT; } 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 +672,58 @@ 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) { + const std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + if (userId != AccountDelegate::MAIN_DEVICE_ACCOUNT_ID) { ZLOGE("not support sub account"); return Status::NOT_SUPPORT; } - std::initializer_list backPathListDE = {BackupHandler::GetBackupPath(deviceAccountId, + 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, 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) { @@ -866,17 +752,18 @@ 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)) { 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()); if (!it.second) { @@ -884,8 +771,8 @@ Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr< 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 +790,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 +818,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,10 +875,10 @@ void KvStoreDataService::StartService() Reporter::GetInstance()->ServiceFault()->Report(msg); } Uninstaller::GetInstance().Init(this); - +#ifndef UT_TEST // add softbus permission. AddPermission(); - +#endif std::string backupPath = BackupHandler::GetBackupPath(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, KvStoreAppManager::PATH_DE); ZLOGI("backupPath is : %s ", backupPath.c_str()); @@ -1024,7 +908,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 +918,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 +938,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"); diff --git a/services/distributeddataservice/app/src/kvstore_data_service.h b/services/distributeddataservice/app/src/kvstore_data_service.h index fc06ae3a5..34301ed2e 100755 --- a/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/services/distributeddataservice/app/src/kvstore_data_service.h @@ -87,21 +87,13 @@ public: bool CheckBackupFileExist(const std::string &deviceAccountId, const std::string &bundleName, const std::string &storeId, int securityLevel); - Status RecoverSingleKvStore(const Options &options, const std::string &bundleName, - const std::string &storeId, const std::vector &secretKey, - std::function)> callback); - - Status RecoverMultiKvStore(const Options &options, const std::string &bundleName, - const std::string &storeId, const std::vector &secretKey, - std::function)> callback); - struct GetKvStorePara { std::string bundleName; std::string storeId; std::string trueAppId; - std::string deviceAccountId; - Status getKvStoreStatus = Status::SUCCESS; - KvStoreType funType = KvStoreType::MULTI_VERSION; + std::string userId; + pid_t uid; + Status status = Status::SUCCESS; }; struct SecretKeyPara { std::vector metaKey; @@ -141,9 +133,9 @@ private: void StartService(); - Status CheckParameters(const Options &options, const AppId &appId, const StoreId &storeId, - const KvStoreType &kvStoreType, GetKvStorePara &getKvStorePara); - + 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 GetKvStorePara &KvParas, SecretKeyPara &secretKeyParas); Status RecoverSecretKey(const Status &alreadyCreated, bool &outdated, const std::vector &metaSecretKey, @@ -153,10 +145,10 @@ private: const std::vector &metaKey, KvStoreUserManager &kvStoreUserManager); Status GetKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, std::function)> callback); + KvStoreUserManager &kvUserManager, sptr &kvStore); Status GetSingleKvStoreFailDo(const Options &options, const GetKvStorePara &kvParas, SecretKeyPara &secKeyParas, - KvStoreUserManager &kvUserManager, std::function)> callback); + 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 6b8acbafc..698057cfa 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,15 +33,16 @@ 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) +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_(deviceAccountId), + deviceAccountId_(userId), bundleName_(bundleName), storeId_(storeId), - storePath_(Constant::Concatenate({ appDirectory, storeId })), - kvStoreDelegate_(kvStoreDelegate), + appId_(appId), + storePath_(Constant::Concatenate({ directory, storeId })), + kvStoreDelegate_(delegate), storeObserverMutex_(), observerSet_(), openCount_(1) @@ -48,6 +50,11 @@ KvStoreImpl::KvStoreImpl(const Options &options, ZLOGI("construct"); } +std::string KvStoreImpl::GetStoreId() +{ + return storeId_; +} + void KvStoreImpl::GetKvStoreSnapshot(sptr observer, std::function)> callback) { @@ -517,12 +524,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 +784,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 daf5eedb1..d399045e9 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 9ffd34af4..12bee07cd 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp @@ -96,7 +96,7 @@ void KvStoreMetaManager::InitMetaData() ZLOGI("get meta failed."); return; } - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + const std::string userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); auto metaKey = GetMetaKey(AccountDelegate::MAIN_DEVICE_ACCOUNT_ID, "default", META_DB_APP_ID, Constant::SERVICE_META_DB_NAME); struct KvStoreMetaData metaData { @@ -128,7 +128,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}; @@ -261,7 +260,7 @@ Status KvStoreMetaManager::CheckUpdateServiceMeta(const std::vector &me DistributedDB::CipherPassword dbPassword; const std::string deviceAccountId = AccountDelegate::MAIN_DEVICE_ACCOUNT_ID; - const std::string userId = AccountDelegate::GetInstance()->GetCurrentHarmonyAccountId(); + const std::string userId = AccountDelegate::GetInstance()->GetCurrentAccountId(); std::initializer_list backList = {userId, "_", META_DB_APP_ID, "_", Constant::SERVICE_META_DB_NAME}; std::string backupName = Constant::Concatenate(backList); std::initializer_list backFullList = {BackupHandler::GetBackupPath(deviceAccountId, pathType), "/", @@ -644,38 +643,36 @@ 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, 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); + 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, securityLevel), 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, 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); + 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, securityLevel), key); } key.assign(key.size(), 0); } diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h index f4542a36c..46ea8c6b0 100755 --- a/services/distributeddataservice/app/src/kvstore_meta_manager.h +++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h @@ -225,11 +225,11 @@ public: 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, + 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, + sptr store); void GetStrategyMetaKey(const StrategyMeta ¶ms, std::string &retVal); diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.cpp b/services/distributeddataservice/app/src/kvstore_user_manager.cpp index 237431185..7e61eaf67 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 5ef3a1d41..96c0a9703 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.h +++ b/services/distributeddataservice/app/src/kvstore_user_manager.h @@ -24,18 +24,33 @@ 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) + { + // ZLOGI("begin."); + 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()) { + // ZLOGE("emplace failed."); + 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 +74,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 c9ba96be8..d2414ce9d 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/single_kvstore_impl.cpp @@ -19,6 +19,7 @@ #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" @@ -36,6 +37,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 +68,28 @@ 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) +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_(deviceAccountId), + deviceAccountId_(userId), bundleName_(bundleName), storeId_(storeId), - storePath_(Constant::Concatenate({ appDirectory, storeId })), - kvStoreNbDelegate_(kvStoreNbDelegate), + appId_(appId), + storePath_(Constant::Concatenate({ directory, storeId })), + kvStoreNbDelegate_(delegate), observerMapMutex_(), observerMap_(), storeResultSetMutex_(), storeResultSetMap_(), openCount_(1), - flowCtrlManager_(BURST_CAPACITY, SUSTAINED_CAPACITY) + 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; } @@ -164,7 +167,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 +202,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; } @@ -244,7 +247,7 @@ Status SingleKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sp bool deviceCoordinate) { ZLOGD("start."); - if (!flowCtrlManager_.IsTokenEnough()) { + if (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); return Status::EXCEED_MAX_ACCESS_RATE; } @@ -324,7 +327,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 +374,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 +432,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; } @@ -502,7 +505,7 @@ void SingleKvStoreImpl::GetResultSet(const Key &prefixKey, 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; @@ -580,7 +583,7 @@ void SingleKvStoreImpl::GetResultSetWithQuery(const std::string &query, 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; @@ -650,7 +653,7 @@ void SingleKvStoreImpl::GetResultSetWithQuery(const std::string &query, 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,7 +717,7 @@ 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; } @@ -742,7 +745,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 +783,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 +805,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 +1053,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 +1066,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; } @@ -1166,12 +1169,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; @@ -1322,7 +1324,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 +1378,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 +1429,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 +1459,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 +1490,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 +1552,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 +1572,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 +1597,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 +1671,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 124bd7e9f..68b4bbb17 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; @@ -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. @@ -145,7 +149,7 @@ private: 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 92d2dfccd..693efe4f1 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 66b6b7bc3..d045f50f5 100755 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -230,11 +230,12 @@ ohos_unittest("KvStoreBackupTest") { "../src/query_helper.cpp", "../src/rdb/rdb_service.cpp", "../src/single_kvstore_impl.cpp", - "unittest/kvstore_app_manager.cpp", + "../src/kvstore_app_manager.cpp", + "../src/kvstore_data_service.cpp", "unittest/kvstore_backup_test.cpp", - "unittest/kvstore_data_service.cpp", ] + cflags_cc = [ "-DUT_TEST" ] configs = [ ":module_private_config" ] external_deps = [ 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 dcb56f2cf..34578d2ef 100644 --- a/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp +++ b/services/distributeddataservice/app/test/moduletest/distributeddata_account_event_test.cpp @@ -33,6 +33,7 @@ #include "constant.h" #include "common_event_subscriber.h" #include "common_event_support.h" +#include "common_event_define.h" #include "common_event_manager.h" #include "ohos/aafwk/content/intent.h" #include "ohos_account_kits.h" @@ -40,7 +41,7 @@ using namespace testing::ext; using namespace OHOS::DistributedKv; using namespace OHOS; -using namespace OHOS::EventFwk; +using namespace Notification; static const int SYSTEM_USER_ID = 1000; @@ -68,36 +69,33 @@ void DistributedDataAccountEventTest::TearDownTestCase() void DistributedDataAccountEventTest::HarmonyAccountLogin() { - Want want; - want.SetAction(CommonEventSupport::COMMON_EVENT_HWID_LOGIN); - CommonEventData commonEventData(want); - CommonEventData event(want); - CommonEventPublishInfo publishInfo; - auto err = CommonEventManager::PublishCommonEvent(event, publishInfo, nullptr); + sptr intent = new AAFwk::Intent(); + intent->SetAction(CommonEventSupport::COMMON_EVENT_HWID_LOGIN); + sptr event = new CommonEventData(intent); + sptr publishInfo = new CommonEventPublishInfo(); + auto err = CommonEventManager::GetInstance().PublishCommonEventData(event, publishInfo, nullptr); EXPECT_EQ(ERR_OK, err); sleep(WAIT_TIME_FOR_ACCOUNT_OPERATION); } void DistributedDataAccountEventTest::HarmonyAccountLogout() { - Want want; - want.SetAction(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); - CommonEventData commonEventData(want); - CommonEventData event(want); - CommonEventPublishInfo publishInfo; - auto err = CommonEventManager::PublishCommonEvent(event, publishInfo, nullptr); + sptr intent = new AAFwk::Intent(); + intent->SetAction(CommonEventSupport::COMMON_EVENT_HWID_LOGOUT); + sptr event = new CommonEventData(intent); + sptr publishInfo = new CommonEventPublishInfo(); + auto err = CommonEventManager::GetInstance().PublishCommonEventData(event, publishInfo, nullptr); EXPECT_EQ(ERR_OK, err); sleep(WAIT_TIME_FOR_ACCOUNT_OPERATION); } void DistributedDataAccountEventTest::HarmonyAccountDelete() { - Want want; - want.SetAction(CommonEventSupport::COMMON_EVENT_HWID_TOKEN_INVALID); - CommonEventData commonEventData(want); - CommonEventData event(want); - CommonEventPublishInfo publishInfo; - auto err = CommonEventManager::PublishCommonEvent(event, publishInfo, nullptr); + sptr intent = new AAFwk::Intent(); + intent->SetAction(CommonEventSupport::COMMON_EVENT_HWID_TOKEN_INVALID); + sptr event = new CommonEventData(intent); + sptr publishInfo = new CommonEventPublishInfo(); + auto err = CommonEventManager::GetInstance().PublishCommonEventData(event, publishInfo, nullptr); EXPECT_EQ(ERR_OK, err); sleep(WAIT_TIME_FOR_ACCOUNT_OPERATION); } 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 a5cdb6c9b..000000000 --- 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_data_service.cpp b/services/distributeddataservice/app/test/unittest/kvstore_data_service.cpp deleted file mode 100644 index 1e1a02755..000000000 --- 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.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/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn new file mode 100644 index 000000000..d879d6e37 --- /dev/null +++ b/services/distributeddataservice/framework/BUILD.gn @@ -0,0 +1,59 @@ +# 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. +import("//build/ohos.gni") +import("//build/ohos_var.gni") + +group("build_module") { + deps = [ ":distributeddatasvcfwk" ] +} +config("module_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common" + ] +} + +ohos_shared_library("distributeddatasvcfwk") { + sources = [ + "checker/default/system_checker.cpp", + "checker/default/bundle_checker.cpp", + "checker/checker_manager.cpp", + "eventcenter/event.cpp", + "eventcenter/event_center.cpp", + "metadata/meta_data.cpp", + "metadata/secret_key_meta_data.cpp", + "metadata/store_meta_data.cpp", + "metadata/strategy_meta_data.cpp", + "metadata/user_meta_data.cpp", + "serializable/serializable.cpp", + "utils/constant.cpp", + ] + cflags = [ "-Wno-multichar" ] + + cflags_cc = [ "-fvisibility=hidden" ] + + configs = [ ":module_public_config" ] + # ldflags = [ "-Wl,--exclude-libs,libcrypto_static.a" ] + deps = [ + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + public_configs = [ ":module_public_config" ] + subsystem_name = "distributeddatamgr" +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/checker/checker_manager.cpp b/services/distributeddataservice/framework/checker/checker_manager.cpp new file mode 100644 index 000000000..7ba8d61d1 --- /dev/null +++ b/services/distributeddataservice/framework/checker/checker_manager.cpp @@ -0,0 +1,95 @@ +/* +* 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 "checker/checker_manager.h" +#include "account/account_delegate.h" +using namespace OHOS::DistributedKv; +namespace OHOS { +namespace DistributedData { +CheckerManager &CheckerManager::GetInstance() +{ + static CheckerManager instance; + return instance; +} + +void CheckerManager::LoadCheckers(std::vector &checkers) +{ + for (const auto &checker : checkers) { + if (checkers_.find(checker) != checkers_.end()) { + continue; + } + auto it = getters_.Find(checker); + if (!it.first || it.second == nullptr) { + continue; + } + auto *bundleChecker = it.second(); + if (bundleChecker == nullptr) { + continue; + } + bundleChecker->Initialize(); + checkers_[checker] = bundleChecker; + } +} + +void CheckerManager::RegisterPlugin(const std::string &checker, std::function getter) +{ + auto it = getters_.Find(checker); + if (it.first) { + return; + } + getters_[checker] = getter; +} + +std::string CheckerManager::GetAppId(const std::string &bundleName, pid_t uid) +{ + // std::string userId = Account + // std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + for (auto &[name, checker] : checkers_ ) { + if (checker == nullptr) { + continue; + } + auto appId = checker->GetAppId(uid, bundleName); + if (appId.empty()) { + continue; + } + return appId; + } + return ""; +} + +bool CheckerManager::IsValid(const std::string &bundleName, pid_t uid) +{ + // std::string userId = AccountDelegate::GetInstance()->GetDeviceAccountIdByUID(uid); + for (auto &[name, checker] : checkers_ ) { + if (checker == nullptr) { + continue; + } + if (!checker->IsValid(uid, bundleName)) { + continue; + } + return true; + } + return false; +} + +CheckerManager::Checker *CheckerManager::GetChecker(const std::string &checker) +{ + auto it = checkers_.find(checker); + if (it == checkers_.end()) { + return nullptr; + } + return it->second; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/checker/default/bundle_checker.cpp b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp new file mode 100644 index 000000000..1da472719 --- /dev/null +++ b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp @@ -0,0 +1,87 @@ +/* +* 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 "checker/default/bundle_checker.h" +#include "bundlemgr/bundle_mgr_client.h" +namespace OHOS { +namespace DistributedData { +using namespace AppExecFwk; +BundleChecker BundleChecker::instance_; +constexpr pid_t BundleChecker::SYSTEM_UID; +BundleChecker::BundleChecker() +{ + CheckerManager::GetInstance().RegisterPlugin( + "BundleChecker", [this]() -> auto { return this; }); +} + +BundleChecker::~BundleChecker() +{ +} + +void BundleChecker::Initialize() +{ +} + +bool BundleChecker::SetTrustInfo(const CheckerManager::Trust &trust) +{ + trusts_[trust.bundleName] = trust.appId; + return true; +} + +std::string BundleChecker::GetAppId(pid_t uid, const std::string &bundleName) +{ + std::string bundle = bundleName; + if (uid != CheckerManager::INVALID_UID) { + auto success = BundleMgrClient::GetInstance()->GetBundleNameForUid(uid, bundle); + if (uid < SYSTEM_UID || !success || bundle != bundleName) { + return ""; + } + } + + auto bundleInfo = std::make_unique(); + auto success = BundleMgrClient::GetInstance()->GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo); + if (!success) { + return ""; + } + auto it = trusts_.find(bundleName); + if (it != trusts_.end() && (it->second == bundleInfo->appId)) { + return bundleName; + } + + return bundleInfo->appId; +} + +bool BundleChecker::IsValid(pid_t uid, const std::string &bundleName) +{ + std::string bundle = bundleName; + auto success = BundleMgrClient::GetInstance()->GetBundleNameForUid(uid, bundle); + if (uid < SYSTEM_UID || !success || bundle != bundleName) { + return false; + } + + auto bundleInfo = std::make_unique(); + success = BundleMgrClient::GetInstance()->GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo); + if (!success) { + return ""; + } + auto it = trusts_.find(bundleName); + if (it != trusts_.end() && (it->second == bundleInfo->appId)) { + return true; + } + + return true; +} +} +} \ 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 new file mode 100644 index 000000000..c497fb951 --- /dev/null +++ b/services/distributeddataservice/framework/checker/default/system_checker.cpp @@ -0,0 +1,58 @@ +/* +* 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 "checker/default/system_checker.h" +namespace OHOS { +namespace DistributedData { +SystemChecker SystemChecker::instance_; +constexpr pid_t SystemChecker::SYSTEM_UID; +SystemChecker::SystemChecker() +{ + CheckerManager::GetInstance().RegisterPlugin( + "SystemChecker", [this]() -> auto { return this; }); +} + +SystemChecker::~SystemChecker() +{ +} + +void SystemChecker::Initialize() +{ +} + +bool SystemChecker::SetTrustInfo(const CheckerManager::Trust &trust) +{ + trusts_[trust.bundleName] = trust.appId; + return true; +} + +std::string SystemChecker::GetAppId(pid_t uid, const std::string &bundleName) +{ + if (trusts_.find(bundleName) == trusts_.end() || uid >= SYSTEM_UID || uid == CheckerManager::INVALID_UID) { + return ""; + } + return trusts_[bundleName]; +} + +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; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/app/src/kvstore_common.h b/services/distributeddataservice/framework/eventcenter/event.cpp old mode 100755 new mode 100644 similarity index 65% rename from services/distributeddataservice/app/src/kvstore_common.h rename to services/distributeddataservice/framework/eventcenter/event.cpp index 41d4eb139..19bda662b --- a/services/distributeddataservice/app/src/kvstore_common.h +++ b/services/distributeddataservice/framework/eventcenter/event.cpp @@ -13,19 +13,18 @@ * 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; -}; +#include "eventcenter/event.h" +namespace OHOS { +namespace DistributedData { +Event::Event(int32_t evtId) : evtId_(evtId) +{ +} +Event::~Event() +{ +} +int32_t Event::GetEventId() const +{ + return evtId_; +} } -#endif // KVSTORE_COMMON_H +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/eventcenter/event_center.cpp b/services/distributeddataservice/framework/eventcenter/event_center.cpp new file mode 100644 index 000000000..2dd0bd147 --- /dev/null +++ b/services/distributeddataservice/framework/eventcenter/event_center.cpp @@ -0,0 +1,146 @@ +/* + * 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 "eventcenter/event_center.h" +namespace OHOS { +namespace DistributedData { +thread_local EventCenter::AsyncQueue *EventCenter::asyncQueue_ = nullptr; +constexpr int32_t EventCenter::AsyncQueue::MAX_CAPABILITY; +EventCenter &EventCenter::GetInstance() +{ + static EventCenter eventCenter; + return eventCenter; +} + +bool EventCenter::Subscribe(int32_t evtId, const std::function &observer) +{ + return observers_.Compute(evtId, [&observer](const auto &id, auto &list) -> bool { + list.push_back(observer); + return true; + }); +} + +bool EventCenter::Unsubscribe(int32_t evtId) +{ + return observers_.Erase(evtId); +} + +int32_t EventCenter::PostEvent(std::unique_ptr evt) const +{ + if (evt == nullptr) { + return CODE_INVALID_ARGS; + } + if (asyncQueue_ == nullptr) { + Defer defer; + Dispatch(*evt); + return CODE_SYNC; + } + asyncQueue_->Post(std::move(evt)); + return CODE_ASYNC; +} + +void EventCenter::Dispatch(const Event &evt) const +{ + auto observers = observers_.Find(evt.GetEventId()); + if (!observers.first) { + return; + } + + for (const auto &observer : observers.second) { + observer(evt); + } +} + +EventCenter::Defer::Defer(std::function handler, int32_t evtId) +{ + if (asyncQueue_ == nullptr) { + asyncQueue_ = new (std::nothrow) AsyncQueue(); + } + + if (asyncQueue_ == nullptr) { + return; + } + + ++(*asyncQueue_); + asyncQueue_->AddHandler(evtId, std::move(handler)); +} + +EventCenter::Defer::~Defer() +{ + if (asyncQueue_ == nullptr) { + return; + } + --(*asyncQueue_); + if ((*asyncQueue_) <= 0) { + delete asyncQueue_; + asyncQueue_ = nullptr; + } +} + +EventCenter::AsyncQueue &EventCenter::AsyncQueue::operator++() +{ + ++depth_; + return *this; +} + +EventCenter::AsyncQueue &EventCenter::AsyncQueue::operator--() +{ + --depth_; + if (depth_ > 0) { + return *this; + } + depth_ = 1; + for (int32_t count = 0; !events_.empty() && count < MAX_CAPABILITY; count++) { + auto &evt = events_.front(); + // dispatch to resident handlers + GetInstance().Dispatch(*evt); + + // dispatch to temporary handlers + auto handler = handlers_.find(evt->GetEventId()); + if (handler != handlers_.end()) { + handler->second(*evt); + } + events_.pop(); + } + depth_ = 0; + return *this; +} + +bool EventCenter::AsyncQueue::operator<=(int32_t depth) const +{ + return depth_ <= depth; +} + +void EventCenter::AsyncQueue::Post(std::unique_ptr evt) +{ + events_.push(std::move(evt)); +} + +void EventCenter::AsyncQueue::AddHandler(int32_t evtId, std::function handler) +{ + if (evtId == Event::EVT_INVALID || handler == nullptr) { + return; + } + + // The topper layer event will be effective + if (handlers_.find(evtId) != handlers_.end()) { + return; + } + + handlers_[evtId] = std::move(handler); +} +} +} + diff --git a/services/distributeddataservice/framework/include/checker/checker_manager.h b/services/distributeddataservice/framework/include/checker/checker_manager.h new file mode 100644 index 000000000..cd74df00e --- /dev/null +++ b/services/distributeddataservice/framework/include/checker/checker_manager.h @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_CHECKER_MANAGER_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_CHECKER_MANAGER_H +#include "visibility.h" +#include "concurrent_map.h" +namespace OHOS { +namespace DistributedData { +class CheckerManager { +public: + static constexpr pid_t INVALID_UID = 0; + struct Trust { + std::string bundleName; + std::string appId; + std::string packageName; + std::string base64Key; + std::string checker; + }; + class Checker { + protected: + API_EXPORT ~Checker() = default; + public: + virtual void Initialize() = 0; + virtual bool SetTrustInfo(const Trust &trust) = 0; + virtual std::string GetAppId(pid_t uid, const std::string &bundleName) = 0; + virtual bool IsValid(pid_t uid, const std::string &bundleName) = 0; + }; + API_EXPORT static CheckerManager &GetInstance(); + API_EXPORT void RegisterPlugin(const std::string &checker, std::function getter); + API_EXPORT std::string GetAppId(const std::string &bundleName, pid_t uid); + API_EXPORT bool IsValid(const std::string &bundleName, pid_t uid); + API_EXPORT void LoadCheckers(std::vector &checkers); + API_EXPORT Checker *GetChecker(const std::string &checker); +private: + std::map checkers_; + ConcurrentMap> getters_; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_CHECKER_MANAGER_H diff --git a/services/distributeddataservice/framework/include/checker/default/bundle_checker.h b/services/distributeddataservice/framework/include/checker/default/bundle_checker.h new file mode 100644 index 000000000..91eefe491 --- /dev/null +++ b/services/distributeddataservice/framework/include/checker/default/bundle_checker.h @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_BUNDLE_CHECKER_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_BUNDLE_CHECKER_H +#include "checker/checker_manager.h" +namespace OHOS { +namespace DistributedData { +class BundleChecker : public CheckerManager::Checker { +public: + BundleChecker(); + ~BundleChecker(); + void Initialize() override; + bool SetTrustInfo(const CheckerManager::Trust &trust) override; + std::string GetAppId(pid_t uid, const std::string &bundleName) override; + bool IsValid(pid_t uid, const std::string &bundleName) override; +private: + static BundleChecker instance_; + static constexpr pid_t SYSTEM_UID = 10000; + std::map trusts_; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CHECKER_BUNDLE_CHECKER_H diff --git a/services/distributeddataservice/framework/include/checker/default/system_checker.h b/services/distributeddataservice/framework/include/checker/default/system_checker.h new file mode 100644 index 000000000..dbb46e6d6 --- /dev/null +++ b/services/distributeddataservice/framework/include/checker/default/system_checker.h @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SYSTEM_CHECKER_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SYSTEM_CHECKER_H +#include "checker/checker_manager.h" +#include +namespace OHOS { +namespace DistributedData { +class SystemChecker : public CheckerManager::Checker { +public: + SystemChecker(); + ~SystemChecker(); + void Initialize() override; + bool SetTrustInfo(const CheckerManager::Trust &trust) override; + std::string GetAppId(pid_t uid, const std::string &bundleName) override; + bool IsValid(pid_t uid, const std::string &bundleName) override; +private: + static constexpr pid_t SYSTEM_UID = 10000; + std::map trusts_; + static SystemChecker instance_; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_SYSTEM_CHECKER_H diff --git a/services/distributeddataservice/framework/include/eventcenter/event.h b/services/distributeddataservice/framework/include/eventcenter/event.h new file mode 100644 index 000000000..92d9cecde --- /dev/null +++ b/services/distributeddataservice/framework/include/eventcenter/event.h @@ -0,0 +1,40 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_H +#include +#include +#include +#include "visibility.h" +namespace OHOS { +namespace DistributedData { +class Event { +public: + enum EventId : int32_t { + EVT_INVALID, + EVT_INITED, + EVT_UPDATE, + EVT_CUSTOM = 0x1000 + }; + API_EXPORT Event(int32_t evtId); + API_EXPORT virtual ~Event(); + API_EXPORT int32_t GetEventId() const; +private: + int32_t evtId_; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_H diff --git a/services/distributeddataservice/framework/include/eventcenter/event_center.h b/services/distributeddataservice/framework/include/eventcenter/event_center.h new file mode 100644 index 000000000..fb418f6d9 --- /dev/null +++ b/services/distributeddataservice/framework/include/eventcenter/event_center.h @@ -0,0 +1,67 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H +#include +#include +#include +#include "concurrent_map.h" +#include "eventcenter/event.h" +#include "visibility.h" +namespace OHOS { +namespace DistributedData { +class EventCenter { +public: + enum : int32_t { + CODE_SYNC = 1, + CODE_ASYNC, + CODE_INVALID_ARGS, + }; + + class Defer final { + public: + API_EXPORT Defer(std::function handler = nullptr, int32_t evtId = Event::EVT_INVALID); + API_EXPORT ~Defer(); + void *operator new (size_t size) = delete; + void *operator new[] (size_t size) = delete; + void operator delete (void *) = delete; + void operator delete[] (void *) = delete; + }; + API_EXPORT static EventCenter &GetInstance(); + API_EXPORT bool Subscribe(int32_t evtId, const std::function &observer); + API_EXPORT bool Unsubscribe(int32_t evtId); + API_EXPORT int32_t PostEvent(std::unique_ptr evt) const; +private: + void Dispatch(const Event &evt) const; + class AsyncQueue final { + public: + static constexpr int32_t MAX_CAPABILITY = 100; + AsyncQueue &operator++(); + AsyncQueue &operator--(); + bool operator<=(int32_t depth) const; + void Post(std::unique_ptr event); + void AddHandler(int32_t evtId, std::function handler); + private: + std::map> handlers_; + std::queue> events_; + int32_t depth_ = 0; + }; + ConcurrentMap>> observers_; + static thread_local AsyncQueue *asyncQueue_; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_EVENTCENTER_EVENT_CENTER_H diff --git a/services/distributeddataservice/framework/include/metadata/meta_data.h b/services/distributeddataservice/framework/include/metadata/meta_data.h new file mode 100644 index 000000000..8059e0c58 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/meta_data.h @@ -0,0 +1,32 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_META_DATA_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_META_DATA_H +#include "metadata/secret_key_meta_data.h" +#include "metadata/store_meta_data.h" +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +struct MetaData final : public Serializable { + int32_t kvStoreType; + StoreMetaData kvStoreMetaData; + SecretKeyMetaData secretKeyMetaData; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_META_DATA_H diff --git a/services/distributeddataservice/adapter/include/autils/serializable.h b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h old mode 100755 new mode 100644 similarity index 49% rename from services/distributeddataservice/adapter/include/autils/serializable.h rename to services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h index cdefafe3b..f5104a811 --- a/services/distributeddataservice/adapter/include/autils/serializable.h +++ b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h @@ -1,45 +1,33 @@ -/* - * 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 +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_SECRET_KEY_META_DATA_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_SECRET_KEY_META_DATA_H +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +struct SecretKeyMetaData final : public Serializable { + std::vector time {}; + std::vector sKey {}; + int32_t kvStoreType = 0; + ~SecretKeyMetaData() { + sKey.assign(sKey.size(), 0); + } + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_SECRET_KEY_META_DATA_H diff --git a/services/distributeddataservice/framework/include/metadata/store_meta_data.h b/services/distributeddataservice/framework/include/metadata/store_meta_data.h new file mode 100644 index 000000000..2000d6c93 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/store_meta_data.h @@ -0,0 +1,44 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_STORE_META_DATA_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_STORE_META_DATA_H +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +struct StoreMetaData final : public Serializable { + bool isAutoSync = false; + bool isBackup = false; + bool isDirty = false; + bool isEncrypt = false; + int32_t kvStoreType = 0; + int32_t securityLevel = 0; + int32_t uid = -1; + std::string appId = ""; + std::string appType = ""; + std::string bundleName = ""; + std::string dataDir = ""; + std::string deviceAccountId = ""; // todo change to userId + std::string deviceId = ""; + std::string schema = ""; + std::string storeId = ""; + std::string userId = ""; + uint32_t version = 0; + + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_STORE_META_DATA_H diff --git a/services/distributeddataservice/framework/include/serializable/serializable.h b/services/distributeddataservice/framework/include/serializable/serializable.h new file mode 100644 index 000000000..f17dcf3b4 --- /dev/null +++ b/services/distributeddataservice/framework/include/serializable/serializable.h @@ -0,0 +1,101 @@ +/* + * 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_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H +#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H +#include "visibility.h" +#include +#ifndef JSON_NOEXCEPTION +#define JSON_NOEXCEPTION +#endif +#include +namespace OHOS { +namespace DistributedData { +#ifndef GET_NAME +#define GET_NAME(value) #value +#endif +struct Serializable { +public: + using json = nlohmann::json; + API_EXPORT json Marshall() const; + API_EXPORT bool Unmarshall(const std::string &jsonStr); + API_EXPORT static json ToJson(const std::string &jsonStr); + virtual bool Marshal(json &node) const = 0; + virtual bool Unmarshal(const json &node) = 0; + API_EXPORT static bool GetValue(const json &node, const std::string &name, std::string &value); + API_EXPORT static bool GetValue(const json &node, const std::string &name, uint32_t &value); + API_EXPORT static bool GetValue(const json &node, const std::string &name, int32_t &value); + API_EXPORT static bool GetValue(const json &node, const std::string &name, int64_t &value); + API_EXPORT static bool GetValue(const json &node, const std::string &name, bool &value); + API_EXPORT static bool GetValue(const json &node, const std::string &name, std::vector &value); + API_EXPORT static bool GetValue(const json &node, const std::string &name, Serializable &value); + API_EXPORT static bool SetValue(json &node, const std::string &value); + API_EXPORT static bool SetValue(json &node, const uint32_t &value); + API_EXPORT static bool SetValue(json &node, const int32_t &value); + API_EXPORT static bool SetValue(json &node, const int64_t &value); + API_EXPORT static bool SetValue(json &node, const bool &value); + API_EXPORT static bool SetValue(json &node, const std::vector &value); + API_EXPORT static bool SetValue(json &node, const Serializable &value); +protected: + API_EXPORT ~Serializable() = default; + + template + static bool GetValue(const json &node, const std::string &name, T *&value) + { + auto &subNode = GetSubNode(node, name); + if (subNode.is_null()) { + return false; + } + value = new T(); + bool result = GetValue(subNode, "", *value); + if (!result) { + delete value; + value = nullptr; + } + return result; + } + template + static bool GetValue(const json &node, const std::string &name, std::vector &values) + { + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_array()) { + return false; + } + bool result = true; + values.resize(subNode.size()); + for (int i = 0; i < subNode.size(); ++i) { + result &= GetValue(subNode[i], "", values[i]); + } + return result; + } + + template + static bool SetValue(json &node, const std::vector &values) + { + bool result = true; + int i = 0; + node = json::value_t::array; + for (const auto &value : values) { + result &= SetValue(node[i], value); + i++; + } + return result; + } + + API_EXPORT static const json &GetSubNode(const json &node, const std::string &name); +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h new file mode 100644 index 000000000..68f4165fb --- /dev/null +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef KV_DATASERVICE_CONSTANT_H +#define KV_DATASERVICE_CONSTANT_H + +#include +#include +#include +#include +#include +#include +#include +#include "visibility.h" +#include "autils/visibility.h" + +namespace OHOS { +namespace DistributedKv { +class KvStoreMetaRow { +public: + KVSTORE_API static const std::string KEY_PREFIX; + + KVSTORE_API static std::vector GetKeyFor(const std::string &key); +}; + +class SecretMetaRow { +public: + KVSTORE_API static const std::string KEY_PREFIX; + + KVSTORE_API 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); + + // delete left bland in s by reference. + template + static void LeftTrim(T &s); + + // delete right bland in s by reference. + template + static void RightTrim(T &s); + + // delete both left and right bland in s by reference. + template + static void Trim(T &s); + + // delete left bland in s by reference, not change raw string. + template + static T LeftTrimCopy(T s); + + // delete right bland in s by reference, not change raw string. + template + static T RightTrimCopy(T s); + + // delete both left and right bland in s by reference, not change raw string. + template + static T TrimCopy(T s); + + // get default device account id. + KVSTORE_API static std::string GetDefaultDeviceAccountId(); + + // get default harmony account name. + KVSTORE_API static std::string GetDefaultHarmonyAccountName(); + + // default group id for synchronization based on harmony account. + KVSTORE_API 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; + + // version for distributed kv data service. + KVSTORE_API static const std::string VERSION; + + // meta name for distributed kv data service. + KVSTORE_API static const std::string META_DIR_NAME; + + // name for distributed kv data service. + KVSTORE_API static const std::string SERVICE_NAME; + + // root path for distributed kv data service. + KVSTORE_API static const std::string ROOT_PATH; + + // root path for distributeddata service and system services. + KVSTORE_API 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; + + // the max length for key is 256. + KVSTORE_API static const size_t MAX_KEY_LENGTH; + + // the max length for value is 1M. + KVSTORE_API static const size_t MAX_VALUE_LENGTH; + + // the max length for StoreId is 64. + KVSTORE_API static const size_t MAX_STORE_ID_LENGTH; + + // the max batch for putBatch is 128. + KVSTORE_API static const size_t MAX_BATCH_SIZE; + + // the max capacity for ipc is 800KB. + KVSTORE_API static const size_t MAX_IPC_CAPACITY; + + // service meta db name. + KVSTORE_API static const std::string SERVICE_META_DB_NAME; + + KVSTORE_API static const std::string KEY_SEPARATOR; + + KVSTORE_API static const mode_t DEFAULT_MODE; + + KVSTORE_API static const mode_t DEFAULT_MODE_DIR; + + KVSTORE_API static const mode_t DEFAULT_MODE_FILE; + + KVSTORE_API static const int SWITCH_RAW_DATA_SIZE; + + 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; +}; + +// trim from start (in place) +template +void Constant::LeftTrim(T &s) +{ + s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); +} + +// trim from end (in place) +template +void Constant::RightTrim(T &s) +{ + s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); +} + +// trim from both ends (in place) +template +void Constant::Trim(T &s) +{ + LeftTrim(s); + RightTrim(s); +} + +// trim from start (copying) +template +T Constant::LeftTrimCopy(T s) +{ + LeftTrim(s); + return s; +} + +// trim from end (copying) +template +T Constant::RightTrimCopy(T s) +{ + RightTrim(s); + return s; +} + +// trim from both ends (copying) +template +T Constant::TrimCopy(T s) +{ + Trim(s); + return s; +} +} // namespace DistributedKv +} // namespace OHOS +#endif // KV_DATASERVICE_CONSTANT_H + diff --git a/services/distributeddataservice/framework/metadata/meta_data.cpp b/services/distributeddataservice/framework/metadata/meta_data.cpp new file mode 100644 index 000000000..090ca2d3c --- /dev/null +++ b/services/distributeddataservice/framework/metadata/meta_data.cpp @@ -0,0 +1,34 @@ +/* + * 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 "metadata/meta_data.h" +namespace OHOS { +namespace DistributedData { +bool MetaData::Marshal(json &node) const +{ + SetValue(node[GET_NAME(kvStoreType)], kvStoreType); + SetValue(node[GET_NAME(kvStoreMetaData)], kvStoreMetaData); + SetValue(node[GET_NAME(secretKeyMetaData)], secretKeyMetaData); + return true; +} +bool MetaData::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(kvStoreType), kvStoreType); + GetValue(node, GET_NAME(kvStoreMetaData), kvStoreMetaData); + GetValue(node, GET_NAME(secretKeyMetaData), secretKeyMetaData); + return true; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp new file mode 100644 index 000000000..b534f9695 --- /dev/null +++ b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp @@ -0,0 +1,33 @@ +/* + * 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 "metadata/secret_key_meta_data.h" +namespace OHOS { +namespace DistributedData { +bool SecretKeyMetaData::Marshal(json &node) const +{ + SetValue(node[GET_NAME(time)], time); + SetValue(node[GET_NAME(sKey)], sKey); + SetValue(node[GET_NAME(kvStoreType)], kvStoreType); + return true; +} +bool SecretKeyMetaData::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(time), time); + GetValue(node, GET_NAME(sKey), sKey); + GetValue(node, GET_NAME(kvStoreType), kvStoreType); + return true; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/metadata/store_meta_data.cpp b/services/distributeddataservice/framework/metadata/store_meta_data.cpp new file mode 100644 index 000000000..a730149dd --- /dev/null +++ b/services/distributeddataservice/framework/metadata/store_meta_data.cpp @@ -0,0 +1,60 @@ +/* + * 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 "metadata/store_meta_data.h" +namespace OHOS { +namespace DistributedData { +bool StoreMetaData::Marshal(Serializable::json &node) const +{ + SetValue(node[GET_NAME(appId)], appId); + SetValue(node[GET_NAME(appType)], appType); + SetValue(node[GET_NAME(bundleName)], bundleName); + SetValue(node[GET_NAME(dataDir)], dataDir); + SetValue(node[GET_NAME(deviceAccountId)], deviceAccountId); + SetValue(node[GET_NAME(deviceId)], deviceId); + SetValue(node[GET_NAME(isAutoSync)], isAutoSync); + SetValue(node[GET_NAME(isBackup)], isBackup); + SetValue(node[GET_NAME(isEncrypt)], isEncrypt); + SetValue(node[GET_NAME(kvStoreType)], kvStoreType); + SetValue(node[GET_NAME(schema)], schema); + SetValue(node[GET_NAME(storeId)], storeId); + SetValue(node[GET_NAME(uid)], uid); + SetValue(node[GET_NAME(version)], version); + SetValue(node[GET_NAME(securityLevel)], securityLevel); + SetValue(node[GET_NAME(isDirty)], isDirty); + return true; +} +bool StoreMetaData::Unmarshal(const Serializable::json &node) +{ + GetValue(node, GET_NAME(appId), appId); + GetValue(node, GET_NAME(appType), appType); + GetValue(node, GET_NAME(bundleName), bundleName); + GetValue(node, GET_NAME(dataDir), dataDir); + GetValue(node, GET_NAME(deviceAccountId), deviceAccountId); + GetValue(node, GET_NAME(deviceId), deviceId); + GetValue(node, GET_NAME(isAutoSync), isAutoSync); + GetValue(node, GET_NAME(isBackup), isBackup); + GetValue(node, GET_NAME(isEncrypt), isEncrypt); + GetValue(node, GET_NAME(kvStoreType), kvStoreType); + GetValue(node, GET_NAME(schema), schema); + GetValue(node, GET_NAME(storeId), storeId); + GetValue(node, GET_NAME(uid), uid); + GetValue(node, GET_NAME(version), version); + GetValue(node, GET_NAME(securityLevel), securityLevel); + GetValue(node, GET_NAME(isDirty), isDirty); + return true; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/serializable/serializable.cpp b/services/distributeddataservice/framework/serializable/serializable.cpp new file mode 100644 index 000000000..540f0912c --- /dev/null +++ b/services/distributeddataservice/framework/serializable/serializable.cpp @@ -0,0 +1,186 @@ +/* + * 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 "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +Serializable::json Serializable::Marshall() const +{ + json root; + Marshal(root); + return root; +} + +bool Serializable::Unmarshall(const std::string &jsonStr) +{ + json jsonObj = json::parse(jsonStr, nullptr, false); + if (jsonObj.is_discarded()) { + // if the string size is less than 1, means the string is invalid. + if (jsonStr.empty()) { + return false; + } + jsonObj = json::parse(jsonStr.substr(1), nullptr, false); // drop first char to adapt A's value; + if (jsonObj.is_discarded()) { + return false; + } + } + return Unmarshal(jsonObj); +} + +Serializable::json Serializable::ToJson(const std::string &jsonStr) +{ + json jsonObj = json::parse(jsonStr, nullptr, false); + if (jsonObj.is_discarded()) { + // if the string size is less than 1, means the string is invalid. + if (jsonStr.empty()) { + return {}; + } + jsonObj = json::parse(jsonStr.substr(1), nullptr, false); // drop first char to adapt A's value; + if (jsonObj.is_discarded()) { + return {}; + } + } + return jsonObj; +} + +bool Serializable::GetValue(const json &node, const std::string &name, std::string &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_string()) { + return false; + } + value = subNode; + return true; +} + +bool Serializable::GetValue(const json &node, const std::string &name, uint32_t &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_number_unsigned()) { + return false; + } + subNode.get_to(value); + return true; +} + +bool Serializable::GetValue(const json &node, const std::string &name, int32_t &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_number_integer()) { + return false; + } + subNode.get_to(value); + return true; +} + +bool Serializable::GetValue(const json &node, const std::string &name, int64_t &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_number_integer()) { + return false; + } + subNode.get_to(value); + return true; +} + +bool Serializable::GetValue(const json &node, const std::string &name, bool &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_boolean()) { + return false; + } + subNode.get_to(value); + return true; +} + +bool Serializable::GetValue(const json &node, const std::string &name, std::vector &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_array()) { + return false; + } + value = std::vector(subNode); + return true; +} + +bool Serializable::GetValue(const json &node, const std::string &name, Serializable &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null() || !subNode.is_object()) { + return false; + } + return value.Unmarshal(subNode); +} + +bool Serializable::SetValue(json &node, const std::string &value) +{ + node = value; + return true; +} + +bool Serializable::SetValue(json &node, const uint32_t &value) +{ + node = value; + return true; +} + +bool Serializable::SetValue(json &node, const int32_t &value) +{ + node = value; + return true; +} + +bool Serializable::SetValue(json &node, const int64_t &value) +{ + node = value; + return true; +} + +bool Serializable::SetValue(json &node, const bool &value) +{ + node = value; + return true; +} + +bool Serializable::SetValue(json &node, const std::vector &value) +{ + node = value; + return true; +} + +bool Serializable::SetValue(json &node, const Serializable &value) +{ + return value.Marshal(node); +} + +const Serializable::json &Serializable::GetSubNode(const json &node, const std::string &name) +{ + static const json jsonNull = json::value_t::null; + if (node.is_discarded() || node.is_null()) { + return jsonNull; + } + + if (name.empty()) { + return node; + } + + auto it = node.find(name); + if (it == node.end()) { + return jsonNull; + } + return *it; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/checker_manager_test.cpp b/services/distributeddataservice/framework/test/checker_manager_test.cpp new file mode 100644 index 000000000..5b0b07ed5 --- /dev/null +++ b/services/distributeddataservice/framework/test/checker_manager_test.cpp @@ -0,0 +1,94 @@ +/* +* 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 "checker/checker_manager.h" +#include +using namespace testing::ext; +using namespace OHOS::DistributedData; +class CheckerManagerSuite : public testing::Test { +public: + static void SetUpTestCase(void) {} + static void TearDownTestCase(void) {} + void SetUp() {} + void TearDown() {} +}; +/** +* @tc.name: checkers +* @tc.desc: checker the bundle name of the system abilities. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(CheckerManagerSuite, Checkers, TestSize.Level0) +{ + auto *checker = CheckerManager::GetInstance().GetChecker("SystemChecker"); + ASSERT_NE(checker, nullptr); + checker = CheckerManager::GetInstance().GetChecker("BundleChecker"); + ASSERT_NE(checker, nullptr); + checker = CheckerManager::GetInstance().GetChecker("OtherChecker"); + ASSERT_EQ(checker, nullptr); +} + +/** +* @tc.name: SystemChecker bms +* @tc.desc: checker the bundle name of the system abilities. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(CheckerManagerSuite, SystemCheckerBMS, TestSize.Level0) +{ + ASSERT_EQ("bundle_manager_service", CheckerManager::GetInstance().GetAppId("bundle_manager_service", 1000)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid("bundle_manager_service", 1000)); +} + +/** +* @tc.name: SystemChecker form +* @tc.desc: checker the bundle name of the system abilities. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(CheckerManagerSuite, SystemCheckerForm, TestSize.Level0) +{ + ASSERT_EQ("form_storage", CheckerManager::GetInstance().GetAppId("form_storage", 1000)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid("form_storage", 1000)); +} + +/** +* @tc.name: SystemChecker ivi +* @tc.desc: checker the bundle name of the system abilities. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(CheckerManagerSuite, SystemCheckerIVI, TestSize.Level0) +{ + ASSERT_EQ("ivi_config_manager", CheckerManager::GetInstance().GetAppId("ivi_config_manager", 1000)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid("ivi_config_manager", 1000)); +} + +/** +* @tc.name: BundleChecker +* @tc.desc: checker the bundle name of the bundle abilities. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(CheckerManagerSuite, BundleChecker, TestSize.Level0) +{ + ASSERT_EQ("com.huawei.ohos.toteweather", CheckerManager::GetInstance().GetAppId("com.huawei.ohos.toteweather", 100000)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid("com.huawei.ohos.toteweather", 100000)); +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/event_center_test.cpp b/services/distributeddataservice/framework/test/event_center_test.cpp new file mode 100644 index 000000000..d126b64d5 --- /dev/null +++ b/services/distributeddataservice/framework/test/event_center_test.cpp @@ -0,0 +1,154 @@ +/* + * 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 "eventcenter/event_center.h" +#include "eventcenter/event.h" +#include "log_print.h" +#include +using namespace testing::ext; +using namespace OHOS::DistributedData; +class EventCenterSuite : public testing::Test { +public: + enum TestEventId : int32_t { + TEST_EVT_UNKNOWN = Event::EVT_CUSTOM, + TEST_EVT_BEGIN = Event::EVT_CUSTOM + 1, + TEST_EVT_MIDDLE, + TEST_EVT_END, + }; + class TestBegin : public Event { + public: + TestBegin(): Event(TEST_EVT_BEGIN) {}; + }; + class TestMiddle : public Event { + public: + TestMiddle(): Event(TEST_EVT_MIDDLE) {}; + }; + class TestEnd : public Event { + public: + TestEnd(): Event(TEST_EVT_END) {}; + }; + static void SetUpTestCase(void) {} + static void TearDownTestCase(void) {} + void SetUp() + { + waitEvent_ = TEST_EVT_UNKNOWN; + currEvent_ = TEST_EVT_UNKNOWN; + EventCenter::GetInstance().Subscribe(TEST_EVT_BEGIN, [this](const Event &evt){ + ASSERT_EQ(waitEvent_, TEST_EVT_BEGIN); + EventCenter::Defer defer; + EventCenter::GetInstance().PostEvent(std::make_unique()); + currEvent_ = TEST_EVT_BEGIN; + waitEvent_ = TEST_EVT_MIDDLE; + }); + EventCenter::GetInstance().Subscribe(TEST_EVT_MIDDLE, [this](const Event &evt){ + ASSERT_EQ(waitEvent_, TEST_EVT_MIDDLE); + EventCenter::Defer defer; + EventCenter::GetInstance().PostEvent(std::make_unique()); + currEvent_ = TEST_EVT_MIDDLE; + waitEvent_ = TEST_EVT_END; + }); + EventCenter::GetInstance().Subscribe(TEST_EVT_END, [this](const Event &evt){ + ASSERT_EQ(waitEvent_, TEST_EVT_END); + currEvent_ = TEST_EVT_END; + waitEvent_ = TEST_EVT_UNKNOWN; + }); + } + + void TearDown() + { + EventCenter::GetInstance().Unsubscribe(TEST_EVT_BEGIN); + EventCenter::GetInstance().Unsubscribe(TEST_EVT_MIDDLE); + EventCenter::GetInstance().Unsubscribe(TEST_EVT_END); + waitEvent_ = TEST_EVT_UNKNOWN; + currEvent_ = TEST_EVT_UNKNOWN; + } + +protected: + int32_t waitEvent_ = TEST_EVT_UNKNOWN; + int32_t currEvent_ = TEST_EVT_UNKNOWN; +}; + +/** +* @tc.name: TopLayerASyncEvent +* @tc.desc: the async event on the top layer will dispatch, until the function completed. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(EventCenterSuite, TopLayerASyncEvent, TestSize.Level2) +{ + ZLOGI("EventCenterSuite ASyncEvent begin."); + auto test = [this]() { + EventCenter::Defer defer; + EventCenter::GetInstance().PostEvent(std::make_unique()); + waitEvent_ = TEST_EVT_BEGIN; + }; + test(); + ASSERT_EQ(currEvent_, TEST_EVT_END); + ASSERT_EQ(waitEvent_, TEST_EVT_UNKNOWN); +} + +/** +* @tc.name: SubLayerASyncEvent +* @tc.desc: the async event on sub layer will defer to dispatch, until the top layer function completed. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(EventCenterSuite, SubLayerASyncEvent, TestSize.Level2) +{ + ZLOGI("EventCenterSuite ASyncEvent begin."); + EventCenter::Defer defer; + EventCenter::GetInstance().PostEvent(std::make_unique()); + waitEvent_ = TEST_EVT_BEGIN; + ASSERT_EQ(currEvent_, TEST_EVT_UNKNOWN); + ASSERT_EQ(waitEvent_, TEST_EVT_BEGIN); +} + +/** +* @tc.name: ASyncEventWithoutDefer +* @tc.desc: async event without defer may call or not +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(EventCenterSuite, ASyncEventWithoutDefer, TestSize.Level2) +{ + ZLOGI("EventCenterSuite ASyncEvent begin."); + EventCenter::Defer defer; + waitEvent_ = TEST_EVT_BEGIN; + auto test = [this]() { + EventCenter::GetInstance().PostEvent(std::make_unique()); + }; + test(); + ASSERT_EQ(currEvent_, TEST_EVT_UNKNOWN); + ASSERT_EQ(waitEvent_, TEST_EVT_BEGIN); +} + + +/** +* @tc.name: ImmediatelyASyncEvent +* @tc.desc: post the async event, there is top layer and no defer; we will dispatch the async event Immediately. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(EventCenterSuite, ImmediatelyASyncEvent, TestSize.Level2) +{ + ZLOGI("EventCenterSuite ASyncEvent begin."); + waitEvent_ = TEST_EVT_BEGIN; + EventCenter::GetInstance().PostEvent(std::make_unique()); + ASSERT_EQ(currEvent_, TEST_EVT_END); + ASSERT_EQ(waitEvent_, TEST_EVT_UNKNOWN); +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/serializable_test.cpp b/services/distributeddataservice/framework/test/serializable_test.cpp new file mode 100644 index 000000000..1ee62aefc --- /dev/null +++ b/services/distributeddataservice/framework/test/serializable_test.cpp @@ -0,0 +1,162 @@ +/* + * 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 "SerializableTest" + +#include "serializable//serializable.h" +#include "log_print.h" +#include +using namespace testing::ext; +using namespace OHOS::DistributedData; + +class SerializableSuite : public testing::Test { +public: + struct Normal : public Serializable { + public: + std::string name = "Test"; + int32_t count = 0; + uint32_t status = 1; + int64_t value = 2; + bool isClear = false; + std::vector cols{"123", "345", "789"}; + std::vector> colrow{{123, 345, 789}, {123, 345, 789}}; + + bool Marshal(json &node) const override + { + SetValue(node[GET_NAME(name)], name); + SetValue(node[GET_NAME(count)], count); + SetValue(node[GET_NAME(status)], status); + SetValue(node[GET_NAME(value)], value); + SetValue(node[GET_NAME(isClear)], isClear); + SetValue(node[GET_NAME(cols)], cols); + SetValue(node[GET_NAME(colrow)], colrow); + return true; + } + bool Unmarshal(const json &node) override + { + GetValue(node, GET_NAME(name), name); + GetValue(node, GET_NAME(count), count); + GetValue(node, GET_NAME(status), status); + GetValue(node, GET_NAME(value), value); + GetValue(node, GET_NAME(isClear), isClear); + GetValue(node, GET_NAME(cols), cols); + GetValue(node, GET_NAME(colrow), colrow); + return true; + } + bool operator == (const Normal &ref) const + { + return name == ref.name && count == ref.count && status == ref.status && value == ref.value + && isClear == ref.isClear && cols == ref.cols; + } + }; + + struct NormalEx : public Serializable { + public: + std::vector normals {Normal(), Normal()}; + Normal normal; + int32_t count = 123; + std::string name = "wdt"; + bool Marshal(json &node) const override + { + SetValue(node[GET_NAME(normals)], normals); + SetValue(node[GET_NAME(normal)], normal); + SetValue(node[GET_NAME(count)], count); + SetValue(node[GET_NAME(name)], name); + return true; + } + bool Unmarshal(const json &node) override + { + GetValue(node, GET_NAME(normals), normals); + GetValue(node, GET_NAME(normal), normal); + GetValue(node, GET_NAME(count), count); + GetValue(node, GET_NAME(name), name); + return true; + } + bool operator==(const NormalEx &normalEx) const + { + return normals == normalEx.normals && count == normalEx.count && name == normalEx.name; + } + }; + static void SetUpTestCase(void) + { + } + static void TearDownTestCase(void) + { + } + void SetUp() + { + Test::SetUp(); + } + void TearDown() + { + Test::TearDown(); + } +}; + +/** +* @tc.name: SerializableSuiteGetVal +* @tc.desc: Get Value. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(SerializableSuite, GetNormalVal, TestSize.Level2) +{ + ZLOGI("SerializableSuite GetVal begin."); + Normal normal; + normal.name = "normal"; + normal.count = -1; + normal.status = 12; + normal.value = -56; + normal.isClear = true; + normal.cols = {"adfasdfas"}; + auto jstr = to_string(normal.Marshall()); + Normal normal1; + normal1.Unmarshall(jstr); + ASSERT_TRUE(normal == normal1) << normal1.name; +} + +/** +* @tc.name: Delete Serializable +* @tc.desc: can delete child class, but not delete parent class point. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(SerializableSuite, DeleteSerializable, TestSize.Level2) +{ + ZLOGI("SerializableSuite GetVal begin."); + NormalEx *normalEx = new NormalEx(); + delete normalEx; +} + +/** +* @tc.name: SerializableSuiteGetMutilVal +* @tc.desc: mutil value case. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(SerializableSuite, GetMutilVal, TestSize.Level2) +{ + ZLOGI("SerializableSuite GetVal begin."); + + NormalEx normalEx; + normalEx.normals = {Normal()}; + normalEx.name = "normalEx"; + auto jstr = to_string(normalEx.Marshall()); + NormalEx normal1; + normal1.Unmarshall(jstr); + ASSERT_TRUE(normalEx == normal1) << normal1.name; +} diff --git a/services/distributeddataservice/framework/utils/constant.cpp b/services/distributeddataservice/framework/utils/constant.cpp new file mode 100644 index 000000000..75b77bb9e --- /dev/null +++ b/services/distributeddataservice/framework/utils/constant.cpp @@ -0,0 +1,124 @@ +/* + * 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/constant.h" +#include +#include +#include + +namespace OHOS { +namespace DistributedKv { +// the Key Prefix for Meta data of KvStore. +const std::string KvStoreMetaRow::KEY_PREFIX = "KvStoreMetaData"; + +const std::string SecretMetaRow::KEY_PREFIX = "SecretKey"; + +/* version for distributed kv data service. */ +const std::string Constant::VERSION = "1"; + +/* meta name for distributed kv data service. */ +const std::string Constant::META_DIR_NAME = "Meta"; + +/* name for distributed kv data service. */ +const std::string Constant::SERVICE_NAME = "mdds"; + +/* root path for distributed kv data service. */ +const std::string Constant::ROOT_PATH = "/data/misc_de/0"; + +/* root path for distributeddata service and system services. */ +const std::string Constant::ROOT_PATH_DE = "/data/misc_de/0"; + +/* root path for self-developed and non-self-developed app. */ +const std::string Constant::ROOT_PATH_CE = "/data/misc_ce/0"; + +// the max length for key is 1024. +const size_t Constant::MAX_KEY_LENGTH = 1024; + +// the max length for StoreId is 128. +const size_t Constant::MAX_STORE_ID_LENGTH = 128; + +// the max length for value is 4M. +const size_t Constant::MAX_VALUE_LENGTH = 4 * 1024 * 1024; + +// the max batch for putBatch is 128. +const size_t Constant::MAX_BATCH_SIZE = 128; + +// the max capacity for ipc is 800K. +const size_t Constant::MAX_IPC_CAPACITY = 800 * 1024; + +// the default mode is 0755, stands for r/w/x for user, r/x for group, r/x for others. +const mode_t Constant::DEFAULT_MODE = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; + +// the mode for dir is 0755, r/w/x for user, r/-/x for group, r/-/x for others. +const mode_t Constant::DEFAULT_MODE_DIR = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; + +// the mode for file is 0600, r/w/- for user, -/-/- for group, -/-/- for others. +const mode_t Constant::DEFAULT_MODE_FILE = S_IRUSR | S_IWUSR; + +// Size threshold of switching to large data is a little smaller than MAX_IPC_CAPACITY. +const int Constant::SWITCH_RAW_DATA_SIZE = 700 * 1024; + +const int Constant::MAX_OPEN_KVSTORES = 16; + +// default group id for synchronization. +const std::string Constant::DEFAULT_GROUP_ID = "default"; + +// true indicates the ownership of distributed data is DEVICE, otherwise, ACCOUNT +const bool Constant::STOREID_ONLY_FLAG = true; + +// service meta db name. +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 }); + return std::vector(str.begin(), str.end()); +} + +std::vector SecretMetaRow::GetKeyFor(const std::string &key) +{ + std::string str = Constant::Concatenate({SecretMetaRow::KEY_PREFIX, Constant::KEY_SEPARATOR, key }); + return std::vector(str.begin(), str.end()); +} + +std::string Constant::Concatenate(std::initializer_list stringList) +{ + std::string result; + size_t result_size = 0; + for (const std::string &str : stringList) { + result_size += str.size(); + } + result.reserve(result_size); + for (const std::string &str : stringList) { + result.append(str.data(), str.size()); + } + return result; +} + +std::string Constant::GetDefaultDeviceAccountId() +{ + return "0"; +} + +std::string Constant::GetDefaultHarmonyAccountName() +{ + return "default"; +} +} // namespace DistributedKv +} // namespace OHOS diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn new file mode 100644 index 000000000..516fd56f1 --- /dev/null +++ b/services/distributeddataservice/service/BUILD.gn @@ -0,0 +1,58 @@ +# 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. +import("//build/ohos.gni") +import("//build/ohos_var.gni") + +group("build_module") { + deps = [ ":distributeddatasvc" ] +} +config("module_public_config") { + visibility = [ ":*" ] + include_dirs = [ + "bootstrap/include", + "config/include", + "directory/include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common" + ] +} + +ohos_shared_library("distributeddatasvc") { + sources = [ + "bootstrap/src/bootstrap.cpp", + "config/src/model/checker_config.cpp", + "config/src/model/component_config.cpp", + "config/src/model/directory_config.cpp", + "config/src/model/global_config.cpp", + "config/src/model/network_config.cpp", + "config/src/model/protocol_config.cpp", + "config/src/config_factory.cpp", + "directory/src/directory_manager.cpp" + ] + cflags = [ "-Wno-multichar" ] + + cflags_cc = [ "-fvisibility=hidden" ] + + configs = [ ":module_public_config" ] + # ldflags = [ "-Wl,--exclude-libs,libcrypto_static.a" ] + deps = [ + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + public_configs = [ ":module_public_config" ] + subsystem_name = "distributeddatamgr" +} \ No newline at end of file diff --git a/services/distributeddataservice/service/bootstrap/CMakeLists.txt b/services/distributeddataservice/service/bootstrap/CMakeLists.txt new file mode 100644 index 000000000..72d567cdc --- /dev/null +++ b/services/distributeddataservice/service/bootstrap/CMakeLists.txt @@ -0,0 +1,87 @@ +cmake_minimum_required(VERSION 3.10.2) +project(bootstrap) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y -fno-rtti -fvisibility=hidden -D_GNU_SOURCE") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -fPIC -fpic -ffunction-sections -D_GLIBC_MOCK") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") +#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") +#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") +set(MOCK_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../mock") +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src bootstrapSrc) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../frameworks/common) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../config/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../directory/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../framework/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../interfaces/innerkits/distributeddata/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/base/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/safwk/native/include) +include_directories(${MOCK_DIR}) +include_directories(${MOCK_DIR}/uapi) +include_directories(${MOCK_DIR}/innerkits/sensor/sensor_interface_native/include) +include_directories(${MOCK_DIR}/innerkits/miscdevice/vibrator_interface_native/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/want/include/ohos/aafwk/content) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/intent/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/ability_manager/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/base/include) +include_directories(${MOCK_DIR}/innerkits/jsapi_worker/worker_init/include) +include_directories(${MOCK_DIR}/innerkits/os_account_standard/libaccountkits/include) +include_directories(${MOCK_DIR}/innerkits/deviceauth_standard/deviceauth_sdk/include) +include_directories(${MOCK_DIR}/innerkits/samgr_standard/samgr_proxy/include) +include_directories(${MOCK_DIR}/innerkits/ipc/ipc_core/include) +include_directories(${MOCK_DIR}/innerkits/ipc/ipc_single/include) +include_directories(${MOCK_DIR}/innerkits/ipc/libdbinder/include) +include_directories(${MOCK_DIR}/innerkits/resmgr_standard/global_resmgr/include) +include_directories(${MOCK_DIR}/innerkits/power_manager_native/powermgr_client/include) +include_directories(${MOCK_DIR}/innerkits/napi/ace_napi/include) +include_directories(${MOCK_DIR}/innerkits/hisysevent_native/libhisysevent/include) +include_directories(${MOCK_DIR}/innerkits/appverify/libhapverify/include) +include_directories(${MOCK_DIR}/innerkits/huks_standard/libhukssdk/include) +include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_ability/include) +include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_client/include) +include_directories(${MOCK_DIR}/innerkits/safwk/system_ability_fwk/include) +include_directories(${MOCK_DIR}/innerkits/ipc_js/rpc/include) +include_directories(${MOCK_DIR}/innerkits/dataclassification/fbe_iudf_xattr/include) +include_directories(${MOCK_DIR}/innerkits/dataclassification/hwdsl/include) +include_directories(${MOCK_DIR}/innerkits/battery_manager_native/batterysrv_client/include) +include_directories(${MOCK_DIR}/innerkits/permission_standard/libpermissionsdk_standard/include) +include_directories(${MOCK_DIR}/innerkits/hilog_native/libhilog/include) +include_directories(${MOCK_DIR}/innerkits/display_manager_native/displaymgr/include) +include_directories(${MOCK_DIR}/innerkits/i18n_standard/phonenumber_standard/include) +include_directories(${MOCK_DIR}/innerkits/i18n_standard/zone_util/include) +include_directories(${MOCK_DIR}/innerkits/bytrace_standard/bytrace_core/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/proxy/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/event/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/common/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libinput-third-mmi/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_base/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/eventhandler_native/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/fmskit_native/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/libeventhandler/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_core/include) +include_directories(${MOCK_DIR}/innerkits/hitrace_native/libhitrace/include) +include_directories(${MOCK_DIR}/innerkits/dmsfwk_standard/zuri/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_services/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_core/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_innerkits/include) +include_directories(${MOCK_DIR}/innerkits/multimedia_image_standard/image/include) +include_directories(${MOCK_DIR}/innerkits/ril_adapter/hril/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_dataability/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_preferences/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_rdb/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_appdatafwk/include) +include_directories(${MOCK_DIR}/innerkits/startup_l2/syspara/include) +include_directories(${MOCK_DIR}/innerkits/hicollie_native/libhicollie/include) +include_directories(${MOCK_DIR}/innerkits/dsoftbus_standard/softbus_client/include) +include_directories(${MOCK_DIR}/innerkits/device_manager_base/devicemanagersdk/include) +include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/app_distributeddata/include) +include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/distributeddata_inner/include) +#include_directories(${MOCK_DIR}/innerkits/utils_base/utils/include/include) +set(links secure mock frameworks config svcFwk directory) +set(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/../../../../") +add_library(bootstrap SHARED ${bootstrapSrc}) +target_link_libraries(bootstrap ${links}) diff --git a/services/distributeddataservice/service/bootstrap/include/bootstrap.h b/services/distributeddataservice/service/bootstrap/include/bootstrap.h new file mode 100644 index 000000000..b99b96f59 --- /dev/null +++ b/services/distributeddataservice/service/bootstrap/include/bootstrap.h @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_DISTRIBUTEDDATASERVICE_BOOTSTRAP_BOOTSTRAP_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_DISTRIBUTEDDATASERVICE_BOOTSTRAP_BOOTSTRAP_H +#include "visibility.h" +#include +namespace OHOS { +namespace DistributedData { +class Bootstrap { +public: + API_EXPORT static Bootstrap &GetInstance(); + API_EXPORT std::string GetProcessLabel(); + API_EXPORT void LoadComponents(); + API_EXPORT void LoadCheckers(); + API_EXPORT void LoadNetworks(); + API_EXPORT void LoadDirectory(); +private: + static constexpr const char *DEFAULT_LABEL = "distributeddata"; + using Constructor = void(*)(const char *); +}; +} +} +#endif //OHOS_DISTRIBUTED_DATA_SERVICES_DISTRIBUTEDDATASERVICE_BOOTSTRAP_BOOTSTRAP_H diff --git a/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp new file mode 100644 index 000000000..2d467d682 --- /dev/null +++ b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp @@ -0,0 +1,87 @@ +/* +* 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 "bootstrap.h" + +#include + +#include "checker/checker_manager.h" +#include "config_factory.h" +#include "directory_manager.h" +namespace OHOS { +namespace DistributedData { +Bootstrap &Bootstrap::GetInstance() +{ + static Bootstrap bootstrap; + return bootstrap; +} + +std::string Bootstrap::GetProcessLabel() +{ + auto *global = ConfigFactory::GetInstance().GetGlobalConfig(); + if (global == nullptr || global->processLabel.empty()) { + return DEFAULT_LABEL; + } + return global->processLabel; +} + +void Bootstrap::LoadComponents() +{ + auto *comps = ConfigFactory::GetInstance().GetComponentConfig(); + if (comps == nullptr) { + return; + } + for (auto &comp : *comps) { + auto handle = dlopen(comp.lib.c_str(), RTLD_LAZY); + auto ctor = (Constructor)dlsym(handle, comp.constructor.c_str()); + if (ctor == nullptr) { + continue; + } + ctor(comp.params.c_str()); + } +} + +void Bootstrap::LoadCheckers() +{ + auto *checkers = ConfigFactory::GetInstance().GetCheckerConfig(); + if (checkers == nullptr) { + return; + } + CheckerManager::GetInstance().LoadCheckers(checkers->checkers); + for (const auto &trust : checkers->trusts) { + auto *checker = CheckerManager::GetInstance().GetChecker(trust.checker); + if (checker == nullptr) { + continue; + } + checker->SetTrustInfo(trust); + } +} + +void Bootstrap::LoadNetworks() +{ +} +void Bootstrap::LoadDirectory() +{ + auto *global = ConfigFactory::GetInstance().GetGlobalConfig(); + if (global == nullptr || global->directory == nullptr) { + return; + } + for (const auto &strategy : global->directory->strategy) { + DirectoryManager::GetInstance().AddParams(strategy); + } + DirectoryManager::GetInstance().SetCurrentVersion(global->directory->currentStrategyVersion); +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/CMakeLists.txt b/services/distributeddataservice/service/config/CMakeLists.txt new file mode 100644 index 000000000..af844568a --- /dev/null +++ b/services/distributeddataservice/service/config/CMakeLists.txt @@ -0,0 +1,88 @@ +cmake_minimum_required(VERSION 3.10.2) +project(config) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y -fno-rtti -fvisibility=hidden -D_GNU_SOURCE") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -fPIC -fpic -ffunction-sections -D_GLIBC_MOCK") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") +#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") +#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") +set(MOCK_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../mock") +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src configSrc) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src/model configSrc) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/model) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../frameworks/common) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../framework/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../directory/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../interfaces/innerkits/distributeddata/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/base/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/safwk/native/include) +include_directories(${MOCK_DIR}) +include_directories(${MOCK_DIR}/uapi) +include_directories(${MOCK_DIR}/innerkits/sensor/sensor_interface_native/include) +include_directories(${MOCK_DIR}/innerkits/miscdevice/vibrator_interface_native/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/want/include/ohos/aafwk/content) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/intent/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/ability_manager/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/base/include) +include_directories(${MOCK_DIR}/innerkits/jsapi_worker/worker_init/include) +include_directories(${MOCK_DIR}/innerkits/os_account_standard/libaccountkits/include) +include_directories(${MOCK_DIR}/innerkits/deviceauth_standard/deviceauth_sdk/include) +include_directories(${MOCK_DIR}/innerkits/samgr_standard/samgr_proxy/include) +include_directories(${MOCK_DIR}/innerkits/ipc/ipc_core/include) +include_directories(${MOCK_DIR}/innerkits/ipc/ipc_single/include) +include_directories(${MOCK_DIR}/innerkits/ipc/libdbinder/include) +include_directories(${MOCK_DIR}/innerkits/resmgr_standard/global_resmgr/include) +include_directories(${MOCK_DIR}/innerkits/power_manager_native/powermgr_client/include) +include_directories(${MOCK_DIR}/innerkits/napi/ace_napi/include) +include_directories(${MOCK_DIR}/innerkits/hisysevent_native/libhisysevent/include) +include_directories(${MOCK_DIR}/innerkits/appverify/libhapverify/include) +include_directories(${MOCK_DIR}/innerkits/huks_standard/libhukssdk/include) +include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_ability/include) +include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_client/include) +include_directories(${MOCK_DIR}/innerkits/safwk/system_ability_fwk/include) +include_directories(${MOCK_DIR}/innerkits/ipc_js/rpc/include) +include_directories(${MOCK_DIR}/innerkits/dataclassification/fbe_iudf_xattr/include) +include_directories(${MOCK_DIR}/innerkits/dataclassification/hwdsl/include) +include_directories(${MOCK_DIR}/innerkits/battery_manager_native/batterysrv_client/include) +include_directories(${MOCK_DIR}/innerkits/permission_standard/libpermissionsdk_standard/include) +include_directories(${MOCK_DIR}/innerkits/hilog_native/libhilog/include) +include_directories(${MOCK_DIR}/innerkits/display_manager_native/displaymgr/include) +include_directories(${MOCK_DIR}/innerkits/i18n_standard/phonenumber_standard/include) +include_directories(${MOCK_DIR}/innerkits/i18n_standard/zone_util/include) +include_directories(${MOCK_DIR}/innerkits/bytrace_standard/bytrace_core/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/proxy/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/event/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/common/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libinput-third-mmi/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_base/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/eventhandler_native/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/fmskit_native/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/libeventhandler/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_core/include) +include_directories(${MOCK_DIR}/innerkits/hitrace_native/libhitrace/include) +include_directories(${MOCK_DIR}/innerkits/dmsfwk_standard/zuri/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_services/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_core/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_innerkits/include) +include_directories(${MOCK_DIR}/innerkits/multimedia_image_standard/image/include) +include_directories(${MOCK_DIR}/innerkits/ril_adapter/hril/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_dataability/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_preferences/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_rdb/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_appdatafwk/include) +include_directories(${MOCK_DIR}/innerkits/startup_l2/syspara/include) +include_directories(${MOCK_DIR}/innerkits/hicollie_native/libhicollie/include) +include_directories(${MOCK_DIR}/innerkits/dsoftbus_standard/softbus_client/include) +include_directories(${MOCK_DIR}/innerkits/device_manager_base/devicemanagersdk/include) +include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/app_distributeddata/include) +include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/distributeddata_inner/include) +#include_directories(${MOCK_DIR}/innerkits/utils_base/utils/include/include) +set(links secure mock frameworks svcFwk directory) +set(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/../../../../") +add_library(config SHARED ${configSrc}) +target_link_libraries(config ${links}) diff --git a/services/distributeddataservice/service/config/include/config_factory.h b/services/distributeddataservice/service/config/include/config_factory.h new file mode 100644 index 000000000..681db11e2 --- /dev/null +++ b/services/distributeddataservice/service/config/include/config_factory.h @@ -0,0 +1,42 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_CONFIG_CONFIG_FACTORY_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_CONFIG_FACTORY_H +#include +#include "visibility.h" +#include "model/global_config.h" +namespace OHOS { +namespace DistributedData { +class ConfigFactory { +public: + API_EXPORT static ConfigFactory &GetInstance(); + API_EXPORT int32_t Initialize(); + API_EXPORT std::vector *GetComponentConfig(); + API_EXPORT NetworkConfig *GetNetworkConfig(); + API_EXPORT CheckerConfig *GetCheckerConfig(); + API_EXPORT GlobalConfig *GetGlobalConfig(); +private: + static constexpr const char *CONF_PATH = "/system/etc/distributeddata/conf"; + ConfigFactory(); + ~ConfigFactory(); + + std::string file_; + GlobalConfig config_; + bool isInited = false; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_CONFIG_FAC 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7+ \ No newline at end of file diff --git a/services/distributeddataservice/service/config/include/model/checker_config.h b/services/distributeddataservice/service/config/include/model/checker_config.h new file mode 100644 index 000000000..ec51177fa --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/checker_config.h @@ -0,0 +1,38 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_CHECKER_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_CHECKER_CONFIG_H +#include "serializable/serializable.h" +#include "checker/checker_manager.h" +namespace OHOS { +namespace DistributedData { +class CheckerConfig final : public Serializable { +public: + class Trust final + : public Serializable + , public CheckerManager::Trust { + public: + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + }; + std::vector checkers; + std::vector trusts; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_CHECKER_CONFIG_H diff --git a/services/distributeddataservice/service/config/include/model/component_config.h b/services/distributeddataservice/service/config/include/model/component_config.h new file mode 100644 index 000000000..ed9df6c75 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/component_config.h @@ -0,0 +1,33 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_COMPONENT_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_COMPONENT_CONFIG_H +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +class ComponentConfig final : public Serializable { +public: + std::string description = ""; + std::string lib = ""; + std::string constructor = ""; + std::string destructor = ""; + std::string params = ""; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_COMPONENT_CONFIG_H diff --git a/services/distributeddataservice/service/config/include/model/directory_config.h b/services/distributeddataservice/service/config/include/model/directory_config.h new file mode 100644 index 000000000..789e3fb7b --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/directory_config.h @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2022 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DIRECTORY_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DIRECTORY_CONFIG_H +#include "serializable/serializable.h" +#include "directory_manager.h" +namespace OHOS { +namespace DistributedData { +class DirectoryConfig final : public Serializable { +public: + struct DirectoryStrategy final + : public Serializable + , public DirectoryManager::Strategy { + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + }; + std::string currentStrategyVersion; + std::vector strategy; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; + +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DIRECTORY_CONFIG_H diff --git a/services/distributeddataservice/service/config/include/model/global_config.h b/services/distributeddataservice/service/config/include/model/global_config.h new file mode 100644 index 000000000..ac72dd7c3 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/global_config.h @@ -0,0 +1,40 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_GLOBAL_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_GLOBAL_CONFIG_H +#include "serializable/serializable.h" +#include "model/checker_config.h" +#include "model/component_config.h" +#include "model/network_config.h" +#include "model/directory_config.h" +namespace OHOS { +namespace DistributedData { +class GlobalConfig final : public Serializable { +public: + std::string processLabel; + std::string metaData; + std::string version; + std::vector features; + std::vector *components = nullptr; + CheckerConfig *bundleChecker = nullptr; + NetworkConfig *networks = nullptr; + DirectoryConfig *directory = nullptr; + bool Marshal(json &node) const override; + bool Unmarshal(const json &node); +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_GLOBAL_CONFIG_H diff --git a/services/distributeddataservice/service/config/include/model/network_config.h b/services/distributeddataservice/service/config/include/model/network_config.h new file mode 100644 index 000000000..505782492 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/network_config.h @@ -0,0 +1,33 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_NETWORK_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_NETWORK_CONFIG_H +#include "serializable/serializable.h" +#include "protocol_config.h" +namespace OHOS { +namespace DistributedData { +class NetworkConfig final : public Serializable { +public: + std::vector chains; + std::vector routers; + std::vector transports; + std::vector protocols; + bool Marshal(json &node) const; + bool Unmarshal(const json &node); +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_NETWORK_CONFIG_H diff --git a/services/distributeddataservice/service/config/include/model/protocol_config.h b/services/distributeddataservice/service/config/include/model/protocol_config.h new file mode 100644 index 000000000..bdbe4c79d --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/protocol_config.h @@ -0,0 +1,31 @@ +/* + * 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_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_PROTOCOL_CONFIG_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_PROTOCOL_CONFIG_H +#include "serializable/serializable.h" +namespace OHOS { +namespace DistributedData { +class ProtocolConfig final : public Serializable { +public: + std::string name; + std::string address; + std::string transport; + bool Marshal(json &node) const; + bool Unmarshal(const json &node); +}; +} +} +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_PROTOCOL_CONFIG_H diff --git a/services/distributeddataservice/service/config/src/config_factory.cpp b/services/distributeddataservice/service/config/src/config_factory.cpp new file mode 100644 index 000000000..c689aba36 --- /dev/null +++ b/services/distributeddataservice/service/config/src/config_factory.cpp @@ -0,0 +1,71 @@ +/* + * 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 "config_factory.h" +#include +namespace OHOS { +namespace DistributedData { +ConfigFactory::ConfigFactory() + : file_(std::string(CONF_PATH) + "/config.json") +{ +} + +ConfigFactory::~ConfigFactory() +{ +} + +ConfigFactory &ConfigFactory::GetInstance() +{ + static ConfigFactory factory; + if (!factory.isInited) { + factory.Initialize(); + } + return factory; +} + +int32_t ConfigFactory::Initialize() +{ + std::string jsonStr; + std::ifstream fin(file_); + while (!fin.eof()) { + std::string line; + std::getline(fin, line); + jsonStr += line; + } + config_.Unmarshall(jsonStr); + isInited = true; + return 0; +} + +std::vector *ConfigFactory::GetComponentConfig() +{ + return config_.components; +} + +NetworkConfig *ConfigFactory::GetNetworkConfig() +{ + return config_.networks; +} + +CheckerConfig *ConfigFactory::GetCheckerConfig() +{ + return config_.bundleChecker; +} + +GlobalConfig *ConfigFactory::GetGlobalConfig() +{ + return &config_; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/checker_config.cpp b/services/distributeddataservice/service/config/src/model/checker_config.cpp new file mode 100644 index 000000000..35fb58b14 --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/checker_config.cpp @@ -0,0 +1,53 @@ +/* + * 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 "model/checker_config.h" +namespace OHOS { +namespace DistributedData { +bool CheckerConfig::Trust::Marshal(json &node) const +{ + SetValue(node[GET_NAME(bundleName)], bundleName); + SetValue(node[GET_NAME(appId)], appId); + SetValue(node[GET_NAME(packageName)], packageName); + SetValue(node[GET_NAME(base64Key)], base64Key); + SetValue(node[GET_NAME(checker)], checker); + return true; +} + +bool CheckerConfig::Trust::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(bundleName), bundleName); + GetValue(node, GET_NAME(appId), appId); + GetValue(node, GET_NAME(packageName), packageName); + GetValue(node, GET_NAME(base64Key), base64Key); + GetValue(node, GET_NAME(checker), checker); + return true; +} + +bool CheckerConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(checkers)], checkers); + SetValue(node[GET_NAME(trusts)], trusts); + return true; +} + +bool CheckerConfig::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(checkers), checkers); + GetValue(node, GET_NAME(trusts), trusts); + return true; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/component_config.cpp b/services/distributeddataservice/service/config/src/model/component_config.cpp new file mode 100644 index 000000000..9fed56bb1 --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/component_config.cpp @@ -0,0 +1,44 @@ +/* + * 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 "model/component_config.h" +namespace OHOS { +namespace DistributedData { +bool ComponentConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(description)], description); + SetValue(node[GET_NAME(lib)], lib); + SetValue(node[GET_NAME(constructor)], constructor); + SetValue(node[GET_NAME(destructor)], destructor); + if (!params.empty()) { + node[GET_NAME(params)] = ToJson(params); + } + return true; +} + +bool ComponentConfig::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(description), description); + GetValue(node, GET_NAME(lib), lib); + GetValue(node, GET_NAME(constructor), constructor); + GetValue(node, GET_NAME(destructor), destructor); + const auto &subNode = GetSubNode(node, GET_NAME(params)); + if (!subNode.is_null()) { + params = to_string(subNode); + } + return true; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/directory_config.cpp b/services/distributeddataservice/service/config/src/model/directory_config.cpp new file mode 100644 index 000000000..5cde0ec35 --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/directory_config.cpp @@ -0,0 +1,52 @@ +/* +* 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 "model/directory_config.h" +namespace OHOS { +namespace DistributedData { +bool DirectoryConfig::DirectoryStrategy::Marshal(json &node) const +{ + SetValue(node[GET_NAME(version)], version); + SetValue(node[GET_NAME(holder)], holder); + SetValue(node[GET_NAME(path)], path); + SetValue(node[GET_NAME(metaPath)], metaPath); + return true; +} + +bool DirectoryConfig::DirectoryStrategy::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(version), version); + GetValue(node, GET_NAME(holder), holder); + GetValue(node, GET_NAME(path), path); + GetValue(node, GET_NAME(metaPath), metaPath); + return true; +} + +bool DirectoryConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(currentStrategyVersion)], currentStrategyVersion); + SetValue(node[GET_NAME(strategy)], strategy); + return true; +} + +bool DirectoryConfig::Unmarshal(const json &node) +{ + bool ret = true; + ret &= GetValue(node, GET_NAME(currentStrategyVersion), currentStrategyVersion); + ret &= GetValue(node, GET_NAME(strategy), strategy); + return ret; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/global_config.cpp b/services/distributeddataservice/service/config/src/model/global_config.cpp new file mode 100644 index 000000000..8f91037ea --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/global_config.cpp @@ -0,0 +1,45 @@ +/* + * 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 "model/global_config.h" +namespace OHOS { +namespace DistributedData { +bool GlobalConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(processLabel)], processLabel); + SetValue(node[GET_NAME(metaData)], metaData); + SetValue(node[GET_NAME(version)], version); + SetValue(node[GET_NAME(features)], features); + SetValue(node[GET_NAME(components)], components); + SetValue(node[GET_NAME(bundleChecker)], bundleChecker); + SetValue(node[GET_NAME(networks)], networks); + SetValue(node[GET_NAME(directory)], directory); + return true; +} + +bool GlobalConfig::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(processLabel), processLabel); + GetValue(node, GET_NAME(metaData), metaData); + GetValue(node, GET_NAME(version), version); + GetValue(node, GET_NAME(features), features); + GetValue(node, GET_NAME(components), components); + GetValue(node, GET_NAME(bundleChecker), bundleChecker); + GetValue(node, GET_NAME(networks), networks); + GetValue(node, GET_NAME(directory), directory); + return true; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/network_config.cpp b/services/distributeddataservice/service/config/src/model/network_config.cpp new file mode 100644 index 000000000..20c0049fe --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/network_config.cpp @@ -0,0 +1,37 @@ +/* + * 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 "model/network_config.h" +namespace OHOS { +namespace DistributedData { +bool NetworkConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(chains)], chains); + SetValue(node[GET_NAME(routers)], routers); + SetValue(node[GET_NAME(transports)], transports); + SetValue(node[GET_NAME(protocols)], protocols); + return true; +} + +bool NetworkConfig::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(chains), chains); + GetValue(node, GET_NAME(routers), routers); + GetValue(node, GET_NAME(transports), transports); + GetValue(node, GET_NAME(protocols), protocols); + return true; +} +} // namespace DistributedData +} // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/config/src/model/protocol_config.cpp b/services/distributeddataservice/service/config/src/model/protocol_config.cpp new file mode 100644 index 000000000..8e5161e95 --- /dev/null +++ b/services/distributeddataservice/service/config/src/model/protocol_config.cpp @@ -0,0 +1,35 @@ +/* + * 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 "model/protocol_config.h" +namespace OHOS { +namespace DistributedData { +bool ProtocolConfig::Marshal(json &node) const +{ + SetValue(node[GET_NAME(name)], name); + SetValue(node[GET_NAME(address)], address); + SetValue(node[GET_NAME(transport)], transport); + return true; +} + +bool ProtocolConfig::Unmarshal(const json &node) +{ + GetValue(node, GET_NAME(name), name); + GetValue(node, GET_NAME(address), address); + GetValue(node, GET_NAME(transport), transport); + return true; +} +} +} \ No newline at end of file diff --git a/services/distributeddataservice/service/directory/CMakeLists.txt b/services/distributeddataservice/service/directory/CMakeLists.txt new file mode 100644 index 000000000..629fe644e --- /dev/null +++ b/services/distributeddataservice/service/directory/CMakeLists.txt @@ -0,0 +1,86 @@ +cmake_minimum_required(VERSION 3.10.2) +project(directory) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y -fno-rtti -fvisibility=hidden -D_GNU_SOURCE") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -fPIC -fpic -ffunction-sections -D_GLIBC_MOCK") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") +#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") +#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") +set(MOCK_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../mock") +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src directorySrc) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../frameworks/common) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../framework/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../interfaces/innerkits/distributeddata/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../adapter/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/base/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/safwk/native/include) +include_directories(${MOCK_DIR}) +include_directories(${MOCK_DIR}/uapi) +include_directories(${MOCK_DIR}/innerkits/sensor/sensor_interface_native/include) +include_directories(${MOCK_DIR}/innerkits/miscdevice/vibrator_interface_native/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/want/include/ohos/aafwk/content) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/intent/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/ability_manager/include) +include_directories(${MOCK_DIR}/innerkits/aafwk_standard/base/include) +include_directories(${MOCK_DIR}/innerkits/jsapi_worker/worker_init/include) +include_directories(${MOCK_DIR}/innerkits/os_account_standard/libaccountkits/include) +include_directories(${MOCK_DIR}/innerkits/deviceauth_standard/deviceauth_sdk/include) +include_directories(${MOCK_DIR}/innerkits/samgr_standard/samgr_proxy/include) +include_directories(${MOCK_DIR}/innerkits/ipc/ipc_core/include) +include_directories(${MOCK_DIR}/innerkits/ipc/ipc_single/include) +include_directories(${MOCK_DIR}/innerkits/ipc/libdbinder/include) +include_directories(${MOCK_DIR}/innerkits/resmgr_standard/global_resmgr/include) +include_directories(${MOCK_DIR}/innerkits/power_manager_native/powermgr_client/include) +include_directories(${MOCK_DIR}/innerkits/napi/ace_napi/include) +include_directories(${MOCK_DIR}/innerkits/hisysevent_native/libhisysevent/include) +include_directories(${MOCK_DIR}/innerkits/appverify/libhapverify/include) +include_directories(${MOCK_DIR}/innerkits/huks_standard/libhukssdk/include) +include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_ability/include) +include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_client/include) +include_directories(${MOCK_DIR}/innerkits/safwk/system_ability_fwk/include) +include_directories(${MOCK_DIR}/innerkits/ipc_js/rpc/include) +include_directories(${MOCK_DIR}/innerkits/dataclassification/fbe_iudf_xattr/include) +include_directories(${MOCK_DIR}/innerkits/dataclassification/hwdsl/include) +include_directories(${MOCK_DIR}/innerkits/battery_manager_native/batterysrv_client/include) +include_directories(${MOCK_DIR}/innerkits/permission_standard/libpermissionsdk_standard/include) +include_directories(${MOCK_DIR}/innerkits/hilog_native/libhilog/include) +include_directories(${MOCK_DIR}/innerkits/display_manager_native/displaymgr/include) +include_directories(${MOCK_DIR}/innerkits/i18n_standard/phonenumber_standard/include) +include_directories(${MOCK_DIR}/innerkits/i18n_standard/zone_util/include) +include_directories(${MOCK_DIR}/innerkits/bytrace_standard/bytrace_core/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/proxy/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/event/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/common/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include/include) +include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libinput-third-mmi/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_base/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/eventhandler_native/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/fmskit_native/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/libeventhandler/include) +include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_core/include) +include_directories(${MOCK_DIR}/innerkits/hitrace_native/libhitrace/include) +include_directories(${MOCK_DIR}/innerkits/dmsfwk_standard/zuri/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_services/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_core/include) +include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_innerkits/include) +include_directories(${MOCK_DIR}/innerkits/multimedia_image_standard/image/include) +include_directories(${MOCK_DIR}/innerkits/ril_adapter/hril/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_dataability/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_preferences/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_rdb/include) +include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_appdatafwk/include) +include_directories(${MOCK_DIR}/innerkits/startup_l2/syspara/include) +include_directories(${MOCK_DIR}/innerkits/hicollie_native/libhicollie/include) +include_directories(${MOCK_DIR}/innerkits/dsoftbus_standard/softbus_client/include) +include_directories(${MOCK_DIR}/innerkits/device_manager_base/devicemanagersdk/include) +include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/app_distributeddata/include) +include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/distributeddata_inner/include) +#include_directories(${MOCK_DIR}/innerkits/utils_base/utils/include/include) +set(links secure mock frameworks svcFwk) +set(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/../../../../") +add_library(directory SHARED ${directorySrc}) +target_link_libraries(directory ${links}) diff --git a/services/distributeddataservice/service/directory/include/directory_manager.h b/services/distributeddataservice/service/directory/include/directory_manager.h new file mode 100644 index 000000000..a40214c67 --- /dev/null +++ b/services/distributeddataservice/service/directory/include/directory_manager.h @@ -0,0 +1,96 @@ +/* + * 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 SDB_DIRECTORY_MANAGER_H +#define SDB_DIRECTORY_MANAGER_H + +#include +#include +#include "visibility.h" +#include "kvstore_context.h" +#include "metadata/store_meta_data.h" +namespace OHOS::DistributedData { +enum PathType { + PATH_DE, + PATH_CE, +}; +class StoreMetaData; +class DirWorker { +public: + DirWorker() = default; + virtual std::string GetDir(ClientContext clientContext, PathType type) = 0; + virtual bool CreateDir(ClientContext clientContext, PathType type) = 0; + virtual std::string GetBackupDir(ClientContext clientContext, PathType type) = 0; + virtual std::string GetSecretKeyDir(ClientContext clientContext, PathType type) = 0; + virtual std::string GetMetaDir() = 0; +}; + +class ServerDirWorker : public DirWorker { +public: + static ServerDirWorker &GetInstance(); + + std::string GetDir(ClientContext clientContext, PathType type) override; + bool CreateDir(ClientContext clientContext, PathType type) override; + std::string GetBackupDir(ClientContext clientContext, PathType type) override; + std::string GetSecretKeyDir(ClientContext clientContext, PathType type) override; + std::string GetMetaDir() override; + +public: + static std::map rootPathMap_; +}; + +class ClientDirWorker : public DirWorker { +public: + static ClientDirWorker &GetInstance(); + + std::string GetDir(ClientContext clientContext, PathType type) override; + bool CreateDir(ClientContext clientContext, PathType type) override; + std::string GetBackupDir(ClientContext clientContext, PathType type) override; + std::string GetSecretKeyDir(ClientContext clientContext, PathType type) override; + std::string GetMetaDir() override; +}; + +class DirectoryManager { +public: + struct Strategy { + std::string version; + std::string holder; + std::string path; + std::string metaPath; + }; + API_EXPORT static DirectoryManager &GetInstance(); + API_EXPORT std::string CreatePath(const ClientContext &context, PathType type); + API_EXPORT std::string GetStorePath(const StoreMetaData &metaData); + API_EXPORT std::string GetStoreBackupPath(const StoreMetaData &metaData); + API_EXPORT std::string GetMetaDataStorePath(); + + API_EXPORT void AddParams(const Strategy &strategy); + API_EXPORT void SetCurrentVersion(const std::string &version); + + inline static std::string JoinPath(std::initializer_list stringList) + { + std::string tmpPath; + for (const std::string &str : stringList) { + tmpPath += (str + "/"); + } + return tmpPath; + } +private: + std::map patterns_; + std::string version_; +}; +} // namespace OHOS::DistributedKv + +#endif //SDB_DIRECTORY_MANAGER_H diff --git a/services/distributeddataservice/service/directory/include/kvstore_context.h b/services/distributeddataservice/service/directory/include/kvstore_context.h new file mode 100644 index 000000000..b50dbdb27 --- /dev/null +++ b/services/distributeddataservice/service/directory/include/kvstore_context.h @@ -0,0 +1,30 @@ +/* + * 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 + +#include "types.h" + +#ifndef SDB_KVSTORE_CONTEXT_H +#define SDB_KVSTORE_CONTEXT_H +namespace OHOS::DistributedData { +struct ClientContext { + std::string userId {}; + std::string bundleName {}; + std::string dataDir {}; +}; +} + +#endif //SDB_KVSTORE_CONTEXT_H \ No newline at end of file diff --git a/services/distributeddataservice/service/directory/src/directory_manager.cpp b/services/distributeddataservice/service/directory/src/directory_manager.cpp new file mode 100644 index 000000000..dc7c713fd --- /dev/null +++ b/services/distributeddataservice/service/directory/src/directory_manager.cpp @@ -0,0 +1,151 @@ +/* + * 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 "directory_manager.h" + +#include + +#include "utils/constant.h" +#include "autils/directory_utils.h" +#include "directory_ex.h" +#include "kvstore_context.h" +#include "log/log_print.h" +namespace OHOS::DistributedData { +using namespace DistributedKv; +std::map ServerDirWorker::rootPathMap_ = { + { PATH_DE, "/data/misc_de/0/mdds" }, + { PATH_CE, "/data/misc_ce/0/mdds" }, +}; +std::string ServerDirWorker::GetDir(ClientContext clientContext, PathType type) +{ + if (rootPathMap_.find(type) == rootPathMap_.end()) { + return ""; + } + return DirectoryManager::JoinPath({ rootPathMap_.at(type), clientContext.userId, + Constant::GetDefaultHarmonyAccountName(), clientContext.bundleName }); +} +bool ServerDirWorker::CreateDir(ClientContext clientContext, PathType type) +{ + std::string directory = GetDir(clientContext, type); + bool ret = ForceCreateDirectory(directory); + if (!ret) { + 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() +{ + static ServerDirWorker instance; + return instance; +} +std::string ServerDirWorker::GetBackupDir(ClientContext clientContext, PathType type) +{ + if (rootPathMap_.find(type) == rootPathMap_.end()) { + return ""; + } + return DirectoryManager::JoinPath({ rootPathMap_.at(type), clientContext.userId, + Constant::GetDefaultHarmonyAccountName(), clientContext.bundleName, "backup" }); +} +std::string ServerDirWorker::GetMetaDir() +{ + return DirectoryManager::JoinPath({ rootPathMap_.at(PATH_DE), "Meta" }); +} +std::string ServerDirWorker::GetSecretKeyDir(ClientContext clientContext, PathType type) +{ + return GetDir(clientContext, type); +} +std::string ClientDirWorker::GetDir(ClientContext clientContext, PathType type) +{ + return clientContext.dataDir; +} +bool ClientDirWorker::CreateDir(ClientContext clientContext, PathType type) +{ + return true; +} +ClientDirWorker &ClientDirWorker::GetInstance() +{ + static ClientDirWorker instance; + return instance; +} +std::string ClientDirWorker::GetBackupDir(ClientContext clientContext, PathType type) +{ + return DirectoryManager::JoinPath({ clientContext.dataDir, "backup" }); +} +std::string ClientDirWorker::GetMetaDir() +{ + return std::string("/data/service/el1/public/distributeddata/DistributedKvDataService/Meta/"); +} +std::string ClientDirWorker::GetSecretKeyDir(ClientContext clientContext, PathType type) +{ + return GetDir(clientContext, type); +} + +std::string DirectoryManager::CreatePath(const ClientContext &context, PathType type) +{ + return ""; +} + +DirectoryManager &DirectoryManager::GetInstance() +{ + static DirectoryManager instance; + return instance; +} + +std::string DirectoryManager::GetStorePath(const StoreMetaData &metaData) +{ + // todo implement; +// switch (metaData.version) { +// case 0: +// return std::string("/data/service/el") + std::to_string(metaData.securityLevel) + "/0/database/ddms/" +// + metaData.deviceAccountId + "/" + metaData.bundleName; +// case 1: +// // "/data/{type}/{security}/{userId}/{packageName}/database/{bundleName}"; +// return std::string("/data/") + (metaData.uid < 10000 ? "app" : "service") + "/el" +// + std::to_string(metaData.securityLevel) + metaData.deviceAccountId +// + (metaData.uid < 10000 ? "" : "/{packageName}") + "/database/" + metaData.bundleName; +// } + return {}; +} + +std::string DirectoryManager::GetStoreBackupPath(const StoreMetaData &metaData) +{ + return GetStorePath(metaData) + "/backup/"; +} + +std::string DirectoryManager::GetMetaDataStorePath() +{ + return "/data/service/el0/0/database/ddms/metadata/"; +} +void DirectoryManager::AddParams(const Strategy &strategy) +{ + patterns_[strategy.version] = strategy; +} +void DirectoryManager::SetCurrentVersion(const std::string &version) +{ + version_ = version; +} +} // namespace OHOS::DistributedData \ No newline at end of file diff --git a/services/distributeddataservice/service/test/config_factory_test.cpp b/services/distributeddataservice/service/test/config_factory_test.cpp new file mode 100644 index 000000000..ba468996f --- /dev/null +++ b/services/distributeddataservice/service/test/config_factory_test.cpp @@ -0,0 +1,137 @@ +/* +* 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 "config_factory.h" +#include +using namespace testing::ext; +using namespace OHOS::DistributedData; +class ConfigFactorySuite : public testing::Test { +public: + static void SetUpTestCase(void) { + int32_t result = ConfigFactory::GetInstance().Initialize(); + } + static void TearDownTestCase(void) {} + void SetUp() + { + } + + void TearDown() + { + } +}; + +/** +* @tc.name: GlobalConfig +* @tc.desc: load the config.json global info. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(ConfigFactorySuite, GlobalConfig, TestSize.Level0) +{ + auto *global = ConfigFactory::GetInstance().GetGlobalConfig(); + ASSERT_NE(global, nullptr); + ASSERT_EQ(global->processLabel, "distributeddata"); + ASSERT_EQ(global->metaData, "service_meta"); + ASSERT_EQ(global->version, "000.000.001"); + std::vector features{"kvdb", "rdb", "object", "backup", "data_sync"}; + ASSERT_EQ(global->features, features); +} + +/** +* @tc.name: ComponentConfig +* @tc.desc: load the config.json component info. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(ConfigFactorySuite, ComponentConfig, TestSize.Level0) +{ + auto *components = ConfigFactory::GetInstance().GetComponentConfig(); + ASSERT_NE(components, nullptr); + ASSERT_EQ(components->size(), 2); + const ComponentConfig &config = (*components)[0]; + ASSERT_EQ(config.description, "3rd party adapter"); + ASSERT_EQ(config.lib, "libdistributedadapter.z.so"); + ASSERT_EQ(config.constructor, ""); + ASSERT_EQ(config.destructor, ""); + ASSERT_EQ(config.params, "{\"count\":1,\"key\":\"value\"}"); + const ComponentConfig &cfg = (*components)[1]; + ASSERT_EQ(cfg.lib, "libdistributedadapter.z.so"); +} + + +/** +* @tc.name: CheckerConfig +* @tc.desc: load the config.json checkers info. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(ConfigFactorySuite, CheckerConfig, TestSize.Level0) +{ + auto *checker = ConfigFactory::GetInstance().GetCheckerConfig(); + ASSERT_NE(checker, nullptr); + std::vector checkers{ "SystemChecker", "BundleChecker", "PackageChecker", "ExternalChecker" }; + ASSERT_EQ(checker->checkers, checkers); + ASSERT_EQ(checker->trusts[0].bundleName, "bundle_manager_service"); + ASSERT_EQ(checker->trusts[0].appId, "bundle_manager_service"); + ASSERT_EQ(checker->trusts[0].checker, "SystemChecker"); + ASSERT_EQ(checker->trusts[1].bundleName, "form_storage"); + ASSERT_EQ(checker->trusts[1].appId, "form_storage"); + ASSERT_EQ(checker->trusts[1].checker, "SystemChecker"); + ASSERT_EQ(checker->trusts[2].bundleName, "ivi_config_manager"); + ASSERT_EQ(checker->trusts[2].appId, "ivi_config_manager"); + ASSERT_EQ(checker->trusts[2].checker, "SystemChecker"); + ASSERT_EQ(checker->trusts[3].bundleName, "com.huawei.ohos.toteweather"); + ASSERT_EQ(checker->trusts[3].appId, "com.huawei.toteweather_adfasdflaskdfasdf"); + ASSERT_EQ(checker->trusts[3].checker, "BundleChecker"); + ASSERT_EQ(checker->trusts[4].bundleName, "com.huawei.ohos.toteweather"); + ASSERT_EQ(checker->trusts[4].packageName, "com.huawei.android.toteweather"); + ASSERT_EQ(checker->trusts[4].base64Key, "adfasdfasdfasdfasdfasdfasdf"); + ASSERT_EQ(checker->trusts[4].checker, "PackageChecker"); + ASSERT_EQ(checker->trusts[5].bundleName, "com.android.providers.calendar"); + ASSERT_EQ(checker->trusts[5].packageName, "com.android.providers.calendar"); + ASSERT_EQ(checker->trusts[5].base64Key, "adfasdfasdfasdfasdfasdfasdf"); + ASSERT_EQ(checker->trusts[5].checker, "PackageChecker"); +} + +/** +* @tc.name: NetworkConfig +* @tc.desc: load the config.json networks info. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(ConfigFactorySuite, NetworkConfig, TestSize.Level0) +{ + auto *networks = ConfigFactory::GetInstance().GetNetworkConfig(); + ASSERT_NE(networks, nullptr); + std::vector chains{ "loadBalance", "authentication", "traffic-control", "router", "transport", + "fault-inject" }; + ASSERT_EQ(networks->chains, chains); + std::vector routers{ "DPRouter", "HOS3.0Router", "OHOSRouter" }; + ASSERT_EQ(networks->routers, routers); + std::vector transports{ "hicom", "wareengine", "SoftBus" }; + ASSERT_EQ(networks->transports, transports); + ASSERT_EQ(networks->protocols[0].name, "SoftBus DP"); + ASSERT_EQ(networks->protocols[0].address, "com.huawei.deviceprofile"); + ASSERT_EQ(networks->protocols[0].transport, "SoftBus"); + ASSERT_EQ(networks->protocols[1].name, "SoftBus Huawei"); + ASSERT_EQ(networks->protocols[1].address, "com.huawei.hwddmp"); + ASSERT_EQ(networks->protocols[1].transport, "SoftBus"); + ASSERT_EQ(networks->protocols[2].name, "SoftBus OHOS"); + ASSERT_EQ(networks->protocols[2].address, "ohos.distributeddata"); + ASSERT_EQ(networks->protocols[2].transport, "SoftBus"); +} \ No newline at end of file diff --git a/services/distributeddataservice/service/test/directory_manager_test.cpp b/services/distributeddataservice/service/test/directory_manager_test.cpp new file mode 100644 index 000000000..1d2ad8d9d --- /dev/null +++ b/services/distributeddataservice/service/test/directory_manager_test.cpp @@ -0,0 +1,96 @@ +/* + * 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 "directory_manager.h" + +#include +#include +#include +#include +#include +#include "types.h" + +using namespace testing::ext; +using namespace OHOS::DistributedData; +using namespace OHOS::DistributedKv; +using namespace OHOS; + +class DirectoryManagerTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() { } + void TearDown() { } +}; + +/** +* @tc.name: GetStoragePath01 +* @tc.desc: test get db dir +* @tc.type: FUNC +* @tc.require: +* @tc.author: baoyayong +*/ +HWTEST_F(DirectoryManagerTest, GetStoragePath01, TestSize.Level0) +{ + StoreMetaData metaData; + metaData.userId = "10"; + metaData.bundleName = "com.sample.helloworld"; + metaData.dataDir = "/data/app/el1/10/com.sample.helloworld"; + metaData.securityLevel = SecurityLevel::S2; + auto path = DirectoryManager::GetInstance().GetStorePath(metaData); + EXPECT_EQ(path, metaData.dataDir); + + metaData.securityLevel = SecurityLevel::S0; + path = DirectoryManager::GetInstance().GetStorePath(metaData); + EXPECT_EQ(path, "/data/misc_de/0/mdds/10/default/com.sample.helloworld/"); +} + +/** +* @tc.name: GetStorageBackupPath01 +* @tc.desc: test get db backup dir +* @tc.type: FUNC +* @tc.require: +* @tc.author: baoyayong +*/ +HWTEST_F(DirectoryManagerTest, GetStorageBackupPath01, TestSize.Level0) +{ + StoreMetaData metaData; + metaData.userId = "10"; + metaData.bundleName = "com.sample.helloworld"; + metaData.dataDir = "/data/app/el1/10/com.sample.helloworld"; + metaData.securityLevel = SecurityLevel::S2; + auto path = DirectoryManager::GetInstance().GetStoreBackupPath(metaData); + EXPECT_EQ(path, metaData.dataDir + "/backup/"); + + metaData.securityLevel = SecurityLevel::S0; + path = DirectoryManager::GetInstance().GetStoreBackupPath(metaData); + EXPECT_EQ(path, "/data/misc_de/0/mdds/10/default/com.sample.helloworld/backup/"); +} + +/** +* @tc.name: GetStorageMetaPath01 +* @tc.desc: test get db meta dir +* @tc.type: FUNC +* @tc.require: +* @tc.author: baoyayong +*/ +HWTEST_F(DirectoryManagerTest, GetStorageMetaPath01, TestSize.Level0) +{ + auto path = DirectoryManager::GetInstance().GetMetaDataStorePath(); + EXPECT_EQ(path, "/data/service/el1/public/distributeddata/DistributedKvDataService/Meta/"); + + path = DirectoryManager::GetInstance().GetMetaDataStorePath(); + EXPECT_EQ(path, "/data/misc_de/0/mdds/Meta/"); +} -- Gitee From 612624aa24e3bf2c284e535097ec73de9af5943a Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Fri, 21 Jan 2022 21:03:57 +0800 Subject: [PATCH 2/5] add config files Signed-off-by: Sven Wang --- bundle.json | 3 +- conf/BUILD.gn | 27 ++++++++++++++ conf/config.json | 94 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 1 deletion(-) create mode 100644 conf/BUILD.gn create mode 100644 conf/config.json diff --git a/bundle.json b/bundle.json index b994fbd68..14d83f757 100644 --- a/bundle.json +++ b/bundle.json @@ -87,7 +87,8 @@ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/app:build_module", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:build_module", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:build_module", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:build_module" + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:build_module", + "//foundation/distributeddatamgr/distributeddatamgr/services/conf:build_module" ], "inner_kits": [ { diff --git a/conf/BUILD.gn b/conf/BUILD.gn new file mode 100644 index 000000000..984a97605 --- /dev/null +++ b/conf/BUILD.gn @@ -0,0 +1,27 @@ +# 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. +import("//build/ohos.gni") +import("//build/ohos_var.gni") + +#/system/etc/distributeddata/conf +group("build_module") { + deps = [ ":default_conf" ] +} +ohos_prebuilt_etc("default_conf") { + source = "config.json" + relative_install_dir = "distributeddata/conf" + subsystem_name = "distributeddatamgr" + part_name = "distributed_data_conf" +} + + diff --git a/conf/config.json b/conf/config.json new file mode 100644 index 000000000..eb441d10c --- /dev/null +++ b/conf/config.json @@ -0,0 +1,94 @@ +{ + "processLabel": "distributeddata", + "metaData": "service_meta", + "version": "000.000.001", + "features": ["kvdb", "rdb", "object", "backup", "data_sync"], + "components": [ + { + "description": "3rd party adapter", + "lib": "libconfigdemo.z.so", + "constructor": "", + "destructor": "", + "params": { + "key": "value", + "count": 1 + } + }, + { + "lib": "libconfigdemo2.z.so" + } + ], + "bundleChecker": { + "checkers": [ + "SystemChecker", + "BundleChecker", + "PackageChecker", + "ExternalChecker" + ], + "trusts": [ + { + "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" + } + ] + }, + "networks": { + "chains": [ + "loadBalance", + "authentication", + "traffic-control", + "router", + "transport", + "fault-inject" + ], + "routers": [ + "OHOSRouter" + ], + "transports": [ + "SoftBus" + ], + "protocols": [ + { + "name": "SoftBus OHOS", + "address": "ohos.distributeddata", + "transport": "SoftBus" + } + ] + }, + "directory": { + "workers": [ + "appWorker", + "serverWorker" + ], + "metaPath": "/data/service/el0/0/database/ddms/metadata/", + "strategy": [ + { + "version": "0", + "holder": "ddms", + "path": "/data/{security}/0/mdds/{userId}/{bundleName}", + "metaPath": "/data/misc_de/0/mdds/Meta" + }, + { + "version": "1", + "holder": "ddms", + "path": "/data/service/{security}/0/database/ddms/{userId}/{bundleName}" + }, + { + "version": "2", + "hodler": "caller", + "path": "/data/{type}/{security}/{userId}/{packageName}/database/{bundleName}" + } + ] + } +} \ No newline at end of file -- Gitee From 91d495198a7bdae4255890a0cdab13afe8424922 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Fri, 21 Jan 2022 22:58:23 +0800 Subject: [PATCH 3/5] fixed device kvstore not correct code Signed-off-by: Sven Wang --- .../app/src/device_kvstore_impl.cpp | 31 +++++----- .../app/src/device_kvstore_impl.h | 7 ++- .../app/src/device_kvstore_observer_impl.cpp | 45 +++++++-------- .../app/src/device_kvstore_observer_impl.h | 3 +- .../app/src/device_kvstore_resultset_impl.cpp | 22 ++----- .../app/src/device_kvstore_resultset_impl.h | 8 +-- .../app/src/kvstore_resultset_impl.cpp | 7 +-- .../app/src/kvstore_resultset_impl.h | 3 +- .../app/src/single_kvstore_impl.cpp | 57 +++++++------------ .../app/src/single_kvstore_impl.h | 10 +++- 10 files changed, 79 insertions(+), 114 deletions(-) diff --git a/services/distributeddataservice/app/src/device_kvstore_impl.cpp b/services/distributeddataservice/app/src/device_kvstore_impl.cpp index e1d576f3b..18440f667 100644 --- a/services/distributeddataservice/app/src/device_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/device_kvstore_impl.cpp @@ -16,9 +16,13 @@ #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 { @@ -107,12 +111,7 @@ void DeviceKvStoreImpl::GetResultSet(const Key &prefixKey, return; } Key decorateKey(tmpkey); - SingleKvStoreImpl::GetResultSet(decorateKey, callback, true); -} - -Status DeviceKvStoreImpl::SubscribeKvStore(const SubscribeType subscribeType, sptr observer) -{ - return SingleKvStoreImpl::SubscribeKvStore(subscribeType, observer, true); + SingleKvStoreImpl::GetResultSet(decorateKey, callback); } Status DeviceKvStoreImpl::PutBatch(const std::vector &entries) @@ -156,12 +155,6 @@ Status DeviceKvStoreImpl::GetEntriesWithQuery(const std::string &query, std::vec return ret; } -void DeviceKvStoreImpl::GetResultSetWithQuery(const std::string &query, - std::function)> callback) -{ - SingleKvStoreImpl::GetResultSetWithQuery(query, callback, true); -} - std::string DeviceKvStoreImpl::localDeviceId_; std::string DeviceKvStoreImpl::GetLocalDeviceId() { @@ -233,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 02e499263..e00b3b5e5 100755 --- a/services/distributeddataservice/app/src/device_kvstore_impl.h +++ b/services/distributeddataservice/app/src/device_kvstore_impl.h @@ -33,15 +33,16 @@ public: 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 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); diff --git a/services/distributeddataservice/app/src/device_kvstore_observer_impl.cpp b/services/distributeddataservice/app/src/device_kvstore_observer_impl.cpp index 72e5788ce..97934ea17 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 bd9b1fd22..0147caf1c 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 465f14e43..fac7e84b7 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 fc126a51c..06e62c168 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_resultset_impl.cpp b/services/distributeddataservice/app/src/kvstore_resultset_impl.cpp index 36e0bb459..6d474a404 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 b0880f932..c0b4d101e 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/single_kvstore_impl.cpp b/services/distributeddataservice/app/src/single_kvstore_impl.cpp index d2414ce9d..e0019380f 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.cpp +++ b/services/distributeddataservice/app/src/single_kvstore_impl.cpp @@ -24,7 +24,6 @@ #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" @@ -240,12 +239,6 @@ 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 (!flowCtrl_.IsTokenEnough()) { ZLOGE("flow control denied"); @@ -259,8 +252,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; @@ -296,6 +288,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 { @@ -501,8 +498,7 @@ 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 (!flowCtrl_.IsTokenEnough()) { @@ -532,11 +528,9 @@ 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) { @@ -566,21 +560,8 @@ void SingleKvStoreImpl::GetResultSet(const Key &prefixKey, } } -void SingleKvStoreImpl::GetResultSet(const Key &prefixKey, - std::function)> callback) -{ - GetResultSet(prefixKey, callback, false); -} - 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 (!flowCtrl_.IsTokenEnough()) { @@ -611,10 +592,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) { @@ -650,6 +630,12 @@ 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__)); @@ -723,16 +709,15 @@ Status SingleKvStoreImpl::CloseResultSet(sptr resultSet) } 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); @@ -1116,7 +1101,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; @@ -1267,7 +1252,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)); diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.h b/services/distributeddataservice/app/src/single_kvstore_impl.h index 68b4bbb17..bc4e85bae 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.h +++ b/services/distributeddataservice/app/src/single_kvstore_impl.h @@ -76,11 +76,15 @@ public: 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; @@ -144,7 +148,7 @@ private: std::mutex observerMapMutex_; std::map observerMap_; std::mutex storeResultSetMutex_; - std::map> storeResultSetMap_; + std::map> storeResultSetMap_; sptr syncCallback_; int openCount_; -- Gitee From 6ff163575ccc7bc3d3861f106bcaa39e158e1388 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Fri, 21 Jan 2022 23:55:01 +0800 Subject: [PATCH 4/5] fixed code style Signed-off-by: Sven Wang --- conf/config.json | 6 +-- .../app/src/kvstore_app_manager.cpp | 1 - .../app/src/kvstore_data_service.cpp | 2 - .../app/src/kvstore_user_manager.h | 2 - .../app/src/single_kvstore_impl.h | 4 -- .../include/checker/checker_manager.h | 4 +- .../include/metadata/secret_key_meta_data.h | 4 +- .../metadata/secret_key_meta_data.cpp | 4 ++ .../framework/test/checker_manager_test.cpp | 12 +++--- .../framework/test/event_center_test.cpp | 16 ++++---- .../framework/test/serializable_test.cpp | 8 ++-- .../service/bootstrap/include/bootstrap.h | 6 +-- .../service/config/include/config_factory.h | 2 +- .../config/include/model/checker_config.h | 5 +-- .../config/include/model/directory_config.h | 4 +- .../directory/include/directory_manager.h | 2 +- .../directory/include/kvstore_context.h | 2 +- .../directory/src/directory_manager.cpp | 10 ----- .../service/test/config_factory_test.cpp | 41 ++++++------------- 19 files changed, 48 insertions(+), 87 deletions(-) diff --git a/conf/config.json b/conf/config.json index eb441d10c..5a311cee7 100644 --- a/conf/config.json +++ b/conf/config.json @@ -56,13 +56,13 @@ "OHOSRouter" ], "transports": [ - "SoftBus" + "softbus" ], "protocols": [ { - "name": "SoftBus OHOS", + "name": "OHOS softbus", "address": "ohos.distributeddata", - "transport": "SoftBus" + "transport": "softbus" } ] }, diff --git a/services/distributeddataservice/app/src/kvstore_app_manager.cpp b/services/distributeddataservice/app/src/kvstore_app_manager.cpp index c6c490ac3..0c51894e8 100755 --- a/services/distributeddataservice/app/src/kvstore_app_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_manager.cpp @@ -446,7 +446,6 @@ DistributedDB::KvStoreDelegateManager *KvStoreAppManager::GetDelegateManager(Pat DirectoryUtils::ChangeModeFileOnly(directory, Constant::DEFAULT_MODE_FILE); trueAppId_ = CheckerManager::GetInstance().GetAppId(bundleName_, uid_); - // trueAppId_ = KvStoreUtils::GetAppIdByBundleName(bundleName_); if (trueAppId_.empty()) { delegateManagers_[type] = nullptr; ZLOGW("trueAppId_ empty(permission issues?)"); diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index a3a0f0eec..6cb4f432c 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -70,7 +70,6 @@ KvStoreDataService::KvStoreDataService(bool runOnCreate) clientDeathObserverMap_() { ZLOGI("begin."); - // Initialize(); } KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate) @@ -81,7 +80,6 @@ KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate clientDeathObserverMap_() { ZLOGI("begin"); - // Initialize(); } KvStoreDataService::~KvStoreDataService() diff --git a/services/distributeddataservice/app/src/kvstore_user_manager.h b/services/distributeddataservice/app/src/kvstore_user_manager.h index 96c0a9703..af22549e1 100755 --- a/services/distributeddataservice/app/src/kvstore_user_manager.h +++ b/services/distributeddataservice/app/src/kvstore_user_manager.h @@ -34,7 +34,6 @@ public: Status GetKvStore(const Options &options, const std::string &bundleName, const std::string &storeId, pid_t uid, const std::vector &cipherKey, sptr &kvStore) { - // ZLOGI("begin."); std::lock_guard lg(appMutex_); auto it = appMap_.find(bundleName); if (it == appMap_.end()) { @@ -45,7 +44,6 @@ public: } } if (it == appMap_.end()) { - // ZLOGE("emplace failed."); kvStore = nullptr; return Status::ERROR; } diff --git a/services/distributeddataservice/app/src/single_kvstore_impl.h b/services/distributeddataservice/app/src/single_kvstore_impl.h index bc4e85bae..2e2eaae5b 100755 --- a/services/distributeddataservice/app/src/single_kvstore_impl.h +++ b/services/distributeddataservice/app/src/single_kvstore_impl.h @@ -74,10 +74,6 @@ 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); - void GetResultSetWithQuery(const std::string &query, - std::function)> callback, bool deviceCoordinate); void OnDump(int fd) const; protected: diff --git a/services/distributeddataservice/framework/include/checker/checker_manager.h b/services/distributeddataservice/framework/include/checker/checker_manager.h index cd74df00e..6b8f9aa10 100644 --- a/services/distributeddataservice/framework/include/checker/checker_manager.h +++ b/services/distributeddataservice/framework/include/checker/checker_manager.h @@ -30,13 +30,13 @@ public: std::string checker; }; class Checker { - protected: - API_EXPORT ~Checker() = default; public: virtual void Initialize() = 0; virtual bool SetTrustInfo(const Trust &trust) = 0; virtual std::string GetAppId(pid_t uid, const std::string &bundleName) = 0; virtual bool IsValid(pid_t uid, const std::string &bundleName) = 0; + protected: + API_EXPORT ~Checker() = default; }; API_EXPORT static CheckerManager &GetInstance(); API_EXPORT void RegisterPlugin(const std::string &checker, std::function getter); diff --git a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h index f5104a811..2b93aa5fa 100644 --- a/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h @@ -22,9 +22,7 @@ struct SecretKeyMetaData final : public Serializable { std::vector time {}; std::vector sKey {}; int32_t kvStoreType = 0; - ~SecretKeyMetaData() { - sKey.assign(sKey.size(), 0); - } + ~SecretKeyMetaData(); bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; }; diff --git a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp index b534f9695..b844394a2 100644 --- a/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp +++ b/services/distributeddataservice/framework/metadata/secret_key_meta_data.cpp @@ -15,6 +15,10 @@ #include "metadata/secret_key_meta_data.h" namespace OHOS { namespace DistributedData { +SecretKeyMetaData::~SecretKeyMetaData() +{ + sKey.assign(sKey.size(), 0); +} bool SecretKeyMetaData::Marshal(json &node) const { SetValue(node[GET_NAME(time)], time); diff --git a/services/distributeddataservice/framework/test/checker_manager_test.cpp b/services/distributeddataservice/framework/test/checker_manager_test.cpp index 5b0b07ed5..0da2d35f5 100644 --- a/services/distributeddataservice/framework/test/checker_manager_test.cpp +++ b/services/distributeddataservice/framework/test/checker_manager_test.cpp @@ -17,7 +17,7 @@ #include using namespace testing::ext; using namespace OHOS::DistributedData; -class CheckerManagerSuite : public testing::Test { +class CheckerManagerTest : public testing::Test { public: static void SetUpTestCase(void) {} static void TearDownTestCase(void) {} @@ -31,7 +31,7 @@ public: * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(CheckerManagerSuite, Checkers, TestSize.Level0) +HWTEST_F(CheckerManagerTest, Checkers, TestSize.Level0) { auto *checker = CheckerManager::GetInstance().GetChecker("SystemChecker"); ASSERT_NE(checker, nullptr); @@ -48,7 +48,7 @@ HWTEST_F(CheckerManagerSuite, Checkers, TestSize.Level0) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(CheckerManagerSuite, SystemCheckerBMS, TestSize.Level0) +HWTEST_F(CheckerManagerTest, SystemCheckerBMS, TestSize.Level0) { ASSERT_EQ("bundle_manager_service", CheckerManager::GetInstance().GetAppId("bundle_manager_service", 1000)); ASSERT_TRUE(CheckerManager::GetInstance().IsValid("bundle_manager_service", 1000)); @@ -61,7 +61,7 @@ HWTEST_F(CheckerManagerSuite, SystemCheckerBMS, TestSize.Level0) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(CheckerManagerSuite, SystemCheckerForm, TestSize.Level0) +HWTEST_F(CheckerManagerTest, SystemCheckerForm, TestSize.Level0) { ASSERT_EQ("form_storage", CheckerManager::GetInstance().GetAppId("form_storage", 1000)); ASSERT_TRUE(CheckerManager::GetInstance().IsValid("form_storage", 1000)); @@ -74,7 +74,7 @@ HWTEST_F(CheckerManagerSuite, SystemCheckerForm, TestSize.Level0) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(CheckerManagerSuite, SystemCheckerIVI, TestSize.Level0) +HWTEST_F(CheckerManagerTest, SystemCheckerIVI, TestSize.Level0) { ASSERT_EQ("ivi_config_manager", CheckerManager::GetInstance().GetAppId("ivi_config_manager", 1000)); ASSERT_TRUE(CheckerManager::GetInstance().IsValid("ivi_config_manager", 1000)); @@ -87,7 +87,7 @@ HWTEST_F(CheckerManagerSuite, SystemCheckerIVI, TestSize.Level0) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(CheckerManagerSuite, BundleChecker, TestSize.Level0) +HWTEST_F(CheckerManagerTest, BundleChecker, TestSize.Level0) { ASSERT_EQ("com.huawei.ohos.toteweather", CheckerManager::GetInstance().GetAppId("com.huawei.ohos.toteweather", 100000)); ASSERT_TRUE(CheckerManager::GetInstance().IsValid("com.huawei.ohos.toteweather", 100000)); diff --git a/services/distributeddataservice/framework/test/event_center_test.cpp b/services/distributeddataservice/framework/test/event_center_test.cpp index d126b64d5..7c554e0d3 100644 --- a/services/distributeddataservice/framework/test/event_center_test.cpp +++ b/services/distributeddataservice/framework/test/event_center_test.cpp @@ -18,7 +18,7 @@ #include using namespace testing::ext; using namespace OHOS::DistributedData; -class EventCenterSuite : public testing::Test { +class EventCenterTest : public testing::Test { public: enum TestEventId : int32_t { TEST_EVT_UNKNOWN = Event::EVT_CUSTOM, @@ -44,21 +44,21 @@ public: { waitEvent_ = TEST_EVT_UNKNOWN; currEvent_ = TEST_EVT_UNKNOWN; - EventCenter::GetInstance().Subscribe(TEST_EVT_BEGIN, [this](const Event &evt){ + EventCenter::GetInstance().Subscribe(TEST_EVT_BEGIN, [this](const Event &evt) { ASSERT_EQ(waitEvent_, TEST_EVT_BEGIN); EventCenter::Defer defer; EventCenter::GetInstance().PostEvent(std::make_unique()); currEvent_ = TEST_EVT_BEGIN; waitEvent_ = TEST_EVT_MIDDLE; }); - EventCenter::GetInstance().Subscribe(TEST_EVT_MIDDLE, [this](const Event &evt){ + EventCenter::GetInstance().Subscribe(TEST_EVT_MIDDLE, [this](const Event &evt) { ASSERT_EQ(waitEvent_, TEST_EVT_MIDDLE); EventCenter::Defer defer; EventCenter::GetInstance().PostEvent(std::make_unique()); currEvent_ = TEST_EVT_MIDDLE; waitEvent_ = TEST_EVT_END; }); - EventCenter::GetInstance().Subscribe(TEST_EVT_END, [this](const Event &evt){ + EventCenter::GetInstance().Subscribe(TEST_EVT_END, [this](const Event &evt) { ASSERT_EQ(waitEvent_, TEST_EVT_END); currEvent_ = TEST_EVT_END; waitEvent_ = TEST_EVT_UNKNOWN; @@ -86,7 +86,7 @@ protected: * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(EventCenterSuite, TopLayerASyncEvent, TestSize.Level2) +HWTEST_F(EventCenterTest, TopLayerASyncEvent, TestSize.Level2) { ZLOGI("EventCenterSuite ASyncEvent begin."); auto test = [this]() { @@ -106,7 +106,7 @@ HWTEST_F(EventCenterSuite, TopLayerASyncEvent, TestSize.Level2) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(EventCenterSuite, SubLayerASyncEvent, TestSize.Level2) +HWTEST_F(EventCenterTest, SubLayerASyncEvent, TestSize.Level2) { ZLOGI("EventCenterSuite ASyncEvent begin."); EventCenter::Defer defer; @@ -123,7 +123,7 @@ HWTEST_F(EventCenterSuite, SubLayerASyncEvent, TestSize.Level2) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(EventCenterSuite, ASyncEventWithoutDefer, TestSize.Level2) +HWTEST_F(EventCenterTest, ASyncEventWithoutDefer, TestSize.Level2) { ZLOGI("EventCenterSuite ASyncEvent begin."); EventCenter::Defer defer; @@ -144,7 +144,7 @@ HWTEST_F(EventCenterSuite, ASyncEventWithoutDefer, TestSize.Level2) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(EventCenterSuite, ImmediatelyASyncEvent, TestSize.Level2) +HWTEST_F(EventCenterTest, ImmediatelyASyncEvent, TestSize.Level2) { ZLOGI("EventCenterSuite ASyncEvent begin."); waitEvent_ = TEST_EVT_BEGIN; diff --git a/services/distributeddataservice/framework/test/serializable_test.cpp b/services/distributeddataservice/framework/test/serializable_test.cpp index 1ee62aefc..21d06fd55 100644 --- a/services/distributeddataservice/framework/test/serializable_test.cpp +++ b/services/distributeddataservice/framework/test/serializable_test.cpp @@ -20,7 +20,7 @@ using namespace testing::ext; using namespace OHOS::DistributedData; -class SerializableSuite : public testing::Test { +class SerializableTest : public testing::Test { public: struct Normal : public Serializable { public: @@ -111,7 +111,7 @@ public: * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(SerializableSuite, GetNormalVal, TestSize.Level2) +HWTEST_F(SerializableTest, GetNormalVal, TestSize.Level2) { ZLOGI("SerializableSuite GetVal begin."); Normal normal; @@ -134,7 +134,7 @@ HWTEST_F(SerializableSuite, GetNormalVal, TestSize.Level2) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(SerializableSuite, DeleteSerializable, TestSize.Level2) +HWTEST_F(SerializableTest, DeleteSerializable, TestSize.Level2) { ZLOGI("SerializableSuite GetVal begin."); NormalEx *normalEx = new NormalEx(); @@ -148,7 +148,7 @@ HWTEST_F(SerializableSuite, DeleteSerializable, TestSize.Level2) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(SerializableSuite, GetMutilVal, TestSize.Level2) +HWTEST_F(SerializableTest, GetMutilVal, TestSize.Level2) { ZLOGI("SerializableSuite GetVal begin."); diff --git a/services/distributeddataservice/service/bootstrap/include/bootstrap.h b/services/distributeddataservice/service/bootstrap/include/bootstrap.h index b99b96f59..3d4d15dba 100644 --- a/services/distributeddataservice/service/bootstrap/include/bootstrap.h +++ b/services/distributeddataservice/service/bootstrap/include/bootstrap.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_DISTRIBUTEDDATASERVICE_BOOTSTRAP_BOOTSTRAP_H -#define OHOS_DISTRIBUTED_DATA_SERVICES_DISTRIBUTEDDATASERVICE_BOOTSTRAP_BOOTSTRAP_H +#ifndef OHOS_DISTRIBUTED_DATA_SERVICES_BOOTSTRAP_BOOTSTRAP_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_BOOTSTRAP_BOOTSTRAP_H #include "visibility.h" #include namespace OHOS { @@ -33,4 +33,4 @@ private: }; } } -#endif //OHOS_DISTRIBUTED_DATA_SERVICES_DISTRIBUTEDDATASERVICE_BOOTSTRAP_BOOTSTRAP_H +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_BOOTSTRAP_BOOTSTRAP_H diff --git a/services/distributeddataservice/service/config/include/config_factory.h b/services/distributeddataservice/service/config/include/config_factory.h index 681db11e2..deb6f8b5f 100644 --- a/services/distributeddataservice/service/config/include/config_factory.h +++ b/services/distributeddataservice/service/config/include/config_factory.h @@ -39,4 +39,4 @@ private: }; } } -#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_CONFIG_FAC 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7+ \ No newline at end of file +#endif // OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_CONFIG_FACTORY_H \ No newline at end of file diff --git a/services/distributeddataservice/service/config/include/model/checker_config.h b/services/distributeddataservice/service/config/include/model/checker_config.h index ec51177fa..883d2d102 100644 --- a/services/distributeddataservice/service/config/include/model/checker_config.h +++ b/services/distributeddataservice/service/config/include/model/checker_config.h @@ -21,10 +21,7 @@ namespace OHOS { namespace DistributedData { class CheckerConfig final : public Serializable { public: - class Trust final - : public Serializable - , public CheckerManager::Trust { - public: + struct Trust final : public Serializable, public CheckerManager::Trust { bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; }; diff --git a/services/distributeddataservice/service/config/include/model/directory_config.h b/services/distributeddataservice/service/config/include/model/directory_config.h index 789e3fb7b..2add4df2f 100644 --- a/services/distributeddataservice/service/config/include/model/directory_config.h +++ b/services/distributeddataservice/service/config/include/model/directory_config.h @@ -21,9 +21,7 @@ namespace OHOS { namespace DistributedData { class DirectoryConfig final : public Serializable { public: - struct DirectoryStrategy final - : public Serializable - , public DirectoryManager::Strategy { + struct DirectoryStrategy final : public Serializable, public DirectoryManager::Strategy { bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; }; diff --git a/services/distributeddataservice/service/directory/include/directory_manager.h b/services/distributeddataservice/service/directory/include/directory_manager.h index a40214c67..eb700b63c 100644 --- a/services/distributeddataservice/service/directory/include/directory_manager.h +++ b/services/distributeddataservice/service/directory/include/directory_manager.h @@ -93,4 +93,4 @@ private: }; } // namespace OHOS::DistributedKv -#endif //SDB_DIRECTORY_MANAGER_H +#endif // SDB_DIRECTORY_MANAGER_H diff --git a/services/distributeddataservice/service/directory/include/kvstore_context.h b/services/distributeddataservice/service/directory/include/kvstore_context.h index b50dbdb27..8bdbdd5dc 100644 --- a/services/distributeddataservice/service/directory/include/kvstore_context.h +++ b/services/distributeddataservice/service/directory/include/kvstore_context.h @@ -27,4 +27,4 @@ struct ClientContext { }; } -#endif //SDB_KVSTORE_CONTEXT_H \ No newline at end of file +#endif // SDB_KVSTORE_CONTEXT_H \ No newline at end of file diff --git a/services/distributeddataservice/service/directory/src/directory_manager.cpp b/services/distributeddataservice/service/directory/src/directory_manager.cpp index dc7c713fd..e7a109490 100644 --- a/services/distributeddataservice/service/directory/src/directory_manager.cpp +++ b/services/distributeddataservice/service/directory/src/directory_manager.cpp @@ -118,16 +118,6 @@ DirectoryManager &DirectoryManager::GetInstance() std::string DirectoryManager::GetStorePath(const StoreMetaData &metaData) { // todo implement; -// switch (metaData.version) { -// case 0: -// return std::string("/data/service/el") + std::to_string(metaData.securityLevel) + "/0/database/ddms/" -// + metaData.deviceAccountId + "/" + metaData.bundleName; -// case 1: -// // "/data/{type}/{security}/{userId}/{packageName}/database/{bundleName}"; -// return std::string("/data/") + (metaData.uid < 10000 ? "app" : "service") + "/el" -// + std::to_string(metaData.securityLevel) + metaData.deviceAccountId -// + (metaData.uid < 10000 ? "" : "/{packageName}") + "/database/" + metaData.bundleName; -// } return {}; } diff --git a/services/distributeddataservice/service/test/config_factory_test.cpp b/services/distributeddataservice/service/test/config_factory_test.cpp index ba468996f..fe725bccf 100644 --- a/services/distributeddataservice/service/test/config_factory_test.cpp +++ b/services/distributeddataservice/service/test/config_factory_test.cpp @@ -16,7 +16,7 @@ #include using namespace testing::ext; using namespace OHOS::DistributedData; -class ConfigFactorySuite : public testing::Test { +class ConfigFactoryTest : public testing::Test { public: static void SetUpTestCase(void) { int32_t result = ConfigFactory::GetInstance().Initialize(); @@ -38,7 +38,7 @@ public: * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(ConfigFactorySuite, GlobalConfig, TestSize.Level0) +HWTEST_F(ConfigFactoryTest, GlobalConfig, TestSize.Level0) { auto *global = ConfigFactory::GetInstance().GetGlobalConfig(); ASSERT_NE(global, nullptr); @@ -56,19 +56,19 @@ HWTEST_F(ConfigFactorySuite, GlobalConfig, TestSize.Level0) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(ConfigFactorySuite, ComponentConfig, TestSize.Level0) +HWTEST_F(ConfigFactoryTest, ComponentConfig, TestSize.Level0) { auto *components = ConfigFactory::GetInstance().GetComponentConfig(); ASSERT_NE(components, nullptr); ASSERT_EQ(components->size(), 2); const ComponentConfig &config = (*components)[0]; ASSERT_EQ(config.description, "3rd party adapter"); - ASSERT_EQ(config.lib, "libdistributedadapter.z.so"); + ASSERT_EQ(config.lib, "libconfigdemo.z.so"); ASSERT_EQ(config.constructor, ""); ASSERT_EQ(config.destructor, ""); ASSERT_EQ(config.params, "{\"count\":1,\"key\":\"value\"}"); const ComponentConfig &cfg = (*components)[1]; - ASSERT_EQ(cfg.lib, "libdistributedadapter.z.so"); + ASSERT_EQ(cfg.lib, "libconfigdemo2.z.so"); } @@ -79,7 +79,7 @@ HWTEST_F(ConfigFactorySuite, ComponentConfig, TestSize.Level0) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(ConfigFactorySuite, CheckerConfig, TestSize.Level0) +HWTEST_F(ConfigFactoryTest, CheckerConfig, TestSize.Level0) { auto *checker = ConfigFactory::GetInstance().GetCheckerConfig(); ASSERT_NE(checker, nullptr); @@ -94,17 +94,6 @@ HWTEST_F(ConfigFactorySuite, CheckerConfig, TestSize.Level0) ASSERT_EQ(checker->trusts[2].bundleName, "ivi_config_manager"); ASSERT_EQ(checker->trusts[2].appId, "ivi_config_manager"); ASSERT_EQ(checker->trusts[2].checker, "SystemChecker"); - ASSERT_EQ(checker->trusts[3].bundleName, "com.huawei.ohos.toteweather"); - ASSERT_EQ(checker->trusts[3].appId, "com.huawei.toteweather_adfasdflaskdfasdf"); - ASSERT_EQ(checker->trusts[3].checker, "BundleChecker"); - ASSERT_EQ(checker->trusts[4].bundleName, "com.huawei.ohos.toteweather"); - ASSERT_EQ(checker->trusts[4].packageName, "com.huawei.android.toteweather"); - ASSERT_EQ(checker->trusts[4].base64Key, "adfasdfasdfasdfasdfasdfasdf"); - ASSERT_EQ(checker->trusts[4].checker, "PackageChecker"); - ASSERT_EQ(checker->trusts[5].bundleName, "com.android.providers.calendar"); - ASSERT_EQ(checker->trusts[5].packageName, "com.android.providers.calendar"); - ASSERT_EQ(checker->trusts[5].base64Key, "adfasdfasdfasdfasdfasdfasdf"); - ASSERT_EQ(checker->trusts[5].checker, "PackageChecker"); } /** @@ -114,24 +103,18 @@ HWTEST_F(ConfigFactorySuite, CheckerConfig, TestSize.Level0) * @tc.require: * @tc.author: Sven Wang */ -HWTEST_F(ConfigFactorySuite, NetworkConfig, TestSize.Level0) +HWTEST_F(ConfigFactoryTest, NetworkConfig, TestSize.Level0) { auto *networks = ConfigFactory::GetInstance().GetNetworkConfig(); ASSERT_NE(networks, nullptr); std::vector chains{ "loadBalance", "authentication", "traffic-control", "router", "transport", "fault-inject" }; ASSERT_EQ(networks->chains, chains); - std::vector routers{ "DPRouter", "HOS3.0Router", "OHOSRouter" }; + std::vector routers{ "OHOSRouter" }; ASSERT_EQ(networks->routers, routers); - std::vector transports{ "hicom", "wareengine", "SoftBus" }; + std::vector transports{ "softbus" }; ASSERT_EQ(networks->transports, transports); - ASSERT_EQ(networks->protocols[0].name, "SoftBus DP"); - ASSERT_EQ(networks->protocols[0].address, "com.huawei.deviceprofile"); - ASSERT_EQ(networks->protocols[0].transport, "SoftBus"); - ASSERT_EQ(networks->protocols[1].name, "SoftBus Huawei"); - ASSERT_EQ(networks->protocols[1].address, "com.huawei.hwddmp"); - ASSERT_EQ(networks->protocols[1].transport, "SoftBus"); - ASSERT_EQ(networks->protocols[2].name, "SoftBus OHOS"); - ASSERT_EQ(networks->protocols[2].address, "ohos.distributeddata"); - ASSERT_EQ(networks->protocols[2].transport, "SoftBus"); + ASSERT_EQ(networks->protocols[0].name, "OHOS softbus"); + ASSERT_EQ(networks->protocols[0].address, "ohos.distributeddata"); + ASSERT_EQ(networks->protocols[0].transport, "softbus"); } \ No newline at end of file -- Gitee From 6f91841de7315acf3ddabc8d7f5cfd96d5e7ddc7 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Sun, 23 Jan 2022 15:41:55 +0800 Subject: [PATCH 5/5] fixed build gn Signed-off-by: Sven Wang --- bundle.json | 2 +- conf/BUILD.gn | 2 - .../distributeddatafwk/src/itypes_util.cpp | 6 +- .../distributeddata/include/js_util.h | 10 ++- .../distributeddata/include/napi_queue.h | 2 - .../distributeddata/src/entry_point.cpp | 1 - interfaces/innerkits/distributeddata/BUILD.gn | 2 +- .../adapter/include/log/log_print.h | 31 ++++--- .../adapter/security/src/security.cpp | 3 +- services/distributeddataservice/app/BUILD.gn | 10 +++ .../app/src/kvstore_app_manager.cpp | 4 +- .../app/src/kvstore_data_service.cpp | 33 +++---- .../app/src/rdb/rdb_device_store.cpp | 8 +- .../app/src/rdb/rdb_device_store.h | 4 +- .../app/src/rdb/rdb_service.cpp | 83 ++++++++---------- .../app/src/rdb/rdb_service.h | 18 ++-- .../app/src/rdb/rdb_store.cpp | 16 ++-- .../app/src/rdb/rdb_store.h | 2 +- .../app/src/rdb/rdb_store_factory.cpp | 4 +- .../app/src/rdb/rdb_store_factory.h | 4 +- .../distributeddataservice/app/test/BUILD.gn | 4 +- .../distributeddataservice/framework/BUILD.gn | 20 +++-- .../framework/checker/checker_manager.cpp | 4 +- .../checker/default/bundle_checker.cpp | 2 +- .../include/serializable/serializable.h | 5 +- .../framework/include/utils/constant.h | 1 - .../framework/test/event_center_test.cpp | 1 + .../distributeddataservice/service/BUILD.gn | 14 +-- .../config/include/model/global_config.h | 2 +- .../config/include/model/network_config.h | 4 +- .../config/include/model/protocol_config.h | 4 +- .../service/directory/CMakeLists.txt | 86 ------------------- .../directory/include/directory_manager.h | 2 - .../directory/include/kvstore_context.h | 1 - .../directory/src/directory_manager.cpp | 2 +- 35 files changed, 152 insertions(+), 245 deletions(-) delete mode 100644 services/distributeddataservice/service/directory/CMakeLists.txt diff --git a/bundle.json b/bundle.json index 14d83f757..3a7ca7ec2 100644 --- a/bundle.json +++ b/bundle.json @@ -88,7 +88,7 @@ "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/libs/distributeddb:build_module", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:build_module", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/service:build_module", - "//foundation/distributeddatamgr/distributeddatamgr/services/conf:build_module" + "//foundation/distributeddatamgr/distributeddatamgr/conf:build_module" ], "inner_kits": [ { diff --git a/conf/BUILD.gn b/conf/BUILD.gn index 984a97605..f4f705214 100644 --- a/conf/BUILD.gn +++ b/conf/BUILD.gn @@ -23,5 +23,3 @@ ohos_prebuilt_etc("default_conf") { subsystem_name = "distributeddatamgr" part_name = "distributed_data_conf" } - - diff --git a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp index 200e2d3c7..7d4c53a0b 100644 --- a/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp +++ b/frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp @@ -12,10 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#define LOG_TAG "ITypesUtil" + #include "itypes_util.h" -#include -#include #include +#include "constant.h" +#include "log_print.h" namespace OHOS { namespace DistributedKv { diff --git a/frameworks/jskitsimpl/distributeddata/include/js_util.h b/frameworks/jskitsimpl/distributeddata/include/js_util.h index a601b3541..10a25b9aa 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 c402a9124..afb65f967 100644 --- a/frameworks/jskitsimpl/distributeddata/include/napi_queue.h +++ b/frameworks/jskitsimpl/distributeddata/include/napi_queue.h @@ -24,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/src/entry_point.cpp b/frameworks/jskitsimpl/distributeddata/src/entry_point.cpp index 972653176..d3f105d41 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/interfaces/innerkits/distributeddata/BUILD.gn b/interfaces/innerkits/distributeddata/BUILD.gn index e41c87bf5..aa988f49f 100755 --- a/interfaces/innerkits/distributeddata/BUILD.gn +++ b/interfaces/innerkits/distributeddata/BUILD.gn @@ -59,6 +59,7 @@ ohos_shared_library("distributeddata_inner") { "../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_single.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_sync_callback.cpp", + "../../../frameworks/innerkitsimpl/distributeddatafwk/src/itypes_util.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_client_death_observer.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_death_recipient_impl.cpp", @@ -68,7 +69,6 @@ ohos_shared_library("distributeddata_inner") { "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_snapshot_client.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_sync_callback_client.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/single_kvstore_client.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/itypes_utils.cpp", "include/types.h", ] diff --git a/services/distributeddataservice/adapter/include/log/log_print.h b/services/distributeddataservice/adapter/include/log/log_print.h index ee71fd78a..efac6ada2 100755 --- a/services/distributeddataservice/adapter/include/log/log_print.h +++ b/services/distributeddataservice/adapter/include/log/log_print.h @@ -16,38 +16,43 @@ #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" }; - +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001620, "ZDDC" }; +} } // end namespace AppDistributesdKv +namespace DistributedData { +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001630, "ZDD" }; +} +} // end namespace DistributedData } // 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/security/src/security.cpp b/services/distributeddataservice/adapter/security/src/security.cpp index 0c7b9bebf..dd8ddf5ce 100755 --- a/services/distributeddataservice/adapter/security/src/security.cpp +++ b/services/distributeddataservice/adapter/security/src/security.cpp @@ -83,7 +83,8 @@ DBStatus Security::RegOnAccessControlledEvent(const OnAccessControlledEvent &cal return OK; }; // retry after 10 second, 10 * 1000 * 1000 mains 1 second - for (BlockInteger retry(10 * 1000 * 1000); retry < RETRY_MAX_TIMES && !result; ++retry) { + BlockInteger retry(10 * 1000 * 1000); + for (; retry < RETRY_MAX_TIMES && !result; ++retry) { result = SubscribeUserStatus(observer); } diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn index 845a86314..480e80d74 100755 --- a/services/distributeddataservice/app/BUILD.gn +++ b/services/distributeddataservice/app/BUILD.gn @@ -40,6 +40,14 @@ config("module_private_config") { "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include/rdb", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/service/bootstrap/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/service/config/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/service/directory/include", + "//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/system/safwk/native/include", "../adapter/include/account", "../adapter/include/permission", @@ -106,7 +114,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/kvstore_app_manager.cpp b/services/distributeddataservice/app/src/kvstore_app_manager.cpp index 0c51894e8..a916de0fa 100755 --- a/services/distributeddataservice/app/src/kvstore_app_manager.cpp +++ b/services/distributeddataservice/app/src/kvstore_app_manager.cpp @@ -113,7 +113,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & auto it = stores_[type].find(storeId); if (it != stores_[type].end()) { kvStore = it->second; - ZLOGI("find store in map refcount: %d.", kvStoreImpl->GetSptrRefCount()); + ZLOGI("find store in map refcount: %d.", kvStore->GetSptrRefCount()); kvStore->IncreaseOpenCount(); return Status::SUCCESS; } @@ -183,7 +183,7 @@ Status KvStoreAppManager::GetKvStore(const Options &options, const std::string & auto it = singleStores_[type].find(storeId); if (it != singleStores_[type].end()) { kvStore = it->second; - ZLOGI("find store in map refcount: %d.", singleKvStoreImpl->GetSptrRefCount()); + ZLOGI("find store in map refcount: %d.", kvStore->GetSptrRefCount()); kvStore->IncreaseOpenCount(); return Status::SUCCESS; } diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp index 6cb4f432c..0f6a9b49e 100644 --- a/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -17,12 +17,9 @@ #include "kvstore_data_service.h" #include -#include #include -#include #include #include -#include #include #include #include "auto_launch_export.h" @@ -33,7 +30,6 @@ #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" @@ -201,8 +197,8 @@ Status KvStoreDataService::GetKvStore(const Options &options, const AppId &appId KvStoreMetaManager::GetInstance().ReKey(param.userId, param.bundleName, param.storeId, store); } - ZLOGD("get kvstore return status:%d, deviceAccountId:[%s], bundleName:[%s].", - statusTmp, KvStoreUtils::ToBeAnonymous(deviceAccountId).c_str(), bundleName.c_str()); + ZLOGD("get kvstore return status:%d, userId:[%s], bundleName:[%s].", + statusTmp, KvStoreUtils::ToBeAnonymous(param.userId).c_str(), appId.appId.c_str()); if (statusTmp == Status::SUCCESS) { return UpdateMetaData(options, param, keyPara.metaKey, it->second); } @@ -730,14 +726,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; } } @@ -1065,16 +1061,11 @@ void KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient:: 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."); + if (!appId.IsValid() || !storeId.IsValid()) { + ZLOGE("invalid bundleName 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) { @@ -1085,20 +1076,20 @@ Status KvStoreDataService::DeleteKvStore(const AppId &appId, const StoreId &stor Status status; auto it = deviceAccountMap_.find(deviceAccountId); if (it != deviceAccountMap_.end()) { - status = (it->second).DeleteKvStore(trueAppId, storeIdTmp); + status = (it->second).DeleteKvStore(trueAppId, storeId.storeId); } else { KvStoreUserManager kvStoreUserManager(deviceAccountId); - status = kvStoreUserManager.DeleteKvStore(trueAppId, storeIdTmp); + status = kvStoreUserManager.DeleteKvStore(trueAppId, storeId.storeId); } if (status == Status::SUCCESS) { - auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", bundleName, storeIdTmp); + auto metaKey = KvStoreMetaManager::GetMetaKey(deviceAccountId, "default", appId.appId, 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(deviceAccountId, appId.appId, storeId.storeId); + KvStoreMetaManager::GetInstance().DeleteStrategyMeta(appId.appId, storeId.storeId); } return status; } diff --git a/services/distributeddataservice/app/src/rdb/rdb_device_store.cpp b/services/distributeddataservice/app/src/rdb/rdb_device_store.cpp index 7c86ff61f..953527dce 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_device_store.cpp +++ b/services/distributeddataservice/app/src/rdb/rdb_device_store.cpp @@ -28,14 +28,14 @@ void RdbDeviceStore::Initialize() RdbStoreFactory::RegisterCreator(RDB_DEVICE_COLLABORATION, creator); } -RdbStore* RdbDeviceStore::CreateStore(const RdbStoreParam ¶m) +RdbStore* RdbDeviceStore::CreateStore(const RdbStoreParam ¶m, pid_t uid) { ZLOGI("create device collaboration store"); - return new(std::nothrow) RdbDeviceStore(param); + return new(std::nothrow) RdbDeviceStore(param, uid); } -RdbDeviceStore::RdbDeviceStore(const RdbStoreParam ¶m) - : RdbStore(param), manager_(nullptr), delegate_(nullptr) +RdbDeviceStore::RdbDeviceStore(const RdbStoreParam ¶m, pid_t uid) + : RdbStore(param, uid), manager_(nullptr), delegate_(nullptr) { ZLOGI("construct %{public}s", param.storeName_.c_str()); } diff --git a/services/distributeddataservice/app/src/rdb/rdb_device_store.h b/services/distributeddataservice/app/src/rdb/rdb_device_store.h index c924d81d7..3b812e015 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_device_store.h +++ b/services/distributeddataservice/app/src/rdb/rdb_device_store.h @@ -27,12 +27,12 @@ class RelationalStoreDelegate; namespace OHOS::DistributedKv { class RdbDeviceStore : public RdbStore { public: - explicit RdbDeviceStore(const RdbStoreParam& param); + explicit RdbDeviceStore(const RdbStoreParam& param, pid_t uid); ~RdbDeviceStore() override; static void Initialize(); - static RdbStore* CreateStore(const RdbStoreParam& param); + static RdbStore* CreateStore(const RdbStoreParam& param, pid_t uid); /* IPC interface */ int SetDistributedTables(const std::vector& tables) override; diff --git a/services/distributeddataservice/app/src/rdb/rdb_service.cpp b/services/distributeddataservice/app/src/rdb/rdb_service.cpp index cc7b4686b..05431c273 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_service.cpp +++ b/services/distributeddataservice/app/src/rdb/rdb_service.cpp @@ -16,25 +16,20 @@ #define LOG_TAG "RdbService" #include "rdb_service.h" -#include "kvstore_utils.h" +#include "checker/checker_manager.h" #include "log_print.h" #include "rdb_store.h" #include "rdb_store_factory.h" - +#include namespace OHOS::DistributedKv { -static bool operator==(const sptr& store, const std::string& appId) -{ - auto* storePtr = (RdbStore*)store.GetRefPtr(); - return storePtr != nullptr && (storePtr->GetAppId() == appId); -} - +using namespace OHOS::DistributedData; void RdbService::Initialzie() { RdbStoreFactory::Initialize(); } -RdbService::ClientDeathRecipient::ClientDeathRecipient(DeathCallback& callback) - : callback_(callback) +RdbService::ClientDeathRecipient::ClientDeathRecipient(std::function&)> callback) + : callback_(std::move(callback)) { ZLOGI("construct"); } @@ -52,74 +47,67 @@ void RdbService::ClientDeathRecipient::OnRemoteDied(const wptr& o } } -void RdbService::ClearClientRecipient(const std::string& bundleName, sptr& proxy) +void RdbService::ClearClientRecipient(sptr& proxy) { std::lock_guard lock(recipientsLock_); - ZLOGI("remove %{public}s", bundleName.c_str()); recipients_.erase(proxy); } -void RdbService::ClearClientStores(const std::string& bundleName) +void RdbService::ClearClientStores(pid_t pid) { ZLOGI("enter"); - auto appId = KvStoreUtils::GetAppIdByBundleName(bundleName); std::lock_guard lock(storesLock_); - for (auto it = stores_.begin(); it != stores_.end();) { - if (it->second == appId) { - ZLOGI("remove %{public}s", it->first.c_str()); - stores_.erase(it++); - } else { - it++; - } + auto it = stores_.find(pid); + if (it == stores_.end()) { + return; } + for (auto storeIt = it->second.begin(); storeIt != it->second.end();) { + stores_.erase(it++); + } + stores_.erase(pid); } -void RdbService::OnClientDied(const std::string &bundleName, sptr& proxy) -{ - ZLOGI("%{public}s died", bundleName.c_str()); - ClearClientRecipient(bundleName, proxy); - ClearClientStores(bundleName); -} - -bool RdbService::CheckAccess(const RdbStoreParam& param) const +void RdbService::OnClientDied(pid_t pid, sptr& proxy) { - return !KvStoreUtils::GetAppIdByBundleName(param.bundleName_).empty(); + ClearClientRecipient(proxy); + ClearClientStores(pid); } -sptr RdbService::CreateStore(const RdbStoreParam& param) +sptr RdbService::CreateStore(const RdbStoreParam& param, pid_t uid, pid_t pid) { - sptr store = RdbStoreFactory::CreateStore(param); + sptr store = nullptr; + std::lock_guard lock(storesLock_); + auto &stores = stores_[pid]; + auto it = stores.find(param.storeName_); + if (it != stores.end()) { + return it->second; + } + store = RdbStoreFactory::CreateStore(param, uid); if (store == nullptr) { ZLOGE("create temp store failed"); return nullptr; } - std::lock_guard lock(storesLock_); - for (const auto& entry : stores_) { - if (*store == *entry.second) { - ZLOGI("find %{public}s", store->GetStoreId().c_str()); - return entry.second; - } - } - ZLOGI("create new store %{public}s", param.storeName_.c_str()); if (store->Init() != 0) { ZLOGE("store init failed"); return nullptr; } - stores_.insert({store->GetIdentifier(), store}); + stores.insert({param.storeName_, store}); return store; } sptr RdbService::GetRdbStore(const RdbStoreParam& 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 CreateStore(param); + return CreateStore(param, uid, pid); } int RdbService::RegisterClientDeathRecipient(const std::string& bundleName, sptr proxy) @@ -130,10 +118,11 @@ int RdbService::RegisterClientDeathRecipient(const std::string& bundleName, sptr } std::lock_guard lock(recipientsLock_); - 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( + [pid, this](sptr& object) { + OnClientDied(pid, object); + }); if (recipient == nullptr) { ZLOGE("malloc failed"); return -1; diff --git a/services/distributeddataservice/app/src/rdb/rdb_service.h b/services/distributeddataservice/app/src/rdb/rdb_service.h index 40b132644..bfab7e15c 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_service.h +++ b/services/distributeddataservice/app/src/rdb/rdb_service.h @@ -30,31 +30,27 @@ 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); static void Initialzie(); private: - bool CheckAccess(const RdbStoreParam& param) const; + sptr CreateStore(const RdbStoreParam& param, pid_t uid, pid_t pid); - sptr CreateStore(const RdbStoreParam& param); + void ClearClientRecipient(sptr& proxy); - void ClearClientRecipient(const std::string& bundleName, sptr& proxy); - - void ClearClientStores(const std::string& bundleName); + void ClearClientStores(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_; }; - std::mutex storesLock_; - std::map> stores_; // identifier + std::map>> stores_; // identifier std::mutex recipientsLock_; std::map, sptr> recipients_; }; diff --git a/services/distributeddataservice/app/src/rdb/rdb_store.cpp b/services/distributeddataservice/app/src/rdb/rdb_store.cpp index a93631886..1769fc8b4 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_store.cpp +++ b/services/distributeddataservice/app/src/rdb/rdb_store.cpp @@ -16,23 +16,19 @@ #define LOG_TAG "RdbStore" #include "rdb_store.h" -#include "kvstore_utils.h" +#include "account_delegate.h" +#include "checker/checker_manager.h" #include "log_print.h" - namespace OHOS::DistributedKv { -static std::string GetCurrentUserId() -{ - return "0"; -} - -RdbStore::RdbStore(const RdbStoreParam ¶m) +using namespace OHOS::DistributedData; +RdbStore::RdbStore(const RdbStoreParam ¶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_ = 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/distributeddataservice/app/src/rdb/rdb_store.h b/services/distributeddataservice/app/src/rdb/rdb_store.h index 1fdad04ca..6e0ecb8f5 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_store.h +++ b/services/distributeddataservice/app/src/rdb/rdb_store.h @@ -22,7 +22,7 @@ namespace OHOS::DistributedKv { class RdbStore : public RdbStoreStub { public: - explicit RdbStore(const RdbStoreParam& param); + explicit RdbStore(const RdbStoreParam& param, pid_t uid); RdbStore() = delete; RdbStore(const RdbStore&) = delete; diff --git a/services/distributeddataservice/app/src/rdb/rdb_store_factory.cpp b/services/distributeddataservice/app/src/rdb/rdb_store_factory.cpp index 0fd19ea88..f88b6cc45 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_store_factory.cpp +++ b/services/distributeddataservice/app/src/rdb/rdb_store_factory.cpp @@ -42,7 +42,7 @@ int RdbStoreFactory::RegisterCreator(int type, Creator &creator) return 0; } -RdbStore* RdbStoreFactory::CreateStore(const RdbStoreParam& param) +RdbStore* RdbStoreFactory::CreateStore(const RdbStoreParam& param, pid_t uid) { int type = param.type_; if (type < 0 || type >= RDB_DISTRIBUTED_TYPE_MAX) { @@ -50,7 +50,7 @@ RdbStore* RdbStoreFactory::CreateStore(const RdbStoreParam& param) return nullptr; } - return (creators_[type])(param); + return (creators_[type])(param, uid); } } diff --git a/services/distributeddataservice/app/src/rdb/rdb_store_factory.h b/services/distributeddataservice/app/src/rdb/rdb_store_factory.h index 5e7afbf99..eea4b9575 100644 --- a/services/distributeddataservice/app/src/rdb/rdb_store_factory.h +++ b/services/distributeddataservice/app/src/rdb/rdb_store_factory.h @@ -22,13 +22,13 @@ namespace OHOS::DistributedKv { class RdbStoreFactory { public: - using Creator = std::function; + using Creator = std::function; static void Initialize(); static int RegisterCreator(int type, Creator& creator); - static RdbStore* CreateStore(const RdbStoreParam& param); + static RdbStore* CreateStore(const RdbStoreParam& param, pid_t uid); private: static Creator creators_[RDB_DISTRIBUTED_TYPE_MAX]; diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index d045f50f5..5c25fac7b 100755 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -220,6 +220,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", @@ -230,8 +232,6 @@ ohos_unittest("KvStoreBackupTest") { "../src/query_helper.cpp", "../src/rdb/rdb_service.cpp", "../src/single_kvstore_impl.cpp", - "../src/kvstore_app_manager.cpp", - "../src/kvstore_data_service.cpp", "unittest/kvstore_backup_test.cpp", ] diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index d879d6e37..6d8935b09 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -20,22 +20,22 @@ config("module_public_config") { visibility = [ ":*" ] include_dirs = [ "include", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common" + "//third_party/json/single_include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", ] } ohos_shared_library("distributeddatasvcfwk") { sources = [ - "checker/default/system_checker.cpp", - "checker/default/bundle_checker.cpp", "checker/checker_manager.cpp", + "checker/default/bundle_checker.cpp", + "checker/default/system_checker.cpp", "eventcenter/event.cpp", "eventcenter/event_center.cpp", "metadata/meta_data.cpp", "metadata/secret_key_meta_data.cpp", "metadata/store_meta_data.cpp", - "metadata/strategy_meta_data.cpp", - "metadata/user_meta_data.cpp", "serializable/serializable.cpp", "utils/constant.cpp", ] @@ -44,6 +44,7 @@ ohos_shared_library("distributeddatasvcfwk") { cflags_cc = [ "-fvisibility=hidden" ] configs = [ ":module_public_config" ] + # ldflags = [ "-Wl,--exclude-libs,libcrypto_static.a" ] deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", @@ -51,9 +52,14 @@ ohos_shared_library("distributeddatasvcfwk") { ] external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:intent", + "ability_runtime:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] - public_configs = [ ":module_public_config" ] subsystem_name = "distributeddatamgr" -} \ No newline at end of file +} diff --git a/services/distributeddataservice/framework/checker/checker_manager.cpp b/services/distributeddataservice/framework/checker/checker_manager.cpp index 7ba8d61d1..5e67baf64 100644 --- a/services/distributeddataservice/framework/checker/checker_manager.cpp +++ b/services/distributeddataservice/framework/checker/checker_manager.cpp @@ -53,8 +53,6 @@ void CheckerManager::RegisterPlugin(const std::string &checker, std::functionGetDeviceAccountIdByUID(uid); for (auto &[name, checker] : checkers_ ) { if (checker == nullptr) { continue; @@ -65,7 +63,7 @@ std::string CheckerManager::GetAppId(const std::string &bundleName, pid_t uid) } return appId; } - return ""; + return bundleName; } 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 1da472719..85cf6909a 100644 --- a/services/distributeddataservice/framework/checker/default/bundle_checker.cpp +++ b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp @@ -74,7 +74,7 @@ bool BundleChecker::IsValid(pid_t uid, const std::string &bundleName) auto bundleInfo = std::make_unique(); success = BundleMgrClient::GetInstance()->GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo); if (!success) { - return ""; + return false; } auto it = trusts_.find(bundleName); if (it != trusts_.end() && (it->second == bundleInfo->appId)) { diff --git a/services/distributeddataservice/framework/include/serializable/serializable.h b/services/distributeddataservice/framework/include/serializable/serializable.h index f17dcf3b4..fb6b32ecc 100644 --- a/services/distributeddataservice/framework/include/serializable/serializable.h +++ b/services/distributeddataservice/framework/include/serializable/serializable.h @@ -29,6 +29,7 @@ namespace DistributedData { struct Serializable { public: using json = nlohmann::json; + using size_type= nlohmann::json::size_type; API_EXPORT json Marshall() const; API_EXPORT bool Unmarshall(const std::string &jsonStr); API_EXPORT static json ToJson(const std::string &jsonStr); @@ -75,7 +76,7 @@ protected: } bool result = true; values.resize(subNode.size()); - for (int i = 0; i < subNode.size(); ++i) { + for (size_type i = 0; i < subNode.size(); ++i) { result &= GetValue(subNode[i], "", values[i]); } return result; @@ -85,7 +86,7 @@ protected: static bool SetValue(json &node, const std::vector &values) { bool result = true; - int i = 0; + size_type i = 0; node = json::value_t::array; for (const auto &value : values) { result &= SetValue(node[i], value); diff --git a/services/distributeddataservice/framework/include/utils/constant.h b/services/distributeddataservice/framework/include/utils/constant.h index 68f4165fb..11402e7c3 100644 --- a/services/distributeddataservice/framework/include/utils/constant.h +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -24,7 +24,6 @@ #include #include #include "visibility.h" -#include "autils/visibility.h" namespace OHOS { namespace DistributedKv { diff --git a/services/distributeddataservice/framework/test/event_center_test.cpp b/services/distributeddataservice/framework/test/event_center_test.cpp index 7c554e0d3..a94713bb2 100644 --- a/services/distributeddataservice/framework/test/event_center_test.cpp +++ b/services/distributeddataservice/framework/test/event_center_test.cpp @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#define LOG_TAG "EventCenterTest" #include "eventcenter/event_center.h" #include "eventcenter/event.h" #include "log_print.h" diff --git a/services/distributeddataservice/service/BUILD.gn b/services/distributeddataservice/service/BUILD.gn index 516fd56f1..1d73ba91d 100644 --- a/services/distributeddataservice/service/BUILD.gn +++ b/services/distributeddataservice/service/BUILD.gn @@ -22,30 +22,35 @@ config("module_public_config") { "bootstrap/include", "config/include", "directory/include", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common" + "//third_party/json/single_include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework/include", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", ] } ohos_shared_library("distributeddatasvc") { sources = [ "bootstrap/src/bootstrap.cpp", + "config/src/config_factory.cpp", "config/src/model/checker_config.cpp", "config/src/model/component_config.cpp", "config/src/model/directory_config.cpp", "config/src/model/global_config.cpp", "config/src/model/network_config.cpp", "config/src/model/protocol_config.cpp", - "config/src/config_factory.cpp", - "directory/src/directory_manager.cpp" + "directory/src/directory_manager.cpp", ] cflags = [ "-Wno-multichar" ] cflags_cc = [ "-fvisibility=hidden" ] configs = [ ":module_public_config" ] + # ldflags = [ "-Wl,--exclude-libs,libcrypto_static.a" ] deps = [ "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/framework:distributeddatasvcfwk", "//utils/native/base:utils", ] @@ -53,6 +58,5 @@ ohos_shared_library("distributeddatasvc") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] - public_configs = [ ":module_public_config" ] subsystem_name = "distributeddatamgr" -} \ No newline at end of file +} diff --git a/services/distributeddataservice/service/config/include/model/global_config.h b/services/distributeddataservice/service/config/include/model/global_config.h index ac72dd7c3..a88f19eca 100644 --- a/services/distributeddataservice/service/config/include/model/global_config.h +++ b/services/distributeddataservice/service/config/include/model/global_config.h @@ -33,7 +33,7 @@ public: NetworkConfig *networks = nullptr; DirectoryConfig *directory = nullptr; bool Marshal(json &node) const override; - bool Unmarshal(const json &node); + bool Unmarshal(const json &node) override; }; } } diff --git a/services/distributeddataservice/service/config/include/model/network_config.h b/services/distributeddataservice/service/config/include/model/network_config.h index 505782492..fbcb02a45 100644 --- a/services/distributeddataservice/service/config/include/model/network_config.h +++ b/services/distributeddataservice/service/config/include/model/network_config.h @@ -25,8 +25,8 @@ public: std::vector routers; std::vector transports; std::vector protocols; - bool Marshal(json &node) const; - bool Unmarshal(const json &node); + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; }; } } diff --git a/services/distributeddataservice/service/config/include/model/protocol_config.h b/services/distributeddataservice/service/config/include/model/protocol_config.h index bdbe4c79d..383fb6759 100644 --- a/services/distributeddataservice/service/config/include/model/protocol_config.h +++ b/services/distributeddataservice/service/config/include/model/protocol_config.h @@ -23,8 +23,8 @@ public: std::string name; std::string address; std::string transport; - bool Marshal(json &node) const; - bool Unmarshal(const json &node); + bool Marshal(json &node) const override; + bool Unmarshal(const json &node) override; }; } } diff --git a/services/distributeddataservice/service/directory/CMakeLists.txt b/services/distributeddataservice/service/directory/CMakeLists.txt deleted file mode 100644 index 629fe644e..000000000 --- a/services/distributeddataservice/service/directory/CMakeLists.txt +++ /dev/null @@ -1,86 +0,0 @@ -cmake_minimum_required(VERSION 3.10.2) -project(directory) - -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y -fno-rtti -fvisibility=hidden -D_GNU_SOURCE") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -fPIC -fpic -ffunction-sections -D_GLIBC_MOCK") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wl,--no-as-needed -ldl") -#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") -#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") -set(MOCK_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../mock") -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/src directorySrc) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../frameworks/common) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../framework/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../interfaces/innerkits/distributeddata/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../adapter/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/base/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../../utils_native/safwk/native/include) -include_directories(${MOCK_DIR}) -include_directories(${MOCK_DIR}/uapi) -include_directories(${MOCK_DIR}/innerkits/sensor/sensor_interface_native/include) -include_directories(${MOCK_DIR}/innerkits/miscdevice/vibrator_interface_native/include) -include_directories(${MOCK_DIR}/innerkits/aafwk_standard/want/include/ohos/aafwk/content) -include_directories(${MOCK_DIR}/innerkits/aafwk_standard/intent/include) -include_directories(${MOCK_DIR}/innerkits/aafwk_standard/ability_manager/include) -include_directories(${MOCK_DIR}/innerkits/aafwk_standard/base/include) -include_directories(${MOCK_DIR}/innerkits/jsapi_worker/worker_init/include) -include_directories(${MOCK_DIR}/innerkits/os_account_standard/libaccountkits/include) -include_directories(${MOCK_DIR}/innerkits/deviceauth_standard/deviceauth_sdk/include) -include_directories(${MOCK_DIR}/innerkits/samgr_standard/samgr_proxy/include) -include_directories(${MOCK_DIR}/innerkits/ipc/ipc_core/include) -include_directories(${MOCK_DIR}/innerkits/ipc/ipc_single/include) -include_directories(${MOCK_DIR}/innerkits/ipc/libdbinder/include) -include_directories(${MOCK_DIR}/innerkits/resmgr_standard/global_resmgr/include) -include_directories(${MOCK_DIR}/innerkits/power_manager_native/powermgr_client/include) -include_directories(${MOCK_DIR}/innerkits/napi/ace_napi/include) -include_directories(${MOCK_DIR}/innerkits/hisysevent_native/libhisysevent/include) -include_directories(${MOCK_DIR}/innerkits/appverify/libhapverify/include) -include_directories(${MOCK_DIR}/innerkits/huks_standard/libhukssdk/include) -include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_ability/include) -include_directories(${MOCK_DIR}/innerkits/inputmethod_native/inputmethod_client/include) -include_directories(${MOCK_DIR}/innerkits/safwk/system_ability_fwk/include) -include_directories(${MOCK_DIR}/innerkits/ipc_js/rpc/include) -include_directories(${MOCK_DIR}/innerkits/dataclassification/fbe_iudf_xattr/include) -include_directories(${MOCK_DIR}/innerkits/dataclassification/hwdsl/include) -include_directories(${MOCK_DIR}/innerkits/battery_manager_native/batterysrv_client/include) -include_directories(${MOCK_DIR}/innerkits/permission_standard/libpermissionsdk_standard/include) -include_directories(${MOCK_DIR}/innerkits/hilog_native/libhilog/include) -include_directories(${MOCK_DIR}/innerkits/display_manager_native/displaymgr/include) -include_directories(${MOCK_DIR}/innerkits/i18n_standard/phonenumber_standard/include) -include_directories(${MOCK_DIR}/innerkits/i18n_standard/zone_util/include) -include_directories(${MOCK_DIR}/innerkits/bytrace_standard/bytrace_core/include) -include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include) -include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/proxy/include) -include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/event/include) -include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-client/include/common/include) -include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include) -include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libmmi-server/include/include) -include_directories(${MOCK_DIR}/innerkits/multimodalinput_base/libinput-third-mmi/include) -include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_base/include) -include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/eventhandler_native/include) -include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/fmskit_native/include) -include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/libeventhandler/include) -include_directories(${MOCK_DIR}/innerkits/appexecfwk_standard/appexecfwk_core/include) -include_directories(${MOCK_DIR}/innerkits/hitrace_native/libhitrace/include) -include_directories(${MOCK_DIR}/innerkits/dmsfwk_standard/zuri/include) -include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_services/include) -include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_core/include) -include_directories(${MOCK_DIR}/innerkits/ces_standard/cesfwk_innerkits/include) -include_directories(${MOCK_DIR}/innerkits/multimedia_image_standard/image/include) -include_directories(${MOCK_DIR}/innerkits/ril_adapter/hril/include) -include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_dataability/include) -include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_preferences/include) -include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_rdb/include) -include_directories(${MOCK_DIR}/innerkits/native_appdatamgr/native_appdatafwk/include) -include_directories(${MOCK_DIR}/innerkits/startup_l2/syspara/include) -include_directories(${MOCK_DIR}/innerkits/hicollie_native/libhicollie/include) -include_directories(${MOCK_DIR}/innerkits/dsoftbus_standard/softbus_client/include) -include_directories(${MOCK_DIR}/innerkits/device_manager_base/devicemanagersdk/include) -include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/app_distributeddata/include) -include_directories(${MOCK_DIR}/innerkits/distributeddatamgr/distributeddata_inner/include) -#include_directories(${MOCK_DIR}/innerkits/utils_base/utils/include/include) -set(links secure mock frameworks svcFwk) -set(LIBRARY_OUTPUT_PATH "${PROJECT_BINARY_DIR}/../../../../") -add_library(directory SHARED ${directorySrc}) -target_link_libraries(directory ${links}) diff --git a/services/distributeddataservice/service/directory/include/directory_manager.h b/services/distributeddataservice/service/directory/include/directory_manager.h index eb700b63c..433089578 100644 --- a/services/distributeddataservice/service/directory/include/directory_manager.h +++ b/services/distributeddataservice/service/directory/include/directory_manager.h @@ -26,7 +26,6 @@ enum PathType { PATH_DE, PATH_CE, }; -class StoreMetaData; class DirWorker { public: DirWorker() = default; @@ -92,5 +91,4 @@ private: std::string version_; }; } // namespace OHOS::DistributedKv - #endif // SDB_DIRECTORY_MANAGER_H diff --git a/services/distributeddataservice/service/directory/include/kvstore_context.h b/services/distributeddataservice/service/directory/include/kvstore_context.h index 8bdbdd5dc..f1aa7726d 100644 --- a/services/distributeddataservice/service/directory/include/kvstore_context.h +++ b/services/distributeddataservice/service/directory/include/kvstore_context.h @@ -26,5 +26,4 @@ struct ClientContext { std::string dataDir {}; }; } - #endif // SDB_KVSTORE_CONTEXT_H \ No newline at end of file diff --git a/services/distributeddataservice/service/directory/src/directory_manager.cpp b/services/distributeddataservice/service/directory/src/directory_manager.cpp index e7a109490..feed7f7f3 100644 --- a/services/distributeddataservice/service/directory/src/directory_manager.cpp +++ b/services/distributeddataservice/service/directory/src/directory_manager.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#define LOG_TAG "DirectoryManager" #include "directory_manager.h" #include -- Gitee