modify udmf build config

Signed-off-by: ding_dong_dong <dingdongdong4@huawei.com>
This commit is contained in:
ding_dong_dong 2023-06-25 17:49:17 +08:00
parent f43465fae2
commit 456e93eebb
40 changed files with 2624 additions and 2 deletions

View File

@ -29,6 +29,7 @@ group("fuzztest") {
testonly = true
deps = []
deps += [
"services/distributeddataservice/service/test/fuzztest:fuzztest",
"test/fuzztest/autolaunch_fuzzer:fuzztest",
"test/fuzztest/kvstoredisksize_fuzzer:fuzztest",
]

View File

@ -74,7 +74,8 @@
"os_account",
"relational_store",
"safwk",
"samgr"
"samgr",
"udmf"
],
"third_party": [
"cjson",
@ -92,7 +93,8 @@
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:build_module",
"//foundation/distributeddatamgr/datamgr_service/conf:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service/data_share:build_module"
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service/data_share:build_module",
"//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service/udmf:build_module"
],
"inner_kits": [],
"test": [

View File

@ -32,6 +32,10 @@ ipc_core_path = "//foundation/communication/ipc/interfaces/innerkits/ipc_core"
device_manager_path = "//foundation/distributedhardware/device_manager"
data_service_path = "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice"
udmf_path = "//foundation/distributeddatamgr/udmf"
declare_args() {
datamgr_service_power = true
if (!defined(global_parts_info.power_manager_native_powermgr_client) ||

View File

@ -0,0 +1,21 @@
# Copyright (c) 2023 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")
#########################################################################################
group("fuzztest") {
testonly = true
deps = [ "udmfservice_fuzzer:fuzztest" ]
}

View File

@ -0,0 +1,68 @@
# Copyright (c) 2023 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.
##############################hydra-fuzz########################################
import("//build/config/features.gni")
import("//build/test.gni")
import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni")
##############################fuzztest##########################################
ohos_fuzztest("UdmfServiceFuzzTest") {
module_out_path = "datamgr_service/service"
include_dirs = [
"${udmf_path}/framework/common",
"${udmf_path}/interfaces/innerkits/common",
"${udmf_path}/interfaces/innerkits/data",
"${data_service_path}/framework/include",
"${data_service_path}/service/udmf/lifecycle",
"${data_service_path}/service/udmf/permission",
"${data_service_path}/service/udmf/preprocess",
"${data_service_path}/service/udmf/store",
"${data_service_path}/service/udmf",
"${kv_store_path}/frameworks/common",
]
fuzz_config_file =
"${data_service_path}/service/test/fuzztest/udmfservice_fuzzer"
cflags = [
"-g",
"-O0",
"-Wno-unused-variable",
"-fno-omit-frame-pointer",
]
sources = [ "udmfservice_fuzzer.cpp" ]
deps = [ "${data_service_path}/service/udmf:udmf_server" ]
external_deps = [
"ability_base:zuri",
"ability_runtime:uri_permission_mgr",
"access_token:libaccesstoken_sdk",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"kv_store:distributeddata_inner",
"udmf:udmf_client",
]
}
###############################################################################
group("fuzztest") {
testonly = true
deps = [ ":UdmfServiceFuzzTest" ]
}
###############################################################################

View File

@ -0,0 +1,16 @@
/*
* Copyright (c) 2023 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.
*/
FUZZ

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) 2023 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.
-->
<fuzz_config>
<fuzztest>
<!-- maximum length of a test input -->
<max_len>1000</max_len>
<!-- maximum total time in seconds to run the fuzzer -->
<max_total_time>300</max_total_time>
<!-- memory usage limit in Mb -->
<rss_limit_mb>4096</rss_limit_mb>
</fuzztest>
</fuzz_config>

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2023 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 "udmfservice_fuzzer.h"
#include <cstddef>
#include <cstdint>
#include "udmf_service_impl.h"
#include "message_parcel.h"
#include "securec.h"
using namespace OHOS::UDMF;
namespace OHOS {
const std::u16string INTERFACE_TOKEN = u"OHOS.UDMF.UdmfService";
bool OnRemoteRequestFuzz(const uint8_t* data, size_t size)
{
uint32_t code = static_cast<uint32_t>(*data);
MessageParcel request;
request.WriteInterfaceToken(INTERFACE_TOKEN);
request.WriteBuffer(data, size);
request.RewindRead(0);
MessageParcel reply;
std::shared_ptr<UdmfServiceStub> udmfServiceStub = std::make_shared<UdmfServiceImpl>();
udmfServiceStub->OnRemoteRequest(code, request, reply);
return true;
}
}
/* Fuzzer entry point */
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
if (data == nullptr) {
return 0;
}
OHOS::OnRemoteRequestFuzz(data, size);
return 0;
}

View File

@ -0,0 +1,21 @@
/*
* Copyright (c) 2023 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 UDMF_SERVICE_FUZZER_H
#define UDMF_SERVICE_FUZZER_H
#define FUZZ_PROJECT_NAME "udmfservice_fuzzer"
#endif // UDMF_SERVICE_FUZZER_H

View File

@ -0,0 +1,74 @@
# 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("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni")
group("build_module") {
deps = [ ":udmf_server" ]
}
config("module_public_config") {
visibility = [ ":*" ]
include_dirs = [
"${udmf_path}/framework/common",
"${udmf_path}/interfaces/innerkits/common",
"${udmf_path}/interfaces/innerkits/data",
"${data_service_path}/framework/include",
"${data_service_path}/service/udmf/lifecycle",
"${data_service_path}/service/udmf/permission",
"${data_service_path}/service/udmf/preprocess",
"${data_service_path}/service/udmf/store",
"${data_service_path}/service/udmf",
"${kv_store_path}/frameworks/common",
]
}
ohos_shared_library("udmf_server") {
sources = [
"data_manager.cpp",
"lifecycle/clean_after_get.cpp",
"lifecycle/clean_on_startup.cpp",
"lifecycle/clean_on_timeout.cpp",
"lifecycle/lifecycle_manager.cpp",
"lifecycle/lifecycle_policy.cpp",
"permission/checker_manager.cpp",
"permission/data_checker.cpp",
"permission/uri_permission_manager.cpp",
"preprocess/preprocess_utils.cpp",
"store/runtime_store.cpp",
"store/store_cache.cpp",
"udmf_service_impl.cpp",
"udmf_service_stub.cpp",
]
configs = [ ":module_public_config" ]
deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
external_deps = [
"ability_base:zuri",
"ability_runtime:uri_permission_mgr",
"access_token:libaccesstoken_sdk",
"bundle_framework:appexecfwk_core",
"c_utils:utils",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"kv_store:distributeddata_inner",
"udmf:udmf_client",
]
subsystem_name = "distributeddatamgr"
part_name = "datamgr_service"
}

View File

@ -0,0 +1,341 @@
/*
* Copyright (c) 2023 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 "DataManager"
#include "data_manager.h"
#include "checker_manager.h"
#include "file.h"
#include "lifecycle/lifecycle_manager.h"
#include "log_print.h"
#include "preprocess_utils.h"
#include "uri_permission_manager.h"
namespace OHOS {
namespace UDMF {
const std::string MSDP_PROCESS_NAME = "msdp_sa";
const std::string DATA_PREFIX = "udmf://";
DataManager::DataManager()
{
authorizationMap_[UD_INTENTION_MAP.at(UD_INTENTION_DRAG)] = MSDP_PROCESS_NAME;
CheckerManager::GetInstance().LoadCheckers();
}
DataManager::~DataManager()
{
}
DataManager &DataManager::GetInstance()
{
static DataManager instance;
return instance;
}
int32_t DataManager::SaveData(CustomOption &option, UnifiedData &unifiedData, std::string &key)
{
if (unifiedData.IsEmpty()) {
ZLOGE("Invalid parameters, have no record");
return E_INVALID_PARAMETERS;
}
if (!UnifiedDataUtils::IsValidIntention(option.intention)) {
ZLOGE("Invalid parameters intention: %{public}d.", option.intention);
return E_INVALID_PARAMETERS;
}
// imput runtime info before put it into store and save one privilege
if (PreProcessUtils::RuntimeDataImputation(unifiedData, option) != E_OK) {
ZLOGE("Imputation failed");
return E_UNKNOWN;
}
for (auto &record : unifiedData.GetRecords()) {
std::string uid = PreProcessUtils::IdGenerator();
record->SetUid(uid);
}
std::string intention = unifiedData.GetRuntime()->key.intention;
auto store = storeCache_.GetStore(intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
if (!UnifiedDataUtils::IsPersist(intention) && store->Clear() != E_OK) {
ZLOGE("Clear store failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
if (store->Put(unifiedData) != E_OK) {
ZLOGE("Put unified data failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
key = unifiedData.GetRuntime()->key.GetUnifiedKey();
ZLOGD("Put unified data successful, key: %{public}s.", key.c_str());
return E_OK;
}
int32_t DataManager::RetrieveData(const QueryOption &query, UnifiedData &unifiedData)
{
UnifiedKey key(query.key);
if (!key.IsValid()) {
ZLOGE("Unified key: %{public}s is invalid.", query.key.c_str());
return E_INVALID_PARAMETERS;
}
auto store = storeCache_.GetStore(key.intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
int32_t res = store->Get(query.key, unifiedData);
if (res != E_OK) {
ZLOGE("Get data from store failed, intention: %{public}s.", key.intention.c_str());
return res;
}
if (unifiedData.IsEmpty()) {
return E_OK;
}
std::shared_ptr<Runtime> runtime = unifiedData.GetRuntime();
CheckerManager::CheckInfo info;
info.tokenId = query.tokenId;
if (!CheckerManager::GetInstance().IsValid(runtime->privileges, info)) {
return E_NO_PERMISSION;
}
std::string bundleName;
if (!PreProcessUtils::GetHapBundleNameByToken(query.tokenId, bundleName)) {
return E_ERROR;
}
if (runtime->createPackage != bundleName) {
auto records = unifiedData.GetRecords();
for (auto record : records) {
auto type = record->GetType();
std::string uri = "";
if (type == UDType::FILE || type == UDType::IMAGE || type == UDType::VIDEO || type == UDType::AUDIO
|| type == UDType::FOLDER) {
auto file = static_cast<File *>(record.get());
uri = file->GetUri();
}
if (!uri.empty() && (UriPermissionManager::GetInstance().GrantUriPermission(uri, bundleName) != E_OK)) {
return E_NO_PERMISSION;
}
}
}
if (LifeCycleManager::GetInstance().DeleteOnGet(key) != E_OK) {
ZLOGE("Remove data failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
int32_t DataManager::RetrieveBatchData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet)
{
std::vector<UnifiedData> dataSet;
std::shared_ptr<Store> store;
auto status = QueryDataCommon(query, dataSet, store);
if (status != E_OK) {
ZLOGE("QueryDataCommon failed.");
return status;
}
if (dataSet.empty()) {
ZLOGW("DataSet has no data, key: %{public}s, intention: %{public}d.", query.key.c_str(), query.intention);
return E_OK;
}
for (const auto &data : dataSet) {
unifiedDataSet.push_back(data);
}
return E_OK;
}
int32_t DataManager::UpdateData(const QueryOption &query, UnifiedData &unifiedData)
{
UnifiedKey key(query.key);
if (!key.IsValid()) {
ZLOGE("Unified key: %{public}s is invalid.", query.key.c_str());
return E_INVALID_PARAMETERS;
}
if (unifiedData.IsEmpty()) {
ZLOGE("Invalid parameters, unified data has no record.");
return E_INVALID_PARAMETERS;
}
auto store = storeCache_.GetStore(key.intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
UnifiedData data;
int32_t res = store->Get(query.key, data);
if (res != E_OK) {
ZLOGE("Get data from store failed, intention: %{public}s.", key.intention.c_str());
return res;
}
if (data.IsEmpty()) {
ZLOGE("Invalid parameter, unified data has no record; intention: %{public}s.", key.intention.c_str());
return E_INVALID_PARAMETERS;
}
std::shared_ptr<Runtime> runtime = data.GetRuntime();
runtime->lastModifiedTime = PreProcessUtils::GetTimeStamp();
unifiedData.SetRuntime(*runtime);
for (auto &record : unifiedData.GetRecords()) {
record->SetUid(PreProcessUtils::IdGenerator());
}
if (store->Update(unifiedData) != E_OK) {
ZLOGE("Update unified data failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
int32_t DataManager::DeleteData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet)
{
std::vector<UnifiedData> dataSet;
std::shared_ptr<Store> store;
auto status = QueryDataCommon(query, dataSet, store);
if (status != E_OK) {
ZLOGE("QueryDataCommon failed.");
return status;
}
if (dataSet.empty()) {
ZLOGW("DataSet has no data, key: %{public}s, intention: %{public}d.", query.key.c_str(), query.intention);
return E_OK;
}
std::shared_ptr<Runtime> runtime;
std::vector<std::string> deleteKeys;
for (const auto &data : dataSet) {
runtime = data.GetRuntime();
unifiedDataSet.push_back(data);
deleteKeys.push_back(runtime->key.key);
}
if (store->DeleteBatch(deleteKeys) != E_OK) {
ZLOGE("Remove data failed.");
return E_DB_ERROR;
}
return E_OK;
}
int32_t DataManager::GetSummary(const QueryOption &query, Summary &summary)
{
UnifiedKey key(query.key);
if (!key.IsValid()) {
ZLOGE("Unified key: %{public}s is invalid.", query.key.c_str());
return E_INVALID_PARAMETERS;
}
auto store = storeCache_.GetStore(key.intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
if (store->GetSummary(query.key, summary) != E_OK) {
ZLOGE("Store get summary failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
int32_t DataManager::AddPrivilege(const QueryOption &query, const Privilege &privilege)
{
UnifiedKey key(query.key);
if (!key.IsValid()) {
ZLOGE("Unified key: %{public}s is invalid.", query.key.c_str());
return E_INVALID_PARAMETERS;
}
std::string processName;
if (!PreProcessUtils::GetNativeProcessNameByToken(query.tokenId, processName)) {
return E_UNKNOWN;
}
if (processName != authorizationMap_[key.intention]) {
ZLOGE("Process: %{public}s have no permission", processName.c_str());
return E_NO_PERMISSION;
}
auto store = storeCache_.GetStore(key.intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
UnifiedData data;
int32_t res = store->Get(query.key, data);
if (res != E_OK) {
ZLOGE("Get data from store failed, intention: %{public}s.", key.intention.c_str());
return res;
}
if (data.IsEmpty()) {
ZLOGE("Invalid parameters, unified data has no record, intention: %{public}s.", key.intention.c_str());
return E_INVALID_PARAMETERS;
}
data.GetRuntime()->privileges.emplace_back(privilege);
if (store->Update(data) != E_OK) {
ZLOGE("Update unified data failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
int32_t DataManager::Sync(const QueryOption &query, const std::vector<std::string> &devices)
{
UnifiedKey key(query.key);
if (!key.IsValid()) {
ZLOGE("Unified key: %{public}s is invalid.", query.key.c_str());
return E_INVALID_PARAMETERS;
}
auto store = storeCache_.GetStore(key.intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
if (store->Sync(devices) != E_OK) {
ZLOGE("Store sync failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
int32_t DataManager::QueryDataCommon(
const QueryOption &query, std::vector<UnifiedData> &dataSet, std::shared_ptr<Store> &store)
{
auto find = UD_INTENTION_MAP.find(query.intention);
std::string intention = find == UD_INTENTION_MAP.end() ? intention : find->second;
if (!UnifiedDataUtils::IsValidOptions(query.key, intention)) {
ZLOGE("Unified key: %{public}s and intention: %{public}s is invalid.", query.key.c_str(), intention.c_str());
return E_INVALID_PARAMETERS;
}
std::string dataPrefix = DATA_PREFIX + intention;
UnifiedKey key(query.key);
key.IsValid();
if (intention.empty()) {
dataPrefix = key.key;
intention = key.intention;
}
ZLOGD("dataPrefix = %{public}s, intention: %{public}s.", dataPrefix.c_str(), intention.c_str());
store = storeCache_.GetStore(intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
if (store->GetBatchData(dataPrefix, dataSet) != E_OK) {
ZLOGE("Get dataSet failed, dataPrefix: %{public}s.", dataPrefix.c_str());
return E_DB_ERROR;
}
return E_OK;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,54 @@
/*
* Copyright (c) 2023 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 UDMF_DATA_MANAGER_H
#define UDMF_DATA_MANAGER_H
#include <map>
#include <memory>
#include <mutex>
#include <vector>
#include "error_code.h"
#include "store_cache.h"
#include "unified_data.h"
#include "unified_types.h"
namespace OHOS {
namespace UDMF {
class DataManager {
public:
virtual ~DataManager();
static DataManager &GetInstance();
int32_t SaveData(CustomOption &option, UnifiedData &unifiedData, std::string &key);
int32_t RetrieveData(const QueryOption &query, UnifiedData &unifiedData);
int32_t RetrieveBatchData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet);
int32_t UpdateData(const QueryOption &query, UnifiedData &unifiedData);
int32_t DeleteData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet);
int32_t GetSummary(const QueryOption &query, Summary &summary);
int32_t AddPrivilege(const QueryOption &query, const Privilege &privilege);
int32_t Sync(const QueryOption &query, const std::vector<std::string> &devices);
private:
DataManager();
int32_t QueryDataCommon(const QueryOption &query, std::vector<UnifiedData> &dataSet, std::shared_ptr<Store> &store);
StoreCache storeCache_;
std::map<std::string, std::string> authorizationMap_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_DATA_MANAGER_H

View File

@ -0,0 +1,21 @@
/*
* Copyright (c) 2023 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 "clean_after_get.h"
namespace OHOS {
namespace UDMF {
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,26 @@
/*
* Copyright (c) 2023 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 UDMF_CLEAN_AFTER_GET_H
#define UDMF_CLEAN_AFTER_GET_H
#include "lifecycle_policy.h"
namespace OHOS {
namespace UDMF {
class CleanAfterGet : public LifeCyclePolicy {
public:
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_CLEAN_AFTER_GET_H

View File

@ -0,0 +1,30 @@
/*
* Copyright (c) 2023 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 "clean_on_startup.h"
namespace OHOS {
namespace UDMF {
Status CleanOnStartup::DeleteOnTimeout(const std::string &intention)
{
return E_OK;
}
Status CleanOnStartup::DeleteOnGet(const UnifiedKey &key)
{
return E_OK;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,28 @@
/*
* Copyright (c) 2023 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 UDMF_CLEAN_ON_STARTUP_H
#define UDMF_CLEAN_ON_STARTUP_H
#include "lifecycle_policy.h"
namespace OHOS {
namespace UDMF {
class CleanOnStartup : public LifeCyclePolicy {
public:
Status DeleteOnTimeout(const std::string &intention) override;
Status DeleteOnGet(const UnifiedKey &key) override;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_CLEAN_ON_STARTUP_H

View File

@ -0,0 +1,30 @@
/*
* Copyright (c) 2023 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 "clean_on_timeout.h"
namespace OHOS {
namespace UDMF {
Status CleanOnTimeout::DeleteOnStart(const std::string &intention)
{
return LifeCyclePolicy::DeleteOnTimeout(intention);
}
Status CleanOnTimeout::DeleteOnGet(const UnifiedKey &key)
{
return E_OK;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,28 @@
/*
* Copyright (c) 2023 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 UDMF_CLEAN_ON_TIMEOUT_H
#define UDMF_CLEAN_ON_TIMEOUT_H
#include "lifecycle_policy.h"
namespace OHOS {
namespace UDMF {
class CleanOnTimeout : public LifeCyclePolicy {
public:
Status DeleteOnStart(const std::string &intention) override;
Status DeleteOnGet(const UnifiedKey &key) override;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_CLEAN_ON_TIMEOUT_H

View File

@ -0,0 +1,92 @@
/*
* Copyright (c) 2023 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 "LifeCycleManager"
#include "lifecycle_manager.h"
#include <algorithm>
#include <cinttypes>
#include "log_print.h"
namespace OHOS {
namespace UDMF {
std::shared_ptr<ExecutorPool> LifeCycleManager::executorPool_ = std::make_shared<ExecutorPool>(2, 1);
std::unordered_map<std::string, std::shared_ptr<LifeCyclePolicy>> LifeCycleManager::intentionPolicyMap_ = {
{ UD_INTENTION_MAP.at(UD_INTENTION_DRAG), std::make_shared<CleanAfterGet>() },
};
LifeCycleManager &LifeCycleManager::GetInstance()
{
static LifeCycleManager instance;
return instance;
}
Status LifeCycleManager::DeleteOnGet(const UnifiedKey &key)
{
auto findPolicy = intentionPolicyMap_.find(key.intention);
if (findPolicy == intentionPolicyMap_.end()) {
ZLOGE("Invalid intention, intention: %{public}s.", key.intention.c_str());
return E_INVALID_PARAMETERS;
}
auto policy = findPolicy->second;
return policy->DeleteOnGet(key);
}
Status LifeCycleManager::DeleteOnStart()
{
Status status = E_OK;
std::shared_ptr<LifeCyclePolicy> LifeCyclePolicy;
for (const auto &intentionPolicyPair : intentionPolicyMap_) {
LifeCyclePolicy = GetPolicy(intentionPolicyPair.first);
status = status == E_OK ? LifeCyclePolicy->DeleteOnStart(intentionPolicyPair.first) : status;
}
return status;
}
Status LifeCycleManager::DeleteOnSchedule()
{
ExecutorPool::TaskId taskId =
executorPool_->Schedule(&LifeCycleManager::DeleteOnTimeout, LifeCyclePolicy::INTERVAL);
if (taskId == ExecutorPool::INVALID_TASK_ID) {
ZLOGE("ExecutorPool Schedule failed.");
return E_ERROR;
}
ZLOGI("ScheduleTask start, TaskId: %{public}" PRIu64 ".", taskId);
return E_OK;
}
std::shared_ptr<LifeCyclePolicy> LifeCycleManager::GetPolicy(const std::string &intention)
{
auto findPolicy = intentionPolicyMap_.find(intention);
if (findPolicy == intentionPolicyMap_.end()) {
return nullptr;
}
return findPolicy->second;
}
Status LifeCycleManager::DeleteOnTimeout()
{
Status status = E_OK;
std::shared_ptr<LifeCyclePolicy> LifeCyclePolicy;
for (const auto &intentionPolicyPair : intentionPolicyMap_) {
LifeCyclePolicy = LifeCycleManager::GetInstance().GetPolicy(intentionPolicyPair.first);
status = status == E_OK ? LifeCyclePolicy->DeleteOnTimeout(intentionPolicyPair.first) : status;
}
return status;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,47 @@
/*
* Copyright (c) 2023 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 UDMF_LIFECYCLE_MANAGER_H
#define UDMF_LIFECYCLE_MANAGER_H
#include <chrono>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "clean_after_get.h"
#include "clean_on_startup.h"
#include "clean_on_timeout.h"
#include "executor_pool.h"
#include "lifecycle_policy.h"
namespace OHOS {
namespace UDMF {
class LifeCycleManager {
public:
static LifeCycleManager &GetInstance();
Status DeleteOnGet(const UnifiedKey &key);
Status DeleteOnStart();
Status DeleteOnSchedule();
private:
static std::shared_ptr<ExecutorPool> executorPool_;
static std::unordered_map<std::string, std::shared_ptr<LifeCyclePolicy>> intentionPolicyMap_;
static std::shared_ptr<LifeCyclePolicy> GetPolicy(const std::string &intention);
static Status DeleteOnTimeout();
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_LIFECYCLE_MANAGER_H

View File

@ -0,0 +1,101 @@
/*
* Copyright (c) 2023 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 "LifeCyclePolicy"
#include "lifecycle_policy.h"
#include <algorithm>
#include "log_print.h"
#include "preprocess/preprocess_utils.h"
namespace OHOS {
namespace UDMF {
using namespace std::chrono;
const LifeCyclePolicy::Duration LifeCyclePolicy::INTERVAL = milliseconds(60 * 60 * 1000);
const std::string LifeCyclePolicy::DATA_PREFIX = "udmf://";
Status LifeCyclePolicy::DeleteOnGet(const UnifiedKey &key)
{
auto store = storeCache_.GetStore(key.intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
if (store->Delete(key.key) != E_OK) {
ZLOGE("Remove data failed, intention: %{public}s.", key.intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
Status LifeCyclePolicy::DeleteOnStart(const std::string &intention)
{
auto store = storeCache_.GetStore(intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
if (store->Clear() != E_OK) {
ZLOGE("Remove data failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
Status LifeCyclePolicy::DeleteOnTimeout(const std::string &intention)
{
auto store = storeCache_.GetStore(intention);
if (store == nullptr) {
ZLOGE("Get store failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
std::vector<std::string> timeoutKeys;
auto status = GetTimeoutKeys(store, INTERVAL, timeoutKeys);
if (status != E_OK) {
ZLOGE("Get timeout keys failed.");
return E_DB_ERROR;
}
if (store->DeleteBatch(timeoutKeys) != E_OK) {
ZLOGE("Remove data failed, intention: %{public}s.", intention.c_str());
return E_DB_ERROR;
}
return E_OK;
}
Status LifeCyclePolicy::GetTimeoutKeys(
const std::shared_ptr<Store> &store, Duration interval, std::vector<std::string> &timeoutKeys)
{
std::vector<UnifiedData> datas;
auto status = store->GetBatchData(DATA_PREFIX, datas);
if (status != E_OK) {
ZLOGE("Get data failed.");
return E_DB_ERROR;
}
if (datas.empty()) {
ZLOGD("entries is empty.");
return E_OK;
}
auto curTime = PreProcessUtils::GetTimeStamp();
for (const auto &data : datas) {
if (curTime > data.GetRuntime()->createTime + duration_cast<milliseconds>(interval).count()
|| curTime < data.GetRuntime()->createTime) {
timeoutKeys.push_back(data.GetRuntime()->key.key);
}
}
return E_OK;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2023 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 UDMF_LIFECYCLE_POLICY_H
#define UDMF_LIFECYCLE_POLICY_H
#include <chrono>
#include <memory>
#include "store_cache.h"
#include "unified_key.h"
namespace OHOS {
namespace UDMF {
class LifeCyclePolicy {
public:
using Duration = std::chrono::steady_clock::duration;
static const Duration INTERVAL;
virtual ~LifeCyclePolicy() = default;
virtual Status DeleteOnGet(const UnifiedKey &key);
virtual Status DeleteOnStart(const std::string &intention);
virtual Status DeleteOnTimeout(const std::string &intention);
virtual Status GetTimeoutKeys(
const std::shared_ptr<Store> &store, Duration interval, std::vector<std::string> &timeoutKeys);
private:
static const std::string DATA_PREFIX;
StoreCache storeCache_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_LIFECYCLE_POLICY_H

View File

@ -0,0 +1,58 @@
/*
* Copyright (c) 2023 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_manager.h"
namespace OHOS {
namespace UDMF {
const std::string DATA_CHECKER = "DataChecker";
CheckerManager &CheckerManager::GetInstance()
{
static CheckerManager instance;
return instance;
}
void CheckerManager::RegisterChecker(const std::string &checker, std::function<Checker *()> getter)
{
getters_.ComputeIfAbsent(checker, [&getter](const auto &) {
return move(getter);
});
}
void CheckerManager::LoadCheckers()
{
getters_.ForEach([this] (const auto &key, const auto &val) {
if (this->checkers_.find(key) != this->checkers_.end()) {
return false;
}
auto *checker = val();
if (checker == nullptr) {
return false;
}
this->checkers_[key] = checker;
return false;
});
}
bool CheckerManager::IsValid(const std::vector<Privilege> &privileges, const CheckInfo &info)
{
auto it = checkers_.find(DATA_CHECKER);
if (it == checkers_.end()) {
return true;
}
return it->second->IsValid(privileges, info);
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,51 @@
/*
* Copyright (c) 2023 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 UDMF_CHECKER_MANAGER_H
#define UDMF_CHECKER_MANAGER_H
#include <vector>
#include "concurrent_map.h"
#include "unified_types.h"
namespace OHOS {
namespace UDMF {
class CheckerManager {
public:
struct CheckInfo {
uint32_t tokenId;
};
class Checker {
public:
virtual bool IsValid(const std::vector<Privilege> &privileges, const CheckInfo &info) = 0;
protected:
~Checker() = default;
};
static CheckerManager &GetInstance();
void RegisterChecker(const std::string &checker, std::function<Checker *()> getter);
void LoadCheckers();
bool IsValid(const std::vector<Privilege> &privileges, const CheckInfo &info);
private:
std::map<std::string, Checker *> checkers_;
ConcurrentMap<std::string, std::function<Checker *()>> getters_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_CHECKER_MANAGER_H

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 2023 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 "DataChecker"
#include "data_checker.h"
#include "utils/anonymous.h"
#include "log_print.h"
namespace OHOS {
namespace UDMF {
__attribute__((used)) DataChecker DataChecker::instance_;
DataChecker::DataChecker() noexcept
{
CheckerManager::GetInstance().RegisterChecker(
"DataChecker", [this]() -> auto { return this; });
}
DataChecker::~DataChecker()
{
}
bool DataChecker::IsValid(const std::vector<Privilege> &privileges, const CheckerManager::CheckInfo &info)
{
for (const auto &privilege : privileges) {
if (privilege.tokenId == info.tokenId) {
return true;
}
}
ZLOGE("Invalid parameters, %{public}s", DistributedData::Anonymous::Change(std::to_string(info.tokenId)).c_str());
return false;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,35 @@
/*
* Copyright (c) 2023 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 UDMF_DATA_CHECKER_H
#define UDMF_DATA_CHECKER_H
#include "checker_manager.h"
namespace OHOS {
namespace UDMF {
class DataChecker : public CheckerManager::Checker {
public:
DataChecker() noexcept;
~DataChecker();
bool IsValid(const std::vector<Privilege> &privileges, const CheckerManager::CheckInfo &info) override;
private:
static DataChecker instance_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_DATA_CHECKER_H

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 2023 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 "UriPermissionManager"
#include "uri_permission_manager.h"
#include "want.h"
#include "uri.h"
#include "uri_permission_manager_client.h"
#include "log_print.h"
namespace OHOS {
namespace UDMF {
UriPermissionManager &UriPermissionManager::GetInstance()
{
static UriPermissionManager instance;
return instance;
}
Status UriPermissionManager::GrantUriPermission(const std::string &path, const std::string &bundleName)
{
Uri uri(path);
int autoRemove = 1;
auto status = AAFwk::UriPermissionManagerClient::GetInstance().GrantUriPermission(
uri, AAFwk::Want::FLAG_AUTH_READ_URI_PERMISSION, bundleName, autoRemove);
if (status != ERR_OK) {
ZLOGE("GrantUriPermission failed, %{public}d", status);
return E_ERROR;
}
return E_OK;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2023 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 UDMF_URI_PERMISSION_MANAGER_H
#define UDMF_URI_PERMISSION_MANAGER_H
#include <memory>
#include <string>
#include "error_code.h"
namespace OHOS {
namespace UDMF {
class UriPermissionManager {
public:
static UriPermissionManager &GetInstance();
Status GrantUriPermission(const std::string &path, const std::string &bundleName);
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_URI_PERMISSION_MANAGER_H

View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 2023 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 "preprocess_utils.h"
#include <sstream>
#include "error_code.h"
#include "accesstoken_kit.h"
#include "bundlemgr/bundle_mgr_client_impl.h"
#include "ipc_skeleton.h"
namespace OHOS {
namespace UDMF {
static constexpr int ID_LEN = 32;
const char SPECIAL = '^';
int32_t PreProcessUtils::RuntimeDataImputation(UnifiedData &data, CustomOption &option)
{
auto it = UD_INTENTION_MAP.find(option.intention);
if (it == UD_INTENTION_MAP.end()) {
return E_UNKNOWN;
}
std::string bundleName;
GetHapBundleNameByToken(option.tokenId, bundleName);
std::string intention = it->second;
UnifiedKey key(intention, bundleName, IdGenerator());
Privilege privilege;
privilege.tokenId = option.tokenId;
Runtime runtime;
runtime.key = key;
runtime.privileges.emplace_back(privilege);
runtime.createTime = GetTimeStamp();
runtime.sourcePackage = bundleName;
runtime.createPackage = bundleName;
data.SetRuntime(runtime);
return E_OK;
}
std::string PreProcessUtils::IdGenerator()
{
std::random_device randomDevice;
int minimum = 48;
int maximum = 121;
std::uniform_int_distribution<int> distribution(minimum, maximum);
std::stringstream idStr;
for (int32_t i = 0; i < ID_LEN; i++) {
auto asc = distribution(randomDevice);
asc = asc >= SPECIAL ? asc + 1 : asc;
idStr << static_cast<uint8_t>(asc);
}
return idStr.str();
}
time_t PreProcessUtils::GetTimeStamp()
{
std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp =
std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
time_t timestamp = tp.time_since_epoch().count();
return timestamp;
}
bool PreProcessUtils::GetHapBundleNameByToken(int tokenId, std::string &bundleName)
{
Security::AccessToken::HapTokenInfo hapInfo;
if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, hapInfo)
!= Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) {
return false;
}
bundleName = hapInfo.bundleName;
return true;
}
bool PreProcessUtils::GetNativeProcessNameByToken(int tokenId, std::string &processName)
{
Security::AccessToken::NativeTokenInfo nativeInfo;
if (Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeInfo)
!= Security::AccessToken::AccessTokenKitRet::RET_SUCCESS) {
return false;
}
processName = nativeInfo.processName;
return true;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2023 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 UDMF_PREPROCESS_UTILS_H
#define UDMF_PREPROCESS_UTILS_H
#include <bitset>
#include <random>
#include <string>
#include <vector>
#include "unified_data.h"
#include "unified_meta.h"
namespace OHOS {
namespace UDMF {
class PreProcessUtils {
public:
static int32_t RuntimeDataImputation(UnifiedData &data, CustomOption &option);
static std::string IdGenerator();
static time_t GetTimeStamp();
static bool GetHapBundleNameByToken(int tokenId, std::string &bundleName);
static bool GetNativeProcessNameByToken(int tokenId, std::string &processName);
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_PREPROCESS_UTILS_H

View File

@ -0,0 +1,43 @@
/*
* Copyright (c) 2023 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 UDMF_SAMEPROCESSIPCGUARD_H
#define UDMF_SAMEPROCESSIPCGUARD_H
#include <string>
#include "ipc_skeleton.h"
namespace OHOS {
namespace UDMF {
class SameProcessIpcGuard {
public:
SameProcessIpcGuard()
{
identity = IPCSkeleton::ResetCallingIdentity();
}
~SameProcessIpcGuard()
{
IPCSkeleton::SetCallingIdentity(identity);
}
private:
std::string identity;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_SAMEPROCESSIPCGUARD_H

View File

@ -0,0 +1,313 @@
/*
* Copyright (c) 2023 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 "RuntimeStore"
#include "runtime_store.h"
#include <algorithm>
#include <vector>
#include "log_print.h"
#include "same_process_ipc_guard.h"
#include "tlv_util.h"
namespace OHOS {
namespace UDMF {
using namespace DistributedKv;
const AppId RuntimeStore::APP_ID = { "distributeddata" };
const std::string RuntimeStore::DATA_PREFIX = "udmf://";
const std::string RuntimeStore::BASE_DIR = "/data/service/el1/public/database/distributeddata";
RuntimeStore::RuntimeStore(const std::string &storeId) : storeId_({ storeId })
{
updateTime();
ZLOGI("Construct runtimeStore: %{public}s.", storeId_.storeId.c_str());
}
RuntimeStore::~RuntimeStore()
{
ZLOGI("Destruct runtimeStore: %{public}s.", storeId_.storeId.c_str());
Close();
}
Status RuntimeStore::Put(const UnifiedData &unifiedData)
{
updateTime();
std::vector<Entry> entries;
std::string unifiedKey = unifiedData.GetRuntime()->key.GetUnifiedKey();
// add unified record
for (const auto &record : unifiedData.GetRecords()) {
if (record == nullptr) {
ZLOGE("record is nullptr.");
return E_INVALID_PARAMETERS;
}
std::vector<uint8_t> recordBytes;
auto recordTlv = TLVObject(recordBytes);
if (!TLVUtil::Writing(record, recordTlv)) {
ZLOGI("Marshall unified record failed.");
return E_WRITE_PARCEL_ERROR;
}
Entry entry = { Key(unifiedKey + "/" + record->GetUid()), Value(recordBytes) };
entries.push_back(entry);
}
// add runtime info
std::vector<uint8_t> runtimeBytes;
auto runtimeTlv = TLVObject(runtimeBytes);
if (!TLVUtil::Writing(*unifiedData.GetRuntime(), runtimeTlv)) {
ZLOGI("Marshall runtime info failed.");
return E_WRITE_PARCEL_ERROR;
}
Entry entry = { Key(unifiedKey), Value(runtimeBytes) };
entries.push_back(entry);
auto status = PutEntries(entries);
return status;
}
Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData)
{
updateTime();
std::vector<Entry> entries;
if (GetEntries(key, entries) != E_OK) {
ZLOGI("GetEntries failed, dataPrefix: %{public}s.", key.c_str());
return E_DB_ERROR;
}
if (entries.empty()) {
ZLOGD("entries is empty.");
return E_OK;
}
return UnMarshalEntries(key, entries, unifiedData);
}
Status RuntimeStore::GetSummary(const std::string &key, Summary &summary)
{
updateTime();
UnifiedData unifiedData;
if (Get(key, unifiedData) != E_OK) {
ZLOGE("Get unified data failed.");
return E_DB_ERROR;
}
for (const auto &record : unifiedData.GetRecords()) {
int64_t recordSize = record->GetSize();
auto it = summary.summary.find(UD_TYPE_MAP.at(record->GetType()));
if (it == summary.summary.end()) {
summary.summary[UD_TYPE_MAP.at(record->GetType())] = recordSize;
} else {
summary.summary[UD_TYPE_MAP.at(record->GetType())] += recordSize;
}
summary.totalSize += recordSize;
}
return E_OK;
}
Status RuntimeStore::Update(const UnifiedData &unifiedData)
{
updateTime();
std::string key = unifiedData.GetRuntime()->key.key;
if (Delete(key) != E_OK) {
ZLOGE("Delete unified data failed.");
return E_DB_ERROR;
}
if (Put(unifiedData) != E_OK) {
ZLOGE("Put unified data failed.");
return E_DB_ERROR;
}
return E_OK;
}
Status RuntimeStore::Delete(const std::string &key)
{
updateTime();
std::vector<Entry> entries;
if (GetEntries(key, entries) != E_OK) {
ZLOGE("GetEntries failed, dataPrefix: %{public}s.", key.c_str());
return E_DB_ERROR;
}
if (entries.empty()) {
ZLOGD("entries is empty.");
return E_OK;
}
std::vector<Key> keys;
for (const auto &entry : entries) {
keys.push_back(entry.key);
}
return DeleteEntries(keys);
}
Status RuntimeStore::DeleteBatch(const std::vector<std::string> &unifiedKeys)
{
updateTime();
ZLOGD("called!");
if (unifiedKeys.empty()) {
ZLOGD("No need to delete!");
return E_OK;
}
for (const std::string &unifiedKey : unifiedKeys) {
if (Delete(unifiedKey) != E_OK) {
ZLOGE("Delete failed, key: %{public}s.", unifiedKey.c_str());
return E_DB_ERROR;
}
}
return E_OK;
}
Status RuntimeStore::Sync(const std::vector<std::string> &devices)
{
updateTime();
SameProcessIpcGuard ipcGuard;
DistributedKv::Status status = kvStore_->Sync(devices, SyncMode::PULL);
if (status != DistributedKv::Status::SUCCESS) {
ZLOGE("Sync kvStore failed, status: %{public}d.", status);
return E_DB_ERROR;
}
return E_OK;
}
Status RuntimeStore::Clear()
{
updateTime();
return Delete(DATA_PREFIX);
}
Status RuntimeStore::GetBatchData(const std::string &dataPrefix, std::vector<UnifiedData> &unifiedDataSet)
{
updateTime();
std::vector<Entry> entries;
auto status = GetEntries(dataPrefix, entries);
if (status != E_OK) {
ZLOGE("GetEntries failed, dataPrefix: %{public}s.", dataPrefix.c_str());
return E_DB_ERROR;
}
if (entries.empty()) {
ZLOGD("entries is empty.");
return E_OK;
}
std::vector<std::string> keySet;
for (const auto &entry : entries) {
std::string keyStr = entry.key.ToString();
if (std::count(keyStr.begin(), keyStr.end(), '/') == SLASH_COUNT_IN_KEY) {
keySet.emplace_back(keyStr);
}
}
for (const std::string &key : keySet) {
UnifiedData data;
if (UnMarshalEntries(key, entries, data) != E_OK) {
return E_READ_PARCEL_ERROR;
}
unifiedDataSet.emplace_back(data);
}
return E_OK;
}
void RuntimeStore::Close()
{
dataManager_.CloseKvStore(APP_ID, storeId_);
}
bool RuntimeStore::Init()
{
Options options;
options.autoSync = false;
options.createIfMissing = true;
options.rebuild = true;
options.backup = false;
options.securityLevel = SecurityLevel::S1;
options.baseDir = BASE_DIR;
options.area = Area::EL1;
options.kvStoreType = KvStoreType::SINGLE_VERSION;
SameProcessIpcGuard ipcGuard;
DistributedKv::Status status = dataManager_.GetSingleKvStore(options, APP_ID, storeId_, kvStore_);
if (status != DistributedKv::Status::SUCCESS) {
ZLOGE("GetKvStore: %{public}s failed, status: %{public}d.", storeId_.storeId.c_str(), status);
return false;
}
return true;
}
Status RuntimeStore::GetEntries(const std::string &dataPrefix, std::vector<Entry> &entries)
{
DataQuery query;
query.KeyPrefix(dataPrefix);
query.OrderByWriteTime(true);
auto status = kvStore_->GetEntries(query, entries);
if (status != DistributedKv::Status::SUCCESS) {
ZLOGE("KvStore getEntries failed, status: %{public}d.", static_cast<int>(status));
return E_DB_ERROR;
}
return E_OK;
}
Status RuntimeStore::PutEntries(const std::vector<Entry> &entries)
{
size_t size = entries.size();
DistributedKv::Status status;
for (size_t index = 0; index < size; index += MAX_BATCH_SIZE) {
std::vector<Entry> batchEntries(
entries.begin() + index, entries.begin() + std::min(index + MAX_BATCH_SIZE, size));
status = kvStore_->PutBatch(batchEntries);
if (status != DistributedKv::Status::SUCCESS) {
ZLOGE("KvStore putBatch failed, status: %{public}d.", status);
return E_DB_ERROR;
}
}
return E_OK;
}
Status RuntimeStore::DeleteEntries(const std::vector<Key> &keys)
{
size_t size = keys.size();
DistributedKv::Status status;
for (size_t index = 0; index < size; index += MAX_BATCH_SIZE) {
std::vector<Key> batchKeys(keys.begin() + index, keys.begin() + std::min(index + MAX_BATCH_SIZE, size));
status = kvStore_->DeleteBatch(batchKeys);
if (status != DistributedKv::Status::SUCCESS) {
ZLOGE("KvStore deleteBatch failed, status: %{public}d.", status);
return E_DB_ERROR;
}
}
return E_OK;
}
Status RuntimeStore::UnMarshalEntries(const std::string &key, std::vector<Entry> &entries, UnifiedData &unifiedData)
{
for (const auto &entry : entries) {
std::string keyStr = entry.key.ToString();
if (keyStr == key) {
Runtime runtime;
auto runtimeTlv = TLVObject(const_cast<std::vector<uint8_t> &>(entry.value.Data()));
if (!TLVUtil::Reading(runtime, runtimeTlv)) {
ZLOGE("Unmarshall runtime info failed.");
return E_READ_PARCEL_ERROR;
}
unifiedData.SetRuntime(runtime);
break;
}
if (keyStr.find(key) == 0) {
std::shared_ptr<UnifiedRecord> record;
auto recordTlv = TLVObject(const_cast<std::vector<uint8_t> &>(entry.value.Data()));
if (!TLVUtil::Reading(record, recordTlv)) {
ZLOGE("Unmarshall unified record failed.");
return E_READ_PARCEL_ERROR;
}
unifiedData.AddRecord(record);
}
}
return E_OK;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,59 @@
/*
* Copyright (c) 2023 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 UDMF_RUNTIMESTORE_H
#define UDMF_RUNTIMESTORE_H
#include "distributed_kv_data_manager.h"
#include "single_kvstore.h"
#include "store.h"
namespace OHOS {
namespace UDMF {
class RuntimeStore final : public Store {
public:
explicit RuntimeStore(const std::string &storeId);
~RuntimeStore();
Status Put(const UnifiedData &unifiedData) override;
Status Get(const std::string &key, UnifiedData &unifiedData) override;
Status GetSummary(const std::string &key, Summary &summary) override;
Status Update(const UnifiedData &unifiedData) override;
Status Delete(const std::string &key) override;
Status DeleteBatch(const std::vector<std::string> &unifiedKeys) override;
Status Sync(const std::vector<std::string> &devices) override;
Status Clear() override;
Status GetBatchData(const std::string &dataPrefix, std::vector<UnifiedData> &unifiedDataSet) override;
void Close() override;
bool Init() override;
private:
static const DistributedKv::AppId APP_ID;
static const std::string DATA_PREFIX;
static const std::string BASE_DIR;
static constexpr std::int32_t SLASH_COUNT_IN_KEY = 4;
static constexpr std::int32_t MAX_BATCH_SIZE = 128;
DistributedKv::DistributedKvDataManager dataManager_;
std::shared_ptr<DistributedKv::SingleKvStore> kvStore_;
DistributedKv::StoreId storeId_;
Status GetEntries(const std::string &dataPrefix, std::vector<DistributedKv::Entry> &entries);
Status PutEntries(const std::vector<DistributedKv::Entry> &entries);
Status DeleteEntries(const std::vector<DistributedKv::Key> &keys);
Status UnMarshalEntries(
const std::string &key, std::vector<DistributedKv::Entry> &entries, UnifiedData &unifiedData);
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_RUNTIMESTORE_H

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2023 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 UDMF_STORE_H
#define UDMF_STORE_H
#include <string>
#include <shared_mutex>
#include "error_code.h"
#include "unified_data.h"
#include "unified_key.h"
#include "unified_types.h"
namespace OHOS {
namespace UDMF {
class Store {
public:
using Time = std::chrono::steady_clock::time_point;
virtual Status Put(const UnifiedData &unifiedData) = 0;
virtual Status Get(const std::string &key, UnifiedData &unifiedData) = 0;
virtual Status GetSummary(const std::string &key, Summary &summary) = 0;
virtual Status Update(const UnifiedData &unifiedData) = 0;
virtual Status Delete(const std::string &key) = 0;
virtual Status DeleteBatch(const std::vector<std::string> &unifiedKeys) = 0;
virtual Status Sync(const std::vector<std::string> &devices) = 0;
virtual Status Clear() = 0;
virtual bool Init() = 0;
virtual void Close() = 0;
virtual Status GetBatchData(const std::string &dataPrefix, std::vector<UnifiedData> &unifiedDataSet) = 0;
bool operator<(const Time &time) const
{
std::shared_lock<decltype(timeMutex_)> lock(timeMutex_);
return time_ < time;
}
void updateTime()
{
std::unique_lock<std::shared_mutex> lock(timeMutex_);
time_ = std::chrono::steady_clock::now() + std::chrono::minutes(INTERVAL);
}
private:
static constexpr int64_t INTERVAL = 1; // 1 min
mutable Time time_;
mutable std::shared_mutex timeMutex_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_STORE_H

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2023 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 "StoreCache"
#include "store_cache.h"
#include <chrono>
#include "log_print.h"
#include "runtime_store.h"
#include "unified_meta.h"
namespace OHOS {
namespace UDMF {
std::shared_ptr<ExecutorPool> StoreCache::executorPool_ = std::make_shared<ExecutorPool>(2, 1);
std::shared_ptr<Store> StoreCache::GetStore(std::string intention)
{
std::shared_ptr<Store> store;
stores_.Compute(intention, [&store](const auto &intention, std::shared_ptr<Store> &storePtr) -> bool {
if (storePtr != nullptr) {
store = storePtr;
return true;
}
if (intention == UD_INTENTION_MAP.at(UD_INTENTION_DRAG)
|| intention == UD_INTENTION_MAP.at(UD_INTENTION_DATA_HUB)) {
storePtr = std::make_shared<RuntimeStore>(intention);
if (!storePtr->Init()) {
ZLOGE("Init runtime store failed.");
return false;
}
store = storePtr;
return true;
}
return false;
});
std::unique_lock<std::mutex> lock(taskMutex_);
if (taskId_ == ExecutorPool::INVALID_TASK_ID) {
taskId_ = executorPool_->Schedule(std::chrono::minutes(INTERVAL), std::bind(&StoreCache::GarbageCollect, this));
}
return store;
}
void StoreCache::GarbageCollect()
{
auto current = std::chrono::steady_clock::now();
stores_.EraseIf([&current](auto &key, std::shared_ptr<Store> &storePtr) {
if (*storePtr < current) {
ZLOGD("GarbageCollect, stores:%{public}s time limit, will be close.", key.c_str());
return true;
}
return false;
});
std::unique_lock<std::mutex> lock(taskMutex_);
if (!stores_.Empty()) {
ZLOGE("GarbageCollect, stores size:%{public}zu", stores_.Size());
taskId_ = executorPool_->Schedule(std::chrono::minutes(INTERVAL), std::bind(&StoreCache::GarbageCollect, this));
} else {
taskId_ = ExecutorPool::INVALID_TASK_ID;
}
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,45 @@
/*
* Copyright (c) 2023 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 UDMF_STORE_CACHE_H
#define UDMF_STORE_CACHE_H
#include <memory>
#include <mutex>
#include "concurrent_map.h"
#include "executor_pool.h"
#include "store.h"
#include "unified_meta.h"
namespace OHOS {
namespace UDMF {
class StoreCache {
public:
std::shared_ptr<Store> GetStore(std::string intention);
private:
void GarbageCollect();
ConcurrentMap<std::string, std::shared_ptr<Store>> stores_;
std::mutex taskMutex_;
ExecutorPool::TaskId taskId_ = ExecutorPool::INVALID_TASK_ID;
static constexpr int64_t INTERVAL = 1; // 1 min
static std::shared_ptr<ExecutorPool> executorPool_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_STORE_CACHE_H

View File

@ -0,0 +1,108 @@
/*
* 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.
*/
#define LOG_TAG "UdmfServiceImpl"
#include "udmf_service_impl.h"
#include "iservice_registry.h"
#include "data_manager.h"
#include "lifecycle/lifecycle_manager.h"
#include "log_print.h"
#include "preprocess_utils.h"
namespace OHOS {
namespace UDMF {
using FeatureSystem = DistributedData::FeatureSystem;
__attribute__((used)) UdmfServiceImpl::Factory UdmfServiceImpl::factory_;
UdmfServiceImpl::Factory::Factory()
{
ZLOGI("Register udmf creator!");
FeatureSystem::GetInstance().RegisterCreator("udmf", [this]() {
if (product_ == nullptr) {
product_ = std::make_shared<UdmfServiceImpl>();
}
return product_;
});
}
UdmfServiceImpl::Factory::~Factory()
{
product_ = nullptr;
}
int32_t UdmfServiceImpl::SetData(CustomOption &option, UnifiedData &unifiedData, std::string &key)
{
ZLOGD("start");
return DataManager::GetInstance().SaveData(option, unifiedData, key);
}
int32_t UdmfServiceImpl::GetData(const QueryOption &query, UnifiedData &unifiedData)
{
ZLOGD("start");
return DataManager::GetInstance().RetrieveData(query, unifiedData);
}
int32_t UdmfServiceImpl::GetBatchData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet)
{
ZLOGD("start");
return DataManager::GetInstance().RetrieveBatchData(query, unifiedDataSet);
}
int32_t UdmfServiceImpl::UpdateData(const QueryOption &query, UnifiedData &unifiedData)
{
ZLOGD("start");
return DataManager::GetInstance().UpdateData(query, unifiedData);
}
int32_t UdmfServiceImpl::DeleteData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet)
{
ZLOGD("start");
return DataManager::GetInstance().DeleteData(query, unifiedDataSet);
}
int32_t UdmfServiceImpl::GetSummary(const QueryOption &query, Summary &summary)
{
ZLOGD("start");
return DataManager::GetInstance().GetSummary(query, summary);
}
int32_t UdmfServiceImpl::AddPrivilege(const QueryOption &query, Privilege &privilege)
{
ZLOGD("start");
return DataManager::GetInstance().AddPrivilege(query, privilege);
}
int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vector<std::string> &devices)
{
ZLOGD("start");
return DataManager::GetInstance().Sync(query, devices);
}
int32_t UdmfServiceImpl::OnInitialize()
{
ZLOGD("start");
Status status = LifeCycleManager::GetInstance().DeleteOnStart();
if (status != E_OK) {
ZLOGE("DeleteOnStart execute failed, status: %{public}d", status);
}
status = LifeCycleManager::GetInstance().DeleteOnSchedule();
if (status != E_OK) {
ZLOGE("ScheduleTask start failed, status: %{public}d", status);
}
return DistributedData::FeatureSystem::STUB_SUCCESS;
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,56 @@
/*
* 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 UDMF_SERVICE_IMPL_H
#define UDMF_SERVICE_IMPL_H
#include <vector>
#include "udmf_service_stub.h"
namespace OHOS {
namespace UDMF {
/*
* UDMF server implementation
*/
class UdmfServiceImpl final : public UdmfServiceStub {
public:
UdmfServiceImpl() = default;
~UdmfServiceImpl() = default;
int32_t SetData(CustomOption &option, UnifiedData &unifiedData, std::string &key) override;
int32_t GetData(const QueryOption &query, UnifiedData &unifiedData) override;
int32_t GetBatchData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet) override;
int32_t UpdateData(const QueryOption &query, UnifiedData &unifiedData) override;
int32_t DeleteData(const QueryOption &query, std::vector<UnifiedData> &unifiedDataSet) override;
int32_t GetSummary(const QueryOption &query, Summary &summary) override;
int32_t AddPrivilege(const QueryOption &query, Privilege &privilege) override;
int32_t Sync(const QueryOption &query, const std::vector<std::string> &devices) override;
int32_t OnInitialize() override;
private:
class Factory {
public:
Factory();
~Factory();
private:
std::shared_ptr<UdmfServiceImpl> product_;
};
static Factory factory_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_SERVICE_IMPL_H

View File

@ -0,0 +1,269 @@
/*
* Copyright (c) 2023 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 "UdmfServiceStub"
#include "udmf_service_stub.h"
#include <vector>
#include "accesstoken_kit.h"
#include "ipc_skeleton.h"
#include "log_print.h"
#include "udmf_types_util.h"
#include "unified_data.h"
#include "unified_meta.h"
namespace OHOS {
namespace UDMF {
UdmfServiceStub::UdmfServiceStub()
{
memberFuncMap_[static_cast<uint32_t>(SET_DATA)] = &UdmfServiceStub::OnSetData;
memberFuncMap_[static_cast<uint32_t>(GET_DATA)] = &UdmfServiceStub::OnGetData;
memberFuncMap_[static_cast<uint32_t>(GET_BATCH_DATA)] = &UdmfServiceStub::OnGetBatchData;
memberFuncMap_[static_cast<uint32_t>(UPDATE_DATA)] = &UdmfServiceStub::OnUpdateData;
memberFuncMap_[static_cast<uint32_t>(DELETE_DATA)] = &UdmfServiceStub::OnDeleteData;
memberFuncMap_[static_cast<uint32_t>(GET_SUMMARY)] = &UdmfServiceStub::OnGetSummary;
memberFuncMap_[static_cast<uint32_t>(ADD_PRIVILEGE)] = &UdmfServiceStub::OnAddPrivilege;
memberFuncMap_[static_cast<uint32_t>(SYNC)] = &UdmfServiceStub::OnSync;
}
UdmfServiceStub::~UdmfServiceStub()
{
memberFuncMap_.clear();
}
int UdmfServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start##code = %{public}u", code);
std::u16string myDescripter = UdmfServiceStub::GetDescriptor();
std::u16string remoteDescripter = data.ReadInterfaceToken();
if (myDescripter != remoteDescripter) {
ZLOGE("end##descriptor checked fail");
return -1;
}
if (CODE_HEAD > code || code >= CODE_BUTT) {
return -1;
}
auto itFunc = memberFuncMap_.find(code);
if (itFunc != memberFuncMap_.end()) {
auto memberFunc = itFunc->second;
if (memberFunc != nullptr) {
return (this->*memberFunc)(data, reply);
}
}
ZLOGI("end##ret = -1");
return -1;
}
int32_t UdmfServiceStub::OnSetData(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
CustomOption customOption;
UnifiedData unifiedData;
if (!ITypesUtil::Unmarshal(data, customOption, unifiedData)) {
ZLOGE("Unmarshal customOption or unifiedData failed!");
return E_READ_PARCEL_ERROR;
}
if (unifiedData.IsEmpty()) {
ZLOGE("Empty data without any record!");
return E_INVALID_PARAMETERS;
}
if (unifiedData.GetSize() > UdmfService::MAX_DATA_SIZE) {
ZLOGE("Exceeded data limit!");
return E_INVALID_PARAMETERS;
}
for (const auto &record : unifiedData.GetRecords()) {
if (record == nullptr) {
ZLOGE("record is nullptr!");
return E_INVALID_PARAMETERS;
}
if (record->GetSize() > UdmfService::MAX_RECORD_SIZE) {
ZLOGE("Exceeded record limit!");
return E_INVALID_PARAMETERS;
}
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
customOption.tokenId = token;
std::string key;
int32_t status = SetData(customOption, unifiedData, key);
if (!ITypesUtil::Marshal(reply, status, key)) {
ZLOGE("Marshal status or key failed, status: %{public}d, key: %{public}s", status, key.c_str());
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
int32_t UdmfServiceStub::OnGetData(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
QueryOption query;
if (!ITypesUtil::Unmarshal(data, query)) {
ZLOGE("Unmarshal queryOption failed!");
return E_READ_PARCEL_ERROR;
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
query.tokenId = token;
UnifiedData unifiedData;
int32_t status = GetData(query, unifiedData);
if (!ITypesUtil::Marshal(reply, status, unifiedData)) {
ZLOGE("Marshal status or unifiedData failed, status: %{public}d", status);
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
int32_t UdmfServiceStub::OnGetBatchData(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
QueryOption query;
if (!ITypesUtil::Unmarshal(data, query)) {
ZLOGE("Unmarshal queryOption failed!");
return E_READ_PARCEL_ERROR;
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
query.tokenId = token;
std::vector<UnifiedData> unifiedDataSet;
int32_t status = GetBatchData(query, unifiedDataSet);
if (!ITypesUtil::Marshal(reply, status, unifiedDataSet)) {
ZLOGE("Marshal status or unifiedDataSet failed, status: %{public}d", status);
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
int32_t UdmfServiceStub::OnUpdateData(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
QueryOption query;
UnifiedData unifiedData;
if (!ITypesUtil::Unmarshal(data, query, unifiedData)) {
ZLOGE("Unmarshal queryOption or unifiedData failed!");
return E_READ_PARCEL_ERROR;
}
if (unifiedData.IsEmpty()) {
ZLOGE("Empty data without any record!");
return E_INVALID_PARAMETERS;
}
if (unifiedData.GetSize() > UdmfService::MAX_DATA_SIZE) {
ZLOGE("Exceeded data limit!");
return E_INVALID_PARAMETERS;
}
for (const auto &record : unifiedData.GetRecords()) {
if (record->GetSize() > UdmfService::MAX_RECORD_SIZE) {
ZLOGE("Exceeded record limit!");
return E_INVALID_PARAMETERS;
}
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
query.tokenId = token;
int32_t status = UpdateData(query, unifiedData);
if (!ITypesUtil::Marshal(reply, status)) {
ZLOGE("Marshal status failed, status: %{public}d", status);
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
int32_t UdmfServiceStub::OnDeleteData(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
QueryOption query;
if (!ITypesUtil::Unmarshal(data, query)) {
ZLOGE("Unmarshal queryOption failed!");
return E_READ_PARCEL_ERROR;
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
query.tokenId = token;
std::vector<UnifiedData> unifiedDataSet;
int32_t status = DeleteData(query, unifiedDataSet);
if (!ITypesUtil::Marshal(reply, status, unifiedDataSet)) {
ZLOGE("Marshal status or unifiedDataSet failed, status: %{public}d", status);
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
int32_t UdmfServiceStub::OnGetSummary(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
QueryOption query;
if (!ITypesUtil::Unmarshal(data, query)) {
ZLOGE("Unmarshal query failed");
return E_READ_PARCEL_ERROR;
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
query.tokenId = token;
Summary summary;
int32_t status = GetSummary(query, summary);
if (!ITypesUtil::Marshal(reply, status, summary)) {
ZLOGE("Marshal summary failed, key: %{public}s", query.key.c_str());
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
int32_t UdmfServiceStub::OnAddPrivilege(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
QueryOption query;
Privilege privilege;
if (!ITypesUtil::Unmarshal(data, query, privilege)) {
ZLOGE("Unmarshal query and privilege failed");
return E_READ_PARCEL_ERROR;
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
query.tokenId = token;
int32_t status = AddPrivilege(query, privilege);
if (!ITypesUtil::Marshal(reply, status)) {
ZLOGE("Marshal status failed, key: %{public}s", query.key.c_str());
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
int32_t UdmfServiceStub::OnSync(MessageParcel &data, MessageParcel &reply)
{
ZLOGI("start");
QueryOption query;
std::vector<std::string> devices;
if (!ITypesUtil::Unmarshal(data, query, devices)) {
ZLOGE("Unmarshal query and devices failed");
return E_READ_PARCEL_ERROR;
}
uint32_t token = static_cast<uint32_t>(IPCSkeleton::GetCallingTokenID());
query.tokenId = token;
int32_t status = Sync(query, devices);
if (!ITypesUtil::Marshal(reply, status)) {
ZLOGE("Marshal status failed, key: %{public}s", query.key.c_str());
return E_WRITE_PARCEL_ERROR;
}
return E_OK;
}
/*
* Check whether the caller has the permission to access data.
*/
bool UdmfServiceStub::VerifyPermission(const std::string &permission)
{
#ifdef UDMF_PERMISSION_ENABLED
uint32_t tokenId = IPCSkeleton::GetCallingTokenID();
int32_t result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, permission);
return result == Security::AccessToken::TypePermissionState::PERMISSION_GRANTED;
#else
return true;
#endif // UDMF_PERMISSION_ENABLED
}
} // namespace UDMF
} // namespace OHOS

