diff --git a/bundle.json b/bundle.json index 143a622272d598d30d1ac1b2952869fbc18fdf15..3a7ca7ec2bb4bb002e420614ff42f59bd29f7c54 100644 --- a/bundle.json +++ b/bundle.json @@ -85,7 +85,10 @@ "//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", + "//foundation/distributeddatamgr/distributeddatamgr/conf:build_module" ], "inner_kits": [ { diff --git a/conf/BUILD.gn b/conf/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..ee2d968ca25a712b3fff1f63005672abc24e482a --- /dev/null +++ b/conf/BUILD.gn @@ -0,0 +1,25 @@ +# 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 = "distributeddatamgr" +} diff --git a/conf/config.json b/conf/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5a311cee7a95c0b2f496a925ad3063c48046ef42 --- /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": "OHOS softbus", + "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 diff --git a/frameworks/common/concurrent_map.h b/frameworks/common/concurrent_map.h index 015e1acab8fc2b3f076c348d41c2c5d3165444e6..7ac32370d3c2cdb7a6e6ef53d532b2142dd43a9e 100644 --- a/frameworks/common/concurrent_map.h +++ b/frameworks/common/concurrent_map.h @@ -13,32 +13,29 @@ * limitations under the License. */ -#ifndef DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H -#define DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H - +#ifndef OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H +#define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_CONCURRENT_MAP_H +#include #include #include -#include - namespace OHOS { -template +template class ConcurrentMap { public: - using key_type = typename std::map::key_type; - using mapped_type = typename std::map::mapped_type; - using value_type = typename std::map::value_type; - using size_type = typename std::map::size_type; - using reference = typename std::map::reference; - using const_reference = typename std::map::const_reference; - using Predicate = std::function; - + 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) { @@ -49,12 +46,12 @@ public: entries_ = std::move(tmp); return *this; } - + ConcurrentMap(ConcurrentMap &&other) noexcept { operator=(std::move(other)); } - + ConcurrentMap &operator=(ConcurrentMap &&other) noexcept { if (this == &other) { @@ -65,7 +62,7 @@ public: entries_ = std::move(tmp); return *this; } - + template bool Emplace(_Args &&...__args) noexcept { @@ -73,7 +70,7 @@ public: 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_); @@ -81,84 +78,76 @@ public: 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); } - - size_type EraseAllIf(const Predicate& predicate) noexcept - { - size_type count = 0; - if (predicate == nullptr) { - return 0; - } - for (auto it = entries_.begin(); it != entries_.end();) { - if (predicate(it->first, it->second)) { - entries_.erase(it++); - count++; - continue; - } - it++; - } - return count; - } - + 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 + + size_type EraseIf(const std::function &action) noexcept { if (action == nullptr) { - return; + return 0; } std::lock_guard lock(mutex_); - for (auto &[key, value] : entries_) { - if (action(key, value)) { - break; +#if __cplusplus > 201703L + auto count = std::erase_if(entries_, + [&action](value_type &value) -> bool { return action(value.first, value.second); }); +#else + auto count = entries_.size(); + for (auto it = entries_.begin(); it != entries_.end();) { + if (action((*it).first, (*it).second)) { + it = entries_.erase(it); + } else { + ++it; } } - return entries_.size(); + count -= entries_.size(); +#endif + return count; } - + mapped_type &operator[](const key_type &key) noexcept { std::lock_guard lock(mutex_); return entries_[key]; } - + void ForEach(const std::function &action) { if (action == nullptr) { @@ -171,7 +160,7 @@ public: } } } - + bool Compute(const key_type &key, const std::function &action) { if (action == nullptr) { @@ -189,7 +178,7 @@ public: action(it->first, it->second); return true; } - + bool ComputeIfPresent(const key_type &key, const std::function &action) { if (action == nullptr) { @@ -203,36 +192,35 @@ public: action(key, it->second); return true; } - - mapped_type ComputeIfAbsent(const key_type &key, const std::function &action) + + bool ComputeIfAbsent(const key_type &key, const std::function &action) { if (action == nullptr) { - return mapped_type(); + return false; } std::lock_guard lock(mutex_); auto it = entries_.find(key); if (it != entries_.end()) { - return it->second; + return false; } - mapped_type value = action(key); - entries_.insert(value_type { key, value }); - return value; + entries_.insert(value_type{key, action(key)}); + return true; } private: - std::map Steal() noexcept + std::map<_Key, _Tp> Steal() noexcept { std::lock_guard lock(mutex_); return std::move(entries_); } - - std::map Clone() const noexcept + + std::map<_Key, _Tp> Clone() const noexcept { std::lock_guard lock(mutex_); return entries_; } private: mutable std::recursive_mutex mutex_; - std::map entries_; + std::map<_Key, _Tp> entries_; }; } -#endif +#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 0000000000000000000000000000000000000000..aad1a383894d9d548850ea4d530c1ba9403f4609 --- /dev/null +++ b/frameworks/common/visibility.h @@ -0,0 +1,26 @@ +/* + * 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_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/interfaces/innerkits/distributeddata/include/visibility.h b/interfaces/innerkits/distributeddata/include/visibility.h index af8fa9b3de8070145828a82566c9dbb0a71a2251..502eda59b754c3eac45274429ec4f0cac1d31206 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/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..49ba332cf487c7bc2cfbb349757a43ab8d486863 --- /dev/null +++ b/services/distributeddataservice/framework/BUILD.gn @@ -0,0 +1,65 @@ +# 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", + "//third_party/json/single_include", + "//foundation/distributeddatamgr/distributeddatamgr/frameworks/common", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include", + ] +} + +ohos_shared_library("distributeddatasvcfwk") { + sources = [ + "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", + "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 = [ + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:intent", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "distributeddatamgr" +} diff --git a/services/distributeddataservice/framework/checker/checker_manager.cpp b/services/distributeddataservice/framework/checker/checker_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1c79200a0a433d5bc5ad54c9afce32395ace8f2 --- /dev/null +++ b/services/distributeddataservice/framework/checker/checker_manager.cpp @@ -0,0 +1,92 @@ +/* +* 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) +{ + for (auto &[name, checker] : checkers_) { + if (checker == nullptr) { + continue; + } + auto appId = checker->GetAppId(uid, bundleName); + if (appId.empty()) { + continue; + } + return appId; + } + return bundleName; +} + +bool CheckerManager::IsValid(const std::string &bundleName, pid_t 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 0000000000000000000000000000000000000000..e6d301e6c8fe60805afdd2b7037ea8151e7ef4c3 --- /dev/null +++ b/services/distributeddataservice/framework/checker/default/bundle_checker.cpp @@ -0,0 +1,90 @@ +/* +* 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 +#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) +{ + BundleMgrClient bmsClient; + std::string bundle = bundleName; + if (uid != CheckerManager::INVALID_UID) { + auto success = bmsClient.GetBundleNameForUid(uid, bundle); + if (uid < SYSTEM_UID || !success || bundle != bundleName) { + return ""; + } + } + + auto bundleInfo = std::make_unique(); + auto success = bmsClient.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) +{ + BundleMgrClient bmsClient; + std::string bundle = bundleName; + auto success = bmsClient.GetBundleNameForUid(uid, bundle); + if (uid < SYSTEM_UID || !success || bundle != bundleName) { + return false; + } + + auto bundleInfo = std::make_unique(); + success = bmsClient.GetBundleInfo(bundle, BundleFlag::GET_BUNDLE_DEFAULT, *bundleInfo); + if (!success) { + return false; + } + auto it = trusts_.find(bundleName); + if (it != trusts_.end() && (it->second == bundleInfo->appId)) { + return true; + } + + return true; +} +} +} \ 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 0000000000000000000000000000000000000000..c497fb9518240ed6afc11fb5b8f8950b32cff89b --- /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/framework/eventcenter/event.cpp b/services/distributeddataservice/framework/eventcenter/event.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19bda662b48a6844aa168af5686f94ed5cc48d64 --- /dev/null +++ b/services/distributeddataservice/framework/eventcenter/event.cpp @@ -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 "eventcenter/event.h" +namespace OHOS { +namespace DistributedData { +Event::Event(int32_t evtId) : evtId_(evtId) +{ +} +Event::~Event() +{ +} +int32_t Event::GetEventId() const +{ + return evtId_; +} +} +} \ 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 0000000000000000000000000000000000000000..2dd0bd1477fc754a275c452d55af2f47f04210e7 --- /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 0000000000000000000000000000000000000000..6b8f9aa105f65b04e9214e94cbbfe82affc8966f --- /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 { + 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); + 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 0000000000000000000000000000000000000000..91eefe491ccfcd6ab0d03d742424efd4b39284b5 --- /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 0000000000000000000000000000000000000000..29c9ccbf29b9b9a649d501959204c016a6821f2d --- /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 +#include "checker/checker_manager.h" +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 0000000000000000000000000000000000000000..92d9cecde2ecd3441e078b0e90d661a584116096 --- /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 0000000000000000000000000000000000000000..fb418f6d9e8ee52f344ea3f7757566b408304bcc --- /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 0000000000000000000000000000000000000000..8059e0c58439085a63e338e6f014889891746569 --- /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/framework/include/metadata/secret_key_meta_data.h b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.h new file mode 100644 index 0000000000000000000000000000000000000000..2b93aa5fa028ed336b6431e9e4981a17b997cd88 --- /dev/null +++ b/services/distributeddataservice/framework/include/metadata/secret_key_meta_data.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_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(); + 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 0000000000000000000000000000000000000000..2000d6c93e07d40f57fc4573cd9a7f778465e212 --- /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 0000000000000000000000000000000000000000..1bd6790fc3e2283017084a665572fb68be52f96a --- /dev/null +++ b/services/distributeddataservice/framework/include/serializable/serializable.h @@ -0,0 +1,102 @@ +/* + * 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 +#include "visibility.h" +#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; + 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); + 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 (size_type 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; + size_type 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 0000000000000000000000000000000000000000..11402e7c3802479c240ebb8df2eb1f0fb135b481 --- /dev/null +++ b/services/distributeddataservice/framework/include/utils/constant.h @@ -0,0 +1,186 @@ +/* + * 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" + +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 0000000000000000000000000000000000000000..090ca2d3ccf4d878ff3ab13e4685ef7b2e63eb13 --- /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 0000000000000000000000000000000000000000..b844394a23a43535db14c6d60c49fbf5d5945232 --- /dev/null +++ b/services/distributeddataservice/framework/metadata/secret_key_meta_data.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 "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); + 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 0000000000000000000000000000000000000000..a730149dd242750ac9ff806200cb6a7d70236980 --- /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 0000000000000000000000000000000000000000..540f0912c38900e5607d42b111d05d13fdc9738a --- /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 0000000000000000000000000000000000000000..31c292433073f5ab046c11eda340430be6f44ed0 --- /dev/null +++ b/services/distributeddataservice/framework/test/checker_manager_test.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 +using namespace testing::ext; +using namespace OHOS::DistributedData; +class CheckerManagerTest : 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(CheckerManagerTest, 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(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)); +} + +/** +* @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(CheckerManagerTest, 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(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)); +} + +/** +* @tc.name: BundleChecker +* @tc.desc: checker the bundle name of the bundle abilities. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(CheckerManagerTest, BundleChecker, TestSize.Level0) +{ + ASSERT_EQ("ohos.test.demo", + CheckerManager::GetInstance().GetAppId("ohos.test.demo", 100000)); + ASSERT_TRUE(CheckerManager::GetInstance().IsValid("ohos.test.demo", 100000)); +} \ No newline at end of file diff --git a/services/distributeddataservice/framework/test/event_center_test.cpp b/services/distributeddataservice/framework/test/event_center_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..11c318c16da1c68b4ab98a3eac2a6625f09e4842 --- /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. + */ +#define LOG_TAG "EventCenterTest" +#include "eventcenter/event_center.h" +#include "gtest/gtest.h" +#include "log_print.h" +using namespace testing::ext; +using namespace OHOS::DistributedData; +class EventCenterTest : public testing::Test { +public: + enum TestEventId { + 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(EventCenterTest, 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(EventCenterTest, 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(EventCenterTest, 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(EventCenterTest, 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 0000000000000000000000000000000000000000..c425811c8b6e60e9638824776b9db435083c55d3 --- /dev/null +++ b/services/distributeddataservice/framework/test/serializable_test.cpp @@ -0,0 +1,160 @@ +/* + * 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 "log_print.h" +#include "serializable/serializable.h" +#include "gtest/gtest.h" +using namespace testing::ext; +using namespace OHOS::DistributedData; + +class SerializableTest : 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(SerializableTest, 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(SerializableTest, 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(SerializableTest, 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 0000000000000000000000000000000000000000..75b77bb9e2c5014a2fd788b4b4fb760f214e078c --- /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 0000000000000000000000000000000000000000..1d73ba91d4cdf0ebc38e3d9acc29d43101c64a3b --- /dev/null +++ b/services/distributeddataservice/service/BUILD.gn @@ -0,0 +1,62 @@ +# 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", + "//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", + "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", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + subsystem_name = "distributeddatamgr" +} diff --git a/services/distributeddataservice/service/bootstrap/CMakeLists.txt b/services/distributeddataservice/service/bootstrap/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..72d567cdcf03813c9bff06ed0e096ce4102a2697 --- /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 0000000000000000000000000000000000000000..0d6f16063640b79e8670273c752855ebe73a58fb --- /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_BOOTSTRAP_BOOTSTRAP_H +#define OHOS_DISTRIBUTED_DATA_SERVICES_BOOTSTRAP_BOOTSTRAP_H +#include +#include "visibility.h" +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_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 0000000000000000000000000000000000000000..2d467d682fddfea9321319aa9d59eb974f399546 --- /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 0000000000000000000000000000000000000000..af844568a5f02b0c02aacda8333d3ef72f7b680f --- /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 0000000000000000000000000000000000000000..deb6f8b5fae8fc0455528bc96cd6382ea7a5d3db --- /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_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 new file mode 100644 index 0000000000000000000000000000000000000000..883d2d102b057fe1e093ee3d0a02401607337d54 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/checker_config.h @@ -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. + */ + +#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: + struct Trust final : public Serializable, public CheckerManager::Trust { + 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 0000000000000000000000000000000000000000..ed9df6c75b05047abbefa2e00904a233284565b3 --- /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 0000000000000000000000000000000000000000..7476cd96fa5fc09542970a0574854fbe948a3642 --- /dev/null +++ b/services/distributeddataservice/service/config/include/model/directory_config.h @@ -0,0 +1,35 @@ +/* +* 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 "directory_manager.h" +#include "serializable/serializable.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 0000000000000000000000000000000000000000..a88f19eca5869345560679f107544fce700c653a --- /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) override; +}; +} +} +#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 0000000000000000000000000000000000000000..fbcb02a4597c7c6b1e6cd14248841224f63a52f8 --- /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 override; + bool Unmarshal(const json &node) override; +}; +} +} +#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 0000000000000000000000000000000000000000..383fb6759f558ad71f7a789a9f13669f15fa73d2 --- /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 override; + bool Unmarshal(const json &node) override; +}; +} +} +#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 0000000000000000000000000000000000000000..c689aba36f27629fdcda4dcc36ddbaeb65c4d831 --- /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 0000000000000000000000000000000000000000..35fb58b1472abef4180f9e8753fdf9af764ceb0f --- /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 0000000000000000000000000000000000000000..9fed56bb177ccbb644249a938fe4157445f78279 --- /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 0000000000000000000000000000000000000000..5cde0ec352d71b1271e79cfa910fc4f464c57b3a --- /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 0000000000000000000000000000000000000000..8f91037ea67a8eb4079ffaadab16b3ff029039d8 --- /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 0000000000000000000000000000000000000000..20c0049fe59963cd9e03aede63438561696d21de --- /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 0000000000000000000000000000000000000000..8e5161e952b06855f31ebc26acc7c9545db9bd8e --- /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/include/directory_manager.h b/services/distributeddataservice/service/directory/include/directory_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..433089578a5950aa8f346078ceca8f8a65cb71d9 --- /dev/null +++ b/services/distributeddataservice/service/directory/include/directory_manager.h @@ -0,0 +1,94 @@ +/* + * 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 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 0000000000000000000000000000000000000000..f1aa7726d7ec491e638c57c98c12806196cfa31c --- /dev/null +++ b/services/distributeddataservice/service/directory/include/kvstore_context.h @@ -0,0 +1,29 @@ +/* + * 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 0000000000000000000000000000000000000000..feed7f7f3189326448b7c6760ba28bb9c13e47dc --- /dev/null +++ b/services/distributeddataservice/service/directory/src/directory_manager.cpp @@ -0,0 +1,141 @@ +/* + * 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 "DirectoryManager" +#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; + 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 0000000000000000000000000000000000000000..fc9a46c6de68e50b8d16b1a4a764c82e115504a1 --- /dev/null +++ b/services/distributeddataservice/service/test/config_factory_test.cpp @@ -0,0 +1,121 @@ +/* +* 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 "gtest/gtest.h" +using namespace testing::ext; +using namespace OHOS::DistributedData; +class ConfigFactoryTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + } + 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(ConfigFactoryTest, 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(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, "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, "libconfigdemo2.z.so"); +} + + +/** +* @tc.name: CheckerConfig +* @tc.desc: load the config.json checkers info. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(ConfigFactoryTest, 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"); +} + +/** +* @tc.name: NetworkConfig +* @tc.desc: load the config.json networks info. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +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{ "OHOSRouter" }; + ASSERT_EQ(networks->routers, routers); + std::vector transports{ "softbus" }; + ASSERT_EQ(networks->transports, transports); + 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 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 0000000000000000000000000000000000000000..1d2ad8d9daf3fc4d75335c5e25566f96fd0b9916 --- /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/"); +} diff --git a/services/rdb/rdb_service_impl.cpp b/services/rdb/rdb_service_impl.cpp index ec4b236ecacf5f740044f593ca68145d8833260e..20abd3c097076233200c87c5a62fa24eccb628d2 100644 --- a/services/rdb/rdb_service_impl.cpp +++ b/services/rdb/rdb_service_impl.cpp @@ -51,7 +51,7 @@ void RdbServiceImpl::ClearClientSyncers(const std::string& bundleName) { ZLOGI("enter"); std::string appId = DistributedKv::KvStoreUtils::GetAppIdByBundleName(bundleName); - auto count = syncers_.EraseAllIf([&appId] (const std::string& key, const sptr& value) { + auto count = syncers_.EraseIf([&appId](const std::string &key, sptr &value) -> bool { return value->GetAppId() == appId; }); ZLOGI("remove %{public}d", static_cast(count)); @@ -72,15 +72,15 @@ bool RdbServiceImpl::CheckAccess(const RdbSyncerParam& param) const sptr RdbServiceImpl::CreateSyncer(const RdbSyncerParam& param) { RdbSyncerImpl* syncerNew = RdbSyncerFactory::GetInstance().CreateSyncer(param); - auto syncer = syncers_.ComputeIfAbsent(syncerNew->GetIdentifier(), - [&syncerNew] (const std::string& key) { + syncers_.ComputeIfAbsent(syncerNew->GetIdentifier(), + [&syncerNew] (const auto& key) -> auto { ZLOGI("create new syncer %{public}s", key.c_str()); + if (syncerNew != nullptr) { + syncerNew->Init(); + } return sptr(syncerNew); }); - if (syncer != nullptr) { - syncer->Init(); - } - return syncer; + return syncers_[syncerNew->GetIdentifier()]; } sptr RdbServiceImpl::GetRdbSyncerInner(const RdbSyncerParam& param)