View File

@ -0,0 +1,60 @@
/*
* Copyright (c) 2023 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 UDMF_SERVICE_STUB_H
#define UDMF_SERVICE_STUB_H
#include <map>
#include <string>
#include "feature/feature_system.h"
#include "message_parcel.h"
#include "error_code.h"
#include "udmf_service.h"
namespace OHOS {
namespace UDMF {
/*
* UDMF server stub
*/
class UdmfServiceStub : public UdmfService, public DistributedData::FeatureSystem::Feature {
public:
UdmfServiceStub();
virtual ~UdmfServiceStub() override;
int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply) override;
private:
int32_t OnSetData(MessageParcel &data, MessageParcel &reply);
int32_t OnGetData(MessageParcel &data, MessageParcel &reply);
int32_t OnGetBatchData(MessageParcel &data, MessageParcel &reply);
int32_t OnUpdateData(MessageParcel &data, MessageParcel &reply);
int32_t OnDeleteData(MessageParcel &data, MessageParcel &reply);
int32_t OnGetSummary(MessageParcel &data, MessageParcel &reply);
int32_t OnAddPrivilege(MessageParcel &data, MessageParcel &reply);
int32_t OnSync(MessageParcel &data, MessageParcel &reply);
bool VerifyPermission(const std::string &permission);
const std::string READ_PERMISSION = "ohos.permission.READ_UDMF_DATA";
const std::string WRITE_PERMISSION = "ohos.permission.WRITE_UDMF_DATA";
const std::string SYNC_PERMISSION = "ohos.permission.SYNC_UDMF_DATA";
using UdmfServiceFunc = int32_t (UdmfServiceStub::*)(MessageParcel &data, MessageParcel &reply);
std::map<uint32_t, UdmfServiceFunc> memberFuncMap_;
};
} // namespace UDMF
} // namespace OHOS
#endif // UDMF_SERVICE_STUB_H