diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md
index a76fddfde304eb5067aa7e0e386707e83fcbdf79..648f36643af9043975f033adb2689131176c165a 100755
--- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md
+++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md
@@ -7,4 +7,57 @@
* **FUZZ**:Pass/Fail/NA
* **ACTS**:Pass/Fail/NA
* **DCTS**:Pass/Fail/NA
-* **DST**:Pass/Fail/NA
\ No newline at end of file
+* **DST**:Pass/Fail/NA
+
+### 稳定性排查:
+- [ ] 【规则】禁止在锁内向其他进程发送IPC(进程间通信);
+- [ ] 【规则】禁止将捕获**栈变量引用**的lambda函数**异步到其他线程执行**;
+- [ ] 【规则】禁止传递this指针至其他模块或线程(特别是eventhandler任务);
+- [ ] 【规则】禁止存储string的c_str()方法获取到的指针;
+- [ ] 【规则】成员变量进行赋值或创建需要排查并发;
+- [ ] 【规则】谨慎在未经拷贝的情况下使用外部传入的string、C字符串;
+- [ ] 【规则】map\vector\list\set等stl模板类使用时需要排查并发;
+- [ ] 【规则】谨慎考虑加锁范围,尽可能的小范围加锁;
+- [ ] 【规则】在IPC通信中谨慎使用同步通信方式;
+- [ ] 【规则】禁止将外部传入的裸指针在内部直接构造智能指针;
+- [ ] 【规则】禁止多个独立创建的智能指针管理同一地址;
+- [ ] 【规则】禁止在析构函数中抛异步任务;
+- [ ] 【规则】禁止js对象在非js线程(例如在IPC线程)创建、使用或销毁;
+- [ ] 【规则】禁止在对外接口中未经判空直接使用外部传入的指针;
+- [ ] 【规则】监听回调要确保,回调触发和取消注册并发时无生命周期问题;
+- [ ] 【规则】遍历容器进行删除或插入时注意迭代器失效问题;
+
+### 日志打印排查:
+- [ ] 【规则】禁止打印内存地址,如:%p;
+- [ ] 【规则】禁止打印密钥、文件路径、数据库名称、udidhash、设备名称、账号id等敏感信息;
+- [ ] 【规则】禁止不作匿名化直接打印udid/networkid/uuid/ip/mac等敏感信息;
+- [ ] 【规则】非必要不要在循环内打印日志,防止日志超限;
+
+### 安全编码自检:
+- [ ] 【内存管理】内存申请前必须对内存大小进行合法性校验;
+- [ ] 【内存管理】内存申请后必须判空,判断内存申请是否成功;
+- [ ] 【内存管理】分配和释放内存(or fd等资源)的函数需要成对出现;
+- [ ] 【内存管理】申请内存后异常退出前需要及时进行内存释放;
+- [ ] 【内存管理】禁止使用realloc、alloca函数;
+- [ ] 【内存管理】strdup使用需要注意内存释放;
+- [ ] 【内存管理】正则表达式构造后需释放资源,regcomp/regexec与regfree必须成对使用;
+- [ ] 【内存管理】realpath使用时如果resolved_path为NULL需要注意内存释放;
+- [ ] 【外部输入校验】外部传入的路径要做规范化校验,对路径中的.、..、../等特殊字符严格校验;
+- [ ] 【外部输入校验】按TLV格式解析时需校验解析长度值是否小于等于缓冲区实际值,并校验是否符合业务数据范围;
+- [ ] 【外部输入校验】解析数据后拷贝时需校验源buffer实际缓冲区大小,避免越界读写;
+- [ ] 【外部输入校验】使用外部输入作为循环变量时,需要校验循环变量上限是否合理,防止出现超大循环;
+- [ ] 【外部输入校验】禁止直接使用外部输入作为数组下标,防止出现内存越界;
+- [ ] 【敏感信息】堆、栈中保存密钥、口令(包括加密后的变量)变量使用完后必须显式覆盖或清空;
+- [ ] 【加密算法】禁止使用私有加密算法或不安全加密算法;
+- [ ] 【变量初始化】指针变量、表示资源描述符的变量、bool变量必须赋初值;
+- [ ] 【指针】IPC流程中ReadCString、ReadRawData、readParcelable等结果必须判空;
+- [ ] 【整数运算】整数之间运算时必须严格检查,确保不会出现溢出、反转、除0;
+- [ ] 【整数运算】禁止对有符号整数进行位操作符运算;
+- [ ] 【循环变量】循环次数如果受外部数据控制,需要检验其合法性;
+- [ ] 【循环变量】循环变量和中止条件的数据类型定义保持一致;
+- [ ] 【安全函数】安全函数必须检查返回值,并进行正确处理;
+- [ ] 【安全函数】安全函数目标缓冲区入参大小与目标缓冲区实际大小必须一致;
+- [ ] 【安全函数】禁止封装或者自定义安全函数;
+- [ ] 【常见问题】修改单个函数时,如果涉及新增异常返回分支,必须排查是否需要释放锁、内存、fd等资源;
+- [ ] 【常见问题】函数返回值需与函数签名相同,参数定义需在同一范畴(不能定义bool,返回int32_t),或同一枚举类型;
+- [ ] 【常见问题】格式化打印类型需匹配,例如:int32_t %d; uint32_t %u; long %ld; unsigned long %lu; long long PRId64;
unsigned long long PRIu64;
diff --git a/bundle.json b/bundle.json
index b1a8472dba866d162bf31c03216e699c14086ab1..e80707c82fe8af9d23e8d659598542202d669afc 100644
--- a/bundle.json
+++ b/bundle.json
@@ -81,6 +81,7 @@
"napi",
"netmanager_base",
"os_account",
+ "qos_manager",
"relational_store",
"resource_management",
"safwk",
diff --git a/cfi_blocklist.txt b/cfi_blocklist.txt
new file mode 100644
index 0000000000000000000000000000000000000000..89d302fdc73f6ae208a1956ed722e5016e548e3e
--- /dev/null
+++ b/cfi_blocklist.txt
@@ -0,0 +1,16 @@
+# Copyright (C) 2025 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.
+
+[cfi]
+src:*third_party/googletest/googlemock/include/gmock/*
+src:*third_party/googletest/googletest/include/gtest/*
\ No newline at end of file
diff --git a/datamgr_service.gni b/datamgr_service.gni
index da3e7a494d5e4474f2f5e30387cab6d3a8465cfd..7b327ccea5c69ef499da3dbd5991d35f004b2ed9 100644
--- a/datamgr_service.gni
+++ b/datamgr_service.gni
@@ -38,6 +38,8 @@ udmf_path = "//foundation/distributeddatamgr/udmf"
dataobject_path = "//foundation/distributeddatamgr/data_object"
+datamgr_service_path = "//foundation/distributeddatamgr/datamgr_service"
+
declare_args() {
datamgr_service_power = true
if (!defined(global_parts_info.power_manager_native_powermgr_client) ||
diff --git a/services/distributeddataservice/adapter/account/test/BUILD.gn b/services/distributeddataservice/adapter/account/test/BUILD.gn
index 9986137426b1f9c53b81c2b29cbc4caa239409db..39c09ee550b4fef1467c7acf6d978b25fc53b72d 100755
--- a/services/distributeddataservice/adapter/account/test/BUILD.gn
+++ b/services/distributeddataservice/adapter/account/test/BUILD.gn
@@ -12,7 +12,7 @@
# limitations under the License.
import("//build/test.gni")
import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni")
-module_output_path = "datamgr_service/distributeddatafwk"
+module_output_path = "datamgr_service/datamgr_service/distributeddatafwk"
###############################################################################
ohos_unittest("AccountDelegateTest") {
diff --git a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp
index b9b0078f6d5f718b9d66135bb3c7ea8d28d5c678..817824732148815ffdf85897b8b23e59a58eb449 100644
--- a/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp
+++ b/services/distributeddataservice/adapter/communicator/src/device_manager_adapter.cpp
@@ -263,8 +263,9 @@ void DeviceManagerAdapter::OnChanged(const DmDeviceInfo &info)
ZLOGE("get device info fail");
return;
}
- ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d",
- KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType);
+ ZLOGI("[OnChanged] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d osType:%{public}d",
+ KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType,
+ static_cast(dvInfo.authForm), dvInfo.osType);
}
void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info)
@@ -275,8 +276,9 @@ void DeviceManagerAdapter::OnReady(const DmDeviceInfo &info)
return;
}
readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONREADY, dvInfo));
- ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d",
- KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType);
+ ZLOGI("[OnReady] uuid:%{public}s, name:%{public}s, type:%{public}d, authForm:%{public}d, osType:%{public}d",
+ KvStoreUtils::ToBeAnonymous(dvInfo.uuid).c_str(), dvInfo.deviceName.c_str(), dvInfo.deviceType,
+ static_cast(dvInfo.authForm), dvInfo.osType);
auto task = [this, dvInfo]() {
observers_.ForEachCopies([&dvInfo](const auto &key, auto &value) {
if (value != nullptr) {
@@ -326,6 +328,11 @@ void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const Device
deviceInfos_.Set(dvInfo.uuid, dvInfo);
deviceInfos_.Set(dvInfo.udid, dvInfo);
readyDevices_.InsertOrAssign(dvInfo.uuid, std::make_pair(DeviceState::DEVICE_ONLINE, dvInfo));
+ if (dvInfo.osType != OH_OS_TYPE) {
+ otherDeviceInfos_.Set(dvInfo.networkId, dvInfo);
+ otherDeviceInfos_.Set(dvInfo.uuid, dvInfo);
+ otherDeviceInfos_.Set(dvInfo.udid, dvInfo);
+ }
break;
}
case DeviceChangeType::DEVICE_OFFLINE: {
@@ -333,6 +340,11 @@ void DeviceManagerAdapter::SaveDeviceInfo(const DeviceInfo &dvInfo, const Device
deviceInfos_.Delete(dvInfo.uuid);
deviceInfos_.Delete(dvInfo.udid);
readyDevices_.Erase(dvInfo.uuid);
+ if (dvInfo.osType != OH_OS_TYPE) {
+ otherDeviceInfos_.Delete(dvInfo.networkId);
+ otherDeviceInfos_.Delete(dvInfo.uuid);
+ otherDeviceInfos_.Delete(dvInfo.udid);
+ }
break;
}
default: {
@@ -409,7 +421,7 @@ bool DeviceManagerAdapter::IsOHOSType(const std::string &id)
int32_t DeviceManagerAdapter::GetAuthType(const std::string &id)
{
DeviceInfo dvInfo;
- if (!deviceInfos_.Get(id, dvInfo)) {
+ if (!otherDeviceInfos_.Get(id, dvInfo) && !deviceInfos_.Get(id, dvInfo)) {
InitDeviceInfo();
deviceInfos_.Get(id, dvInfo);
}
diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp
index 81b9f74e4cf492bf50fd8eb15cdeade7abb8343c..f4df6deecc68bd90d9e58361b9bff9fd9c29ab2b 100644
--- a/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp
+++ b/services/distributeddataservice/adapter/communicator/src/softbus_adapter_standard.cpp
@@ -207,7 +207,8 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn
uint32_t qosType)
{
std::shared_ptr conn;
- connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType](const auto &key,
+ std::string networkId = DmAdapter::GetInstance().ToNetworkID(deviceId.deviceId);
+ connects_.Compute(deviceId.deviceId, [&pipeInfo, &deviceId, &conn, qosType, &networkId](const auto &key,
std::vector> &connects) -> bool {
for (auto &connect : connects) {
if (connect == nullptr) {
@@ -218,7 +219,7 @@ std::shared_ptr SoftBusAdapter::GetConnect(const PipeInfo &pipeIn
return true;
}
}
- auto connect = std::make_shared(pipeInfo, deviceId, qosType);
+ auto connect = std::make_shared(pipeInfo, deviceId, networkId, qosType);
connects.emplace_back(connect);
conn = connect;
return true;
@@ -354,23 +355,24 @@ std::string SoftBusAdapter::DelConnect(int32_t socket, bool isForce)
if (!isForce && DmAdapter::GetInstance().IsOHOSType(deviceId)) {
return false;
}
+ std::string networkId;
for (auto iter = connects.begin(); iter != connects.end();) {
if (*iter != nullptr && **iter == socket) {
name += deviceId;
name += " ";
+ networkId = (*iter)->GetNetworkId();
iter = connects.erase(iter);
} else {
iter++;
}
}
- if (connects.empty()) {
- closedConnect.insert(deviceId);
+ if (connects.empty() && !networkId.empty()) {
+ closedConnect.insert(std::move(networkId));
return true;
}
return false;
});
- for (const auto &deviceId : closedConnect) {
- auto networkId = DmAdapter::GetInstance().GetDeviceInfo(deviceId).networkId;
+ for (const auto &networkId : closedConnect) {
ConnectManager::GetInstance()->OnSessionClose(networkId);
}
return name;
diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp
index f4451869fc0dd6eb479961ce84b27b9aaed1e225..23c8c79167f5735c46c620a3d592cda106bede2b 100644
--- a/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp
+++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.cpp
@@ -28,8 +28,8 @@ namespace OHOS::AppDistributedKv {
using namespace OHOS::DistributedKv;
using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter;
using Context = DistributedData::CommunicatorContext;
-SoftBusClient::SoftBusClient(const PipeInfo& pipeInfo, const DeviceId& deviceId, uint32_t type)
- : type_(type), pipe_(pipeInfo), device_(deviceId)
+SoftBusClient::SoftBusClient(const PipeInfo& pipeInfo, const DeviceId& deviceId, const std::string& networkId,
+ uint32_t type) : type_(type), pipe_(pipeInfo), device_(deviceId), networkId_(networkId)
{
mtu_ = DEFAULT_MTU_SIZE;
}
@@ -125,8 +125,7 @@ int32_t SoftBusClient::CreateSocket() const
SocketInfo socketInfo;
std::string peerName = pipe_.pipeId;
socketInfo.peerName = const_cast(peerName.c_str());
- std::string networkId = DmAdapter::GetInstance().ToNetworkID(device_.deviceId);
- socketInfo.peerNetworkId = const_cast(networkId.c_str());
+ socketInfo.peerNetworkId = const_cast(networkId_.c_str());
std::string clientName = pipe_.pipeId;
socketInfo.name = const_cast(clientName.c_str());
std::string pkgName = "ohos.distributeddata";
@@ -177,7 +176,7 @@ int32_t SoftBusClient::Open(int32_t socket, uint32_t type, const ISocketListener
UpdateBindInfo(socket, mtu, status, async);
ZLOGI("open %{public}s, session:%{public}s success, socket:%{public}d",
KvStoreUtils::ToBeAnonymous(device_.deviceId).c_str(), pipe_.pipeId.c_str(), socket_);
- ConnectManager::GetInstance()->OnSessionOpen(DmAdapter::GetInstance().GetDeviceInfo(device_.deviceId).networkId);
+ ConnectManager::GetInstance()->OnSessionOpen(networkId_);
return status;
}
@@ -256,4 +255,9 @@ Status SoftBusClient::ReuseConnect(const ISocketListener *listener)
int32_t status = Open(socket, QOS_REUSE, listener, false);
return status == SOFTBUS_OK ? Status::SUCCESS : Status::NETWORK_ERROR;
}
+
+const std::string& SoftBusClient::GetNetworkId() const
+{
+ return networkId_;
+}
} // namespace OHOS::AppDistributedKv
\ No newline at end of file
diff --git a/services/distributeddataservice/adapter/communicator/src/softbus_client.h b/services/distributeddataservice/adapter/communicator/src/softbus_client.h
index 67709bf9007d755123e27b8bfc25033dae199c50..a0196c94f3203f1475bb84c3c5c111e4dbc6ee31 100644
--- a/services/distributeddataservice/adapter/communicator/src/softbus_client.h
+++ b/services/distributeddataservice/adapter/communicator/src/softbus_client.h
@@ -33,7 +33,8 @@ public:
QOS_REUSE,
QOS_BUTT
};
- SoftBusClient(const PipeInfo &pipeInfo, const DeviceId &deviceId, uint32_t type = QOS_HML);
+ SoftBusClient(const PipeInfo &pipeInfo, const DeviceId &deviceId, const std::string& networkId,
+ uint32_t type = QOS_HML);
~SoftBusClient();
using Time = std::chrono::steady_clock::time_point;
@@ -51,6 +52,7 @@ public:
void UpdateExpireTime(bool async = true);
int32_t GetSoftBusError();
Status ReuseConnect(const ISocketListener *listener);
+ const std::string& GetNetworkId() const;
private:
int32_t Open(int32_t socket, uint32_t type, const ISocketListener *listener, bool async = true);
@@ -95,6 +97,7 @@ private:
int32_t socket_ = INVALID_SOCKET_ID;
int32_t bindState_ = -1;
int32_t softBusError_ = 0;
+ const std::string networkId_;
};
} // namespace OHOS::AppDistributedKv
diff --git a/services/distributeddataservice/adapter/communicator/test/BUILD.gn b/services/distributeddataservice/adapter/communicator/test/BUILD.gn
index cf89c446402bb35ba4990b5aeeb1aa178e8026db..5e5a3489d5438eaa917185bec97fa6ec43cf30bd 100755
--- a/services/distributeddataservice/adapter/communicator/test/BUILD.gn
+++ b/services/distributeddataservice/adapter/communicator/test/BUILD.gn
@@ -188,11 +188,31 @@ ohos_unittest("ProcessCommunicatorImplTest") {
ohos_unittest("SoftbusAdapterStandardTest") {
module_out_path = module_output_path
- sources = [ "unittest/softbus_adapter_standard_test.cpp" ]
+ sources = [
+ "../src/app_pipe_handler.cpp",
+ "../src/app_pipe_handler.h",
+ "../src/app_pipe_mgr.cpp",
+ "../src/app_pipe_mgr.h",
+ "../src/ark_communication_provider.cpp",
+ "../src/communication_provider.cpp",
+ "../src/communication_provider_impl.cpp",
+ "../src/communicator_context.cpp",
+ "../src/data_buffer.cpp",
+ "../src/device_manager_adapter.cpp",
+ "../src/process_communicator_impl.cpp",
+ "../src/softbus_adapter.h",
+ "../src/softbus_client.cpp",
+ "../src/softbus_client.h",
+ "unittest/softbus_adapter_standard_test.cpp",
+ ]
+
include_dirs = [
"${data_service_path}/adapter/include/communicator",
"${data_service_path}/framework/include/dfx",
"../src",
+ "../../include/communicator",
+ "../../include/utils",
+ "${data_service_path}/framework/include/utils",
]
external_deps = [
"access_token:libaccesstoken_sdk",
@@ -203,14 +223,19 @@ ohos_unittest("SoftbusAdapterStandardTest") {
"dsoftbus:softbus_client",
"hilog:libhilog",
"ipc:ipc_core",
+ "json:nlohmann_json_static",
+ "kv_store:datamgr_common",
"kv_store:distributeddata_inner",
+ "kv_store:distributeddb",
]
cflags = [
"-Dprivate=public",
"-Dprotected=public",
]
deps = [
- "${data_service_path}/adapter/communicator:distributeddata_communicator",
+ "${data_service_path}/adapter/utils:distributeddata_utils",
+ "${data_service_path}/framework:distributeddatasvcfwk",
+ "../../dfx:distributeddata_dfx",
]
defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
}
diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp
index 8999b2ea1ba94968594463d6553ae9c38e788cb2..f5c4cc30cc37bfaf066e57ce6dbbd0408689a40a 100644
--- a/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp
+++ b/services/distributeddataservice/adapter/communicator/test/unittest/process_communicator_impl_test.cpp
@@ -22,6 +22,8 @@
#include "communication_provider.h"
#include "device_manager_adapter_mock.h"
#include "process_communicator_impl.h"
+#include "softbus_adapter.h"
+#include "softbus_error_code.h"
using namespace testing;
using namespace testing::ext;
@@ -31,12 +33,13 @@ using OnDeviceChange = DistributedDB::OnDeviceChange;
using OnDataReceive = DistributedDB::OnDataReceive;
using OnSendAble = DistributedDB::OnSendAble;
using DeviceInfos = DistributedDB::DeviceInfos;
-using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo;
+using DeviceInfoo = OHOS::AppDistributedKv::DeviceInfo;
using UserInfo = DistributedDB::UserInfo;
namespace OHOS::AppDistributedKv {
class MockCommunicationProvider : public CommunicationProvider {
public:
+ ~MockCommunicationProvider() = default;
static MockCommunicationProvider& Init()
{
static MockCommunicationProvider instance;
@@ -79,7 +82,7 @@ public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
- void TearDown() {}
+ void TearDown();
ProcessCommunicatorImpl* communicator_;
MockCommunicationProvider* mockProvider;
@@ -114,6 +117,11 @@ void ProcessCommunicatorImplTest::SetUp(void)
mockProvider = &MockCommunicationProvider::Init();
}
+void ProcessCommunicatorImplTest::TearDown(void)
+{
+ mockProvider = nullptr;
+}
+
void ProcessCommunicatorImplTest::SetUpTestCase(void)
{
deviceManagerAdapterMock = std::make_shared();
@@ -123,6 +131,7 @@ void ProcessCommunicatorImplTest::SetUpTestCase(void)
void ProcessCommunicatorImplTest::TearDownTestCase()
{
deviceManagerAdapterMock = nullptr;
+ BDeviceManagerAdapter::deviceManagerAdapter = nullptr;
}
/**
@@ -285,9 +294,9 @@ HWTEST_F(ProcessCommunicatorImplTest, GetRemoteOnlineDeviceInfosList, TestSize.L
auto remoteDevInfos = communicator_->GetRemoteOnlineDeviceInfosList();
EXPECT_EQ(remoteDevInfos.empty(), true);
- DeviceInfo deviceInfo;
+ DeviceInfoo deviceInfo;
deviceInfo.uuid = "GetRemoteOnlineDeviceInfosList";
- std::vector devInfos;
+ std::vector devInfos;
devInfos.push_back(deviceInfo);
EXPECT_CALL(*deviceManagerAdapterMock, GetRemoteDevices()).WillRepeatedly(Return(devInfos));
remoteDevInfos = communicator_->GetRemoteOnlineDeviceInfosList();
@@ -304,7 +313,7 @@ HWTEST_F(ProcessCommunicatorImplTest, GetRemoteOnlineDeviceInfosList, TestSize.L
HWTEST_F(ProcessCommunicatorImplTest, OnMessage, TestSize.Level0)
{
ASSERT_NE(communicator_, nullptr);
- DeviceInfo deviceInfo;
+ DeviceInfoo deviceInfo;
deviceInfo.uuid = "OnMessageTest";
uint8_t data[] = {0x10, 0x20, 0x30, 0x40, 0x50};
uint8_t *ptr = data;
@@ -329,7 +338,7 @@ HWTEST_F(ProcessCommunicatorImplTest, OnMessage, TestSize.Level0)
HWTEST_F(ProcessCommunicatorImplTest, OnDeviceChanged, TestSize.Level0)
{
ASSERT_NE(communicator_, nullptr);
- DeviceInfo deviceInfo;
+ DeviceInfoo deviceInfo;
deviceInfo.uuid = "cloudDeviceUuid";
EXPECT_NO_FATAL_FAILURE(communicator_->OnDeviceChanged(deviceInfo, DeviceChangeType::DEVICE_ONREADY));
EXPECT_NO_FATAL_FAILURE(communicator_->OnDeviceChanged(deviceInfo, DeviceChangeType::DEVICE_OFFLINE));
@@ -351,7 +360,7 @@ HWTEST_F(ProcessCommunicatorImplTest, OnDeviceChanged, TestSize.Level0)
HWTEST_F(ProcessCommunicatorImplTest, OnSessionReady, TestSize.Level0)
{
ASSERT_NE(communicator_, nullptr);
- DeviceInfo deviceInfo;
+ DeviceInfoo deviceInfo;
deviceInfo.uuid = "OnSessionReadyTest";
communicator_->sessionListener_ = nullptr;
EXPECT_NO_FATAL_FAILURE(communicator_->OnSessionReady(deviceInfo, 1));
@@ -448,4 +457,50 @@ HWTEST_F(ProcessCommunicatorImplTest, GetDataUserInfo, TestSize.Level0)
userInfos.push_back(user3);
status = communicator_->GetDataUserInfo(ptr, totalLen, label, userInfos);
EXPECT_EQ(status, DistributedDB::OK);
+}
+
+/**
+* @tc.name: ReuseConnect01
+* @tc.desc: reuse connect
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: wangbin
+ */
+HWTEST_F(ProcessCommunicatorImplTest, ReuseConnect01, TestSize.Level0)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ PipeInfo pipe;
+ pipe.pipeId = "appId";
+ pipe.userId = "groupId";
+ DeviceId device = {"DeviceId"};
+ auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device);
+ EXPECT_EQ(status, Status::NOT_SUPPORT);
+ EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(testing::_)).WillOnce(testing::Return(true))
+ .WillRepeatedly(testing::Return(true));
+ status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device);
+ EXPECT_EQ(status, Status::NETWORK_ERROR);
+}
+
+/**
+* @tc.name: CloseSession
+* @tc.desc: close session
+* @tc.type: FUNC
+* @tc.author: nhj
+*/
+HWTEST_F(ProcessCommunicatorImplTest, CloseSession, TestSize.Level1)
+{
+ std::string networkId = "networkId";
+ auto flag = SoftBusAdapter::GetInstance();
+ ASSERT_NE(flag, nullptr);
+ std::string uuid = "CloseSessionTest";
+ EXPECT_CALL(*deviceManagerAdapterMock, GetUuidByNetworkId(testing::_)).WillOnce(testing::Return(uuid))
+ .WillRepeatedly(testing::Return(uuid));
+ std::shared_ptr conn = nullptr;
+ std::vector> clients;
+ clients.emplace_back(conn);
+ auto result = SoftBusAdapter::GetInstance()->connects_.Insert(uuid, clients);
+ EXPECT_EQ(result, true);
+ auto status = SoftBusAdapter::GetInstance()->CloseSession(networkId);
+ SoftBusAdapter::GetInstance()->connects_.Clear();
+ EXPECT_EQ(status, true);
}
\ No newline at end of file
diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp
index b4b4e92b347d0fce0a8f3b042970b066882d2896..842b4777781ad6790ac9be831e7dd4e66cb5d72a 100644
--- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp
+++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_adapter_standard_test.cpp
@@ -12,14 +12,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-#define LOG_TAG "SoftbusAdapterStandardTest"
-
#include "app_device_change_listener.h"
#include
#include "gtest/gtest.h"
#include
-#include "log_print.h"
#include "softbus_adapter.h"
+#include "softbus_adapter_standard.cpp"
+#include "softbus_error_code.h"
#include "types.h"
#include
#include
@@ -27,6 +26,7 @@
namespace OHOS::Test {
using namespace testing::ext;
using namespace OHOS::AppDistributedKv;
+using namespace OHOS::DistributedData;
using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo;
class AppDataChangeListenerImpl : public AppDataChangeListener {
struct ServerSocketInfo {
@@ -41,9 +41,7 @@ class AppDataChangeListenerImpl : public AppDataChangeListener {
void AppDataChangeListenerImpl::OnMessage(const OHOS::AppDistributedKv::DeviceInfo &info,
const uint8_t *ptr, const int size, const struct PipeInfo &id) const
-{
- ZLOGI("data %{public}s %s", info.deviceName.c_str(), ptr);
-}
+{}
class SoftbusAdapterStandardTest : public testing::Test {
public:
@@ -65,6 +63,7 @@ protected:
*/
HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange, TestSize.Level0)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(nullptr, {});
EXPECT_EQ(status, Status::INVALID_ARGUMENT);
}
@@ -78,12 +77,16 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange, TestSize.Level0)
*/
HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
PipeInfo appId;
appId.pipeId = "appId";
appId.userId = "groupId";
const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId);
EXPECT_EQ(status, Status::SUCCESS);
+ status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId);
+ delete dataListener;
+ EXPECT_EQ(status, Status::ERROR);
}
/**
@@ -95,11 +98,13 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange01, TestSize.Level0)
*/
HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
PipeInfo appId;
appId.pipeId = "";
appId.userId = "groupId";
const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
auto status = SoftBusAdapter::GetInstance()->StartWatchDataChange(dataListener, appId);
+ delete dataListener;
EXPECT_EQ(status, Status::SUCCESS);
}
@@ -111,7 +116,6 @@ HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange02, TestSize.Level0)
*/
HWTEST_F(SoftbusAdapterStandardTest, StartWatchDeviceChange03, TestSize.Level1)
{
- ZLOGI("begin.");
PipeInfo appId;
appId.pipeId = "appId06";
appId.userId = "groupId06";
@@ -139,6 +143,9 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange, TestSize.Level0)
const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId);
EXPECT_EQ(status, Status::SUCCESS);
+ status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId);
+ delete dataListener;
+ EXPECT_EQ(status, Status::ERROR);
}
/**
@@ -150,14 +157,35 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange, TestSize.Level0)
*/
HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
PipeInfo appId;
appId.pipeId = "";
appId.userId = "groupId";
const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
auto status = SoftBusAdapter::GetInstance()->StopWatchDataChange(dataListener, appId);
+ delete dataListener;
EXPECT_EQ(status, Status::SUCCESS);
}
+/**
+* @tc.name: GetExpireTime
+* @tc.desc: GetExpireTime Test
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: wangbin
+ */
+HWTEST_F(SoftbusAdapterStandardTest, GetExpireTime, TestSize.Level0)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ PipeInfo appId;
+ appId.pipeId = "appId";
+ appId.userId = "groupId";
+ DeviceId id = {"DeviceId"};
+ std::shared_ptr conn = std::make_shared(
+ appId, id, "", SoftBusClient::QoSType::QOS_HML);
+ EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->GetExpireTime(conn));
+}
+
/**
* @tc.name: SendData
* @tc.desc: parse sent data
@@ -166,6 +194,7 @@ HWTEST_F(SoftbusAdapterStandardTest, StopWatchDataChange01, TestSize.Level0)
*/
HWTEST_F(SoftbusAdapterStandardTest, SendData, TestSize.Level1)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
PipeInfo id;
id.pipeId = "appId";
@@ -209,6 +238,189 @@ HWTEST_F(SoftbusAdapterStandardTest, SendData01, TestSize.Level1)
delete dataListener;
}
+/**
+* @tc.name: StartCloseSessionTask
+* @tc.desc: StartCloseSessionTask tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, StartCloseSessionTask, TestSize.Level1)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ std::shared_ptr conn = nullptr;
+ std::vector> clients;
+ clients.emplace_back(conn);
+ auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients);
+ EXPECT_EQ(status, true);
+ SoftBusAdapter::GetInstance()->connects_.Clear();
+ EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->StartCloseSessionTask("deviceId02"));
+}
+
+/**
+* @tc.name: OnClientShutdown
+* @tc.desc: DelConnect tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, OnClientShutdown, TestSize.Level1)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ PipeInfo appId;
+ appId.pipeId = "appId";
+ appId.userId = "groupId";
+ DeviceId id = {"DeviceId"};
+ std::shared_ptr conn1 = std::make_shared(
+ appId, id, "", SoftBusClient::QoSType::QOS_HML);
+ std::shared_ptr conn2 = nullptr;
+ std::vector> clients;
+ clients.emplace_back(conn1);
+ clients.emplace_back(conn2);
+ auto status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId01", clients);
+ EXPECT_EQ(status, true);
+ status = SoftBusAdapter::GetInstance()->connects_.Insert("deviceId02", {});
+ EXPECT_EQ(status, true);
+ auto name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, true);
+ EXPECT_EQ(name, "deviceId01 ");
+ name = SoftBusAdapter::GetInstance()->OnClientShutdown(-1, false);
+ EXPECT_EQ(name, "");
+ name = SoftBusAdapter::GetInstance()->OnClientShutdown(1, true);
+ SoftBusAdapter::GetInstance()->connects_.Clear();
+ EXPECT_EQ(name, "");
+}
+
+/**
+* @tc.name: NotifyDataListeners
+* @tc.desc: NotifyDataListeners tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, NotifyDataListeners, TestSize.Level1)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ PipeInfo appId;
+ appId.pipeId = "appId";
+ appId.userId = "groupId";
+ std::string content = "Helloworlds";
+ const uint8_t *t = reinterpret_cast(content.c_str());
+ SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear();
+ EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId));
+ const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
+ SoftBusAdapter::GetInstance()->dataChangeListeners_.Insert(appId.pipeId, dataListener);
+ delete dataListener;
+ SoftBusAdapter::GetInstance()->dataChangeListeners_.Clear();
+ EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->NotifyDataListeners(t, 1, "deviceId", appId));
+}
+
+/**
+* @tc.name: ListenBroadcastMsg
+* @tc.desc: ListenBroadcastMsg tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, ListenBroadcastMsg, TestSize.Level1)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ SoftBusAdapter::GetInstance()->onBroadcast_= nullptr;
+ PipeInfo appId;
+ appId.pipeId = "appId";
+ appId.userId = "groupId";
+ auto result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, nullptr);
+ EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM);
+
+ auto listener = [](const std::string &message, const LevelInfo &info) {};
+ result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener);
+ EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_INVALID_PARAM);
+ result = SoftBusAdapter::GetInstance()->ListenBroadcastMsg(appId, listener);
+ EXPECT_EQ(result, SoftBusErrNo::SOFTBUS_ALREADY_EXISTED);
+}
+
+/**
+* @tc.name: OnBroadcast
+* @tc.desc: OnBroadcast tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, OnBroadcast, TestSize.Level1)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ DeviceId id = {"DeviceId"};
+ LevelInfo level;
+ level.dynamic = 1;
+ level.statics = 1;
+ level.switches = 1;
+ level.switchesLen = 1;
+ EXPECT_NE(SoftBusAdapter::GetInstance()->onBroadcast_, nullptr);
+ EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level));
+ SoftBusAdapter::GetInstance()->onBroadcast_ = nullptr;
+ EXPECT_NO_FATAL_FAILURE(SoftBusAdapter::GetInstance()->OnBroadcast(id, level));
+}
+
+/**
+* @tc.name: OnClientSocketChanged
+* @tc.desc: OnClientSocketChanged tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, OnClientSocketChanged, TestSize.Level1)
+{
+ QosTV qosTv;
+ qosTv.qos = QosType::QOS_TYPE_MIN_BW;
+ qosTv.value = 1;
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 1));
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0));
+ qosTv.qos = QosType::QOS_TYPE_MAX_WAIT_TIMEOUT;
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, &qosTv, 0));
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_SATISFIED, nullptr, 0));
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnClientSocketChanged(1, QoSEvent::QOS_NOT_SATISFIED, nullptr, 0));
+}
+
+/**
+* @tc.name: OnServerBytesReceived
+* @tc.desc: OnServerBytesReceived tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, OnServerBytesReceived, TestSize.Level1)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ PeerSocketInfo info;
+ info.name = strdup("");
+ info.networkId = strdup("peertest01");
+ info.pkgName = strdup("ohos.kv.test");
+ info.dataType = TransDataType::DATA_TYPE_MESSAGE;
+ AppDistributedKv::SoftBusAdapter::ServerSocketInfo serinfo;
+ auto result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo);
+ EXPECT_EQ(result, false);
+ char str[] = "Hello";
+ const void* data = static_cast(str);
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10));
+ SoftBusAdapter::GetInstance()->OnBind(1, info);
+ result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, serinfo);
+ EXPECT_EQ(result, true);
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(1, data, 10));
+ info.name = strdup("name");
+ SoftBusAdapter::GetInstance()->OnBind(2, info);
+ result = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(2, serinfo);
+ EXPECT_EQ(result, true);
+ EXPECT_NO_FATAL_FAILURE(AppDataListenerWrap::OnServerBytesReceived(2, data, 10));
+}
+
+/**
+* @tc.name: GetPipeId
+* @tc.desc: GetPipeId tests
+* @tc.type: FUNC
+* @tc.author:
+*/
+HWTEST_F(SoftbusAdapterStandardTest, GetPipeId, TestSize.Level1)
+{
+ std::string names = "GetPipeId";
+ auto name = AppDataListenerWrap::GetPipeId(names);
+ EXPECT_EQ(name, names);
+ names = "test01_GetPipeId";
+ name = AppDataListenerWrap::GetPipeId(names);
+ EXPECT_EQ(name, "test01");
+}
+
/**
* @tc.name: GetMtuSize
* @tc.desc: get size
@@ -217,6 +429,7 @@ HWTEST_F(SoftbusAdapterStandardTest, SendData01, TestSize.Level1)
*/
HWTEST_F(SoftbusAdapterStandardTest, GetMtuSize, TestSize.Level1)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
PipeInfo id;
id.pipeId = "appId";
@@ -238,6 +451,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetMtuSize, TestSize.Level1)
*/
HWTEST_F(SoftbusAdapterStandardTest, GetTimeout, TestSize.Level1)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
const AppDataChangeListenerImpl *dataListener = new AppDataChangeListenerImpl();
PipeInfo id;
id.pipeId = "appId01";
@@ -258,6 +472,7 @@ HWTEST_F(SoftbusAdapterStandardTest, GetTimeout, TestSize.Level1)
*/
HWTEST_F(SoftbusAdapterStandardTest, IsSameStartedOnPeer, TestSize.Level1)
{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
PipeInfo id;
id.pipeId = "appId01";
id.userId = "groupId01";
@@ -289,6 +504,23 @@ HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect, TestSize.Level1)
delete dataListener;
}
+/**
+* @tc.name: ReuseConnect01
+* @tc.desc: reuse connect
+* @tc.type: FUNC
+* @tc.author: wangbin
+*/
+HWTEST_F(SoftbusAdapterStandardTest, ReuseConnect01, TestSize.Level1)
+{
+ ASSERT_NE(SoftBusAdapter::GetInstance(), nullptr);
+ PipeInfo pipe;
+ pipe.pipeId = "appId";
+ pipe.userId = "groupId";
+ DeviceId device = {"DeviceId"};
+ auto status = SoftBusAdapter::GetInstance()->ReuseConnect(pipe, device);
+ EXPECT_EQ(status, Status::NOT_SUPPORT);
+}
+
/**
* @tc.name: GetConnect
* @tc.desc: get connect
@@ -416,6 +648,6 @@ HWTEST_F(SoftbusAdapterStandardTest, GetPeerSocketInfo01, TestSize.Level1)
auto flag = SoftBusAdapter::GetInstance();
ASSERT_NE(flag, nullptr);
auto status = SoftBusAdapter::GetInstance()->GetPeerSocketInfo(1, info);
- EXPECT_EQ(status, false);
+ EXPECT_EQ(status, true);
}
} // namespace OHOS::Test
\ No newline at end of file
diff --git a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp
index 3ba198442597f4c79adeaf845e4b802a0910dff3..3f1d713deb0fc7b2b05b72ae2cde2ac687dd6375 100644
--- a/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp
+++ b/services/distributeddataservice/adapter/communicator/test/unittest/softbus_client_test.cpp
@@ -46,7 +46,7 @@ void SoftbusClientTest::SetUpTestCase(void)
pipeInfo.pipeId = "pipeId";
pipeInfo.userId = "userId";
DeviceId id = {"DeviceId"};
- client = std::make_shared(pipeInfo, id);
+ client = std::make_shared(pipeInfo, id, "");
}
void SoftbusClientTest::TearDownTestCase(void)
diff --git a/services/distributeddataservice/adapter/dfx/test/BUILD.gn b/services/distributeddataservice/adapter/dfx/test/BUILD.gn
index 78a3fa45b61c20bd967c6e9e912f88d87d399501..67f11fddb9b0cbfe3ecc0de756c135f609152872 100755
--- a/services/distributeddataservice/adapter/dfx/test/BUILD.gn
+++ b/services/distributeddataservice/adapter/dfx/test/BUILD.gn
@@ -36,6 +36,7 @@ ohos_unittest("DistributeddataDfxMSTTest") {
external_deps = [
"c_utils:utils",
"datamgr_service:distributeddatasvcfwk",
+ "googletest:gtest_main",
"hilog:libhilog",
"hisysevent:libhisysevent",
"hitrace:hitrace_meter",
@@ -43,11 +44,7 @@ ohos_unittest("DistributeddataDfxMSTTest") {
"openssl:libcrypto_shared",
]
ldflags = [ "-Wl,--exclude-libs,ALL" ]
- deps = [
- "${data_service_path}/adapter/dfx:distributeddata_dfx",
- "//third_party/googletest:gtest_main",
- "//third_party/openssl:libcrypto_shared",
- ]
+ deps = [ "${data_service_path}/adapter/dfx:distributeddata_dfx" ]
defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
}
@@ -77,6 +74,7 @@ ohos_unittest("DistributeddataDfxUTTest") {
external_deps = [
"c_utils:utils",
"datamgr_service:distributeddatasvcfwk",
+ "googletest:gtest_main",
"hilog:libhilog",
"hisysevent:libhisysevent",
"hitrace:hitrace_meter",
@@ -87,8 +85,6 @@ ohos_unittest("DistributeddataDfxUTTest") {
deps = [
"${data_service_path}/adapter/dfx:distributeddata_dfx",
"${data_service_path}/adapter/utils:distributeddata_utils",
- "//third_party/googletest:gtest_main",
- "//third_party/openssl:libcrypto_shared",
]
defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
}
diff --git a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h
index a50783ae1d148c07b41d3a1286ddf56959fdef71..53135966b3566c5e059880aa4ceb1c7ca0283e84 100644
--- a/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h
+++ b/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h
@@ -103,6 +103,7 @@ private:
const DmDeviceInfo cloudDmInfo;
ConcurrentMap observers_ {};
LRUBucket deviceInfos_ {64};
+ LRUBucket otherDeviceInfos_ {64};
static constexpr size_t TIME_TASK_CAPACITY = 50;
static constexpr int32_t SYNC_TIMEOUT = 60 * 1000; // ms
static constexpr int32_t OH_OS_TYPE = 10;
diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp
index 0372dc5b6d436b84d32075d9d81f714c7ceadcc2..192c32cb6b64126a102e150449a1f5de3457d68b 100644
--- a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp
+++ b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.cpp
@@ -40,6 +40,10 @@ NetworkDelegate::NetworkType NetworkDelegateDefaultImpl::GetNetworkType(bool ret
return NetworkType::NONE;
}
+void NetworkDelegateDefaultImpl::BindExecutor(std::shared_ptr executors)
+{
+}
+
bool NetworkDelegateDefaultImpl::Init()
{
static NetworkDelegateDefaultImpl delegate;
diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h
index db00f8d752eef652288de9391e65764ac8d9588a..b3ddd1a17d745adba678be83928e4d038a2a49ff 100644
--- a/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h
+++ b/services/distributeddataservice/adapter/network/src/network_delegate_default_impl.h
@@ -25,7 +25,7 @@ public:
bool IsNetworkAvailable() override;
void RegOnNetworkChange() override;
NetworkType GetNetworkType(bool retrieve = false) override;
-
+ void BindExecutor(std::shared_ptr executors) override;
private:
NetworkDelegateDefaultImpl();
~NetworkDelegateDefaultImpl();
diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp
index 9389f8dcfbb4d6653f245cf95d52a37935523722..5f6d25db0d70b67be96e8117ea9c8e762fcdb5fb 100644
--- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp
+++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.cpp
@@ -114,22 +114,42 @@ NetworkDelegateNormalImpl::~NetworkDelegateNormalImpl()
void NetworkDelegateNormalImpl::RegOnNetworkChange()
{
- static std::atomic_bool flag = false;
- if (flag.exchange(true)) {
- ZLOGW("run only one");
- return;
+ if (executors_ != nullptr) {
+ executors_->Execute(GetTask(0));
}
- sptr observer = new (std::nothrow) NetConnCallbackObserver(*this);
- if (observer == nullptr) {
- ZLOGE("new operator error.observer is nullptr");
- flag.store(false);
- return;
- }
- auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer);
- if (nRet != NETMANAGER_SUCCESS) {
+}
+
+void NetworkDelegateNormalImpl::BindExecutor(std::shared_ptr executors)
+{
+ executors_ = std::move(executors);
+}
+
+ExecutorPool::Task NetworkDelegateNormalImpl::GetTask(uint32_t retry)
+{
+ return [this, retry] {
+ static std::atomic_bool flag = false;
+ if (flag.exchange(true)) {
+ ZLOGW("run only one");
+ return;
+ }
+ sptr observer = new (std::nothrow) NetConnCallbackObserver(*this);
+ if (observer == nullptr) {
+ ZLOGE("new operator error.observer is nullptr");
+ flag.store(false);
+ return;
+ }
+ auto nRet = NetConnClient::GetInstance().RegisterNetConnCallback(observer);
+ if (nRet == NETMANAGER_SUCCESS) {
+ return;
+ }
ZLOGE("RegisterNetConnCallback failed, ret = %{public}d", nRet);
flag.store(false);
- }
+ if (retry + 1 >= MAX_RETRY_TIME) {
+ ZLOGE("fail to register subscriber!");
+ return;
+ }
+ executors_->Schedule(std::chrono::seconds(RETRY_WAIT_TIME_S), GetTask(retry + 1));
+ };
}
bool NetworkDelegateNormalImpl::IsNetworkAvailable()
diff --git a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h
index c403f8497f46b36df8062e7d7248b5488a28bdea..f4c62051d58b81a257489e62355093e6907bba24 100644
--- a/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h
+++ b/services/distributeddataservice/adapter/network/src/network_delegate_normal_impl.h
@@ -30,6 +30,7 @@ public:
bool IsNetworkAvailable() override;
NetworkType GetNetworkType(bool retrieve = false) override;
void RegOnNetworkChange() override;
+ void BindExecutor(std::shared_ptr executors) override;
friend class NetConnCallbackObserver;
private:
NetworkDelegateNormalImpl();
@@ -43,11 +44,15 @@ private:
std::chrono::steady_clock::now().time_since_epoch())
.count();
}
+ ExecutorPool::Task GetTask(uint32_t retry);
static constexpr int32_t EFFECTIVE_DURATION = 30 * 1000; // ms
static constexpr int32_t NET_LOST_DURATION = 10 * 1000; // ms
+ static constexpr int32_t MAX_RETRY_TIME = 3;
+ static constexpr int32_t RETRY_WAIT_TIME_S = 1;
NetworkType defaultNetwork_ = NONE;
uint64_t expireTime_ = 0;
uint64_t netLostTime_ = 0;
+ std::shared_ptr executors_;
};
} // namespace OHOS::DistributedData
#endif // OHOS_DISTRIBUTED_DATA_NETWORK_NORMAL_DELEGATE_IMPL_H
\ No newline at end of file
diff --git a/services/distributeddataservice/adapter/network/test/BUILD.gn b/services/distributeddataservice/adapter/network/test/BUILD.gn
index 6c030e7689fc89ffb8c2e675c75af1daca97463e..c1b564cc83c05748a2cc5ba119f7fc735a486009 100755
--- a/services/distributeddataservice/adapter/network/test/BUILD.gn
+++ b/services/distributeddataservice/adapter/network/test/BUILD.gn
@@ -12,7 +12,7 @@
# limitations under the License.
import("//build/test.gni")
import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni")
-module_output_path = "datamgr_service/distributeddatafwk"
+module_output_path = "datamgr_service/datamgr_service/distributeddatafwk"
###############################################################################
ohos_unittest("NetworkDelegateTest") {
@@ -47,12 +47,52 @@ ohos_unittest("NetworkDelegateTest") {
defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
}
+ohos_unittest("NetworkDelegateNormalImplTest") {
+ module_out_path = module_output_path
+
+ sources = [
+ "${data_service_path}/framework/network/network_delegate.cpp",
+ "network_delegate_normal_impl_test.cpp",
+ ]
+ include_dirs = [
+ "${data_service_path}/adapter/include/communicator",
+ "${data_service_path}/framework/include/network",
+ "${data_service_path}/adapter/include/utils",
+ "${data_service_path}/framework/include",
+ "${data_service_path}/adapter/network/src",
+ "${data_service_path}/adapter/include",
+ ]
+
+ cflags = [
+ "-Dprivate=public",
+ "-Dprotected=public",
+ ]
+
+ deps = [
+ "${data_service_path}/adapter/communicator:distributeddata_communicator",
+ ]
+
+ external_deps = [
+ "c_utils:utils",
+ "device_manager:devicemanagersdk",
+ "googletest:gtest_main",
+ "hilog:libhilog",
+ "ipc:ipc_core",
+ "kv_store:datamgr_common",
+ "netmanager_base:net_conn_manager_if",
+ ]
+ defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
+}
+
###############################################################################
group("unittest") {
testonly = true
deps = []
- deps += [ ":NetworkDelegateTest" ]
+ deps += [
+ ":NetworkDelegateNormalImplTest",
+ ":NetworkDelegateTest",
+ ]
}
###############################################################################
diff --git a/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..64c63947582916e8168bc65bc6e1443e46f6683b
--- /dev/null
+++ b/services/distributeddataservice/adapter/network/test/network_delegate_normal_impl_test.cpp
@@ -0,0 +1,217 @@
+/*
+* Copyright (c) 2025 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 "network_delegate.h"
+#include "network_delegate_normal_impl.h"
+#include "network_delegate_normal_impl.cpp"
+#include
+#include
+
+using namespace testing::ext;
+using namespace std;
+using namespace OHOS::DistributedData;
+using namespace OHOS::NetManagerStandard;
+using DmDeviceInfo = OHOS::DistributedHardware::DmDeviceInfo;
+namespace OHOS::Test {
+namespace DistributedDataTest {
+class NetworkDelegateNormalImplTest : public testing::Test {
+public:
+ static void SetUpTestCase(void);
+ static void TearDownTestCase(void);
+ void SetUp();
+ void TearDown();
+};
+
+void NetworkDelegateNormalImplTest::SetUpTestCase(void)
+{
+}
+
+void NetworkDelegateNormalImplTest::TearDownTestCase()
+{
+}
+
+void NetworkDelegateNormalImplTest::SetUp()
+{
+}
+
+void NetworkDelegateNormalImplTest::TearDown()
+{
+}
+
+/**
+* @tc.name: GetNetworkType001
+* @tc.desc: GetNetworkType testing exception branching scenarios.
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: suoqilong
+*/
+HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType001, TestSize.Level1)
+{
+ NetworkDelegateNormalImpl delegate;
+ bool retrieve = false;
+ EXPECT_NO_FATAL_FAILURE(delegate.RegOnNetworkChange());
+ NetworkDelegate::NetworkType status = delegate.GetNetworkType(retrieve);
+ EXPECT_EQ(status, NetworkDelegate::NetworkType::NONE);
+}
+
+/**
+* @tc.name: GetNetworkType002
+* @tc.desc: GetNetworkType testing normal branching scenarios.
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: suoqilong
+*/
+HWTEST_F(NetworkDelegateNormalImplTest, GetNetworkType002, TestSize.Level1)
+{
+ NetworkDelegateNormalImpl delegate;
+ bool retrieve = true;
+ EXPECT_NO_FATAL_FAILURE(delegate.RegOnNetworkChange());
+ NetworkDelegate::NetworkType status = delegate.GetNetworkType(retrieve);
+ EXPECT_EQ(status, NetworkDelegate::NetworkType::NONE);
+}
+
+/**
+* @tc.name: IsNetworkAvailable
+* @tc.desc: IsNetworkAvailable testing different branching scenarios.
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: suoqilong
+*/
+HWTEST_F(NetworkDelegateNormalImplTest, IsNetworkAvailable, TestSize.Level1)
+{
+ NetworkDelegateNormalImpl delegate;
+ bool ret = delegate.IsNetworkAvailable(); // false false
+ EXPECT_FALSE(ret);
+
+ DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_);
+ std::fill(info.networkId, info.networkId + sizeof(info.networkId), '\0');
+ NetworkDelegateNormalImpl::NetworkType netWorkType = NetworkDelegate::NetworkType::NONE;
+ NetworkDelegateNormalImpl::NetworkType status = delegate.SetNet(netWorkType);
+ EXPECT_EQ(status, NetworkDelegate::NONE);
+ ret = delegate.IsNetworkAvailable(); // false true
+ EXPECT_FALSE(ret);
+
+ netWorkType = NetworkDelegate::NetworkType::WIFI;
+ status = delegate.SetNet(netWorkType);
+ EXPECT_EQ(status, NetworkDelegate::WIFI);
+ ret = delegate.IsNetworkAvailable(); // true true
+ EXPECT_TRUE(ret);
+
+ netWorkType = NetworkDelegate::NetworkType::NONE;
+ status = delegate.SetNet(netWorkType);
+ EXPECT_EQ(status, NetworkDelegate::NONE);
+ ret = delegate.IsNetworkAvailable(); // false true
+ EXPECT_FALSE(ret);
+
+ netWorkType = NetworkDelegate::NetworkType::WIFI;
+ status = delegate.SetNet(netWorkType);
+ EXPECT_EQ(status, NetworkDelegate::WIFI);
+ ret = delegate.IsNetworkAvailable(); // false true
+ EXPECT_TRUE(ret);
+}
+
+/**
+* @tc.name: NetCapabilitiesChange001
+* @tc.desc: NetCapabilitiesChange testing different branching scenarios.
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: suoqilong
+*/
+HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange001, TestSize.Level1)
+{
+ NetworkDelegateNormalImpl delegate;
+ sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate);
+ sptr netHandle = nullptr;
+ sptr netAllCap = nullptr;
+ int32_t status = observer->NetCapabilitiesChange(netHandle, netAllCap);
+ EXPECT_EQ(status, 0);
+
+ netHandle = new (std::nothrow) NetHandle();
+ status = observer->NetCapabilitiesChange(netHandle, netAllCap);
+ EXPECT_EQ(status, 0);
+
+ netHandle = nullptr;
+ netAllCap = new (std::nothrow) NetAllCapabilities();
+ status = observer->NetCapabilitiesChange(netHandle, netAllCap);
+ EXPECT_EQ(status, 0);
+}
+
+/**
+* @tc.name: NetCapabilitiesChange002
+* @tc.desc: NetCapabilitiesChange testing different branching scenarios.
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: suoqilong
+*/
+HWTEST_F(NetworkDelegateNormalImplTest, NetCapabilitiesChange002, TestSize.Level1)
+{
+ NetworkDelegateNormalImpl delegate;
+ DmDeviceInfo& info = const_cast(delegate.cloudDmInfo_);
+ std::fill(info.networkId, info.networkId + sizeof(info.networkId), '\0');
+ sptr observer = new (std::nothrow) NetConnCallbackObserver(delegate);
+ sptr netHandle = new (std::nothrow) NetHandle();
+ sptr netAllCap = new (std::nothrow) NetAllCapabilities();
+ EXPECT_FALSE(netAllCap->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED));
+ EXPECT_FALSE(!netAllCap->bearerTypes_.empty());
+ int32_t status = observer->NetCapabilitiesChange(netHandle, netAllCap);
+ EXPECT_EQ(status, 0);
+
+ netAllCap->netCaps_.insert(NetManagerStandard::NET_CAPABILITY_VALIDATED);
+ EXPECT_TRUE(netAllCap->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED));
+ EXPECT_FALSE(!netAllCap->bearerTypes_.empty());
+ status = observer->NetCapabilitiesChange(netHandle, netAllCap);
+ EXPECT_EQ(status, 0);
+
+ sptr netAllCaps = new (std::nothrow) NetAllCapabilities();
+ netAllCaps->bearerTypes_.insert(NetManagerStandard::BEARER_WIFI);
+ EXPECT_FALSE(netAllCaps->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED));
+ EXPECT_TRUE(!netAllCaps->bearerTypes_.empty());
+ status = observer->NetCapabilitiesChange(netHandle, netAllCaps);
+ EXPECT_EQ(status, 0);
+
+ netAllCaps->netCaps_.insert(NetManagerStandard::NET_CAPABILITY_VALIDATED);
+ EXPECT_TRUE(netAllCaps->netCaps_.count(NetManagerStandard::NET_CAPABILITY_VALIDATED));
+ EXPECT_TRUE(!netAllCaps->bearerTypes_.empty());
+ status = observer->NetCapabilitiesChange(netHandle, netAllCaps);
+ EXPECT_EQ(status, 0);
+}
+
+/**
+* @tc.name: Convert
+* @tc.desc: Convert testing different branching scenarios.
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: suoqilong
+*/
+HWTEST_F(NetworkDelegateNormalImplTest, Convert, TestSize.Level1)
+{
+ NetManagerStandard::NetBearType bearType = NetManagerStandard::BEARER_WIFI;
+ NetworkDelegateNormalImpl::NetworkType status = Convert(bearType);
+ EXPECT_EQ(status, NetworkDelegate::WIFI);
+
+ bearType = NetManagerStandard::BEARER_CELLULAR;
+ status = Convert(bearType);
+ EXPECT_EQ(status, NetworkDelegate::CELLULAR);
+
+ bearType = NetManagerStandard::BEARER_ETHERNET;
+ status = Convert(bearType);
+ EXPECT_EQ(status, NetworkDelegate::ETHERNET);
+
+ bearType = NetManagerStandard::BEARER_VPN;
+ status = Convert(bearType);
+ EXPECT_EQ(status, NetworkDelegate::OTHER);
+}
+} // namespace DistributedDataTest
+} // namespace OHOS::Test
\ No newline at end of file
diff --git a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn
index 8a1c3084cbfabe1634c0ecdf7ac96ab91539936c..f1f16b53b97aa91b48e36de832466a7d197a9a9c 100755
--- a/services/distributeddataservice/adapter/screenlock/test/BUILD.gn
+++ b/services/distributeddataservice/adapter/screenlock/test/BUILD.gn
@@ -12,7 +12,7 @@
# limitations under the License.
import("//build/test.gni")
import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni")
-module_output_path = "datamgr_service/distributeddatafwk"
+module_output_path = "datamgr_service/datamgr_service/distributeddatafwk"
###############################################################################
ohos_unittest("ScreenLockTest") {
diff --git a/services/distributeddataservice/app/BUILD.gn b/services/distributeddataservice/app/BUILD.gn
index 084cbb75e4cceddd76db9d286434490604f41fe3..45849945d3d997f0c16d3f4abb0ed3df0738ccc9 100644
--- a/services/distributeddataservice/app/BUILD.gn
+++ b/services/distributeddataservice/app/BUILD.gn
@@ -38,7 +38,6 @@ ohos_sa_profile("distributeddata_profile") {
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
- "${kv_store_common_path}",
"${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include",
"${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include",
"${data_service_path}/adapter/include/account",
@@ -125,6 +124,7 @@ ohos_shared_library("distributeddataservice") {
configs = [ ":module_private_config" ]
deps = [
+ "${data_service_path}/adapter/network:distributeddata_network",
"${data_service_path}/adapter/utils:distributeddata_utils",
"${data_service_path}/app/src/checker:distributeddata_checker",
"${data_service_path}/app/src/installer:distributeddata_installer",
@@ -168,4 +168,4 @@ ohos_shared_library("distributeddataservice") {
subsystem_name = "distributeddatamgr"
part_name = "datamgr_service"
defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ]
-}
+}
\ No newline at end of file
diff --git a/services/distributeddataservice/app/src/checker/bundle_checker.cpp b/services/distributeddataservice/app/src/checker/bundle_checker.cpp
index 674e09d5909e7d186dc098af80444a3263476676..b14a5fedda3aa72af2431e96abdc3d82dfa78404 100644
--- a/services/distributeddataservice/app/src/checker/bundle_checker.cpp
+++ b/services/distributeddataservice/app/src/checker/bundle_checker.cpp
@@ -114,7 +114,6 @@ bool BundleChecker::IsValid(const CheckerManager::StoreInfo &info)
if (AccessTokenKit::GetHapTokenInfo(info.tokenId, tokenInfo) != RET_SUCCESS) {
return false;
}
-
return tokenInfo.bundleName == info.bundleName;
}
diff --git a/services/distributeddataservice/app/src/kvstore_data_service.cpp b/services/distributeddataservice/app/src/kvstore_data_service.cpp
old mode 100755
new mode 100644
index 8d732f7d034b8bd451a203b3422d3b05c5882abc..03cae1122ddd7012c4200e037e77725b93842f09
--- a/services/distributeddataservice/app/src/kvstore_data_service.cpp
+++ b/services/distributeddataservice/app/src/kvstore_data_service.cpp
@@ -50,6 +50,7 @@
#include "mem_mgr_proxy.h"
#include "metadata/appid_meta_data.h"
#include "metadata/meta_data_manager.h"
+#include "network/network_delegate.h"
#include "permission_validator.h"
#include "permit_delegate.h"
#include "process_communicator_impl.h"
@@ -298,6 +299,7 @@ void KvStoreDataService::OnStart()
AccountDelegate::GetInstance()->RegisterHashFunc(Crypto::Sha256);
DmAdapter::GetInstance().Init(executors_);
AutoCache::GetInstance().Bind(executors_);
+ NetworkDelegate::GetInstance()->BindExecutor(executors_);
static constexpr int32_t RETRY_TIMES = 50;
static constexpr int32_t RETRY_INTERVAL = 500 * 1000; // unit is ms
for (BlockInteger retry(RETRY_INTERVAL); retry < RETRY_TIMES; ++retry) {
@@ -319,6 +321,9 @@ void KvStoreDataService::OnStart()
}
AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
+ AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID);
+ AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
+ AddSystemAbilityListener(CONCURRENT_TASK_SERVICE_ID);
RegisterStoreInfo();
Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1,
std::placeholders::_2);
@@ -346,6 +351,7 @@ void KvStoreDataService::LoadConfigs()
Bootstrap::GetInstance().LoadBackup(executors_);
Bootstrap::GetInstance().LoadCloud();
Bootstrap::GetInstance().LoadAppIdMappings();
+ Bootstrap::GetInstance().LoadDeviceSyncAppWhiteLists();
}
void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
@@ -353,12 +359,15 @@ void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std::
ZLOGI("add system abilityid:%{public}d", systemAbilityId);
(void)deviceId;
if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
- AccountDelegate::GetInstance()->SubscribeAccountEvent();
Installer::GetInstance().Init(this, executors_);
ScreenManager::GetInstance()->SubscribeScreenEvent();
+ } else if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) {
+ AccountDelegate::GetInstance()->SubscribeAccountEvent();
} else if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 1,
DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
+ } else if (systemAbilityId == COMM_NET_CONN_MANAGER_SYS_ABILITY_ID) {
+ NetworkDelegate::GetInstance()->RegOnNetworkChange();
}
return;
}
@@ -367,10 +376,12 @@ void KvStoreDataService::OnRemoveSystemAbility(int32_t systemAbilityId, const st
{
ZLOGI("remove system abilityid:%{public}d", systemAbilityId);
(void)deviceId;
+ if (systemAbilityId == SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN) {
+ AccountDelegate::GetInstance()->UnsubscribeAccountEvent();
+ }
if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
return;
}
- AccountDelegate::GetInstance()->UnsubscribeAccountEvent();
ScreenManager::GetInstance()->UnsubscribeScreenEvent();
Installer::GetInstance().UnsubscribeEvent();
}
diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp
index f7e315cabb42bfa37b7d29cdf9f3c47e0a8c01c2..304048400b9b514950dff97ca1dd3a33f37ff93e 100644
--- a/services/distributeddataservice/app/src/kvstore_meta_manager.cpp
+++ b/services/distributeddataservice/app/src/kvstore_meta_manager.cpp
@@ -33,8 +33,16 @@
#include "kv_radar_reporter.h"
#include "log_print.h"
#include "matrix_event.h"
+#include "metadata/auto_launch_meta_data.h"
+#include "metadata/capability_meta_data.h"
+#include "metadata/device_meta_data.h"
#include "metadata/meta_data_manager.h"
+#include "metadata/matrix_meta_data.h"
+#include "metadata/strategy_meta_data.h"
#include "metadata/store_meta_data_local.h"
+#include "metadata/strategy_meta_data.h"
+#include "metadata/switches_meta_data.h"
+#include "metadata/user_meta_data.h"
#include "metadata/version_meta_data.h"
#include "runtime_config.h"
#include "safe_block_queue.h"
@@ -46,6 +54,7 @@
#include "utils/crypto.h"
#include "utils/ref_count.h"
#include "utils/converter.h"
+#include "utils/constant.h"
namespace OHOS {
namespace DistributedKv {
@@ -134,9 +143,10 @@ void KvStoreMetaManager::InitMetaData()
ZLOGI("get meta failed.");
return;
}
+
+ CheckMetaDeviceId();
auto uid = getuid();
auto tokenId = IPCSkeleton::GetCallingTokenID();
- const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId();
auto userId = AccountDelegate::GetInstance()->GetUserByToken(tokenId);
StoreMetaData data;
data.appId = label_;
@@ -153,7 +163,7 @@ void KvStoreMetaManager::InitMetaData()
data.dataType = DataType::TYPE_DYNAMICAL;
data.schema = "";
data.storeId = Bootstrap::GetInstance().GetMetaDBName();
- data.account = accountId;
+ data.account = AccountDelegate::GetInstance()->GetCurrentAccountId();
data.uid = static_cast(uid);
data.version = META_STORE_VERSION;
data.securityLevel = SecurityLevel::S1;
@@ -554,5 +564,118 @@ AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListener
{
return AppDistributedKv::ChangeLevelType::MIN;
}
+
+void KvStoreMetaManager::CheckMetaDeviceId()
+{
+ DeviceMetaData deviceMeta;
+ auto localUuid = DmAdapter::GetInstance().GetLocalDevice().uuid;
+ if (localUuid.empty()) {
+ ZLOGW("get uuid failed");
+ return;
+ }
+ if (!MetaDataManager::GetInstance().LoadMeta(deviceMeta.GetKey(), deviceMeta, true)) {
+ deviceMeta.newUuid = localUuid;
+ MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true);
+ return;
+ }
+ if (deviceMeta.newUuid != localUuid) {
+ UpdateStoreMetaData(localUuid, deviceMeta.newUuid);
+ UpdateMetaDatas(localUuid, deviceMeta.newUuid);
+ deviceMeta.oldUuid = deviceMeta.newUuid;
+ deviceMeta.newUuid = localUuid;
+ MetaDataManager::GetInstance().SaveMeta(deviceMeta.GetKey(), deviceMeta, true);
+ ZLOGI("meta changed! curruuid:%{public}s, olduuid:%{public}s", Anonymous::Change(deviceMeta.newUuid).c_str(),
+ Anonymous::Change(deviceMeta.oldUuid).c_str());
+ }
+}
+
+void KvStoreMetaManager::UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid)
+{
+ std::vector storeMetas;
+ MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ oldUuid }), storeMetas, true);
+ for (auto &storeMeta : storeMetas) {
+ auto oldMeta = storeMeta;
+ storeMeta.isNeedUpdateDeviceId = true;
+ storeMeta.deviceId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta, true);
+ MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey(), true);
+
+ StoreMetaData syncStoreMeta;
+ if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKey(), syncStoreMeta)) {
+ syncStoreMeta.deviceId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), syncStoreMeta);
+ MetaDataManager::GetInstance().DelMeta(oldMeta.GetKey());
+ }
+
+ StrategyMeta strategyMeta;
+ if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetStrategyKey(), strategyMeta)) {
+ strategyMeta.devId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(storeMeta.GetStrategyKey(), strategyMeta);
+ MetaDataManager::GetInstance().DelMeta(oldMeta.GetStrategyKey());
+ }
+
+ StoreMetaDataLocal metaDataLocal;
+ if (MetaDataManager::GetInstance().LoadMeta(oldMeta.GetKeyLocal(), metaDataLocal, true)) {
+ MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKeyLocal(), metaDataLocal, true);
+ MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyLocal(), true);
+ }
+
+ AutoLaunchMetaData autoLaunchMetaData;
+ bool isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true);
+ if (!isExist) {
+ oldMeta.storeId = "";
+ isExist = MetaDataManager::GetInstance().LoadMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true);
+ }
+ if (isExist) {
+ MetaDataManager::GetInstance().DelMeta(oldMeta.GetAutoLaunchKey(), true);
+ oldMeta.deviceId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(oldMeta.GetAutoLaunchKey(), autoLaunchMetaData, true);
+ }
+ if (storeMeta.isEncrypt) {
+ MetaDataManager::GetInstance().DelMeta(storeMeta.GetSecretKey(), true);
+ MetaDataManager::GetInstance().DelMeta(storeMeta.GetCloneSecretKey(), true);
+ }
+ }
+}
+
+void KvStoreMetaManager::UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid)
+{
+ MatrixMetaData matrixMeta;
+ if (MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUuid }), matrixMeta, true)) {
+ MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUuid }), true);
+ matrixMeta.deviceId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ newUuid }), matrixMeta, true);
+ }
+
+ if (MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ oldUuid }), matrixMeta)) {
+ MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ oldUuid }));
+ matrixMeta.deviceId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({ newUuid }), matrixMeta);
+ }
+
+ SwitchesMetaData switchesMetaData;
+ if (MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ oldUuid }),
+ switchesMetaData, true)) {
+ MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ oldUuid }), true);
+ switchesMetaData.deviceId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({ newUuid }),
+ switchesMetaData, true);
+ }
+
+ UserMetaData userMeta;
+ if (MetaDataManager::GetInstance().LoadMeta(UserMetaRow::GetKeyFor(oldUuid), userMeta)) {
+ MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor(oldUuid));
+ userMeta.deviceId = newUuid;
+ MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor(newUuid), userMeta);
+ }
+
+ CapMetaData capMetaData;
+ auto capKey = CapMetaRow::GetKeyFor(oldUuid);
+ if (MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData)) {
+ auto newCapKey = CapMetaRow::GetKeyFor(newUuid);
+ MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end()));
+ MetaDataManager::GetInstance().SaveMeta(std::string(newCapKey.begin(), newCapKey.end()), capMetaData);
+ }
+}
} // namespace DistributedKv
} // namespace OHOS
\ No newline at end of file
diff --git a/services/distributeddataservice/app/src/kvstore_meta_manager.h b/services/distributeddataservice/app/src/kvstore_meta_manager.h
index 87bcc7162d8ad9f84f9ac437a5cbd233ca119677..f7b28e1cd2a2a29dbccdb8d170800c051ba829c2 100644
--- a/services/distributeddataservice/app/src/kvstore_meta_manager.h
+++ b/services/distributeddataservice/app/src/kvstore_meta_manager.h
@@ -95,6 +95,12 @@ private:
ExecutorPool::Task GetTask(uint32_t retry);
DistributedDB::KvStoreNbDelegate::Option InitDBOption();
+
+ void CheckMetaDeviceId();
+
+ void UpdateStoreMetaData(const std::string &newUuid, const std::string &oldUuid);
+
+ void UpdateMetaDatas(const std::string &newUuid, const std::string &oldUuid);
static ExecutorPool::Task GetBackupTask(
TaskQueue queue, std::shared_ptr executors, const NbDelegate store);
diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp
index f52cde722d9237a3e8c28bf215cee5d9ca0bdb2e..40d0403a46da7c34c55a1d748319d066ce14be69 100644
--- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp
+++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp
@@ -113,7 +113,8 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize
return DistributedDB::DB_ERROR;
}
size_t expectSize = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair)
- + session_.targetUserIds.size() * sizeof(int) + sizeof(SessionAppId) + session_.appId.size();
+ + session_.targetUserIds.size() * sizeof(int) + sizeof(SessionAppId) + session_.appId.size()
+ + sizeof(SessionStoreId) + session_.storeId.size();
// align message uint width
headSize = GET_ALIGNED_SIZE(expectSize, ALIGN_WIDTH);
@@ -194,16 +195,27 @@ bool RouteHeadHandlerImpl::PackDataBody(uint8_t *data, uint32_t totalLen)
ptr += (sizeof(SessionUserPair) + session_.targetUserIds.size() * sizeof(int));
SessionAppId *appPair = reinterpret_cast(ptr);
+ uint32_t appIdSize = session_.appId.size();
+ appPair->len = HostToNet(appIdSize);
+ uint8_t *end = data + totalLen;
ptr += sizeof(SessionAppId);
+ ret = memcpy_s(appPair->appId, end - ptr, session_.appId.c_str(), appIdSize);
+ if (ret != 0) {
+ ZLOGE("memcpy for app id failed, ret is %{public}d, leftSize is %{public}u, appIdSize is %{public}u",
+ ret, static_cast(end - ptr), appIdSize);
+ return false;
+ }
+ ptr += appIdSize;
- uint8_t *end = data + totalLen;
- uint32_t appIdSize = session_.appId.size();
- ret = memcpy_s(appPair->appId, end - ptr, session_.appId.data(), appIdSize);
+ SessionStoreId *storePair = reinterpret_cast(ptr);
+ uint32_t storeIdSize = session_.storeId.size();
+ ret = memcpy_s(storePair->storeId, end - ptr, session_.storeId.data(), storeIdSize);
if (ret != 0) {
- ZLOGE("strcpy for app id failed, error:%{public}d", errno);
+ ZLOGE("memcpy for store id failed, ret is %{public}d, leftSize is %{public}u, storeIdSize is %{public}u",
+ ret, static_cast(end - ptr), storeIdSize);
return false;
}
- appPair->len = HostToNet(appIdSize);
+ storePair->len = HostToNet(storeIdSize);
return true;
}
@@ -222,6 +234,9 @@ bool RouteHeadHandlerImpl::ParseHeadDataLen(const uint8_t *data, uint32_t totalL
std::string RouteHeadHandlerImpl::ParseStoreId(const std::string &deviceId, const std::string &label)
{
+ if (!session_.storeId.empty()) {
+ return session_.storeId;
+ }
std::vector metaData;
auto prefix = StoreMetaData::GetPrefix({ deviceId });
if (!MetaDataManager::GetInstance().LoadMeta(prefix, metaData)) {
@@ -255,7 +270,7 @@ bool RouteHeadHandlerImpl::ParseHeadDataUser(const uint8_t *data, uint32_t total
metaData.deviceId = session_.targetDeviceId;
metaData.user = DEFAULT_USERID;
metaData.bundleName = session_.appId;
- metaData.storeId = storeId;
+ metaData.storeId = std::move(storeId);
if (!MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData)) {
int foregroundUserId = 0;
AccountDelegate::GetInstance()->QueryForegroundUserId(foregroundUserId);
@@ -369,6 +384,28 @@ bool RouteHeadHandlerImpl::UnPackDataBody(const uint8_t *data, uint32_t totalLen
return false;
}
session_.appId.append(appId->appId, appIdLen);
+ leftSize -= (sizeof(SessionAppId) + appIdLen);
+ if (leftSize > 0) {
+ ptr += (sizeof(SessionAppId) + appIdLen);
+ return UnPackStoreId(ptr, leftSize);
+ }
+ return true;
+}
+
+bool RouteHeadHandlerImpl::UnPackStoreId(const uint8_t *data, uint32_t leftSize)
+{
+ if (leftSize < sizeof(SessionStoreId)) {
+ ZLOGE("failed to parse store id, leftSize:%{public}d.", leftSize);
+ return false;
+ }
+ const uint8_t *ptr = data;
+ const SessionStoreId *storeId = reinterpret_cast(ptr);
+ auto storeIdLen = NetToHost(storeId->len);
+ if (leftSize - sizeof(SessionStoreId) < storeIdLen) {
+ ZLOGE("failed to parse store id, storeIdLen:%{public}d, leftSize:%{public}d.", storeIdLen, leftSize);
+ return false;
+ }
+ session_.storeId = std::string(storeId->storeId, storeIdLen);
return true;
}
} // namespace OHOS::DistributedData
\ No newline at end of file
diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h
index f23360dd7341b4a6430c6d6a30099122b5c0ffc0..11583b7b1d4c712c8129b23f60f7d29dffa456a9 100644
--- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h
+++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h
@@ -53,6 +53,11 @@ struct SessionAppId {
uint32_t len;
char appId[0];
};
+
+struct SessionStoreId {
+ uint32_t len;
+ char storeId[0];
+};
#pragma pack()
class RouteHeadHandlerImpl : public DistributedData::RouteHeadHandler {
@@ -74,6 +79,7 @@ private:
bool UnPackDataHead(const uint8_t *data, uint32_t totalLen, RouteHead &routeHead);
bool UnPackDataBody(const uint8_t *data, uint32_t totalLen);
std::string ParseStoreId(const std::string &deviceId, const std::string &label);
+ bool UnPackStoreId(const uint8_t *data, uint32_t leftSize);
std::string userId_;
std::string appId_;
diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.cpp b/services/distributeddataservice/app/src/session_manager/session_manager.cpp
index e13e43579f07d20b031ee1df5dd331fb0346b4b3..1ef5c834ab26b19bc412b6335aa028cf9890edcd 100644
--- a/services/distributeddataservice/app/src/session_manager/session_manager.cpp
+++ b/services/distributeddataservice/app/src/session_manager/session_manager.cpp
@@ -44,6 +44,7 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string
ZLOGD("begin. peer device:%{public}s", Anonymous::Change(targetDeviceId).c_str());
Session session;
session.appId = local.appId;
+ session.storeId = local.storeId;
session.sourceUserId = local.userId;
session.sourceDeviceId = local.deviceId;
session.targetDeviceId = targetDeviceId;
@@ -64,6 +65,8 @@ Session SessionManager::GetSession(const SessionPoint &local, const std::string
aclParams.accCallee.userId = user.id;
auto [isPermitted, isSameAccount] = AuthDelegate::GetInstance()->CheckAccess(local.userId, user.id,
targetDeviceId, aclParams);
+ ZLOGD("targetDeviceId:%{public}s, user.id:%{public}d, isPermitted:%{public}d, isSameAccount: %{public}d",
+ Anonymous::Change(targetDeviceId).c_str(), user.id, isPermitted, isSameAccount);
if (isPermitted) {
auto it = std::find(session.targetUserIds.begin(), session.targetUserIds.end(), user.id);
if (it == session.targetUserIds.end() && isSameAccount) {
@@ -145,6 +148,8 @@ bool SessionManager::CheckSession(const SessionPoint &local, const SessionPoint
}
auto [isPermitted, isSameAccount] = AuthDelegate::GetInstance()->CheckAccess(local.userId,
peer.userId, peer.deviceId, aclParams);
+ ZLOGD("peer.deviceId:%{public}s, peer.userId:%{public}d, isPermitted:%{public}d, isSameAccount: %{public}d",
+ Anonymous::Change(peer.deviceId).c_str(), peer.userId, isPermitted, isSameAccount);
if (isPermitted && local.userId != UserDelegate::SYSTEM_USER) {
isPermitted = Account::GetInstance()->IsUserForeground(local.userId);
}
@@ -159,6 +164,7 @@ bool Session::Marshal(json &node) const
ret = SetValue(node[GET_NAME(sourceUserId)], sourceUserId) && ret;
ret = SetValue(node[GET_NAME(targetUserIds)], targetUserIds) && ret;
ret = SetValue(node[GET_NAME(appId)], appId) && ret;
+ ret = SetValue(node[GET_NAME(storeId)], storeId) && ret;
return ret;
}
@@ -170,6 +176,7 @@ bool Session::Unmarshal(const json &node)
ret = GetValue(node, GET_NAME(sourceUserId), sourceUserId) && ret;
ret = GetValue(node, GET_NAME(targetUserIds), targetUserIds) && ret;
ret = GetValue(node, GET_NAME(appId), appId) && ret;
+ ret = GetValue(node, GET_NAME(storeId), storeId) && ret;
return ret;
}
} // namespace OHOS::DistributedData
diff --git a/services/distributeddataservice/app/src/session_manager/session_manager.h b/services/distributeddataservice/app/src/session_manager/session_manager.h
index ca83970bc6494277011ba7bdf0aa3f67f341404d..c72c1bef195f8b24c351fae585b0e6e4754c97a8 100644
--- a/services/distributeddataservice/app/src/session_manager/session_manager.h
+++ b/services/distributeddataservice/app/src/session_manager/session_manager.h
@@ -39,6 +39,7 @@ public:
uint32_t sourceUserId;
std::vector targetUserIds;
std::string appId;
+ std::string storeId;
bool Marshal(json &node) const override;
bool Unmarshal(const json &node) override;
inline bool IsValid()
diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn
index 628a466b83cb1fc3ecc9b20f1e43ae12d2a1c2f7..4feefbd64ad7a21b508e3258e22f111e78696e40 100644
--- a/services/distributeddataservice/app/test/BUILD.gn
+++ b/services/distributeddataservice/app/test/BUILD.gn
@@ -13,18 +13,14 @@
import("//build/test.gni")
import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni")
-module_output_path = "datamgr_service/distributeddataservice"
+module_output_path = "datamgr_service/datamgr_service/distributeddataservice"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
- "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include",
- "${kv_store_path}/frameworks/common",
"${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include",
"${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src",
- "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include",
- "${kv_store_path}/interfaces/innerkits/distributeddata/include",
"${data_service_path}/adapter/include/permission",
"${data_service_path}/adapter/include/account",
"${data_service_path}/adapter/include",
@@ -41,9 +37,7 @@ config("module_private_config") {
"${data_service_path}/app/src",
"${data_service_path}/app/src/session_manager",
"${data_service_path}/service/kvdb",
- "${device_manager_path}/interfaces/inner_kits/native_cpp/include",
- "//commonlibrary/c_utils/base/include",
- "//utils/system/safwk/native/include",
+ "${data_service_path}/service/test/mock",
"../include",
"../src",
"../src/security",
@@ -52,7 +46,6 @@ config("module_private_config") {
"../../service/backup/include",
"../../../../interfaces/innerkits/distributeddata",
"../../service/dumper/include",
- "//third_party/json/single_include",
"${data_service_path}/adapter/include/communicator",
]
@@ -109,7 +102,9 @@ ohos_unittest("KvStoreDataServiceTest") {
"common_event_service:cesfwk_innerkits",
"dataclassification:data_transit_mgr",
"device_auth:deviceauth_sdk",
+ "device_manager:devicemanagersdk",
"file_api:securitylabel",
+ "googletest:gtest_main",
"hicollie:libhicollie",
"hilog:libhilog",
"hisysevent:libhisysevent",
@@ -117,6 +112,7 @@ ohos_unittest("KvStoreDataServiceTest") {
"hitrace:libhitracechain",
"ipc:ipc_core",
"kv_store:distributeddata_inner",
+ "kv_store:distributeddata_mgr",
"kv_store:distributeddb",
"memmgr:memmgrclient",
"safwk:system_ability_fwk",
@@ -133,7 +129,6 @@ ohos_unittest("KvStoreDataServiceTest") {
deps = [
"${data_service_path}/framework:distributeddatasvcfwk",
"${data_service_path}/service:distributeddatasvc",
- "//third_party/googletest:gtest_main",
]
part_name = "datamgr_service"
}
@@ -153,6 +148,7 @@ ohos_unittest("SessionManagerTest") {
cfi = true
cfi_cross_dso = true
debug = false
+ blocklist = "${datamgr_service_path}/cfi_blocklist.txt"
}
cflags_cc = [ "-DUT_TEST" ]
@@ -165,10 +161,17 @@ ohos_unittest("SessionManagerTest") {
"c_utils:utils",
"dataclassification:data_transit_mgr",
"device_auth:deviceauth_sdk",
+ "device_manager:devicemanagersdk",
"file_api:securitylabel",
+ "googletest:gmock",
+ "googletest:gtest_main",
"hilog:libhilog",
"hisysevent:libhisysevent",
"ipc:ipc_core",
+ "json:nlohmann_json_static",
+ "kv_store:distributeddata_inner",
+ "kv_store:distributeddata_mgr",
+ "kv_store:distributeddb",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
@@ -183,12 +186,9 @@ ohos_unittest("SessionManagerTest") {
deps = [
"${data_service_path}/adapter/utils:distributeddata_utils",
"${data_service_path}/app/src/checker:distributeddata_checker",
- "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr",
- "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk",
- "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc",
- "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb",
- "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
- "//third_party/googletest:gtest_main",
+ "${data_service_path}/framework:distributeddatasvcfwk",
+ "${data_service_path}/service:distributeddatasvc",
+ "${data_service_path}/service/test/mock:distributeddata_mock_static",
]
part_name = "datamgr_service"
@@ -233,13 +233,16 @@ ohos_unittest("KvStoreDataServiceClearTest") {
"c_utils:utils",
"dataclassification:data_transit_mgr",
"device_auth:deviceauth_sdk",
+ "device_manager:devicemanagersdk",
"file_api:securitylabel",
+ "googletest:gtest_main",
"hicollie:libhicollie",
"hilog:libhilog",
"hisysevent:libhisysevent",
"hitrace:hitrace_meter",
"hitrace:libhitracechain",
"ipc:ipc_core",
+ "json:nlohmann_json_static",
"kv_store:distributeddata_inner",
"kv_store:distributeddata_mgr",
"kv_store:distributeddb",
@@ -261,7 +264,6 @@ ohos_unittest("KvStoreDataServiceClearTest") {
"${data_service_path}/app/src/installer:distributeddata_installer",
"${data_service_path}/framework:distributeddatasvcfwk",
"${data_service_path}/service:distributeddatasvc",
- "//third_party/googletest:gtest_main",
]
part_name = "datamgr_service"
@@ -298,6 +300,7 @@ ohos_unittest("FeatureStubImplTest") {
"c_utils:utils",
"dataclassification:data_transit_mgr",
"device_auth:deviceauth_sdk",
+ "device_manager:devicemanagersdk",
"file_api:securitylabel",
"googletest:gtest_main",
"hilog:libhilog",
@@ -346,14 +349,5 @@ group("unittest") {
###############################################################################
group("moduletest") {
testonly = true
- deps = [
- "//third_party/googletest:gmock",
- "//third_party/googletest:gtest_main",
- "//third_party/sqlite:sqlite",
- ]
-
- deps += [
- #":DistributedDataAccountEventModuleTest",
- ]
}
###############################################################################
diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp
index 8031dc6c64107682bd434dfcaadd6fa5064d5933..e009b52ad7ba4d4f7c0f678354eb313d01ae9fac 100644
--- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp
+++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp
@@ -13,10 +13,18 @@
* limitations under the License.
*/
+#include "session_manager/session_manager.h"
+
+#include
+
#include "accesstoken_kit.h"
+#include "account_delegate_mock.h"
+#include "auth_delegate_mock.h"
#include "bootstrap.h"
#include "device_manager_adapter.h"
-#include "kvstore_meta_manager.h"
+#include "device_manager_adapter_mock.h"
+#include "gtest/gtest.h"
+#include "meta_data_manager_mock.h"
#include "metadata/meta_data_manager.h"
#include "metadata/store_meta_data.h"
#include "nativetoken_kit.h"
@@ -24,18 +32,25 @@
#include "session_manager/upgrade_manager.h"
#include "token_setproc.h"
#include "user_delegate.h"
-#include "gtest/gtest.h"
+#include "user_delegate_mock.h"
+#include "utils/endian_converter.h"
namespace {
+using namespace testing;
using namespace testing::ext;
using namespace OHOS::DistributedKv;
using namespace OHOS::DistributedData;
+using namespace DistributedDB;
using namespace OHOS;
using namespace OHOS::Security::AccessToken;
+using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo;
+using UserInfo = DistributedDB::UserInfo;
constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID";
constexpr int PEER_USER_ID1 = 101;
constexpr int PEER_USER_ID2 = 100;
+constexpr int32_t USER_MAXID = 4;
constexpr int METADATA_UID = 2000000;
+static constexpr int32_t OH_OS_TYPE = 10;
void GrantPermissionNative()
{
@@ -55,20 +70,48 @@ void GrantPermissionNative()
uint64_t tokenId = GetAccessTokenId(&infoInstance);
SetSelfTokenID(tokenId);
AccessTokenKit::ReloadNativeTokenInfo();
- delete []perms;
+ delete[] perms;
}
class SessionManagerTest : public testing::Test {
public:
+ void CreateUserStatus(std::vector &users)
+ {
+ for (int32_t i = 0; i < USER_MAXID; i++) {
+ UserStatus stat;
+ stat.id = i;
+ users.push_back(stat);
+ }
+ }
+ void CreateStoreMetaData(std::vector &datas, SessionPoint local)
+ {
+ StoreMetaData data;
+ data.appId = local.appId;
+ data.storeId = local.storeId;
+ data.bundleName = "com.test.session";
+ StoreMetaData data1;
+ data1.appId = local.appId;
+ data1.storeId = "local.storeId";
+ data1.bundleName = "com.test.session1";
+ StoreMetaData data2;
+ data2.appId = "local.appId";
+ data2.storeId = local.storeId;
+ data2.bundleName = "com.test.session2";
+ StoreMetaData data3;
+ data3.appId = "local.appId";
+ data3.storeId = "local.storeId";
+ data3.bundleName = "com.test.session3";
+ datas.push_back(data);
+ datas.push_back(data1);
+ datas.push_back(data2);
+ datas.push_back(data3);
+ }
static void SetUpTestCase()
{
auto executors = std::make_shared(12, 5);
Bootstrap::GetInstance().LoadComponents();
Bootstrap::GetInstance().LoadDirectory();
Bootstrap::GetInstance().LoadCheckers();
- KvStoreMetaManager::GetInstance().BindExecutor(executors);
- KvStoreMetaManager::GetInstance().InitMetaParameter();
- KvStoreMetaManager::GetInstance().InitMetaListener();
DeviceManagerAdapter::GetInstance().Init(executors);
// init peer device
@@ -102,6 +145,14 @@ public:
metaData.storeType = 1;
MetaDataManager::GetInstance().SaveMeta(metaData.GetKey(), metaData);
GrantPermissionNative();
+ deviceManagerAdapterMock = std::make_shared();
+ BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock;
+ metaDataManagerMock = std::make_shared();
+ BMetaDataManager::metaDataManager = metaDataManagerMock;
+ metaDataMock = std::make_shared>();
+ BMetaData::metaDataManager = metaDataMock;
+ userDelegateMock = std::make_shared();
+ BUserDelegate::userDelegate = userDelegateMock;
}
static void TearDownTestCase()
{
@@ -119,22 +170,149 @@ public:
metaData.uid = METADATA_UID;
metaData.storeType = 1;
MetaDataManager::GetInstance().DelMeta(metaData.GetKey());
+ deviceManagerAdapterMock = nullptr;
+ BDeviceManagerAdapter::deviceManagerAdapter = nullptr;
+ metaDataManagerMock = nullptr;
+ BMetaDataManager::metaDataManager = nullptr;
+ metaDataMock = nullptr;
+ BMetaData::metaDataManager = nullptr;
+ userDelegateMock = nullptr;
+ BUserDelegate::userDelegate = nullptr;
}
void SetUp()
{
+ ConstructValidData();
}
void TearDown()
{
}
+ void ConstructValidData()
+ {
+ const std::string storeId = "test_store";
+ InitializeBuffer();
+ ConstructRouteHead(storeId);
+ ConstructSessionDevicePair();
+ ConstructSessionUserPair();
+ ConstructSessionAppId();
+ ConstructSessionStoreId(storeId);
+
+ const size_t validlLen = sizeof(RouteHead) + sizeof(SessionDevicePair) + sizeof(SessionUserPair)
+ + sizeof(uint32_t) * 1 + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId)
+ + storeId.size();
+ validTotalLen = validlLen;
+ }
+
+ static inline std::shared_ptr deviceManagerAdapterMock = nullptr;
+ static inline std::shared_ptr metaDataManagerMock = nullptr;
+ static inline std::shared_ptr> metaDataMock = nullptr;
+ static inline std::shared_ptr userDelegateMock = nullptr;
+
+private:
+ void InitializeBuffer()
+ {
+ memset_s(dataBuffer, BUFFER_SIZE, 0, BUFFER_SIZE);
+ ptr = dataBuffer;
+ remaining = BUFFER_SIZE;
+ }
+
+ void ConstructRouteHead(const std::string &storeId)
+ {
+ RouteHead head{};
+ head.magic = HostToNet(RouteHead::MAGIC_NUMBER);
+ head.version = HostToNet(RouteHead::VERSION);
+ head.dataLen = HostToNet(sizeof(SessionDevicePair) + sizeof(SessionUserPair) + sizeof(uint32_t) * 1
+ + sizeof(SessionAppId) + APP_STR_LEN + sizeof(SessionStoreId) + storeId.size());
+ head.checkSum = 0;
+
+ errno_t err = memcpy_s(ptr, remaining, &head, sizeof(RouteHead));
+ ASSERT_EQ(err, 0) << "Failed to copy RouteHead";
+ ptr += sizeof(RouteHead);
+ remaining -= sizeof(RouteHead);
+ }
+
+ void ConstructSessionDevicePair()
+ {
+ SessionDevicePair devPair{};
+ constexpr size_t DEV_ID_SIZE = sizeof(devPair.sourceId);
+
+ errno_t err = memset_s(devPair.sourceId, DEV_ID_SIZE, 'A', DEV_ID_SIZE - 1);
+ ASSERT_EQ(err, 0) << "Failed to init sourceId";
+ devPair.sourceId[DEV_ID_SIZE - 1] = '\0';
+
+ err = memset_s(devPair.targetId, DEV_ID_SIZE, 'B', DEV_ID_SIZE - 1);
+ ASSERT_EQ(err, 0) << "Failed to init targetId";
+ devPair.targetId[DEV_ID_SIZE - 1] = '\0';
+
+ err = memcpy_s(ptr, remaining, &devPair, sizeof(SessionDevicePair));
+ ASSERT_EQ(err, 0) << "Failed to copy SessionDevicePair";
+ ptr += sizeof(SessionDevicePair);
+ remaining -= sizeof(SessionDevicePair);
+ }
+
+ void ConstructSessionUserPair()
+ {
+ SessionUserPair userPair{};
+ userPair.sourceUserId = HostToNet(100U);
+ userPair.targetUserCount = HostToNet(1U);
+
+ errno_t err = memcpy_s(ptr, remaining, &userPair, sizeof(SessionUserPair));
+ ASSERT_EQ(err, 0) << "Failed to copy SessionUserPair";
+ ptr += sizeof(SessionUserPair);
+ remaining -= sizeof(SessionUserPair);
+
+ uint32_t targetUser = HostToNet(200U);
+ err = memcpy_s(ptr, remaining, &targetUser, sizeof(uint32_t));
+ ASSERT_EQ(err, 0) << "Failed to copy targetUser";
+ ptr += sizeof(uint32_t);
+ remaining -= sizeof(uint32_t);
+ }
+
+ void ConstructSessionAppId()
+ {
+ SessionAppId appId{};
+ const char *appStr = "test";
+ appId.len = HostToNet(static_cast(APP_STR_LEN));
+
+ errno_t err = memcpy_s(ptr, remaining, &appId, sizeof(SessionAppId));
+ ASSERT_EQ(err, 0) << "Failed to copy SessionAppId";
+ ptr += sizeof(SessionAppId);
+ remaining -= sizeof(SessionAppId);
+
+ err = memcpy_s(ptr, remaining, appStr, APP_STR_LEN);
+ ASSERT_EQ(err, 0) << "Failed to copy appId data";
+ ptr += APP_STR_LEN;
+ remaining -= APP_STR_LEN;
+ }
+ void ConstructSessionStoreId(const std::string &storeId)
+ {
+ SessionStoreId storeIdHeader{};
+ storeIdHeader.len = HostToNet(static_cast(storeId.size()));
+
+ errno_t err = memcpy_s(ptr, remaining, &storeIdHeader, sizeof(SessionStoreId));
+ ASSERT_EQ(err, 0) << "Failed to copy storeId length";
+ ptr += sizeof(SessionStoreId);
+ remaining -= sizeof(SessionStoreId);
+
+ err = memcpy_s(ptr, remaining, storeId.c_str(), storeId.size());
+ ASSERT_EQ(err, 0) << "Failed to copy storeId data";
+ ptr += storeId.size();
+ remaining -= storeId.size();
+ }
+ size_t validTotalLen;
+ uint8_t dataBuffer[1024];
+ static constexpr size_t APP_STR_LEN = 4;
+ uint8_t *ptr = dataBuffer;
+ size_t remaining = BUFFER_SIZE;
+ static constexpr size_t BUFFER_SIZE = sizeof(dataBuffer);
};
/**
-* @tc.name: PackAndUnPack01
-* @tc.desc: test get db dir
-* @tc.type: FUNC
-* @tc.require:
-* @tc.author: illybyy
-*/
+ * @tc.name: PackAndUnPack01
+ * @tc.desc: test get db dir
+ * @tc.type: FUNC
+ * @tc.require:
+ * @tc.author: illybyy
+ */
HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2)
{
const DistributedDB::ExtendInfo info = {
@@ -152,9 +330,317 @@ HWTEST_F(SessionManagerTest, PackAndUnPack01, TestSize.Level2)
auto recvHandler = RouteHeadHandlerImpl::Create({});
ASSERT_NE(recvHandler, nullptr);
uint32_t parseSize = 1;
+ auto res = recvHandler->ParseHeadDataLen(nullptr, routeHeadSize, parseSize);
+ EXPECT_EQ(res, false);
recvHandler->ParseHeadDataLen(data.get(), routeHeadSize, parseSize);
EXPECT_EQ(routeHeadSize, parseSize);
recvHandler->ParseHeadDataUser(data.get(), routeHeadSize, "", users);
ASSERT_EQ(users.size(), 0);
}
+/**
+ * @tc.name: GetHeadDataSize_Test1
+ * @tc.desc: test appId equal processLabel.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1)
+{
+ ExtendInfo info;
+ RouteHeadHandlerImpl routeHeadHandlerImpl(info);
+ uint32_t headSize = 0;
+ routeHeadHandlerImpl.appId_ = Bootstrap::GetInstance().GetProcessLabel();
+ auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize);
+ EXPECT_EQ(status, DistributedDB::OK);
+ EXPECT_EQ(headSize, 0);
+}
+/**
+ * @tc.name: GetHeadDataSize_Test2
+ * @tc.desc: test appId not equal processLabel.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, GetHeadDataSize_Test2, TestSize.Level1)
+{
+ ExtendInfo info;
+ RouteHeadHandlerImpl routeHeadHandlerImpl(info);
+ uint32_t headSize = 0;
+ routeHeadHandlerImpl.appId_ = "otherAppId";
+ auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize);
+ EXPECT_EQ(status, DistributedDB::OK);
+ EXPECT_EQ(headSize, 0);
+}
+/**
+ * @tc.name: GetHeadDataSize_Test3
+ * @tc.desc: test devInfo.osType equal OH_OS_TYPE, appId not equal processLabel.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, GetHeadDataSize_Test3, TestSize.Level1)
+{
+ DeviceInfo deviceInfo;
+ deviceInfo.osType = OH_OS_TYPE;
+ EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo));
+ ExtendInfo info;
+ RouteHeadHandlerImpl routeHeadHandlerImpl(info);
+ uint32_t headSize = 0;
+ routeHeadHandlerImpl.appId_ = "otherAppId";
+ auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize);
+ EXPECT_EQ(status, DistributedDB::DB_ERROR);
+ EXPECT_EQ(headSize, 0);
+}
+/**
+ * @tc.name: GetHeadDataSize_Test4
+ * @tc.desc: test GetHeadDataSize
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, GetHeadDataSize_Test4, TestSize.Level1)
+{
+ DeviceInfo deviceInfo;
+ deviceInfo.osType = OH_OS_TYPE;
+ EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
+ EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo));
+
+ const DistributedDB::ExtendInfo info = {
+ .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
+ };
+ auto sendHandler = RouteHeadHandlerImpl::Create(info);
+ ASSERT_NE(sendHandler, nullptr);
+
+ CapMetaData capMetaData;
+ capMetaData.version = CapMetaData::CURRENT_VERSION;
+ EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _))
+ .WillRepeatedly(DoAll(SetArgReferee<1>(capMetaData), Return(true)));
+ std::vector userStatus;
+ UserStatus userStat1;
+ UserStatus userStat2;
+ UserStatus userStat3;
+ userStat1.id = 1;
+ userStat2.id = 2;
+ userStat3.id = 3;
+ userStatus.push_back(userStat1);
+ userStatus.push_back(userStat2);
+ userStatus.push_back(userStat3);
+ EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillRepeatedly(Return(userStatus));
+
+ uint32_t headSize = 0;
+ auto status = sendHandler->GetHeadDataSize(headSize);
+ EXPECT_EQ(status, DistributedDB::OK);
+ EXPECT_EQ(headSize, 0);
+
+ uint32_t routeHeadSize = 10;
+ std::unique_ptr data = std::make_unique(routeHeadSize);
+ status = sendHandler->FillHeadData(data.get(), routeHeadSize, routeHeadSize);
+ EXPECT_EQ(status, DistributedDB::DB_ERROR);
+}
+/**
+ * @tc.name: ParseHeadDataUserTest001
+ * @tc.desc: test parse null data.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, ParseHeadDataUserTest001, TestSize.Level1)
+{
+ EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
+ const DistributedDB::ExtendInfo info = {
+ .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
+ };
+ auto sendHandler = RouteHeadHandlerImpl::Create(info);
+ ASSERT_NE(sendHandler, nullptr);
+
+ uint32_t totalLen = 10;
+ std::string label = "testLabel";
+ std::vector userInfos;
+
+ bool result = sendHandler->ParseHeadDataUser(nullptr, totalLen, label, userInfos);
+
+ EXPECT_FALSE(result);
+ EXPECT_EQ(userInfos.size(), 0);
+}
+/**
+ * @tc.name: ParseHeadDataUserTest002
+ * @tc.desc: test totalLen < sizeof(RouteHead).
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, ParseHeadDataUserTest002, TestSize.Level1)
+{
+ EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
+ const DistributedDB::ExtendInfo info = {
+ .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
+ };
+ auto sendHandler = RouteHeadHandlerImpl::Create(info);
+ ASSERT_NE(sendHandler, nullptr);
+
+ uint8_t data[10] = { 0 };
+ std::string label = "testLabel";
+ std::vector userInfos;
+
+ bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead) - 1, label, userInfos);
+
+ EXPECT_FALSE(result);
+ EXPECT_EQ(userInfos.size(), 0);
+}
+
+/**
+ * @tc.name: ParseHeadDataUserTest003
+ * @tc.desc: test totalLen < sizeof(RouteHead).
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, ParseHeadDataUserTest003, TestSize.Level1)
+{
+ EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true));
+ const DistributedDB::ExtendInfo info = {
+ .appId = "otherAppId", .storeId = "test_store", .userId = "100", .dstTarget = PEER_DEVICE_ID
+ };
+ auto sendHandler = RouteHeadHandlerImpl::Create(info);
+ ASSERT_NE(sendHandler, nullptr);
+
+ uint8_t data[10] = { 0 };
+ std::string label = "testLabel";
+ std::vector userInfos;
+
+ RouteHead head = { 0 };
+ head.version = RouteHead::VERSION;
+ head.dataLen = static_cast(sizeof(data) - sizeof(RouteHead));
+
+ bool result = sendHandler->ParseHeadDataUser(data, sizeof(RouteHead), label, userInfos);
+
+ EXPECT_FALSE(result);
+ EXPECT_EQ(userInfos.size(), 0);
+}
+
+/**
+ * @tc.name: UnPackData_InvalidMagic
+ * @tc.desc: test invalid magic.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, UnPackData_InvalidMagic, TestSize.Level1)
+{
+ RouteHead *head = reinterpret_cast(dataBuffer);
+ head->magic = 0xFFFF;
+ ExtendInfo info;
+ RouteHeadHandlerImpl routeHeadHandlerImpl(info);
+ uint32_t unpackedSize;
+ EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize));
+}
+
+/**
+ * @tc.name: UnPackData_VersionMismatch
+ * @tc.desc: test version mismatch.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, UnPackData_VersionMismatch, TestSize.Level1)
+{
+ RouteHead *head = reinterpret_cast(dataBuffer);
+ head->version = 0x00;
+ ExtendInfo info;
+ RouteHeadHandlerImpl routeHeadHandlerImpl(info);
+ uint32_t unpackedSize;
+ EXPECT_FALSE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize));
+}
+
+/**
+ * @tc.name: UnPackData_ValidData
+ * @tc.desc: test valid data.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, UnPackData_ValidData, TestSize.Level1)
+{
+ ExtendInfo info;
+ RouteHeadHandlerImpl routeHeadHandlerImpl(info);
+ uint32_t unpackedSize;
+ EXPECT_TRUE(routeHeadHandlerImpl.UnPackData(dataBuffer, validTotalLen, unpackedSize));
+ EXPECT_EQ(unpackedSize, validTotalLen);
+}
+
+/**
+ * @tc.name: ShouldAddSystemUserWhenLocalUserIdIsSystem
+ * @tc.desc: test GetSession.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, ShouldAddSystemUserWhenLocalUserIdIsSystem, TestSize.Level1)
+{
+ SessionPoint local;
+ local.userId = UserDelegate::SYSTEM_USER;
+ local.appId = "test_app";
+ local.deviceId = "local_device";
+ local.storeId = "test_store";
+
+ std::vector users;
+ CreateUserStatus(users);
+ EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(users));
+ EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _))
+ .WillOnce(Return(std::pair(true, true)))
+ .WillOnce(Return(std::pair(true, false)))
+ .WillOnce(Return(std::pair(false, true)))
+ .WillOnce(Return(std::pair(false, false)));
+ std::vector datas;
+ CreateStoreMetaData(datas, local);
+ EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)).WillRepeatedly(DoAll(SetArgReferee<1>(datas), Return(true)));
+
+ Session session = SessionManager::GetInstance().GetSession(local, "target_device");
+ ASSERT_EQ(2, session.targetUserIds.size());
+ EXPECT_EQ(UserDelegate::SYSTEM_USER, session.targetUserIds[0]);
+}
+
+/**
+ * @tc.name: ShouldReturnEarlyWhenGetSendAuthParamsFails
+ * @tc.desc: test GetSession.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, ShouldReturnEarlyWhenGetSendAuthParamsFails, TestSize.Level1)
+{
+ SessionPoint local;
+ local.userId = 100;
+ local.appId = "test_app";
+ local.deviceId = "local_device";
+ EXPECT_CALL(*userDelegateMock, GetRemoteUserStatus(_)).WillOnce(Return(std::vector{}));
+ std::vector datas;
+ EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _)).WillRepeatedly(Return(false));
+
+ Session session = SessionManager::GetInstance().GetSession(local, "target_device");
+
+ EXPECT_TRUE(session.targetUserIds.empty());
+}
+
+/**
+ * @tc.name: CheckSession
+ * @tc.desc: test CheckSession.
+ * @tc.type: FUNC
+ * @tc.author: guochao
+ */
+HWTEST_F(SessionManagerTest, CheckSession, TestSize.Level1)
+{
+ SessionPoint localSys;
+ localSys.userId = UserDelegate::SYSTEM_USER;
+ localSys.appId = "test_app";
+ localSys.deviceId = "local_device";
+ localSys.storeId = "test_store";
+ SessionPoint localNormal;
+ localNormal.userId = 100;
+ localNormal.appId = "test_app";
+ localNormal.deviceId = "local_device";
+ localNormal.storeId = "test_store";
+ std::vector datas;
+ CreateStoreMetaData(datas, localSys);
+ EXPECT_CALL(*metaDataMock, LoadMeta(_, _, _))
+ .WillOnce(DoAll(SetArgReferee<1>(datas), Return(false)))
+ .WillRepeatedly(DoAll(SetArgReferee<1>(datas), Return(true)));
+ EXPECT_CALL(AuthHandlerMock::GetInstance(), CheckAccess(_, _, _, _))
+ .WillOnce(Return(std::pair(false, true)))
+ .WillOnce(Return(std::pair(true, false)));
+ bool result = SessionManager::GetInstance().CheckSession(localSys, localNormal);
+ EXPECT_FALSE(result);
+ result = SessionManager::GetInstance().CheckSession(localSys, localNormal);
+ EXPECT_FALSE(result);
+ result = SessionManager::GetInstance().CheckSession(localNormal, localSys);
+ EXPECT_TRUE(result);
+}
} // namespace
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn
index f85d7b550348928f82494508b66ddc537bca4d41..a99bba56a8357c480ade0ff429361df15181ce3b 100644
--- a/services/distributeddataservice/framework/BUILD.gn
+++ b/services/distributeddataservice/framework/BUILD.gn
@@ -76,6 +76,7 @@ ohos_shared_library("distributeddatasvcfwk") {
"cloud/sync_event.cpp",
"cloud/sync_strategy.cpp",
"communication/connect_manager.cpp",
+ "device_sync_app/device_sync_app_manager.cpp",
"dfx/reporter.cpp",
"directory/directory_manager.cpp",
"dump/dump_manager.cpp",
@@ -88,9 +89,11 @@ ohos_shared_library("distributeddatasvcfwk") {
"metadata/capability_meta_data.cpp",
"metadata/capability_range.cpp",
"metadata/corrupted_meta_data.cpp",
+ "metadata/device_meta_data.cpp",
"metadata/matrix_meta_data.cpp",
"metadata/meta_data.cpp",
"metadata/meta_data_manager.cpp",
+ "metadata/object_user_meta_data.cpp",
"metadata/secret_key_meta_data.cpp",
"metadata/store_debug_info.cpp",
"metadata/store_meta_data.cpp",
diff --git a/services/distributeddataservice/framework/cloud/cloud_db.cpp b/services/distributeddataservice/framework/cloud/cloud_db.cpp
index 863475888ff457cd9be3f5886f66524197822fc5..3d916243ee02ca5b969453b05c26e6279643a478 100644
--- a/services/distributeddataservice/framework/cloud/cloud_db.cpp
+++ b/services/distributeddataservice/framework/cloud/cloud_db.cpp
@@ -40,14 +40,14 @@ int32_t CloudDB::BatchDelete(const std::string &table, VBuckets &extends)
return E_NOT_SUPPORT;
}
-std::shared_ptr CloudDB::Query(const std::string &table, const VBucket &extend)
+std::pair> CloudDB::Query(const std::string &table, const VBucket &extend)
{
- return nullptr;
+ return { E_NOT_SUPPORT, nullptr };
}
-std::shared_ptr CloudDB::Query(GenQuery &query, const VBucket &extend)
+std::pair> CloudDB::Query(GenQuery &query, const VBucket &extend)
{
- return nullptr;
+ return { E_NOT_SUPPORT, nullptr };
}
int32_t CloudDB::PreSharing(const std::string &table, VBuckets &extend)
diff --git a/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e20ee46ef181dd261371ee36788e70cd6f83cc79
--- /dev/null
+++ b/services/distributeddataservice/framework/device_sync_app/device_sync_app_manager.cpp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2025 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 "DeviceSyncAppManager"
+#include "device_sync_app/device_sync_app_manager.h"
+
+namespace OHOS::DistributedData {
+DeviceSyncAppManager::DeviceSyncAppManager()
+{
+}
+
+DeviceSyncAppManager &DeviceSyncAppManager::GetInstance()
+{
+ static DeviceSyncAppManager instance;
+ return instance;
+}
+
+void DeviceSyncAppManager::Initialize(const std::vector &lists)
+{
+ for (const auto &list : lists) {
+ whiteLists_.push_back(list);
+ }
+}
+
+bool DeviceSyncAppManager::Check(const WhiteList &whiteList)
+{
+ for (const auto &info : whiteLists_) {
+ if (info.appId == whiteList.appId && (info.bundleName == whiteList.bundleName) &&
+ (info.version == whiteList.version)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+} // namespace OHOS::DistributedData
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/include/cloud/cloud_db.h b/services/distributeddataservice/framework/include/cloud/cloud_db.h
index fcf7cfca5ca9daad3767417064e393b02a466ef2..58933563237ba73b5b47333cf274534de12f1819 100644
--- a/services/distributeddataservice/framework/include/cloud/cloud_db.h
+++ b/services/distributeddataservice/framework/include/cloud/cloud_db.h
@@ -40,9 +40,9 @@ public:
virtual int32_t BatchDelete(const std::string &table, VBuckets &extends);
- virtual std::shared_ptr Query(const std::string &table, const VBucket &extend);
+ virtual std::pair> Query(const std::string &table, const VBucket &extend);
- virtual std::shared_ptr Query(GenQuery &query, const VBucket &extend);
+ virtual std::pair> Query(GenQuery &query, const VBucket &extend);
virtual int32_t PreSharing(const std::string &table, VBuckets &extend);
diff --git a/services/distributeddataservice/framework/include/cloud/schema_meta.h b/services/distributeddataservice/framework/include/cloud/schema_meta.h
index bc74d210b11676ad6a4835461066605d599ca8d8..33dc0cb41946842ab8e357ee76d2baa23fde2325 100644
--- a/services/distributeddataservice/framework/include/cloud/schema_meta.h
+++ b/services/distributeddataservice/framework/include/cloud/schema_meta.h
@@ -73,7 +73,8 @@ public:
static constexpr const char *SHARING_RESOURCE = "#_sharing_resource";
static constexpr const char *HASH_KEY = "#_hash_key";
- static constexpr uint32_t CURRENT_VERSION = 0x10000;
+ static constexpr uint32_t CURRENT_VERSION = 0x10001;
+ static constexpr uint32_t CLEAN_WATER_VERSION = 0x10001;
static inline uint32_t GetLowVersion(uint32_t metaVersion = CURRENT_VERSION)
{
return metaVersion & 0xFFFF;
@@ -104,4 +105,4 @@ enum AutoSyncType {
};
} // namespace OHOS::DistributedData
-#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CLOUD_SCHEMA_META_H
+#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_CLOUD_SCHEMA_META_H
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h b/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h
new file mode 100644
index 0000000000000000000000000000000000000000..664883bce41c938e7644226cef7392cd7daf0a88
--- /dev/null
+++ b/services/distributeddataservice/framework/include/device_sync_app/device_sync_app_manager.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2025 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H
+#define DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H
+
+#include
+#include
+#include "visibility.h"
+namespace OHOS::DistributedData {
+class DeviceSyncAppManager {
+public:
+ struct WhiteList {
+ std::string appId;
+ std::string bundleName;
+ uint32_t version;
+ };
+ API_EXPORT static DeviceSyncAppManager &GetInstance();
+ API_EXPORT void Initialize(const std::vector &lists);
+ API_EXPORT bool Check(const WhiteList &whiteList);
+
+private:
+ DeviceSyncAppManager();
+ std::vector whiteLists_;
+};
+} // namespace OHOS::DistributedData
+#endif // DISTRIBUTEDDATAMGR_DEVICE_SYNC_APP_MANAGER_H
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/include/metadata/device_meta_data.h b/services/distributeddataservice/framework/include/metadata/device_meta_data.h
new file mode 100644
index 0000000000000000000000000000000000000000..7df8c5564c90f2f750cf90cdd569522bf1dc1d7a
--- /dev/null
+++ b/services/distributeddataservice/framework/include/metadata/device_meta_data.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2025 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_DEVICE_META_DATA_H
+#define OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H
+#include
+
+#include "serializable/serializable.h"
+namespace OHOS::DistributedData {
+class API_EXPORT DeviceMetaData final : public Serializable {
+public:
+ API_EXPORT DeviceMetaData();
+ API_EXPORT ~DeviceMetaData();
+ API_EXPORT bool Marshal(json &node) const override;
+ API_EXPORT bool Unmarshal(const json &node) override;
+ API_EXPORT std::string GetKey() const;
+
+ std::string newUuid = "";
+ std::string oldUuid = "";
+};
+} // namespace OHOS::DistributedData
+#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_METADATA_DEVICE_META_DATA_H
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h
new file mode 100644
index 0000000000000000000000000000000000000000..cd2dd38e44135a2569b93ff5821c623d3c014e77
--- /dev/null
+++ b/services/distributeddataservice/framework/include/metadata/object_user_meta_data.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2025 Huawei Device Co., Ltd.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H
+#define DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H
+
+#include "serializable/serializable.h"
+namespace OHOS::DistributedData {
+class API_EXPORT ObjectUserMetaData final : public Serializable {
+public:
+ std::string userId;
+
+ API_EXPORT bool Marshal(json &node) const override;
+ API_EXPORT bool Unmarshal(const json &node) override;
+ API_EXPORT ObjectUserMetaData();
+
+ API_EXPORT static std::string GetKey();
+
+private:
+ static constexpr const char *KEY_PREFIX = "ObjectUserMetaData";
+};
+} // namespace OHOS::DistributedData
+#endif // DISTRIBUTEDDATAMGR_OBJECT_USER_META_DATA_H
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/include/metadata/store_meta_data.h b/services/distributeddataservice/framework/include/metadata/store_meta_data.h
index e0a614e2d2d47f94119198b21e8972b2e97b807c..2d17763414843203eae334f12a38925ddfec2c59 100644
--- a/services/distributeddataservice/framework/include/metadata/store_meta_data.h
+++ b/services/distributeddataservice/framework/include/metadata/store_meta_data.h
@@ -60,6 +60,7 @@ struct API_EXPORT StoreMetaData final : public Serializable {
std::string account = "";
int32_t authType = 0;
bool asyncDownloadAsset = false;
+ bool isNeedUpdateDeviceId = false;
enum StoreType {
STORE_KV_BEGIN = 0,
diff --git a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h
index a3cb9275bc3378a707afaf9081242386cb5728fd..25feaeded8b904f311a80118c83042a6e25f622f 100644
--- a/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h
+++ b/services/distributeddataservice/framework/include/metadata/strategy_meta_data.h
@@ -29,6 +29,7 @@ struct API_EXPORT StrategyMeta final : public Serializable {
API_EXPORT StrategyMeta(const std::string &devId, const std::string &userId, const std::string &bundleName,
const std::string &storeId);
+ API_EXPORT StrategyMeta() {};
API_EXPORT ~StrategyMeta() {};
API_EXPORT bool Marshal(json &node) const override;
API_EXPORT bool Unmarshal(const json &node) override;
diff --git a/services/distributeddataservice/framework/include/network/network_delegate.h b/services/distributeddataservice/framework/include/network/network_delegate.h
index ae7e9f94aba2dcff0a84aa721585ddb65e6ce35e..38763f58d68e1cff6b7d90c66b64709af52481b0 100644
--- a/services/distributeddataservice/framework/include/network/network_delegate.h
+++ b/services/distributeddataservice/framework/include/network/network_delegate.h
@@ -19,7 +19,8 @@
#include
#include
-#include "types.h"
+#include "executor_pool.h"
+#include "visibility.h"
namespace OHOS {
namespace DistributedData {
@@ -37,6 +38,7 @@ public:
API_EXPORT static bool RegisterNetworkInstance(NetworkDelegate *instance);
virtual bool IsNetworkAvailable() = 0;
virtual void RegOnNetworkChange() = 0;
+ virtual void BindExecutor(std::shared_ptr executors) = 0;
virtual NetworkType GetNetworkType(bool retrieve = false) = 0;
private:
diff --git a/services/distributeddataservice/framework/include/store/general_store.h b/services/distributeddataservice/framework/include/store/general_store.h
index 3789ae685a618496b1f3a170369ea882c40bdf80..dc109463a23646ff36efa977381f77d7c0694f63 100644
--- a/services/distributeddataservice/framework/include/store/general_store.h
+++ b/services/distributeddataservice/framework/include/store/general_store.h
@@ -61,6 +61,7 @@ public:
CLOUD_DATA,
CLOUD_INFO,
LOCAL_DATA,
+ CLEAN_WATER,
CLEAN_MODE_BUTT
};
@@ -197,6 +198,11 @@ public:
virtual std::pair LockCloudDB() = 0;
virtual int32_t UnLockCloudDB() = 0;
+
+ virtual int32_t UpdateDBStatus()
+ {
+ return 0;
+ }
};
} // namespace OHOS::DistributedData
#endif // OHOS_DISTRIBUTED_DATA_SERVICES_FRAMEWORK_STORE_GENERAL_STORE_H
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/include/store/general_value.h b/services/distributeddataservice/framework/include/store/general_value.h
index e1f9b3a18a43b90e8756dfb92b7794276d4e437f..888c9f7c151ab147b1cb9dce1d3080f6875ce9a3 100644
--- a/services/distributeddataservice/framework/include/store/general_value.h
+++ b/services/distributeddataservice/framework/include/store/general_value.h
@@ -115,6 +115,7 @@ struct ReportParam {
std::string prepareTraceId;
SyncStage syncStage = SyncStage::PREPARE;
int32_t errCode = 0;
+ std::string message = "";
};
using Assets = std::vector;
diff --git a/services/distributeddataservice/framework/metadata/device_meta_data.cpp b/services/distributeddataservice/framework/metadata/device_meta_data.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c16c6400f140d94755c3ad0fe9497408e94a9a08
--- /dev/null
+++ b/services/distributeddataservice/framework/metadata/device_meta_data.cpp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2025 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/device_meta_data.h"
+
+namespace OHOS {
+namespace DistributedData {
+static constexpr const char *KEY_PREFIX = "DeviceMeta";
+bool DeviceMetaData::Marshal(json &node) const
+{
+ SetValue(node[GET_NAME(newUuid)], newUuid);
+ SetValue(node[GET_NAME(oldUuid)], oldUuid);
+ return true;
+}
+
+bool DeviceMetaData::Unmarshal(const json &node)
+{
+ GetValue(node, GET_NAME(newUuid), newUuid);
+ GetValue(node, GET_NAME(oldUuid), oldUuid);
+ return true;
+}
+
+DeviceMetaData::DeviceMetaData()
+{
+}
+
+DeviceMetaData::~DeviceMetaData()
+{
+}
+
+std::string DeviceMetaData::GetKey() const
+{
+ return KEY_PREFIX;
+}
+} // namespace DistributedData
+} // namespace OHOS
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c5d5d9e073ae8cd22c4799b1ca85bd8eeabf340f
--- /dev/null
+++ b/services/distributeddataservice/framework/metadata/object_user_meta_data.cpp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2025 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/object_user_meta_data.h"
+
+namespace OHOS::DistributedData {
+ObjectUserMetaData::ObjectUserMetaData()
+{
+}
+bool ObjectUserMetaData::Marshal(json &node) const
+{
+ return SetValue(node[GET_NAME(userId)], userId);
+}
+
+bool ObjectUserMetaData::Unmarshal(const json &node)
+{
+ return GetValue(node, GET_NAME(userId), userId);
+}
+
+std::string ObjectUserMetaData::GetKey()
+{
+ return KEY_PREFIX;
+}
+}
\ 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
index f3d16332619aaf4be82aec62858b71b11dde7a1b..61d6785804a0bcdcc9553cbf4f829d08fd4d5031 100644
--- a/services/distributeddataservice/framework/metadata/store_meta_data.cpp
+++ b/services/distributeddataservice/framework/metadata/store_meta_data.cpp
@@ -57,6 +57,7 @@ bool StoreMetaData::Marshal(json &node) const
SetValue(node[GET_NAME(enableCloud)], enableCloud);
SetValue(node[GET_NAME(cloudAutoSync)], cloudAutoSync);
SetValue(node[GET_NAME(asyncDownloadAsset)], asyncDownloadAsset);
+ SetValue(node[GET_NAME(isNeedUpdateDeviceId)], isNeedUpdateDeviceId);
// compatible with the versions which lower than VERSION_TAG_0000
SetValue(node[GET_NAME(kvStoreType)], storeType);
SetValue(node[GET_NAME(deviceAccountID)], user);
@@ -98,6 +99,7 @@ bool StoreMetaData::Unmarshal(const json &node)
GetValue(node, GET_NAME(enableCloud), enableCloud);
GetValue(node, GET_NAME(cloudAutoSync), cloudAutoSync);
GetValue(node, GET_NAME(asyncDownloadAsset), asyncDownloadAsset);
+ GetValue(node, GET_NAME(isNeedUpdateDeviceId), isNeedUpdateDeviceId);
// compatible with the older versions
if (version < FIELD_CHANGED_TAG) {
GetValue(node, GET_NAME(kvStoreType), storeType);
@@ -138,7 +140,8 @@ bool StoreMetaData::operator==(const StoreMetaData &metaData) const
Constant::NotEqual(isNeedCompress, metaData.isNeedCompress) ||
Constant::NotEqual(enableCloud, metaData.enableCloud) ||
Constant::NotEqual(cloudAutoSync, metaData.cloudAutoSync) ||
- Constant::NotEqual(isManualClean, metaData.isManualClean)) {
+ Constant::NotEqual(isManualClean, metaData.isManualClean) ||
+ Constant::NotEqual(isNeedUpdateDeviceId, metaData.isNeedUpdateDeviceId)) {
return false;
}
return (version == metaData.version && storeType == metaData.storeType && dataType == metaData.dataType &&
diff --git a/services/distributeddataservice/framework/test/BUILD.gn b/services/distributeddataservice/framework/test/BUILD.gn
index 619dc289a82912a2501af701e19cd29e29fa7b7b..4417c7c7a3a08a8a1290cb40426b9b65309162ad 100644
--- a/services/distributeddataservice/framework/test/BUILD.gn
+++ b/services/distributeddataservice/framework/test/BUILD.gn
@@ -14,37 +14,26 @@ import("//build/ohos_var.gni")
import("//build/test.gni")
import("//foundation/distributeddatamgr/datamgr_service/datamgr_service.gni")
-module_output_path = "datamgr_service/distributeddatafwk"
+module_output_path = "datamgr_service/datamgr_service/distributeddatafwk"
###############################################################################
config("module_private_config") {
visibility = [ ":*" ]
include_dirs = [
- "${device_manager_path}/interfaces/inner_kits/native_cpp/include",
- "../include/",
- "../../service/bootstrap/include/",
- "../../service/common/",
- "../../service/rdb/",
- "../../../../../relational_store/interfaces/inner_api/rdb/include",
- "../../../../../relational_store/interfaces/inner_api/common_type/include",
- "${kv_store_distributeddb_path}/interfaces/include",
- "${kv_store_distributeddb_path}/include",
- "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include",
- "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include",
- "${kv_store_common_path}",
- "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src",
- "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include",
- "${kv_store_path}/interfaces/innerkits/distributeddata/include",
+ "${data_service_path}/service/bootstrap/include/",
+ "${data_service_path}/service/common/",
+ "${data_service_path}/service/rdb/",
"${data_service_path}/adapter/include",
"${data_service_path}/framework/include",
"${data_service_path}/service/config/include",
"${data_service_path}/app/src",
"${data_service_path}/adapter/include/account",
+ "${data_service_path}/adapter/include/communicator",
"${data_service_path}/app/src/security",
"${data_service_path}/service/crypto/include",
"${data_service_path}/service/matrix/include",
- "//third_party/json/single_include",
+ "${data_service_path}/service/kvdb",
]
cflags = [ "-Werror" ]
ldflags = [ "-Wl,--whole-archive" ]
@@ -61,17 +50,17 @@ ohos_unittest("CheckerManagerTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"c_utils:utils",
+ "googletest:gtest_main",
"hilog:libhilog",
"ipc:ipc_core",
+ "kv_store:distributeddata_inner",
+ "openssl:libcrypto_shared",
]
deps = [
"${data_service_path}/app/src/checker:distributeddata_checker",
- "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk",
- "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service:distributeddatasvc",
- "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
- "//third_party/googletest:gtest_main",
- "//third_party/openssl:libcrypto_shared",
+ "${data_service_path}/framework:distributeddatasvcfwk",
+ "${data_service_path}/service:distributeddatasvc",
]
}
@@ -83,15 +72,13 @@ ohos_unittest("EventCenterTest") {
external_deps = [
"c_utils:utils",
+ "googletest:gtest_main",
"hilog:libhilog",
"ipc:ipc_core",
+ "kv_store:distributeddata_inner",
]
- deps = [
- "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk",
- "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
- "//third_party/googletest:gtest_main",
- ]
+ deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
}
ohos_unittest("SerializableTest") {
@@ -105,16 +92,14 @@ ohos_unittest("SerializableTest") {
"ability_base:base",
"ability_base:want",
"c_utils:utils",
+ "googletest:gtest_main",
"hilog:libhilog",
"ipc:ipc_core",
+ "kv_store:distributeddata_inner",
+ "openssl:libcrypto_shared",
]
- deps = [
- "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk",
- "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:distributeddata_inner",
- "//third_party/googletest:gtest_main",
- "//third_party/openssl:libcrypto_shared",
- ]
+ deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
}
ohos_unittest("ServiceUtilsTest") {
@@ -133,14 +118,13 @@ ohos_unittest("ServiceUtilsTest") {
"access_token:libaccesstoken_sdk",
"access_token:libnativetoken",
"c_utils:utils",
+ "googletest:gtest_main",
"hilog:libhilog",
"ipc:ipc_core",
+ "json:nlohmann_json_static",
]
- deps = [
- "${data_service_path}/framework:distributeddatasvcfwk",
- "//third_party/googletest:gtest_main",
- ]
+ deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
}
ohos_unittest("StoreTest") {
@@ -170,6 +154,7 @@ ohos_unittest("StoreTest") {
"access_token:libnativetoken",
"c_utils:utils",
"common_event_service:cesfwk_innerkits",
+ "googletest:gtest_main",
"hilog:libhilog",
"ipc:ipc_core",
"kv_store:distributeddata_inner",
@@ -183,7 +168,6 @@ ohos_unittest("StoreTest") {
"${data_service_path}/service:distributeddatasvc",
"${data_service_path}/service/common:distributeddata_common",
"${data_service_path}/service/test/mock:distributeddata_mock_static",
- "//third_party/googletest:gtest_main",
]
}
@@ -213,6 +197,11 @@ ohos_unittest("CloudInfoTest") {
sources = [ "cloud_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
+
+ external_deps = [
+ "json:nlohmann_json_static",
+ "kv_store:datamgr_common",
+ ]
}
ohos_unittest("EventTest") {
@@ -227,6 +216,7 @@ ohos_unittest("GeneralStoreTest") {
sources = [ "general_store_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
+ external_deps = [ "kv_store:datamgr_common" ]
}
ohos_unittest("SubscriptionTest") {
@@ -234,16 +224,18 @@ ohos_unittest("SubscriptionTest") {
sources = [ "subscription_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
+ external_deps = [
+ "json:nlohmann_json_static",
+ "kv_store:datamgr_common",
+ ]
}
ohos_unittest("FeatureTest") {
module_out_path = module_output_path
sources = [ "feature_test.cpp" ]
configs = [ ":module_private_config" ]
- deps = [
- "${data_service_path}/framework:distributeddatasvcfwk",
- "${kv_store_path}/interfaces/innerkits/distributeddata:distributeddata_inner",
- ]
+ deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
+ external_deps = [ "kv_store:distributeddata_inner" ]
}
ohos_unittest("MetaDataManagerTest") {
@@ -255,14 +247,15 @@ ohos_unittest("MetaDataManagerTest") {
external_deps = [
"c_utils:utils",
+ "googletest:gtest_main",
"hilog:libhilog",
"ipc:ipc_core",
+ "json:nlohmann_json_static",
]
deps = [
"${data_service_path}/framework:distributeddatasvcfwk",
"${data_service_path}/service:distributeddatasvc",
- "//third_party/googletest:gtest_main",
]
}
@@ -271,6 +264,7 @@ ohos_unittest("StoreMetaDataLocalTest") {
sources = [ "store_meta_data_local_test.cpp" ]
configs = [ ":module_private_config" ]
deps = [ "${data_service_path}/framework:distributeddatasvcfwk" ]
+ external_deps = [ "json:nlohmann_json_static" ]
}
ohos_unittest("ConstantTest") {
@@ -301,49 +295,29 @@ ohos_unittest("ServiceMetaDataTest") {
debug = false
}
- configs = [ ":module_private_config" ]
-
- include_dirs = [
- "${device_manager_path}/interfaces/inner_kits/native_cpp/include",
- "../include/",
- "../../service/bootstrap/include/",
- "../../service/common/",
- "../../service/rdb/",
- "../../../../../relational_store/interfaces/inner_api/rdb/include",
- "../../../../../relational_store/interfaces/inner_api/common_type/include",
- "${kv_store_distributeddb_path}/interfaces/include",
- "${kv_store_distributeddb_path}/include",
- "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include",
- "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include",
- "${kv_store_common_path}",
- "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src",
- "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include",
- "${kv_store_path}/interfaces/innerkits/distributeddata/include",
- "${data_service_path}/adapter/include",
- "${data_service_path}/framework/include",
- "${data_service_path}/service/config/include",
- "${data_service_path}/app/src",
- "${data_service_path}/adapter/include/account",
- "${data_service_path}/app/src/security",
- "${data_service_path}/service/crypto/include",
- "${data_service_path}/service/matrix/include",
- "${data_service_path}/service/kvdb",
- "//third_party/json/single_include",
- "${data_service_path}/adapter/include/communicator",
+ cflags = [
+ "-Dprivate=public",
+ "-Dprotected=public",
]
+ configs = [ ":module_private_config" ]
+
external_deps = [
"c_utils:utils",
"dataclassification:data_transit_mgr",
"device_auth:deviceauth_sdk",
+ "device_manager:devicemanagersdk",
+ "googletest:gtest_main",
"hilog:libhilog",
"hisysevent:libhisysevent",
"hitrace:hitrace_meter",
"hitrace:libhitracechain",
"ipc:ipc_core",
+ "json:nlohmann_json_static",
"kv_store:distributeddata_inner",
"kv_store:distributeddata_mgr",
"kv_store:distributeddb",
+ "openssl:libcrypto_shared",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
@@ -355,11 +329,6 @@ ohos_unittest("ServiceMetaDataTest") {
"${data_service_path}/app/src/checker:distributeddata_checker",
"${data_service_path}/framework:distributeddatasvcfwk",
"${data_service_path}/service/kvdb:distributeddata_kvdb",
- "${kv_store_distributeddb_path}:distributeddb",
- "${kv_store_path}/interfaces/innerkits/distributeddata:distributeddata_inner",
- "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr",
- "//third_party/googletest:gtest_main",
- "//third_party/openssl:libcrypto_shared",
]
}
diff --git a/services/distributeddataservice/framework/test/cloud_test.cpp b/services/distributeddataservice/framework/test/cloud_test.cpp
index 1940f95fc3bf7f00f54b53f6d4c7e89d7f94f507..5179ef0176e1ec1d57250cbd3ce39694cbc6680e 100644
--- a/services/distributeddataservice/framework/test/cloud_test.cpp
+++ b/services/distributeddataservice/framework/test/cloud_test.cpp
@@ -502,9 +502,9 @@ HWTEST_F(ServicesCloudDBTest, CloudDB, TestSize.Level0)
EXPECT_EQ(result1, GeneralError::E_NOT_SUPPORT);
auto result2 = cloudDB.Query(table, extend);
- EXPECT_EQ(result2, nullptr);
+ EXPECT_EQ(result2.second, nullptr);
result2 = cloudDB.Query(query, extend);
- EXPECT_EQ(result2, nullptr);
+ EXPECT_EQ(result2.second, nullptr);
auto result3 = cloudDB.AliveTime();
EXPECT_EQ(result3, -1);
diff --git a/services/distributeddataservice/framework/test/meta_data_test.cpp b/services/distributeddataservice/framework/test/meta_data_test.cpp
index 6bc7f9186660c6249d080330c6055b655892cef2..58359051ec6464c24a2a9c25a60d52f552f63bca 100644
--- a/services/distributeddataservice/framework/test/meta_data_test.cpp
+++ b/services/distributeddataservice/framework/test/meta_data_test.cpp
@@ -15,6 +15,9 @@
#include "bootstrap.h"
#include "kvstore_meta_manager.h"
+
+#include "metadata/appid_meta_data.h"
+#include "metadata/auto_launch_meta_data.h"
#include "metadata/appid_meta_data.h"
#include "metadata/capability_meta_data.h"
#include "metadata/capability_range.h"
@@ -22,11 +25,14 @@
#include "metadata/matrix_meta_data.h"
#include "metadata/meta_data.h"
#include "metadata/meta_data_manager.h"
+#include "metadata/object_user_meta_data.h"
#include "metadata/secret_key_meta_data.h"
#include "metadata/store_meta_data.h"
#include "metadata/store_meta_data_local.h"
#include "metadata/strategy_meta_data.h"
+#include "metadata/switches_meta_data.h"
#include "metadata/user_meta_data.h"
+#include "metadata/device_meta_data.h"
#include "utils/constant.h"
#include "gtest/gtest.h"
#include
@@ -794,4 +800,212 @@ HWTEST_F(ServiceMetaDataTest, MatrixMetaData, TestSize.Level1)
std::string key = matrixMetaData3.GetConsistentKey();
EXPECT_EQ(key, "MatrixMeta###DEVICE_ID###Consistent");
}
+
+/**
+ * @tc.name: DeviceMetaData
+ * @tc.desc: test DeviceMetaData function
+ * @tc.type: FUNC
+ * @tc.require:
+ * @tc.author: yl
+ */
+HWTEST_F(ServiceMetaDataTest, DeviceMetaData, TestSize.Level1)
+{
+ DeviceMetaData metaData;
+ std::string newUuid = "newuuid";
+ std::string oldUuid = "olduuid";
+ metaData.newUuid = newUuid;
+ metaData.oldUuid = oldUuid;
+ Serializable::json node1;
+ metaData.Marshal(node1);
+ EXPECT_EQ(node1["newUuid"], newUuid);
+ EXPECT_EQ(node1["oldUuid"], oldUuid);
+
+ DeviceMetaData newMetaData;
+ newMetaData.Unmarshal(node1);
+ EXPECT_EQ(newMetaData.newUuid, newUuid);
+ EXPECT_EQ(newMetaData.oldUuid, oldUuid);
+}
+
+/**
+* @tc.name: InitMeta
+* @tc.desc: test Init TestMeta
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: yl
+*/
+HWTEST_F(ServiceMetaDataTest, InitTestMeta, TestSize.Level1)
+{
+ StoreMetaData oldMeta;
+ oldMeta.deviceId = "mockOldUuid";
+ oldMeta.user = "200";
+ oldMeta.bundleName = "test_appid_001";
+ oldMeta.storeId = "test_storeid_001";
+ oldMeta.isEncrypt = true;
+ bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta, true);
+ EXPECT_TRUE(isSuccess);
+ StoreMetaDataLocal metaDataLocal;
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKeyLocal(), metaDataLocal, true);
+ EXPECT_TRUE(isSuccess);
+ SwitchesMetaData switchesMetaData;
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(SwitchesMetaData::GetPrefix({"mockOldUuid"}),
+ switchesMetaData, true);
+ EXPECT_TRUE(isSuccess);
+ AutoLaunchMetaData autoLaunchMetaData;
+ MetaDataManager::GetInstance().SaveMeta(AutoLaunchMetaData::GetPrefix({ oldMeta.deviceId, oldMeta.user,
+ "default", oldMeta.bundleName, "" }), autoLaunchMetaData, true);
+ EXPECT_TRUE(isSuccess);
+ MatrixMetaData matrixMeta0;
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({"mockOldUuid"}), matrixMeta0, true);
+ EXPECT_TRUE(isSuccess);
+
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKey(), oldMeta);
+ EXPECT_TRUE(isSuccess);
+ MatrixMetaData matrixMeta;
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(MatrixMetaData::GetPrefix({"mockOldUuid"}), matrixMeta);
+ EXPECT_TRUE(isSuccess);
+ UserMetaData userMeta;
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(UserMetaRow::GetKeyFor("mockOldUuid"), userMeta);
+ EXPECT_TRUE(isSuccess);
+ CapMetaData capMetaData;
+ auto capKey = CapMetaRow::GetKeyFor("mockOldUuid");
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(std::string(capKey.begin(), capKey.end()), capMetaData);
+ EXPECT_TRUE(isSuccess);
+ StrategyMeta strategyMeta;
+ isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetStrategyKey(), strategyMeta);
+ EXPECT_TRUE(isSuccess);
+}
+
+/**
+* @tc.name: UpdateStoreMetaData
+* @tc.desc: test UpdateStoreMetaData function
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: yl
+*/
+HWTEST_F(ServiceMetaDataTest, UpdateStoreMetaData, TestSize.Level1)
+{
+ std::string mockNewUuid = "mockNewUuid";
+ std::string mockOldUuid = "mockOldUuid";
+ StoreMetaData newMeta;
+ newMeta.deviceId = "mockNewUuid";
+ newMeta.user = "200";
+ newMeta.bundleName = "test_appid_001";
+ newMeta.storeId = "test_storeid_001";
+ KvStoreMetaManager::GetInstance().UpdateStoreMetaData(mockNewUuid, mockOldUuid);
+ bool isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetKey(), newMeta, true);
+ EXPECT_TRUE(isSuccess);
+ EXPECT_TRUE(newMeta.isNeedUpdateDeviceId);
+ isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetKey(), newMeta);
+ EXPECT_TRUE(isSuccess);
+ AutoLaunchMetaData autoLaunchMetaData;
+ isSuccess = MetaDataManager::GetInstance().LoadMeta(AutoLaunchMetaData::GetPrefix({ newMeta.deviceId, newMeta.user,
+ "default", newMeta.bundleName, "" }), autoLaunchMetaData, true);
+ EXPECT_TRUE(isSuccess);
+ StrategyMeta strategyMeta;
+ isSuccess = MetaDataManager::GetInstance().LoadMeta(newMeta.GetStrategyKey(), strategyMeta);
+ EXPECT_TRUE(isSuccess);
+}
+
+/**
+* @tc.name: UpdateMetaDatas
+* @tc.desc: test UpdateMetaDatas function
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: yl
+*/
+HWTEST_F(ServiceMetaDataTest, UpdateMetaDatas, TestSize.Level1)
+{
+ std::string mockNewUuid = "mockNewUuid";
+ std::string mockOldUuid = "mockOldUuid";
+ StoreMetaData newMeta;
+ newMeta.deviceId = "mockNewUuid";
+ newMeta.user = "200";
+ newMeta.bundleName = "test_appid_001";
+ newMeta.storeId = "test_storeid_001";
+ KvStoreMetaManager::GetInstance().UpdateMetaDatas(mockNewUuid, mockOldUuid);
+ MatrixMetaData matrixMeta;
+ bool isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }),
+ matrixMeta, true);
+ EXPECT_TRUE(isSuccess);
+ isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), matrixMeta);
+ EXPECT_TRUE(isSuccess);
+ UserMetaData userMeta;
+ isSuccess = MetaDataManager::GetInstance().LoadMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), userMeta);
+ EXPECT_TRUE(isSuccess);
+ CapMetaData capMetaData;
+ auto capKey = CapMetaRow::GetKeyFor("mockNewUuid");
+ isSuccess = MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMetaData);
+ EXPECT_TRUE(isSuccess);
+ SwitchesMetaData switchesMetaData;
+ isSuccess = MetaDataManager::GetInstance().LoadMeta(SwitchesMetaData::GetPrefix({ "mockNewUuid" }),
+ switchesMetaData, true);
+ EXPECT_TRUE(isSuccess);
+}
+
+/**
+* @tc.name: DelInitTestMeta
+* @tc.desc: test Del TestMeta
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: yl
+*/
+HWTEST_F(ServiceMetaDataTest, DelTestMeta, TestSize.Level1)
+{
+ StoreMetaData newMeta;
+ newMeta.deviceId = "mockNewUuid";
+ newMeta.user = "200";
+ newMeta.bundleName = "test_appid_001";
+ newMeta.storeId = "test_storeid_001";
+ bool isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKey(), true);
+ EXPECT_TRUE(isSuccess);
+ isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKeyLocal(), true);
+ EXPECT_TRUE(isSuccess);
+ isSuccess = MetaDataManager::GetInstance().DelMeta(SwitchesMetaData::GetPrefix({ "mockNewUuid" }), true);
+ EXPECT_TRUE(isSuccess);
+ MetaDataManager::GetInstance().DelMeta(AutoLaunchMetaData::GetPrefix({ "mockNewUuid", newMeta.user,
+ "default", newMeta.bundleName, "" }), true);
+ EXPECT_TRUE(isSuccess);
+ isSuccess = MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({ "mockNewUuid" }), true);
+ EXPECT_TRUE(isSuccess);
+
+ isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetKey());
+ EXPECT_TRUE(isSuccess);
+ isSuccess = MetaDataManager::GetInstance().DelMeta(MatrixMetaData::GetPrefix({"mockNewUuid"}));
+ EXPECT_TRUE(isSuccess);
+ isSuccess = MetaDataManager::GetInstance().DelMeta(UserMetaRow::GetKeyFor("mockNewUuid"));
+ EXPECT_TRUE(isSuccess);
+ auto capKey = CapMetaRow::GetKeyFor("mockNewUuid");
+ isSuccess = MetaDataManager::GetInstance().DelMeta(std::string(capKey.begin(), capKey.end()));
+ EXPECT_TRUE(isSuccess);
+ isSuccess = MetaDataManager::GetInstance().DelMeta(newMeta.GetStrategyKey());
+ EXPECT_TRUE(isSuccess);
+}
+
+/**
+* @tc.name: GetKeyTest
+* @tc.desc: GetKey
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author: yl
+*/
+HWTEST_F(ServiceMetaDataTest, GetKey, TestSize.Level1)
+{
+ DeviceMetaData metaData;
+ std::string expectedPrefix = "DeviceMeta";
+ std::string prefix = metaData.GetKey();
+ EXPECT_EQ(prefix, expectedPrefix);
+}
+
+/**
+* @tc.name: ObjectUserMetaDataGetKey
+* @tc.desc: ObjectUserMetaDataGetKey
+* @tc.type: FUNC
+*/
+HWTEST_F(ServiceMetaDataTest, ObjectUserMetaDataGetKey, TestSize.Level1)
+{
+ ObjectUserMetaData metaData;
+ std::string expectedPrefix = "ObjectUserMetaData";
+ std::string prefix = metaData.GetKey();
+ EXPECT_EQ(prefix, expectedPrefix);
+}
} // namespace OHOS::Test
\ No newline at end of file
diff --git a/services/distributeddataservice/framework/test/store_test.cpp b/services/distributeddataservice/framework/test/store_test.cpp
index 7bc31f25e4a6de819cff4fdb9f756785ad325c62..24e8f52181939b49bec3c1adccfc696b78d2d903 100644
--- a/services/distributeddataservice/framework/test/store_test.cpp
+++ b/services/distributeddataservice/framework/test/store_test.cpp
@@ -30,6 +30,8 @@
using namespace testing::ext;
using namespace OHOS::DistributedData;
namespace OHOS::Test {
+static constexpr const char *TEST_CLOUD_STORE = "test_cloud_store";
+
class GeneralValueTest : public testing::Test {
public:
static void SetUpTestCase(void){};
@@ -260,4 +262,66 @@ HWTEST_F(AutoCacheTest, GetDBStore, TestSize.Level2)
meta.area = GeneralStore::EL5;
EXPECT_NE(AutoCache::GetInstance().GetDBStore(meta, watchers).first, GeneralError::E_SCREEN_LOCKED);
}
+
+/**
+* @tc.name: CloseStore001
+* @tc.desc: AutoCache CloseStore001
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author:
+*/
+HWTEST_F(AutoCacheTest, CloseStore001, TestSize.Level2)
+{
+ GeneralStoreMock* store = new (std::nothrow) GeneralStoreMock();
+ ASSERT_NE(store, nullptr);
+ AutoCache::Watchers watchers;
+ mock_->isLocked_ = true;
+ StoreMetaData meta;
+ meta.area = GeneralStore::EL1;
+ meta.dataDir = "abc";
+ uint32_t tokenId = 123;
+ std::string storeId = TEST_CLOUD_STORE;
+ std::string userId = "";
+ AutoCache autoCache;
+ autoCache.stores_.Compute(tokenId,
+ [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool {
+ std::string storeKey = "key";
+ stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey),
+ std::forward_as_tuple(store, watchers, 0, meta));
+ return !stores.empty();
+ });
+ autoCache.CloseStore(tokenId, storeId, userId);
+ EXPECT_TRUE(autoCache.stores_.Empty());
+}
+
+/**
+* @tc.name: CloseStore002
+* @tc.desc: AutoCache CloseStore002
+* @tc.type: FUNC
+* @tc.require:
+* @tc.author:
+*/
+HWTEST_F(AutoCacheTest, CloseStore002, TestSize.Level2)
+{
+ GeneralStoreMock* store = new (std::nothrow) GeneralStoreMock();
+ ASSERT_NE(store, nullptr);
+ AutoCache::Watchers watchers;
+ mock_->isLocked_ = true;
+ StoreMetaData meta;
+ meta.area = GeneralStore::EL4;
+ meta.dataDir = "abc";
+ uint32_t tokenId = 123;
+ std::string storeId = TEST_CLOUD_STORE;
+ std::string userId = "";
+ AutoCache autoCache;
+ autoCache.stores_.Compute(tokenId,
+ [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool {
+ std::string storeKey = "key";
+ stores.emplace(std::piecewise_construct, std::forward_as_tuple(storeKey),
+ std::forward_as_tuple(store, watchers, 0, meta));
+ return !stores.empty();
+ });
+ autoCache.CloseStore(tokenId, storeId, userId);
+ EXPECT_FALSE(autoCache.stores_.Empty());
+}
} // namespace OHOS::Test
\ No newline at end of file
diff --git a/services/distributeddataservice/rust/extension/cloud_db_impl.cpp b/services/distributeddataservice/rust/extension/cloud_db_impl.cpp
index da137619bfc423220f73d0095506c8fc6b57fc59..3b042ba2418a717b6aa5889562af9b1e912a6f58 100644
--- a/services/distributeddataservice/rust/extension/cloud_db_impl.cpp
+++ b/services/distributeddataservice/rust/extension/cloud_db_impl.cpp
@@ -119,7 +119,7 @@ int32_t CloudDbImpl::BatchDelete(const std::string &table, DBVBuckets &extends)
return ExtensionUtil::ConvertStatus(status);
}
-std::shared_ptr CloudDbImpl::Query(const std::string &table, const DBVBucket &extend)
+std::pair> CloudDbImpl::Query(const std::string &table, const DBVBucket &extend)
{
std::string cursor;
auto it = extend.find(DistributedData::SchemaMeta::CURSOR_FIELD);
@@ -134,7 +134,11 @@ std::shared_ptr CloudDbImpl::Query(const std::string &table, const DBV
};
OhCloudExtCloudDbData *cloudData = nullptr;
auto status = OhCloudExtCloudDbBatchQuery(database_, &info, &cloudData);
- return (status == ERRNO_SUCCESS && cloudData != nullptr) ? std::make_shared(cloudData) : nullptr;
+ if (status == ERRNO_SUCCESS && cloudData != nullptr) {
+ return std::make_pair(DBErr::E_OK, std::make_shared(cloudData));
+ }
+ return status != ERRNO_SUCCESS ? std::make_pair(ExtensionUtil::ConvertStatus(status), nullptr)
+ : std::make_pair(DBErr::E_ERROR, nullptr);
}
int32_t CloudDbImpl::Lock()
diff --git a/services/distributeddataservice/rust/extension/cloud_db_impl.h b/services/distributeddataservice/rust/extension/cloud_db_impl.h
index 099bfaad0ddf004cbdee4b887f02f6a62eaafb12..5351ebbb9d4b5f0b4f8d32736ecd8fad8769e5b9 100644
--- a/services/distributeddataservice/rust/extension/cloud_db_impl.h
+++ b/services/distributeddataservice/rust/extension/cloud_db_impl.h
@@ -36,7 +36,7 @@ public:
int32_t BatchUpdate(const std::string &table, DBVBuckets &&values, DBVBuckets &extends) override;
int32_t BatchUpdate(const std::string &table, DBVBuckets &&values, const DBVBuckets &extends) override;
int32_t BatchDelete(const std::string &table, DBVBuckets &extends) override;
- std::shared_ptr Query(const std::string &table, const DBVBucket &extend) override;
+ std::pair> Query(const std::string &table, const DBVBucket &extend) override;
int32_t Lock() override;
int32_t Heartbeat() override;
int32_t Unlock() override;
diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp
index f47a26209787b06c9b2dcd049f4cd8fee9cd9e11..e5413cff2de360b5e1bdd0f94f13aadce5d7c206 100644
--- a/services/distributeddataservice/rust/extension/cloud_server_impl.cpp
+++ b/services/distributeddataservice/rust/extension/cloud_server_impl.cpp
@@ -28,11 +28,19 @@
#include "utils/anonymous.h"
namespace OHOS::CloudData {
-__attribute__((used)) static bool g_isInit =
- DistributedData::CloudServer::RegisterCloudInstance(new (std::nothrow) CloudServerImpl());
+__attribute__((used)) static bool g_isInit = CloudServerImpl::Init();
using namespace Security::AccessToken;
using DBMetaMgr = DistributedData::MetaDataManager;
using Anonymous = DistributedData::Anonymous;
+
+bool CloudServerImpl::Init()
+{
+ static CloudServerImpl cloudServerInstance;
+ static std::once_flag onceFlag;
+ std::call_once(onceFlag, [&]() { DistributedData::CloudServer::RegisterCloudInstance(&cloudServerInstance); });
+ return true;
+}
+
std::pair CloudServerImpl::GetServerInfo(int32_t userId, bool needSpaceInfo)
{
DBCloudInfo result;
@@ -544,7 +552,7 @@ int32_t CloudServerImpl::Unsubscribe(int32_t userId, const std::mapsecond);
+ uint32_t subId = static_cast(std::atoi(it->second.c_str()));
if (OhCloudExtVectorPush(relation, &subId, sizeof(uint32_t)) != ERRNO_SUCCESS) {
return DBErr::E_ERROR;
}
diff --git a/services/distributeddataservice/rust/extension/cloud_server_impl.h b/services/distributeddataservice/rust/extension/cloud_server_impl.h
index bd7c185e7818e31a7879fd31f1a5fedc4a39aba1..debb7aadf00458b4b9f687a8c43f3abbe698f6fb 100644
--- a/services/distributeddataservice/rust/extension/cloud_server_impl.h
+++ b/services/distributeddataservice/rust/extension/cloud_server_impl.h
@@ -36,6 +36,7 @@ using DBRelation = DBSub::Relation;
using DBErr = DistributedData::GeneralError;
class CloudServerImpl : public DistributedData::CloudServer {
public:
+ static bool Init();
std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override;
std::pair GetAppSchema(int32_t userId, const std::string &bundleName) override;
int32_t Subscribe(int32_t userId, const std::map> &dbs) override;
diff --git a/services/distributeddataservice/service/bootstrap/include/bootstrap.h b/services/distributeddataservice/service/bootstrap/include/bootstrap.h
index 785eadae22b884df1fb7716f5130e48faf3f187b..186217fc5fb7e8dd38ceb7f1754060fe66ce8a24 100644
--- a/services/distributeddataservice/service/bootstrap/include/bootstrap.h
+++ b/services/distributeddataservice/service/bootstrap/include/bootstrap.h
@@ -33,6 +33,7 @@ public:
API_EXPORT void LoadBackup(std::shared_ptr executors);
API_EXPORT void LoadAppIdMappings();
API_EXPORT void LoadThread();
+ API_EXPORT void LoadDeviceSyncAppWhiteLists();
private:
static constexpr const char *DEFAULT_LABEL = "distributeddata";
static constexpr const char *DEFAULT_META = "service_meta";
diff --git a/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp
index 107ca6a668ef4798391a6449365ffc30fa807ae0..41f1b755fa94b4690ca7bf5869cf52b1e5148331 100644
--- a/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp
+++ b/services/distributeddataservice/service/bootstrap/src/bootstrap.cpp
@@ -23,6 +23,7 @@
#include "checker/checker_manager.h"
#include "cloud/cloud_config_manager.h"
#include "config_factory.h"
+#include "device_sync_app/device_sync_app_manager.h"
#include "directory/directory_manager.h"
#include "log_print.h"
#include "thread/thread_manager.h"
@@ -191,5 +192,18 @@ void Bootstrap::LoadThread()
}
ThreadManager::GetInstance().Initialize(config->minThreadNum, config->maxThreadNum, config->ipcThreadNum);
}
+
+void Bootstrap::LoadDeviceSyncAppWhiteLists()
+{
+ auto *deviceSyncAppWhiteLists = ConfigFactory::GetInstance().GetDeviceSyncAppWhiteListConfig();
+ if (deviceSyncAppWhiteLists == nullptr) {
+ return;
+ }
+ std::vector infos;
+ for (auto &info : deviceSyncAppWhiteLists->whiteLists) {
+ infos.push_back({ info.appId, info.bundleName, info.version });
+ }
+ DeviceSyncAppManager::GetInstance().Initialize(infos);
+}
} // namespace DistributedData
} // namespace OHOS
\ No newline at end of file
diff --git a/services/distributeddataservice/service/cloud/cloud_data_translate.cpp b/services/distributeddataservice/service/cloud/cloud_data_translate.cpp
index 80762e38753201781258eb3e455a9b9b3f4f2c19..b1e0983fe70b82a4dc7c03ddca301a061bb64a7b 100644
--- a/services/distributeddataservice/service/cloud/cloud_data_translate.cpp
+++ b/services/distributeddataservice/service/cloud/cloud_data_translate.cpp
@@ -50,7 +50,7 @@ std::vector RdbCloudDataTranslate::AssetsToBlob(const Assets &assets)
auto magicU8 = reinterpret_cast(const_cast(&leMagic));
rawData.insert(rawData.end(), magicU8, magicU8 + sizeof(ASSETS_MAGIC));
rawData.insert(rawData.end(), reinterpret_cast(&num), reinterpret_cast(&num) + sizeof(num));
- for (auto &asset : assets) {
+ for (const auto &asset : assets) {
auto data = AssetToBlob(asset);
rawData.insert(rawData.end(), data.begin(), data.end());
}
diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp
index 2492401664a18bf3233d35bc14309e7836d8da30..fe9aa097bb835088cb0917cf0a5549a2e33e97b9 100644
--- a/services/distributeddataservice/service/cloud/cloud_service_impl.cpp
+++ b/services/distributeddataservice/service/cloud/cloud_service_impl.cpp
@@ -61,7 +61,7 @@ using namespace DistributedDataDfx;
using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter;
using Account = AccountDelegate;
using AccessTokenKit = Security::AccessToken::AccessTokenKit;
-static constexpr uint32_t RESTART_SERVICE_TIME_THRESHOLD = 60;
+static constexpr uint32_t RESTART_SERVICE_TIME_THRESHOLD = 120;
static constexpr const char *FT_ENABLE_CLOUD = "ENABLE_CLOUD";
static constexpr const char *FT_DISABLE_CLOUD = "DISABLE_CLOUD";
static constexpr const char *FT_SWITCH_ON = "SWITCH_ON";
@@ -275,7 +275,9 @@ void CloudServiceImpl::DoClean(int32_t user, const SchemaMeta &schemaMeta, int32
storeInfo.bundleName = meta.bundleName;
storeInfo.user = atoi(meta.user.c_str());
storeInfo.storeName = meta.storeId;
- EventCenter::GetInstance().PostEvent(std::make_unique(CloudEvent::CLEAN_DATA, storeInfo));
+ if (action != GeneralStore::CLEAN_WATER) {
+ EventCenter::GetInstance().PostEvent(std::make_unique(CloudEvent::CLEAN_DATA, storeInfo));
+ }
auto status = store->Clean({}, action, "");
if (status != E_OK) {
ZLOGW("remove device data status:%{public}d, user:%{public}d, bundleName:%{public}s, "
@@ -668,12 +670,17 @@ std::pair CloudServiceImpl::QueryLastSyncInfo(const s
int32_t CloudServiceImpl::OnInitialize()
{
XCollie xcollie(__FUNCTION__, XCollie::XCOLLIE_LOG | XCollie::XCOLLIE_RECOVERY);
- NetworkDelegate::GetInstance()->RegOnNetworkChange();
DistributedDB::RuntimeConfig::SetCloudTranslate(std::make_shared());
- Execute(GenTask(0, 0, CloudSyncScene::SERVICE_INIT,
- { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB }));
std::vector users;
Account::GetInstance()->QueryUsers(users);
+ for (auto user : users) {
+ if (user == DEFAULT_USER) {
+ continue;
+ }
+ CleanWaterVersion(user);
+ }
+ Execute(GenTask(0, 0, CloudSyncScene::SERVICE_INIT,
+ { WORK_CLOUD_INFO_UPDATE, WORK_SCHEMA_UPDATE, WORK_DO_CLOUD_SYNC, WORK_SUB }));
for (auto user : users) {
if (user == DEFAULT_USER) {
continue;
@@ -688,6 +695,35 @@ int32_t CloudServiceImpl::OnInitialize()
return E_OK;
}
+bool CloudServiceImpl::CleanWaterVersion(int32_t user)
+{
+ auto [status, cloudInfo] = GetCloudInfoFromMeta(user);
+ if (status != SUCCESS) {
+ return false;
+ }
+ auto stores = CheckerManager::GetInstance().GetDynamicStores();
+ auto staticStores = CheckerManager::GetInstance().GetStaticStores();
+ stores.insert(stores.end(), staticStores.begin(), staticStores.end());
+ auto keys = cloudInfo.GetSchemaKey();
+ for (const auto &[bundle, key] : keys) {
+ SchemaMeta schemaMeta;
+ if (MetaDataManager::GetInstance().LoadMeta(key, schemaMeta, true) &&
+ schemaMeta.metaVersion < SchemaMeta::CLEAN_WATER_VERSION) {
+ bool found = std::any_of(stores.begin(), stores.end(),
+ [&schemaMeta](const CheckerManager::StoreInfo &storeInfo) {
+ return storeInfo.bundleName == schemaMeta.bundleName;
+ });
+ if (!found) {
+ continue;
+ }
+ DoClean(user, schemaMeta, GeneralStore::CleanMode::CLEAN_WATER);
+ schemaMeta.metaVersion = SchemaMeta::CLEAN_WATER_VERSION;
+ }
+ MetaDataManager::GetInstance().SaveMeta(key, schemaMeta, true);
+ }
+ return true;
+}
+
int32_t CloudServiceImpl::OnBind(const BindInfo &info)
{
if (executor_ != nullptr || info.executors == nullptr) {
@@ -792,7 +828,8 @@ std::pair CloudServiceImpl::GetCloudInfoFromServer(int32_t u
ZLOGD("cloud server is nullptr, user:%{public}d", userId);
return { SERVER_UNAVAILABLE, cloudInfo };
}
- return instance->GetServerInfo(cloudInfo.user, false);
+ auto [code, info] = instance->GetServerInfo(cloudInfo.user, false);
+ return { code != E_OK ? code : info.IsValid() ? E_OK : E_ERROR, info };
}
int32_t CloudServiceImpl::UpdateCloudInfoFromServer(int32_t user)
diff --git a/services/distributeddataservice/service/cloud/cloud_service_impl.h b/services/distributeddataservice/service/cloud/cloud_service_impl.h
index c1ec1dd099cb44a31eabce1bd26ef50a685672ad..21283817f210f1f06cb0611f7a7fc4bff8aec9b3 100644
--- a/services/distributeddataservice/service/cloud/cloud_service_impl.h
+++ b/services/distributeddataservice/service/cloud/cloud_service_impl.h
@@ -145,6 +145,7 @@ private:
bool ReleaseUserInfo(int32_t user, CloudSyncScene scene);
bool DoCloudSync(int32_t user, CloudSyncScene scene);
bool StopCloudSync(int32_t user, CloudSyncScene scene);
+ bool CleanWaterVersion(int32_t user);
static std::pair GetCloudInfo(int32_t userId);
static std::pair GetCloudInfoFromMeta(int32_t userId);
diff --git a/services/distributeddataservice/service/cloud/sync_manager.cpp b/services/distributeddataservice/service/cloud/sync_manager.cpp
index 1391796224bf894a550a943e687400803348fb65..adb7e9e532a792693a0dfd4efac47f05334b6719 100644
--- a/services/distributeddataservice/service/cloud/sync_manager.cpp
+++ b/services/distributeddataservice/service/cloud/sync_manager.cpp
@@ -201,8 +201,8 @@ std::function SyncManager::GetLockChangeHandler()
SyncManager::SyncManager()
{
- EventCenter::GetInstance().Subscribe(CloudEvent::LOCK_CLOUD_CONTAINER, GetLockChangeHandler());
- EventCenter::GetInstance().Subscribe(CloudEvent::UNLOCK_CLOUD_CONTAINER, GetLockChangeHandler());
+ EventCenter::GetInstance().Subscribe(CloudEvent::LOCK_CLOUD_CONTAINER, SyncManager::GetLockChangeHandler());
+ EventCenter::GetInstance().Subscribe(CloudEvent::UNLOCK_CLOUD_CONTAINER, SyncManager::GetLockChangeHandler());
EventCenter::GetInstance().Subscribe(CloudEvent::LOCAL_CHANGE, GetClientChangeHandler());
syncStrategy_ = std::make_shared();
auto metaName = Bootstrap::GetInstance().GetProcessLabel();
@@ -299,15 +299,15 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END,
- E_ERROR });
+ SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second,
+ SyncStage::END, E_ERROR, "!IsOn:" + schema.bundleName });
continue;
}
for (const auto &database : schema.databases) {
if (!info.Contains(database.name)) {
UpdateFinishSyncInfo({ cloud.user, cloud.id, schema.bundleName, database.name }, syncId, E_ERROR);
- Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second, SyncStage::END,
- E_ERROR });
+ SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second,
+ SyncStage::END, E_ERROR, "!Contains:" + database.name });
continue;
}
StoreInfo storeInfo = { 0, schema.bundleName, database.name, cloud.apps[schema.bundleName].instanceId,
@@ -317,8 +317,8 @@ std::function SyncManager::GetPostEventTask(const std::vectorsecond, SyncStage::END,
- status });
+ SyncManager::Report({ cloud.user, schema.bundleName, it == traceIds.end() ? "" : it->second,
+ SyncStage::END, status, "CheckSyncAction" });
info.SetError(status);
continue;
}
@@ -353,13 +353,13 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount
info.SetError(E_CLOUD_DISABLED);
return;
}
- auto traceIds = GetPrepareTraceId(info, cloud);
+ auto traceIds = SyncManager::GetPrepareTraceId(info, cloud);
BatchReport(info.user_, traceIds, SyncStage::PREPARE, E_OK);
UpdateStartSyncInfo(cloudSyncInfos);
auto code = IsValid(info, cloud);
if (code != E_OK) {
BatchUpdateFinishState(cloudSyncInfos, code);
- BatchReport(info.user_, traceIds, SyncStage::END, code);
+ BatchReport(info.user_, traceIds, SyncStage::END, code, "!IsValid");
return;
}
@@ -373,7 +373,7 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount
retryer(RETRY_INTERVAL, E_RETRY_TIMEOUT, GenStore::CLOUD_ERR_OFFSET + E_CLOUD_DISABLED,
it == traceIds.end() ? "" : it->second);
BatchUpdateFinishState(cloudSyncInfos, E_CLOUD_DISABLED);
- BatchReport(info.user_, traceIds, SyncStage::END, E_CLOUD_DISABLED);
+ BatchReport(info.user_, traceIds, SyncStage::END, E_CLOUD_DISABLED, "empty schema:" + info.bundleName_);
return;
}
}
@@ -386,6 +386,34 @@ ExecutorPool::Task SyncManager::GetSyncTask(int32_t times, bool retry, RefCount
};
}
+void SyncManager::StartCloudSync(const DistributedData::SyncEvent &evt, const StoreMetaData &meta,
+ const AutoCache::Store &store, Retryer retryer, DistributedData::GenDetails &details)
+{
+ auto &storeInfo = evt.GetStoreInfo();
+ GenAsync async = evt.GetAsyncDetail();
+ auto prepareTraceId = evt.GetPrepareTraceId();
+ auto user = evt.GetUser();
+ auto &detail = details[SyncInfo::DEFAULT_ID];
+ ReportSyncEvent(evt, BizState::BEGIN, E_OK);
+ SyncParam syncParam = { evt.GetMode(), evt.GetWait(), evt.IsCompensation(), MODE_DEFAULT, prepareTraceId };
+ syncParam.asyncDownloadAsset = meta.asyncDownloadAsset;
+ auto [status, dbCode] = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()),
+ evt.AutoRetry() ? RetryCallback(storeInfo, retryer, evt.GetTriggerMode(), prepareTraceId, user)
+ : GetCallback(async, storeInfo, evt.GetTriggerMode(), prepareTraceId, user), syncParam);
+ if (status != E_OK) {
+ if (async) {
+ detail.code = status;
+ async(std::move(details));
+ }
+ UpdateFinishSyncInfo({ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName,
+ storeInfo.storeName }, storeInfo.syncId, E_ERROR);
+ if (status != GeneralError::E_NOT_SUPPORT) {
+ auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode;
+ ReportSyncEvent(evt, BizState::END, code);
+ }
+ }
+}
+
std::function SyncManager::GetSyncHandler(Retryer retryer)
{
return [this, retryer](const Event &event) {
@@ -393,13 +421,13 @@ std::function SyncManager::GetSyncHandler(Retryer retryer)
auto &storeInfo = evt.GetStoreInfo();
GenAsync async = evt.GetAsyncDetail();
auto prepareTraceId = evt.GetPrepareTraceId();
- auto user = evt.GetUser();
GenDetails details;
auto &detail = details[SyncInfo::DEFAULT_ID];
detail.progress = GenProgress::SYNC_FINISH;
auto [hasMeta, meta] = GetMetaData(storeInfo);
if (!hasMeta) {
- return DoExceptionalCallback(async, details, storeInfo, prepareTraceId);
+ return DoExceptionalCallback(async, details, storeInfo,
+ {0, "", prepareTraceId, SyncStage::END, GeneralError::E_ERROR, "no meta"});
}
auto [code, store] = GetStore(meta, storeInfo.user);
if (code == E_SCREEN_LOCKED) {
@@ -408,51 +436,35 @@ std::function SyncManager::GetSyncHandler(Retryer retryer)
if (store == nullptr) {
ZLOGE("store null, storeId:%{public}s, prepareTraceId:%{public}s", meta.GetStoreAlias().c_str(),
prepareTraceId.c_str());
- return DoExceptionalCallback(async, details, storeInfo, prepareTraceId);
+ return DoExceptionalCallback(async, details, storeInfo,
+ {0, "", prepareTraceId, SyncStage::END, GeneralError::E_ERROR, "store null"});
}
if (!meta.enableCloud) {
ZLOGW("meta.enableCloud is false, storeId:%{public}s, prepareTraceId:%{public}s",
meta.GetStoreAlias().c_str(), prepareTraceId.c_str());
- return DoExceptionalCallback(async, details, storeInfo, prepareTraceId, E_CLOUD_DISABLED);
+ return DoExceptionalCallback(async, details, storeInfo,
+ {0, "", prepareTraceId, SyncStage::END, E_CLOUD_DISABLED, "disable cloud"});
}
ZLOGI("database:<%{public}d:%{public}s:%{public}s:%{public}s> sync start, asyncDownloadAsset?[%{public}d]",
storeInfo.user, storeInfo.bundleName.c_str(), meta.GetStoreAlias().c_str(), prepareTraceId.c_str(),
meta.asyncDownloadAsset);
- ReportSyncEvent(evt, BizState::BEGIN, E_OK);
- SyncParam syncParam = { evt.GetMode(), evt.GetWait(), evt.IsCompensation(), MODE_DEFAULT, prepareTraceId };
- syncParam.asyncDownloadAsset = meta.asyncDownloadAsset;
- auto [status, dbCode] = store->Sync({ SyncInfo::DEFAULT_ID }, *(evt.GetQuery()),
- evt.AutoRetry() ? RetryCallback(storeInfo, retryer, evt.GetTriggerMode(), prepareTraceId, user)
- : GetCallback(async, storeInfo, evt.GetTriggerMode(), prepareTraceId, user), syncParam);
- if (status != E_OK) {
- if (async) {
- detail.code = status;
- async(std::move(details));
- }
- UpdateFinishSyncInfo({ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName,
- storeInfo.storeName }, storeInfo.syncId, E_ERROR);
- if (status != GeneralError::E_NOT_SUPPORT) {
- auto code = dbCode == 0 ? GenStore::CLOUD_ERR_OFFSET + status : dbCode;
- ReportSyncEvent(evt, BizState::END, code);
- }
- }
+ StartCloudSync(evt, meta, store, retryer, details);
};
}
void SyncManager::ReportSyncEvent(const SyncEvent &evt, BizState bizState, int32_t code)
{
- SyncStage syncStage = SyncStage::START;
auto &storeInfo = evt.GetStoreInfo();
if (bizState == BizState::BEGIN) {
- syncStage = SyncStage::START;
RadarReporter::Report({storeInfo.bundleName.c_str(), CLOUD_SYNC, TRIGGER_SYNC,
storeInfo.syncId, evt.GetTriggerMode()}, "GetSyncHandler", bizState);
} else {
- syncStage = SyncStage::END;
RadarReporter::Report({storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC,
storeInfo.syncId, evt.GetTriggerMode(), code}, "GetSyncHandler", bizState);
}
- Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code});
+ SyncStage syncStage = (bizState == BizState::BEGIN) ? SyncStage::START : SyncStage::END;
+ SyncManager::Report({evt.GetUser(), storeInfo.bundleName, evt.GetPrepareTraceId(), syncStage, code,
+ "GetSyncHandler"});
}
std::function SyncManager::GetClientChangeHandler()
@@ -495,8 +507,8 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync
RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_,
dbCode },
"GetRetryer", BizState::END);
- Report({ user, info.bundleName_, prepareTraceId, SyncStage::END,
- dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode });
+ SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END,
+ dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "GetRetryer finish" });
Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC),
"code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode)));
return true;
@@ -512,8 +524,8 @@ SyncManager::Retryer SyncManager::GetRetryer(int32_t times, const SyncInfo &sync
RadarReporter::Report({ info.bundleName_.c_str(), CLOUD_SYNC, FINISH_SYNC, info.syncId_, info.triggerMode_,
dbCode },
"GetRetryer", BizState::END);
- Report({ user, info.bundleName_, prepareTraceId, SyncStage::END,
- dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode });
+ SyncManager::Report({ user, info.bundleName_, prepareTraceId, SyncStage::END,
+ dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "GetRetryer continue" });
Report(FT_CALLBACK, info.bundleName_, static_cast(Fault::CSF_GS_CLOUD_SYNC),
"code=" + std::to_string(code) + ",dbCode=" + std::to_string(static_cast(dbCode)));
return true;
@@ -723,7 +735,7 @@ std::pair SyncManager::GetLastResults(std::mapsecond.code != -1) {
- return { SUCCESS, std::move(iter->second) };
+ return { SUCCESS, iter->second };
}
return { E_ERROR, {} };
}
@@ -757,7 +769,7 @@ std::pair> SyncManager::QueryL
if (lastSyncInfoMap.find(queryKey.storeId) != lastSyncInfoMap.end()) {
continue;
}
- auto [status, syncInfo] = GetLastSyncInfoFromMeta(queryKey);
+ auto [status, syncInfo] = SyncManager::GetLastSyncInfoFromMeta(queryKey);
if (status == SUCCESS) {
lastSyncInfoMap.insert(std::make_pair(std::move(syncInfo.storeId), std::move(syncInfo)));
}
@@ -831,7 +843,7 @@ std::function SyncManager::GetCallback(const Gen
RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId, triggerMode,
dbCode, result.begin()->second.changeCount },
"GetCallback", BizState::END);
- Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode });
+ SyncManager::Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END, dbCode, "GetCallback" });
if (dbCode != 0) {
Report(FT_CALLBACK, storeInfo.bundleName, static_cast(Fault::CSF_GS_CLOUD_SYNC),
"callback failed, dbCode=" + std::to_string(dbCode));
@@ -878,15 +890,16 @@ std::vector SyncManager::GetSchemaMeta(const CloudInfo &cloud, const
}
void SyncManager::DoExceptionalCallback(const GenAsync &async, GenDetails &details, const StoreInfo &storeInfo,
- const std::string &prepareTraceId, int32_t code)
+ const ReportParam ¶m)
{
if (async) {
- details[SyncInfo::DEFAULT_ID].code = code;
+ details[SyncInfo::DEFAULT_ID].code = param.errCode;
async(details);
}
QueryKey queryKey{ storeInfo.user, GetAccountId(storeInfo.user), storeInfo.bundleName, storeInfo.storeName };
- UpdateFinishSyncInfo(queryKey, storeInfo.syncId, code);
- Report({ storeInfo.user, storeInfo.bundleName, prepareTraceId, SyncStage::END, code });
+ UpdateFinishSyncInfo(queryKey, storeInfo.syncId, param.errCode);
+ SyncManager::Report({ storeInfo.user, storeInfo.bundleName, param.prepareTraceId, SyncStage::END,
+ param.errCode, param.message });
}
bool SyncManager::InitDefaultUser(int32_t &user)
@@ -920,8 +933,8 @@ std::function SyncManager::Retr
RadarReporter::Report({ storeInfo.bundleName.c_str(), CLOUD_SYNC, FINISH_SYNC, storeInfo.syncId,
triggerMode, code, details.begin()->second.changeCount },
"RetryCallback", BizState::END);
- Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END,
- dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode });
+ SyncManager::Report({ user, storeInfo.bundleName, prepareTraceId, SyncStage::END,
+ dbCode == GenStore::DB_ERR_OFFSET ? 0 : dbCode, "RetryCallback" });
}
}
retryer(GetInterval(code), code, dbCode, prepareTraceId);
@@ -936,10 +949,11 @@ void SyncManager::BatchUpdateFinishState(const std::vector> &apps) {
apps[meta.bundleName].insert(meta.storeId);
return true;
diff --git a/services/distributeddataservice/service/cloud/sync_manager.h b/services/distributeddataservice/service/cloud/sync_manager.h
index 885cec96ba3d986e5a5a365d5822295738f6c725..bc19b107b1c29f4ae79c2ba187c1ce91b70eeb30 100644
--- a/services/distributeddataservice/service/cloud/sync_manager.h
+++ b/services/distributeddataservice/service/cloud/sync_manager.h
@@ -46,7 +46,6 @@ public:
using TraceIds = std::map;
using SyncStage = DistributedData::SyncStage;
using ReportParam = DistributedData::ReportParam;
- static std::pair GetStore(const StoreMetaData &meta, int32_t user, bool mustBind = true);
class SyncInfo final {
public:
using Store = std::string;
@@ -95,12 +94,13 @@ public:
};
SyncManager();
~SyncManager();
+ static void Report(const ReportParam &reportParam);
+ static std::pair GetStore(const StoreMetaData &meta, int32_t user, bool mustBind = true);
int32_t Bind(std::shared_ptr executor);
int32_t DoCloudSync(SyncInfo syncInfo);
int32_t StopCloudSync(int32_t user = 0);
std::pair> QueryLastSyncInfo(
const std::vector &queryKeys);
- void Report(const ReportParam &reportParam);
void OnScreenUnlocked(int32_t user);
void CleanCompensateSync(int32_t userId);
@@ -137,6 +137,17 @@ private:
static std::vector GetSchemaMeta(const CloudInfo &cloud, const std::string &bundleName);
static bool NeedGetCloudInfo(CloudInfo &cloud);
static GeneralError IsValid(SyncInfo &info, CloudInfo &cloud);
+ static std::function GetLockChangeHandler();
+ static TraceIds GetPrepareTraceId(const SyncInfo &info, const CloudInfo &cloud);
+ static void Report(
+ const std::string &faultType, const std::string &bundleName, int32_t errCode, const std::string &appendix);
+ static std::pair GetLastResults(std::map &infos);
+ static std::pair GetLastSyncInfoFromMeta(const QueryKey &queryKey);
+ static void SaveLastSyncInfo(const QueryKey &queryKey, CloudLastSyncInfo &&info);
+ static void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode,
+ const std::string &message = "");
+ static void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState,
+ int32_t code);
Task GetSyncTask(int32_t times, bool retry, RefCount ref, SyncInfo &&syncInfo);
void UpdateSchema(const SyncInfo &syncInfo);
std::function GetSyncHandler(Retryer retryer);
@@ -151,24 +162,16 @@ private:
std::function GetPostEventTask(const std::vector &schemas, CloudInfo &cloud, SyncInfo &info,
bool retry, const TraceIds &traceIds);
void DoExceptionalCallback(const GenAsync &async, GenDetails &details, const StoreInfo &storeInfo,
- const std::string &prepareTraceId, int32_t code = GeneralError::E_ERROR);
+ const ReportParam ¶m);
bool InitDefaultUser(int32_t &user);
std::function RetryCallback(const StoreInfo &storeInfo,
Retryer retryer, int32_t triggerMode, const std::string &prepareTraceId, int32_t user);
- static std::pair GetLastResults(std::map &infos);
void BatchUpdateFinishState(const std::vector> &cloudSyncInfos, int32_t code);
bool NeedSaveSyncInfo(const QueryKey &queryKey);
- std::function GetLockChangeHandler();
- void BatchReport(int32_t userId, const TraceIds &traceIds, SyncStage syncStage, int32_t errCode);
- TraceIds GetPrepareTraceId(const SyncInfo &info, const CloudInfo &cloud);
+ void StartCloudSync(const DistributedData::SyncEvent &evt, const StoreMetaData &meta,
+ const AutoCache::Store &store, Retryer retryer, DistributedData::GenDetails &details);
std::pair GetMetaData(const StoreInfo &storeInfo);
void AddCompensateSync(const StoreMetaData &meta);
- static void Report(
- const std::string &faultType, const std::string &bundleName, int32_t errCode, const std::string &appendix);
- void ReportSyncEvent(const DistributedData::SyncEvent &evt, DistributedDataDfx::BizState bizState, int32_t code);
- std::pair GetLastSyncInfoFromMeta(const QueryKey &queryKey);
- static void SaveLastSyncInfo(const QueryKey &queryKey, CloudLastSyncInfo &&info);
-
static std::atomic genId_;
std::shared_ptr executor_;
ConcurrentMap actives_;
diff --git a/services/distributeddataservice/service/config/BUILD.gn b/services/distributeddataservice/service/config/BUILD.gn
index a2ea71cf44720ce97423cf1140f3de53a08ea313..b5d6368020292f8baef84a9fa95b80bfbe859348 100644
--- a/services/distributeddataservice/service/config/BUILD.gn
+++ b/services/distributeddataservice/service/config/BUILD.gn
@@ -29,6 +29,8 @@ ohos_source_set("distributeddata_config") {
"src/model/checker_config.cpp",
"src/model/cloud_config.cpp",
"src/model/component_config.cpp",
+ "src/model/datashare_config.cpp",
+ "src/model/device_sync_app_white_list_config.cpp",
"src/model/directory_config.cpp",
"src/model/global_config.cpp",
"src/model/network_config.cpp",
diff --git a/services/distributeddataservice/service/config/include/config_factory.h b/services/distributeddataservice/service/config/include/config_factory.h
index bce10b04a32c1579e11d31ab5f84100eb91a15a4..a5e9dbe089defb8ad393b6afcf842ab2bfa300df 100644
--- a/services/distributeddataservice/service/config/include/config_factory.h
+++ b/services/distributeddataservice/service/config/include/config_factory.h
@@ -33,6 +33,8 @@ public:
API_EXPORT CloudConfig *GetCloudConfig();
API_EXPORT std::vector *GetAppIdMappingConfig();
API_EXPORT ThreadConfig *GetThreadConfig();
+ API_EXPORT DataShareConfig *GetDataShareConfig();
+ API_EXPORT DeviceSyncAppWhiteListConfig *GetDeviceSyncAppWhiteListConfig();
private:
static constexpr const char *CONF_PATH = "/system/etc/distributeddata/conf";
ConfigFactory();
diff --git a/services/distributeddataservice/service/config/include/model/datashare_config.h b/services/distributeddataservice/service/config/include/model/datashare_config.h
new file mode 100644
index 0000000000000000000000000000000000000000..4487c0d1bcbaa3f4f0f6a5af936a31fb0cea4631
--- /dev/null
+++ b/services/distributeddataservice/service/config/include/model/datashare_config.h
@@ -0,0 +1,29 @@
+/*
+* Copyright (c) 2025 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_DATASHARE_CONFIG_H
+#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H
+
+#include "serializable/serializable.h"
+namespace OHOS {
+namespace DistributedData {
+class DataShareConfig final : public Serializable {
+public:
+ bool Marshal(json &node) const override;
+ bool Unmarshal(const json &node) override;
+ std::vector dataShareExtNames;
+};
+} // namespace DistributedData
+} // namespace OHOS
+#endif //OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DATASHARE_CONFIG_H
\ No newline at end of file
diff --git a/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h b/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h
new file mode 100644
index 0000000000000000000000000000000000000000..03729b9c77c52dbdf74d6498087f7856f1e36953
--- /dev/null
+++ b/services/distributeddataservice/service/config/include/model/device_sync_app_white_list_config.h
@@ -0,0 +1,37 @@
+/*
+* Copyright (c) 2025 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_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H
+#define OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H
+
+#include "serializable/serializable.h"
+namespace OHOS {
+namespace DistributedData {
+class DeviceSyncAppWhiteListConfig final : public Serializable {
+public:
+ struct WhiteList final : public Serializable {
+ std::string appId;
+ std::string bundleName;
+ uint32_t version;
+ bool Marshal(json &node) const override;
+ bool Unmarshal(const json &node) override;
+ };
+ bool Marshal(json &node) const override;
+ bool Unmarshal(const json &node) override;
+
+ std::vector whiteLists;
+};
+} // namespace DistributedData
+} // namespace OHOS
+#endif //OHOS_DISTRIBUTED_DATA_SERVICES_CONFIG_MODEL_DEVICE_SYNC_APP_WHITE_LIST_CONFIG_H
diff --git a/services/distributeddataservice/service/config/include/model/global_config.h b/services/distributeddataservice/service/config/include/model/global_config.h
index 91f5a237b3b7309f0e34444e1c4f2cebdb574a8f..751b91f2ee74cd9f0298290ca187ff00af2322ca 100644
--- a/services/distributeddataservice/service/config/include/model/global_config.h
+++ b/services/distributeddataservice/service/config/include/model/global_config.h
@@ -20,9 +20,11 @@
#include "model/checker_config.h"
#include "model/cloud_config.h"
#include "model/component_config.h"
+#include "model/datashare_config.h"
#include "model/directory_config.h"
#include "model/network_config.h"
#include "model/thread_config.h"
+#include "model/device_sync_app_white_list_config.h"
#include "serializable/serializable.h"
namespace OHOS {
namespace DistributedData {
@@ -40,6 +42,8 @@ public:
CloudConfig *cloud = nullptr;
std::vector *appIdMapping = nullptr;
ThreadConfig *thread = nullptr;
+ DataShareConfig *dataShare = nullptr;
+ DeviceSyncAppWhiteListConfig *deviceSyncAppWhiteList = nullptr;
~GlobalConfig();
bool Marshal(json &node) const override;
bool Unmarshal(const json &node) override;
diff --git a/services/distributeddataservice/service/config/src/config_factory.cpp b/services/distributeddataservice/service/config/src/config_factory.cpp
index 3b05fce80631bf9ee5ea0b5bad1b6a56172cf3c8..781e3b55b4a100a2802d70587f8ec501a71c5c74 100644
--- a/services/distributeddataservice/service/config/src/config_factory.cpp
+++ b/services/distributeddataservice/service/config/src/config_factory.cpp
@@ -91,5 +91,15 @@ ThreadConfig *ConfigFactory::GetThreadConfig()
{
return config_.thread;
}
+
+DataShareConfig *ConfigFactory::GetDataShareConfig()
+{
+ return config_.dataShare;
+}
+
+DeviceSyncAppWhiteListConfig *ConfigFactory::GetDeviceSyncAppWhiteListConfig()
+{
+ return config_.deviceSyncAppWhiteList;
+}
} // namespace DistributedData
} // namespace OHOS
\ No newline at end of file
diff --git a/services/distributeddataservice/service/config/src/model/datashare_config.cpp b/services/distributeddataservice/service/config/src/model/datashare_config.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..0eae37a2bb68630dadcef21cf9a51dbed30ed307
--- /dev/null
+++ b/services/distributeddataservice/service/config/src/model/datashare_config.cpp
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2025 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/datashare_config.h"
+namespace OHOS {
+namespace DistributedData {
+bool DataShareConfig::Marshal(json &node) const
+{
+ SetValue(node[GET_NAME(dataShareExtNames)], dataShareExtNames);
+ return true;
+}
+
+bool DataShareConfig::Unmarshal(const json &node)
+{
+ GetValue(node, GET_NAME(dataShareExtNames), dataShareExtNames);
+ return true;
+}
+} // namespace DistributedData
+} // namespace OHOS
\ No newline at end of file
diff --git a/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..594d3f2ae9159af93ae90a2e67edc9eabcc821ba
--- /dev/null
+++ b/services/distributeddataservice/service/config/src/model/device_sync_app_white_list_config.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2025 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/device_sync_app_white_list_config.h"
+namespace OHOS {
+namespace DistributedData {
+bool DeviceSyncAppWhiteListConfig::Marshal(Serializable::json &node) const
+{
+ SetValue(node[GET_NAME(whiteLists)], whiteLists);
+ return true;
+}
+bool DeviceSyncAppWhiteListConfig::Unmarshal(const Serializable::json &node)
+{
+ GetValue(node, GET_NAME(whiteLists), whiteLists);
+ return true;
+}
+
+bool DeviceSyncAppWhiteListConfig::WhiteList::Marshal(Serializable::json &node) const
+{
+ SetValue(node[GET_NAME(appId)], appId);
+ SetValue(node[GET_NAME(bundleName)], bundleName);
+ SetValue(node[GET_NAME(version)], version);
+ return true;
+}
+bool DeviceSyncAppWhiteListConfig::WhiteList::Unmarshal(const Serializable::json &node)
+{
+ GetValue(node, GET_NAME(appId), appId);
+ GetValue(node, GET_NAME(bundleName), bundleName);
+ GetValue(node, GET_NAME(version), version);
+ return true;
+}
+} // namespace DistributedData
+} // namespace OHOS
diff --git a/services/distributeddataservice/service/config/src/model/global_config.cpp b/services/distributeddataservice/service/config/src/model/global_config.cpp
index e64b012260e566a811e6883f32ab5f12e90bce1b..1956f82187097f3203048e0c3cd7c5759bc45f7c 100644
--- a/services/distributeddataservice/service/config/src/model/global_config.cpp
+++ b/services/distributeddataservice/service/config/src/model/global_config.cpp
@@ -30,6 +30,8 @@ bool GlobalConfig::Marshal(json &node) const
SetValue(node[GET_NAME(cloud)], cloud);
SetValue(node[GET_NAME(appIdMapping)], appIdMapping);
SetValue(node[GET_NAME(thread)], thread);
+ SetValue(node[GET_NAME(dataShare)], dataShare);
+ SetValue(node[GET_NAME(deviceSyncAppWhiteList)], deviceSyncAppWhiteList);
return true;
}
@@ -47,6 +49,8 @@ bool GlobalConfig::Unmarshal(const json &node)
GetValue(node, GET_NAME(cloud), cloud);
GetValue(node, GET_NAME(appIdMapping), appIdMapping);
GetValue(node, GET_NAME(thread), thread);
+ GetValue(node, GET_NAME(dataShare), dataShare);
+ GetValue(node, GET_NAME(deviceSyncAppWhiteList), deviceSyncAppWhiteList);
return true;
}
@@ -60,6 +64,7 @@ GlobalConfig::~GlobalConfig()
delete cloud;
delete appIdMapping;
delete thread;
+ delete deviceSyncAppWhiteList;
}
} // namespace DistributedData
} // namespace OHOS
\ No newline at end of file
diff --git a/services/distributeddataservice/service/crypto/src/crypto_manager.cpp b/services/distributeddataservice/service/crypto/src/crypto_manager.cpp
index 16a7754648e8b3c6362f13548d6db3c2e75bd521..e278c678fc1e6628d2c02639d6ced2393483deea 100644
--- a/services/distributeddataservice/service/crypto/src/crypto_manager.cpp
+++ b/services/distributeddataservice/service/crypto/src/crypto_manager.cpp
@@ -64,7 +64,7 @@ bool AddHksParams(HksParamSet *params, const CryptoManager::ParamConfig ¶mCo
};
if (paramConfig.storageLevel > HKS_AUTH_STORAGE_LEVEL_DE) {
hksParam.emplace_back(
- HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::stoi(paramConfig.userId) });
+ HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::atoi(paramConfig.userId.c_str()) });
}
auto ret = HksAddParams(params, aes256Param, sizeof(aes256Param) / sizeof(aes256Param[0]));
@@ -100,7 +100,7 @@ int32_t GetRootKeyParams(HksParamSet *¶ms, uint32_t storageLevel, const std:
{ .tag = HKS_TAG_AUTH_STORAGE_LEVEL, .uint32Param = storageLevel },
};
if (storageLevel > HKS_AUTH_STORAGE_LEVEL_DE) {
- hksParam.emplace_back(HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::stoi(userId) });
+ hksParam.emplace_back(HksParam { .tag = HKS_TAG_SPECIFIC_USER_ID, .int32Param = std::atoi(userId.c_str()) });
}
ret = HksAddParams(params, hksParam.data(), hksParam.size());
diff --git a/services/distributeddataservice/service/data_share/BUILD.gn b/services/distributeddataservice/service/data_share/BUILD.gn
index 5f435aa5e4e169b70ece36b0534ce9b73bc877a1..8bc36903c6e47bf6aadf24dfe0103e78c479b115 100644
--- a/services/distributeddataservice/service/data_share/BUILD.gn
+++ b/services/distributeddataservice/service/data_share/BUILD.gn
@@ -28,6 +28,7 @@ config("module_public_config") {
"${datashare_path}/interfaces/inner_api/common/include",
"${datashare_path}/interfaces/inner_api/consumer/include",
"${data_service_path}/adapter/include/communicator",
+ "${data_service_path}/service/config/include",
"../common",
"../crypto/include",
"../permission/include",
@@ -48,6 +49,7 @@ ohos_source_set("data_share_service") {
sources = [
"common/app_connect_manager.cpp",
"common/bundle_mgr_proxy.cpp",
+ "common/common_utils.cpp",
"common/db_delegate.cpp",
"common/div_strategy.cpp",
"common/extension_ability_manager.cpp",
@@ -130,6 +132,8 @@ ohos_source_set("data_share_service") {
"json:nlohmann_json_static",
"kv_store:datamgr_common",
"kv_store:distributeddb",
+ "qos_manager:concurrent_task_client",
+ "qos_manager:qos",
"relational_store:native_rdb",
"relational_store:rdb_data_share_adapter",
"samgr:samgr_proxy",
diff --git a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp
index 410408bebdc46acdf66bf3aeaac84aff456fb54b..4e5e29b04eac7e6b3eb3cdfa75bab08b493bbffa 100644
--- a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp
+++ b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.cpp
@@ -16,6 +16,7 @@
#include "bundle_mgr_proxy.h"
#include "account/account_delegate.h"
+#include "common_utils.h"
#include "datashare_errno.h"
#include "datashare_radar_reporter.h"
#include "if_system_ability_manager.h"
@@ -114,6 +115,23 @@ int BundleMgrProxy::GetBundleInfoFromBMS(
return E_OK;
}
+int BundleMgrProxy::GetBundleInfoFromBMSWithCheck(
+ const std::string &bundleName, int32_t userId, BundleConfig &bundleConfig, int32_t appIndex)
+{
+ int res = GetBundleInfoFromBMS(bundleName, userId, bundleConfig, appIndex);
+ if (res != E_OK) {
+ return res;
+ }
+ // Not allow normal app visit normal app.
+ if (!DataShareThreadLocal::IsFromSystemApp() && !bundleConfig.isSystemApp) {
+ ZLOGE("Not allow normal app visit normal app, bundle:%{public}s, callingPid:%{public}d",
+ bundleName.c_str(), IPCSkeleton::GetCallingPid());
+ return E_NOT_SYSTEM_APP;
+ }
+
+ return E_OK;
+}
+
std::pair BundleMgrProxy::GetCallerAppIdentifier(
const std::string &bundleName, int32_t userId)
{
@@ -199,6 +217,7 @@ std::pair BundleMgrProxy::ConvertToDataShareBundle(AppExecFwk
return std::make_pair(err, bundleConfig);
}
bundleConfig.extensionInfos = extensionInfos;
+ bundleConfig.isSystemApp = bundleInfo.applicationInfo.isSystemApp;
return std::make_pair(E_OK, bundleConfig);
}
diff --git a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h
index 71bcc496eb74f059dc2830fcd47a6aaa767bb735..c0c3d774e82fdbdbe7415ee47e27ef63020e1910 100644
--- a/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h
+++ b/services/distributeddataservice/service/data_share/common/bundle_mgr_proxy.h
@@ -57,6 +57,7 @@ struct ExtensionAbilityInfo {
struct BundleConfig {
std::string name;
bool singleton = false;
+ bool isSystemApp = false;
std::vector hapModuleInfos;
std::vector extensionInfos;
};
@@ -67,6 +68,8 @@ public:
static std::shared_ptr GetInstance();
int GetBundleInfoFromBMS(const std::string &bundleName, int32_t userId,
BundleConfig &bundleConfig, int32_t appIndex = 0);
+ int GetBundleInfoFromBMSWithCheck(const std::string &bundleName, int32_t userId,
+ BundleConfig &bundleConfig, int32_t appIndex = 0);
void Delete(const std::string &bundleName, int32_t userId, int32_t appIndex);
sptr CheckBMS();
std::pair GetCallerAppIdentifier(const std::string &bundleName, int32_t userId);
diff --git a/services/distributeddataservice/service/data_share/common/common_utils.cpp b/services/distributeddataservice/service/data_share/common/common_utils.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..deeab89cba0a01c3516b8f121b8a9bc15e5b4f91
--- /dev/null
+++ b/services/distributeddataservice/service/data_share/common/common_utils.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2025 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 "CommonUtils"
+#include "common_utils.h"
+
+#include "accesstoken_kit.h"
+#include "config_factory.h"
+#include "log_print.h"
+#include "tokenid_kit.h"
+
+namespace OHOS::DataShare {
+
+bool& DataShareThreadLocal::GetFromSystemApp()
+{
+ static thread_local bool isFromSystemApp = true;
+ return isFromSystemApp;
+}
+
+void DataShareThreadLocal::SetFromSystemApp(bool isFromSystemApp)
+{
+ GetFromSystemApp() = isFromSystemApp;
+}
+
+bool DataShareThreadLocal::IsFromSystemApp()
+{
+ return GetFromSystemApp();
+}
+
+void DataShareThreadLocal::CleanFromSystemApp()
+{
+ SetFromSystemApp(true);
+}
+
+bool CheckSystemAbility(uint32_t tokenId)
+{
+ Security::AccessToken::ATokenTypeEnum tokenType =
+ Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
+ return (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
+ tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL);
+}
+
+// GetTokenType use tokenId, and IsSystemApp use fullTokenId, these are different
+bool CheckSystemCallingPermission(uint32_t tokenId, uint64_t fullTokenId)
+{
+ if (CheckSystemAbility(tokenId)) {
+ return true;
+ }
+ // IsSystemAppByFullTokenID here is not IPC
+ return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId);
+}
+
+} // namespace OHOS::DataShare
diff --git a/services/distributeddataservice/service/data_share/common/common_utils.h b/services/distributeddataservice/service/data_share/common/common_utils.h
new file mode 100644
index 0000000000000000000000000000000000000000..1b8379dc7fdb2f7329ceaac9acabeda848921454
--- /dev/null
+++ b/services/distributeddataservice/service/data_share/common/common_utils.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2025 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 DATASHARESERVICE_COMMON_UTILS_H
+#define DATASHARESERVICE_COMMON_UTILS_H
+
+#include
+#include
+
+namespace OHOS::DataShare {
+struct DataShareThreadLocal {
+ static bool& GetFromSystemApp();
+ static void SetFromSystemApp(bool isFromSystemApp);
+ static bool IsFromSystemApp();
+ static void CleanFromSystemApp();
+};
+
+bool CheckSystemAbility(uint32_t tokenId);
+
+bool CheckSystemCallingPermission(uint32_t tokenId, uint64_t fullTokenId);
+
+} // namespace OHOS::DataShare
+#endif // DATASHARESERVICE_COMMON_UTILS_H
diff --git a/services/distributeddataservice/service/data_share/common/context.h b/services/distributeddataservice/service/data_share/common/context.h
index 62da611a254d8d44c04454d0a122c9623d542028..d19ebf6d162a7d690c2f02bce781b0bc98e8c47d 100644
--- a/services/distributeddataservice/service/data_share/common/context.h
+++ b/services/distributeddataservice/service/data_share/common/context.h
@@ -37,6 +37,7 @@ public:
virtual ~Context() = default;
std::string uri;
int32_t currentUserId = -1;
+ int32_t visitedUserId = -1;
int32_t appIndex = 0;
int32_t haMode = 0;
std::string permission;
diff --git a/services/distributeddataservice/service/data_share/common/db_delegate.h b/services/distributeddataservice/service/data_share/common/db_delegate.h
index 67bde3ade94818ace61918e5354756df6b303efd..0cb36808d507731ba5dcdcff61549766c7fad631 100644
--- a/services/distributeddataservice/service/data_share/common/db_delegate.h
+++ b/services/distributeddataservice/service/data_share/common/db_delegate.h
@@ -128,8 +128,8 @@ public:
static std::shared_ptr GetInstance(
bool reInit = false, const std::string &dir = "", const std::shared_ptr &executors = nullptr);
virtual ~KvDBDelegate() = default;
- virtual int32_t Upsert(const std::string &collectionName, const KvData &value) = 0;
- virtual int32_t Delete(const std::string &collectionName, const std::string &filter) = 0;
+ virtual std::pair Upsert(const std::string &collectionName, const KvData &value) = 0;
+ virtual std::pair Delete(const std::string &collectionName, const std::string &filter) = 0;
virtual int32_t Get(const std::string &collectionName, const Id &id, std::string &value) = 0;
virtual int32_t Get(const std::string &collectionName, const std::string &filter, const std::string &projection,
std::string &result) = 0;
diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp
index 06f8cc6a2f803af9f0b12b1318ff9445ddc3e7ed..be360b40b615c146e1bcbf45acd12be84951b573 100644
--- a/services/distributeddataservice/service/data_share/common/kv_delegate.cpp
+++ b/services/distributeddataservice/service/data_share/common/kv_delegate.cpp
@@ -40,7 +40,8 @@ const char* g_backupFiles[] = {
"dataShare.db.safe",
"dataShare.db.undo",
};
-const char* BACKUP_SUFFIX = ".backup";
+constexpr const char* BACKUP_SUFFIX = ".backup";
+constexpr std::chrono::milliseconds COPY_TIME_OUT_MS = std::chrono::milliseconds(500);
// If isBackUp is true, remove db backup files. Otherwise remove source db files.
void KvDelegate::RemoveDbFile(bool isBackUp) const
@@ -65,12 +66,15 @@ bool KvDelegate::CopyFile(bool isBackup)
std::filesystem::copy_options options = std::filesystem::copy_options::overwrite_existing;
std::error_code code;
bool ret = true;
+ int index = 0;
for (auto &fileName : g_backupFiles) {
std::string src = path_ + "/" + fileName;
std::string dst = src;
isBackup ? dst.append(BACKUP_SUFFIX) : src.append(BACKUP_SUFFIX);
+ TimeoutReport timeoutReport({"", "", "", __FUNCTION__, 0});
// If src doesn't exist, error will be returned through `std::error_code`
bool copyRet = std::filesystem::copy_file(src, dst, options, code);
+ timeoutReport.Report(("file index:" + std::to_string(index)), COPY_TIME_OUT_MS);
if (!copyRet) {
ZLOGE("failed to copy file %{public}s, isBackup %{public}d, err: %{public}s",
fileName, isBackup, code.message().c_str());
@@ -78,6 +82,7 @@ bool KvDelegate::CopyFile(bool isBackup)
RemoveDbFile(isBackup);
break;
}
+ index++;
}
return ret;
}
@@ -128,29 +133,30 @@ bool KvDelegate::RestoreIfNeed(int32_t dbStatus)
return false;
}
-int64_t KvDelegate::Upsert(const std::string &collectionName, const std::string &filter, const std::string &value)
+std::pair KvDelegate::Upsert(const std::string &collectionName, const std::string &filter,
+ const std::string &value)
{
std::lock_guard lock(mutex_);
if (!Init()) {
ZLOGE("init failed, %{public}s", collectionName.c_str());
- return E_ERROR;
+ return std::make_pair(E_ERROR, 0);
}
- int count = GRD_UpsertDoc(db_, collectionName.c_str(), filter.c_str(), value.c_str(), 0);
+ int32_t count = GRD_UpsertDoc(db_, collectionName.c_str(), filter.c_str(), value.c_str(), 0);
if (count <= 0) {
ZLOGE("GRD_UpSertDoc failed,status %{public}d", count);
RestoreIfNeed(count);
- return count;
+ return std::make_pair(count, 0);
}
Flush();
- return E_OK;
+ return std::make_pair(E_OK, count);
}
-int32_t KvDelegate::Delete(const std::string &collectionName, const std::string &filter)
+std::pair KvDelegate::Delete(const std::string &collectionName, const std::string &filter)
{
std::lock_guard lock(mutex_);
if (!Init()) {
ZLOGE("init failed, %{public}s", collectionName.c_str());
- return E_ERROR;
+ return std::make_pair(E_ERROR, 0);
}
std::vector queryResults;
@@ -158,23 +164,25 @@ int32_t KvDelegate::Delete(const std::string &collectionName, const std::string
if (status != E_OK) {
ZLOGE("db GetBatch failed, %{public}s %{public}d", filter.c_str(), status);
// `GetBatch` should decide whether to restore before errors are returned, so skip restoration here.
- return status;
+ return std::make_pair(status, 0);
}
+ int32_t deleteCount = 0;
for (auto &result : queryResults) {
auto count = GRD_DeleteDoc(db_, collectionName.c_str(), result.c_str(), 0);
if (count < 0) {
ZLOGE("GRD_DeleteDoc failed,status %{public}d %{public}s", count, result.c_str());
if (RestoreIfNeed(count)) {
- return count;
+ return std::make_pair(count, 0);
}
continue;
}
+ deleteCount += count;
}
Flush();
if (queryResults.size() > 0) {
ZLOGI("Delete, %{public}s, count %{public}zu", collectionName.c_str(), queryResults.size());
}
- return E_OK;
+ return std::make_pair(E_OK, deleteCount);
}
bool KvDelegate::Init()
@@ -232,7 +240,7 @@ KvDelegate::~KvDelegate()
}
}
-int32_t KvDelegate::Upsert(const std::string &collectionName, const KvData &value)
+std::pair KvDelegate::Upsert(const std::string &collectionName, const KvData &value)
{
std::string id = value.GetId();
if (value.HasVersion() && value.GetVersion() != 0) {
@@ -241,7 +249,7 @@ int32_t KvDelegate::Upsert(const std::string &collectionName, const KvData &valu
if (value.GetVersion() <= version) {
ZLOGE("GetVersion failed,%{public}s id %{private}s %{public}d %{public}d", collectionName.c_str(),
id.c_str(), value.GetVersion(), version);
- return E_VERSION_NOT_NEWER;
+ return std::make_pair(E_VERSION_NOT_NEWER, 0);
}
}
}
diff --git a/services/distributeddataservice/service/data_share/common/kv_delegate.h b/services/distributeddataservice/service/data_share/common/kv_delegate.h
index 3ec92c7cdf01e3fb8c1c79dda4c4bf859e1541f2..fce4ecf31a44784043a05c323ff0e5084f8e7024 100644
--- a/services/distributeddataservice/service/data_share/common/kv_delegate.h
+++ b/services/distributeddataservice/service/data_share/common/kv_delegate.h
@@ -28,8 +28,8 @@ class KvDelegate final : public KvDBDelegate {
public:
KvDelegate(const std::string &path, const std::shared_ptr &executors);
~KvDelegate() override;
- int32_t Upsert(const std::string &collectionName, const KvData &value) override;
- int32_t Delete(const std::string &collectionName, const std::string &filter) override;
+ std::pair Upsert(const std::string &collectionName, const KvData &value) override;
+ std::pair Delete(const std::string &collectionName, const std::string &filter) override;
int32_t Get(const std::string &collectionName, const Id &id, std::string &value) override;
int32_t Get(const std::string &collectionName, const std::string &filter, const std::string &projection,
@@ -41,7 +41,8 @@ public:
private:
bool Init();
bool GetVersion(const std::string &collectionName, const std::string &filter, int &version);
- int64_t Upsert(const std::string &collectionName, const std::string &filter, const std::string &value);
+ std::pair Upsert(const std::string &collectionName, const std::string &filter,
+ const std::string &value);
void Flush();
bool RestoreIfNeed(int32_t dbStatus);
void Backup();
diff --git a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp
index 9ccf692579bc545f9a899c70bb0c85685d202a39..de1036ff2b24476a28b4730fe59b0adbbbd37c79 100644
--- a/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp
+++ b/services/distributeddataservice/service/data_share/common/rdb_delegate.cpp
@@ -341,7 +341,7 @@ bool RdbDelegate::IsLimit(int count, int32_t callingPid, uint32_t callingTokenId
});
ZLOGE("resultSetCount is full, pid: %{public}d, owner is %{public}s", callingPid, logStr.c_str());
std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(callingTokenId).first;
- DataShareFaultInfo faultInfo{RESULTSET_FULL, "callingTokenId:" + std::to_string(callingTokenId),
+ DataShareFaultInfo faultInfo{HiViewFaultAdapter::resultsetFull, "callingTokenId:" + std::to_string(callingTokenId),
"Pid:" + std::to_string(callingPid), "owner:" + logStr, __FUNCTION__, E_RESULTSET_BUSY, appendix};
HiViewFaultAdapter::ReportDataFault(faultInfo);
return true;
diff --git a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp
index 79ca80155a6e32bfd36ac2af3417040ab57d13b1..ba1015c3620bc284370dec48698c13ad7eaeafb1 100644
--- a/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp
+++ b/services/distributeddataservice/service/data_share/common/scheduler_manager.cpp
@@ -87,6 +87,13 @@ void SchedulerManager::Stop(const Key &key)
void SchedulerManager::Enable(const Key &key, int32_t userId, const DistributedData::StoreMetaData &metaData)
{
+ Template tpl;
+ if (!TemplateManager::GetInstance().Get(key, userId, tpl) ||
+ tpl.scheduler_.empty() || tpl.scheduler_.find(REMIND_TIMER_FUNC) == std::string::npos) {
+ ZLOGE("find template scheduler failed, %{public}s, %{public}" PRId64 ", %{public}s",
+ DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str());
+ return;
+ }
bool isTimerStopped = false;
{
std::lock_guard lock(mutex_);
diff --git a/services/distributeddataservice/service/data_share/data/published_data.cpp b/services/distributeddataservice/service/data_share/data/published_data.cpp
index 894a8e58346f1623103f86b440c0b39e123a9596..0e73d871ae31b29bd78076c17e069de2bf0f77ed 100644
--- a/services/distributeddataservice/service/data_share/data/published_data.cpp
+++ b/services/distributeddataservice/service/data_share/data/published_data.cpp
@@ -170,7 +170,7 @@ void PublishedData::Delete(const std::string &bundleName, const int32_t userId)
ZLOGE("db open failed");
return;
}
- int32_t status = delegate->Delete(KvDBDelegate::DATA_TABLE,
+ auto [status, count] = delegate->Delete(KvDBDelegate::DATA_TABLE,
"{\"bundleName\":\"" + bundleName + "\", \"userId\": " + std::to_string(userId) + "}");
if (status != E_OK) {
ZLOGE("db Delete failed, %{public}s %{public}d", bundleName.c_str(), status);
@@ -209,9 +209,9 @@ void PublishedData::ClearAging()
}
if (data.timestamp < lastValidTime && PublishedDataSubscriberManager::GetInstance()
.GetCount(PublishedDataKey(data.key, data.bundleName, data.subscriberId)) == 0) {
- status = delegate->Delete(KvDBDelegate::DATA_TABLE,
+ auto [errorCode, count] = delegate->Delete(KvDBDelegate::DATA_TABLE,
Id(PublishedData::GenId(data.key, data.bundleName, data.subscriberId), data.userId));
- if (status != E_OK) {
+ if (errorCode != E_OK) {
ZLOGE("db Delete failed, %{public}s %{public}s", data.key.c_str(), data.bundleName.c_str());
}
agingSize++;
@@ -249,8 +249,8 @@ void PublishedData::UpdateTimestamp(
return;
}
data.timestamp = now;
- status = delegate->Upsert(KvDBDelegate::DATA_TABLE, PublishedData(data));
- if (status == E_OK) {
+ auto [errorCode, count] = delegate->Upsert(KvDBDelegate::DATA_TABLE, PublishedData(data));
+ if (errorCode == E_OK) {
ZLOGI("update timestamp %{private}s", data.key.c_str());
}
}
diff --git a/services/distributeddataservice/service/data_share/data/template_data.cpp b/services/distributeddataservice/service/data_share/data/template_data.cpp
index baf5dc4d5dda77ae2d5773dba7ec7c9410ec25f7..79219aedefc4cb40bb85498c80b35a826049e236 100644
--- a/services/distributeddataservice/service/data_share/data/template_data.cpp
+++ b/services/distributeddataservice/service/data_share/data/template_data.cpp
@@ -135,13 +135,15 @@ bool TemplateData::Delete(const std::string &bundleName, const int32_t userId)
ZLOGE("db open failed");
return false;
}
- auto status = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE,
+ auto [status, count] = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE,
"{\"bundleName\":\"" + bundleName + "\", \"userId\": " + std::to_string(userId) + "}");
if (status != E_OK) {
ZLOGE("db DeleteById failed, %{public}d", status);
return false;
}
- delegate->NotifyBackup();
+ if (count > 0) {
+ delegate->NotifyBackup();
+ }
return true;
}
@@ -154,12 +156,14 @@ bool TemplateData::Add(const std::string &uri, const int32_t userId, const std::
return false;
}
TemplateData data(uri, bundleName, subscriberId, userId, aTemplate);
- auto status = delegate->Upsert(KvDBDelegate::TEMPLATE_TABLE, data);
+ auto [status, count] = delegate->Upsert(KvDBDelegate::TEMPLATE_TABLE, data);
if (status != E_OK) {
ZLOGE("db Upsert failed, %{public}d", status);
return false;
}
- delegate->NotifyBackup();
+ if (count > 0) {
+ delegate->NotifyBackup();
+ }
return true;
}
@@ -171,13 +175,15 @@ bool TemplateData::Delete(
ZLOGE("db open failed");
return false;
}
- auto status = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE,
+ auto [status, count] = delegate->Delete(KvDBDelegate::TEMPLATE_TABLE,
static_cast(Id(TemplateData::GenId(uri, bundleName, subscriberId), userId)));
if (status != E_OK) {
ZLOGE("db DeleteById failed, %{public}d", status);
return false;
}
- delegate->NotifyBackup();
+ if (count > 0) {
+ delegate->NotifyBackup();
+ }
return true;
}
diff --git a/services/distributeddataservice/service/data_share/data_provider_config.cpp b/services/distributeddataservice/service/data_share/data_provider_config.cpp
index e713b4acb9a0df4e915dab75eff1218e662fa404..74a7630fb64b124ff770c1696c298e162c8dc456 100644
--- a/services/distributeddataservice/service/data_share/data_provider_config.cpp
+++ b/services/distributeddataservice/service/data_share/data_provider_config.cpp
@@ -20,10 +20,13 @@
#include "accesstoken_kit.h"
#include "account/account_delegate.h"
+#include "config_factory.h"
#include "datashare_errno.h"
#include "hap_token_info.h"
+#include "ipc_skeleton.h"
#include "log_print.h"
#include "strategies/general/load_config_common_strategy.h"
+#include "tokenid_kit.h"
#include "uri_utils.h"
#include "utils/anonymous.h"
@@ -61,7 +64,7 @@ std::pair DataProviderConfig::GetBundleInfo()
}
providerInfo_.bundleName = uriConfig_.pathSegments[0];
}
- auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS(
+ auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck(
providerInfo_.bundleName, providerInfo_.visitedUserId, bundleInfo, providerInfo_.appIndex);
return std::make_pair(ret, bundleInfo);
}
@@ -155,7 +158,7 @@ int DataProviderConfig::GetFromExtension()
return E_URI_NOT_EXIST;
}
BundleConfig bundleInfo;
- auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS(
+ auto ret = BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck(
providerInfo_.bundleName, providerInfo_.visitedUserId, bundleInfo, providerInfo_.appIndex);
if (ret != E_OK) {
ZLOGE("BundleInfo failed! bundleName: %{public}s", providerInfo_.bundleName.c_str());
@@ -225,6 +228,17 @@ std::pair DataProviderConfig::GetProvider
GetMetaDataFromUri();
return std::make_pair(ret, providerInfo_);
}
+ if (ret != E_URI_NOT_EXIST) {
+ return std::make_pair(ret, providerInfo_);
+ }
+ auto fullTokenId = IPCSkeleton::GetCallingFullTokenID();
+ Security::AccessToken::HapTokenInfo tokenInfo;
+ auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(IPCSkeleton::GetCallingTokenID(), tokenInfo);
+ if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)
+ || (result == Security::AccessToken::RET_SUCCESS && !IsInExtList(tokenInfo.bundleName))) {
+ ZLOGE("The URI in the extension, is not allowed for silent access.! ret: %{public}d, bundleName: %{public}s,"
+ "uri: %{public}s", ret, tokenInfo.bundleName.c_str(), providerInfo_.uri.c_str());
+ }
ret = GetFromExtension();
if (ret != E_OK) {
ZLOGE("Get providerInfo failed! ret: %{public}d, uri: %{public}s",
@@ -232,4 +246,14 @@ std::pair DataProviderConfig::GetProvider
}
return std::make_pair(ret, providerInfo_);
}
+
+bool DataProviderConfig::IsInExtList(const std::string &bundleName)
+{
+ DataShareConfig *config = ConfigFactory::GetInstance().GetDataShareConfig();
+ if (config == nullptr) {
+ return true;
+ }
+ std::vector& extNames = config->dataShareExtNames;
+ return std::find(extNames.begin(), extNames.end(), bundleName) != extNames.end();
+}
} // namespace OHOS::DataShare
diff --git a/services/distributeddataservice/service/data_share/data_provider_config.h b/services/distributeddataservice/service/data_share/data_provider_config.h
index 6b2770dfe192333d919beb169443e5489ecdb6ea..99099ce8ac4cf8801d32c7f9072aa7dfa25818ce 100644
--- a/services/distributeddataservice/service/data_share/data_provider_config.h
+++ b/services/distributeddataservice/service/data_share/data_provider_config.h
@@ -63,6 +63,7 @@ private:
int GetFromExtensionProperties(const ProfileInfo &profileInfo, const std::string &moduleName);
void GetMetaDataFromUri();
std::pair GetBundleInfo();
+ bool IsInExtList(const std::string &bundleName);
enum class PATH_PARAM : int32_t {
BUNDLE_NAME = 0,
MODULE_NAME,
diff --git a/services/distributeddataservice/service/data_share/data_share_profile_config.cpp b/services/distributeddataservice/service/data_share/data_share_profile_config.cpp
index 9787d9df1dc7c2db46c955850895215c386a399c..ecf2ab8cdc64a6f349d993d1fd9770a3d3900ed2 100644
--- a/services/distributeddataservice/service/data_share/data_share_profile_config.cpp
+++ b/services/distributeddataservice/service/data_share/data_share_profile_config.cpp
@@ -275,9 +275,9 @@ bool DataShareProfileConfig::GetProfileInfo(const std::string &calledBundleName,
{
BundleConfig bundleInfo;
// profile is the same when app clone
- if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS(calledBundleName,
+ if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck(calledBundleName,
currentUserId, bundleInfo) != E_OK) {
- ZLOGE("data share GetBundleInfoFromBMS failed! bundleName: %{public}s, currentUserId = %{public}d",
+ ZLOGE("data share GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s, currentUserId = %{public}d",
calledBundleName.c_str(), currentUserId);
return false;
}
diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp
index a837f76f94fd64a2ad543c4eb976173a5ae91d9b..4029047bab8a89080ffdc0924ab8b0c7f0620296 100644
--- a/services/distributeddataservice/service/data_share/data_share_service_impl.cpp
+++ b/services/distributeddataservice/service/data_share/data_share_service_impl.cpp
@@ -24,6 +24,7 @@
#include "app_connect_manager.h"
#include "common_event_manager.h"
#include "common_event_support.h"
+#include "concurrent_task_client.h"
#include "data_ability_observer_interface.h"
#include "data_share_profile_config.h"
#include "dataobs_mgr_client.h"
@@ -83,11 +84,17 @@ public:
void DataShareServiceImpl::SystemAbilityStatusChangeListener::OnAddSystemAbility(
int32_t systemAbilityId, const std::string &deviceId)
{
- if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
- return;
- }
- ZLOGI("Common event service start. saId:%{public}d", systemAbilityId);
- InitSubEvent();
+ ZLOGI("saId:%{public}d", systemAbilityId);
+ if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
+ InitSubEvent();
+ } else if (systemAbilityId == CONCURRENT_TASK_SERVICE_ID) {
+ std::unordered_map payload;
+ // get current thread pid
+ payload["pid"] = std::to_string(getpid());
+ // request qos auth for current pid
+ OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload);
+ }
+ return;
}
DataShareServiceImpl::Factory::Factory()
@@ -118,7 +125,8 @@ std::pair DataShareServiceImpl::InsertEx(const std::string &ur
callingTokenId}, true);
auto [errCode, ret] = dbDelegate->InsertEx(providerInfo.tableName, valuesBucket);
if (errCode == E_OK && ret > 0) {
- NotifyChange(uri);
+ // only notify specific userId
+ NotifyChange(uri, providerInfo.visitedUserId);
RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData);
} else {
ReportExcuteFault(callingTokenId, providerInfo, errCode, func);
@@ -129,7 +137,7 @@ std::pair DataShareServiceImpl::InsertEx(const std::string &ur
return ExecuteEx(uri, extUri, IPCSkeleton::GetCallingTokenID(), false, callBack);
}
-bool DataShareServiceImpl::NotifyChange(const std::string &uri)
+bool DataShareServiceImpl::NotifyChange(const std::string &uri, int32_t userId)
{
RadarReporter::RadarReport report(RadarReporter::NOTIFY_OBSERVER_DATA_CHANGE,
RadarReporter::NOTIFY_DATA_CHANGE, __FUNCTION__);
@@ -139,8 +147,7 @@ bool DataShareServiceImpl::NotifyChange(const std::string &uri)
report.SetError(RadarReporter::DATA_OBS_EMPTY_ERROR);
return false;
}
-
- ErrCode ret = obsMgrClient->NotifyChange(Uri(uri));
+ ErrCode ret = obsMgrClient->NotifyChange(Uri(uri), userId);
if (ret != ERR_OK) {
ZLOGE("obsMgrClient->NotifyChange error return %{public}d", ret);
report.SetError(RadarReporter::NOTIFY_ERROR);
@@ -166,7 +173,7 @@ std::pair DataShareServiceImpl::UpdateEx(const std::string &ur
callingTokenId}, true);
auto [errCode, ret] = dbDelegate->UpdateEx(providerInfo.tableName, predicate, valuesBucket);
if (errCode == E_OK && ret > 0) {
- NotifyChange(uri);
+ NotifyChange(uri, providerInfo.visitedUserId);
RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData);
} else {
ReportExcuteFault(callingTokenId, providerInfo, errCode, func);
@@ -194,7 +201,7 @@ std::pair DataShareServiceImpl::DeleteEx(const std::string &ur
callingTokenId}, true);
auto [errCode, ret] = dbDelegate->DeleteEx(providerInfo.tableName, predicate);
if (errCode == E_OK && ret > 0) {
- NotifyChange(uri);
+ NotifyChange(uri, providerInfo.visitedUserId);
RdbSubscriberManager::GetInstance().Emit(uri, providerInfo.visitedUserId, metaData);
} else {
ReportExcuteFault(callingTokenId, providerInfo, errCode, func);
@@ -251,7 +258,7 @@ int32_t DataShareServiceImpl::AddTemplate(const std::string &uri, const int64_t
uri.c_str(), subscriberId, tpltId.bundleName_.c_str(), tplt.predicates_.size());
return templateStrategy_.Execute(context, [&uri, &tpltId, &tplt, &context]() -> int32_t {
auto result = TemplateManager::GetInstance().Add(
- Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId, tplt);
+ Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->visitedUserId, tplt);
RdbSubscriberManager::GetInstance().Emit(context->uri, tpltId.subscriberId_, tpltId.bundleName_, context);
return result;
});
@@ -270,7 +277,7 @@ int32_t DataShareServiceImpl::DelTemplate(const std::string &uri, const int64_t
DistributedData::Anonymous::Change(uri).c_str(), subscriberId, tpltId.bundleName_.c_str());
return templateStrategy_.Execute(context, [&uri, &tpltId, &context]() -> int32_t {
return TemplateManager::GetInstance().Delete(
- Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->currentUserId);
+ Key(uri, tpltId.subscriberId_, tpltId.bundleName_), context->visitedUserId);
});
}
@@ -339,7 +346,7 @@ std::vector DataShareServiceImpl::Publish(const Data &data, con
continue;
}
publishedData.emplace_back(context->uri, context->calledBundleName, item.subscriberId_);
- userId = context->currentUserId;
+ userId = context->visitedUserId;
}
if (!publishedData.empty()) {
PublishedDataSubscriberManager::GetInstance().Emit(publishedData, userId, callerBundleName);
@@ -369,7 +376,8 @@ std::vector DataShareServiceImpl::SubscribeRdbData(
auto context = std::make_shared(uri);
results.emplace_back(uri, subscribeStrategy_.Execute(context, [&id, &observer, &context, this]() {
return RdbSubscriberManager::GetInstance().Add(
- Key(context->uri, id.subscriberId_, id.bundleName_), observer, context, binderInfo_.executors);
+ Key(context->uri, id.subscriberId_, id.bundleName_),
+ observer, context, binderInfo_.executors);
}));
}
return results;
@@ -437,7 +445,7 @@ std::vector DataShareServiceImpl::SubscribePublishedData(const
result = subscribeStrategy_.Execute(context, [&subscriberId, &observer, &context]() {
return PublishedDataSubscriberManager::GetInstance().Add(
PublishedDataKey(context->uri, context->callerBundleName, subscriberId), observer,
- context->callerTokenId);
+ context->callerTokenId, context->visitedUserId);
});
results.emplace_back(uri, result);
if (result == E_OK) {
@@ -445,10 +453,10 @@ std::vector DataShareServiceImpl::SubscribePublishedData(const
if (binderInfo_.executors != nullptr) {
binderInfo_.executors->Execute([context, subscriberId]() {
PublishedData::UpdateTimestamp(
- context->uri, context->calledBundleName, subscriberId, context->currentUserId);
+ context->uri, context->calledBundleName, subscriberId, context->visitedUserId);
});
}
- userId = context->currentUserId;
+ userId = context->visitedUserId;
}
}
if (!publishedKeys.empty()) {
@@ -477,7 +485,7 @@ std::vector DataShareServiceImpl::UnsubscribePublishedData(cons
if (result == E_OK && binderInfo_.executors != nullptr) {
binderInfo_.executors->Execute([context, subscriberId]() {
PublishedData::UpdateTimestamp(
- context->uri, context->calledBundleName, subscriberId, context->currentUserId);
+ context->uri, context->calledBundleName, subscriberId, context->visitedUserId);
});
}
return result;
@@ -510,7 +518,7 @@ std::vector DataShareServiceImpl::EnablePubSubs(const std::vect
if (result == E_OK && binderInfo_.executors != nullptr) {
binderInfo_.executors->Execute([context, subscriberId]() {
PublishedData::UpdateTimestamp(
- context->uri, context->calledBundleName, subscriberId, context->currentUserId);
+ context->uri, context->calledBundleName, subscriberId, context->visitedUserId);
});
}
results.emplace_back(uri, result);
@@ -519,7 +527,7 @@ std::vector DataShareServiceImpl::EnablePubSubs(const std::vect
if (PublishedDataSubscriberManager::GetInstance().IsNotifyOnEnabled(pKey, context->callerTokenId)) {
publishedKeys.emplace_back(pKey);
}
- userId = context->currentUserId;
+ userId = context->visitedUserId;
}
}
if (!publishedKeys.empty()) {
@@ -548,7 +556,7 @@ std::vector DataShareServiceImpl::DisablePubSubs(const std::vec
if (result == E_OK && binderInfo_.executors != nullptr) {
binderInfo_.executors->Execute([context, subscriberId]() {
PublishedData::UpdateTimestamp(
- context->uri, context->calledBundleName, subscriberId, context->currentUserId);
+ context->uri, context->calledBundleName, subscriberId, context->visitedUserId);
});
}
return result;
@@ -589,6 +597,7 @@ int32_t DataShareServiceImpl::OnBind(const BindInfo &binderInfo)
DBDelegate::SetExecutorPool(binderInfo.executors);
HiViewAdapter::GetInstance().SetThreadPool(binderInfo.executors);
SubscribeCommonEvent();
+ SubscribeConcurrentTask();
SubscribeTimeChanged();
SubscribeChange();
ZLOGI("end");
@@ -606,6 +615,17 @@ void DataShareServiceImpl::SubscribeCommonEvent()
systemManager->SubscribeSystemAbility(COMMON_EVENT_SERVICE_ID, callback);
}
+void DataShareServiceImpl::SubscribeConcurrentTask()
+{
+ sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
+ if (systemManager == nullptr) {
+ ZLOGE("System mgr is nullptr");
+ return;
+ }
+ sptr callback(new SystemAbilityStatusChangeListener());
+ systemManager->SubscribeSystemAbility(CONCURRENT_TASK_SERVICE_ID, callback);
+}
+
void DataShareServiceImpl::SubscribeChange()
{
EventCenter::GetInstance().Subscribe(RemoteChangeEvent::RDB_META_SAVE, [this](const Event &event) {
@@ -1135,7 +1155,7 @@ void DataShareServiceImpl::ReportExcuteFault(uint32_t callingTokenId, DataProvid
int32_t errCode, std::string &func)
{
std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(callingTokenId).first;
- DataShareFaultInfo faultInfo = {CURD_FAILED, providerInfo.bundleName, providerInfo.moduleName,
+ DataShareFaultInfo faultInfo = {HiViewFaultAdapter::curdFailed, providerInfo.bundleName, providerInfo.moduleName,
providerInfo.storeName, func, errCode, appendix};
HiViewFaultAdapter::ReportDataFault(faultInfo);
}
@@ -1150,13 +1170,14 @@ bool DataShareServiceImpl::VerifyPermission(const std::string &bundleName, const
}
} else {
Security::AccessToken::HapTokenInfo tokenInfo;
- auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo);
- if (result == Security::AccessToken::RET_SUCCESS && tokenInfo.bundleName == bundleName) {
- return true;
- }
// Provider from ProxyData, which does not allow empty permissions and cannot be access without configured
if (permission.empty()) {
- ZLOGE("Permission empty! token:0x%{public}x, bundleName:%{public}s", tokenId, bundleName.c_str());
+ ZLOGI("Permission empty! token:0x%{public}x, bundleName:%{public}s", tokenId, bundleName.c_str());
+ auto result = Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo);
+ if (result == Security::AccessToken::RET_SUCCESS && tokenInfo.bundleName == bundleName) {
+ return true;
+ }
+ ZLOGE("Permission denied!");
return false;
}
// If the permission is NO_PERMISSION, access is also allowed
diff --git a/services/distributeddataservice/service/data_share/data_share_service_impl.h b/services/distributeddataservice/service/data_share/data_share_service_impl.h
index e4d0a7d9d5d94a535750aa961947d451d9392512..90ee77d4a8b5aa4654ae278ce142d95101e3e3d7 100644
--- a/services/distributeddataservice/service/data_share/data_share_service_impl.h
+++ b/services/distributeddataservice/service/data_share/data_share_service_impl.h
@@ -118,13 +118,14 @@ private:
void RegisterDataShareServiceInfo();
void RegisterHandler();
bool SubscribeTimeChanged();
- bool NotifyChange(const std::string &uri);
+ bool NotifyChange(const std::string &uri, int32_t userId);
bool GetCallerBundleName(std::string &bundleName);
std::pair ExecuteEx(const std::string &uri, const std::string &extUri, const int32_t tokenId,
bool isRead, ExecuteCallbackEx callback);
std::pair GetCallerInfo(std::string &bundleName, int32_t &appIndex);
int32_t GetBMSAndMetaDataStatus(const std::string &uri, const int32_t tokenId);
void SubscribeCommonEvent();
+ void SubscribeConcurrentTask();
static void InitSubEvent();
void AutoLaunch(const DistributedData::Event &event);
void SubscribeChange();
diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp
index 229afde9572d7e6fbe7db80d62848490b6cfdfb6..170de1bcb8964843755595f357a3103401f804e7 100644
--- a/services/distributeddataservice/service/data_share/data_share_service_stub.cpp
+++ b/services/distributeddataservice/service/data_share/data_share_service_stub.cpp
@@ -18,6 +18,7 @@
#include "data_share_service_stub.h"
#include
+#include "common_utils.h"
#include "data_share_obs_proxy.h"
#include "hiview_adapter.h"
#include "hiview_fault_adapter.h"
@@ -25,10 +26,25 @@
#include "ishared_result_set.h"
#include "itypes_util.h"
#include "log_print.h"
+#include "qos.h"
#include "utils/anonymous.h"
namespace OHOS {
namespace DataShare {
+
+class DataShareServiceStub::QosManager {
+public:
+ QosManager()
+ {
+ // set thread qos QOS_USER_INTERACTIVE
+ QOS::SetThreadQos(QOS::QosLevel::QOS_USER_INTERACTIVE);
+ }
+ ~QosManager()
+ {
+ QOS::ResetThreadQos();
+ }
+};
+
bool DataShareServiceStub::CheckInterfaceToken(MessageParcel &data)
{
auto localDescriptor = IDataShareService::GetDescriptor();
@@ -51,6 +67,8 @@ int32_t DataShareServiceStub::OnInsertEx(MessageParcel &data, MessageParcel &rep
return IPC_STUB_INVALID_DATA_ERR;
}
auto [errCode, status] = InsertEx(uri, extUri, bucket);
+ ZLOGI("Insert uri:%{public}s, errCode:%{public}x, status:%{public}x",
+ DistributedData::Anonymous::Change(uri).c_str(), errCode, status);
if (!ITypesUtil::Marshal(reply, errCode, status)) {
ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status);
return IPC_STUB_WRITE_PARCEL_ERR;
@@ -70,6 +88,8 @@ int32_t DataShareServiceStub::OnUpdateEx(MessageParcel &data, MessageParcel &rep
return IPC_STUB_INVALID_DATA_ERR;
}
auto [errCode, status] = UpdateEx(uri, extUri, predicate, bucket);
+ ZLOGI("Update uri:%{public}s, errCode:%{public}x, status:%{public}x",
+ DistributedData::Anonymous::Change(uri).c_str(), errCode, status);
if (!ITypesUtil::Marshal(reply, errCode, status)) {
ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status);
return IPC_STUB_WRITE_PARCEL_ERR;
@@ -87,6 +107,8 @@ int32_t DataShareServiceStub::OnDeleteEx(MessageParcel &data, MessageParcel &rep
return IPC_STUB_INVALID_DATA_ERR;
}
auto [errCode, status] = DeleteEx(uri, extUri, predicate);
+ ZLOGI("Delete uri:%{public}s, errCode:%{public}x, status:%{public}x",
+ DistributedData::Anonymous::Change(uri).c_str(), errCode, status);
if (!ITypesUtil::Marshal(reply, errCode, status)) {
ZLOGE("Marshal errCode: 0x%{public}x, status: 0x%{public}x", errCode, status);
return IPC_STUB_WRITE_PARCEL_ERR;
@@ -327,16 +349,35 @@ int32_t DataShareServiceStub::OnNotifyConnectDone(MessageParcel &data, MessagePa
int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply)
{
+ // set thread qos
+ DataShareServiceStub::QosManager qos;
+ // check thread qos
+ QOS::QosLevel curLevel;
+ int qosRet = QOS::GetThreadQos(curLevel);
+
int tryTimes = TRY_TIMES;
while (!isReady_.load() && tryTimes > 0) {
tryTimes--;
std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME));
}
auto callingPid = IPCSkeleton::GetCallingPid();
+ auto fullTokenId = IPCSkeleton::GetCallingFullTokenID();
+ bool isSystemApp = CheckSystemCallingPermission(IPCSkeleton::GetCallingTokenID(), fullTokenId);
+ DataShareThreadLocal::SetFromSystemApp(isSystemApp);
+ if (code >= DATA_SHARE_CMD_SYSTEM_CODE) {
+ if (!isSystemApp) {
+ ZLOGE("CheckSystemCallingPermission fail, token:%{public}" PRIx64
+ ", callingPid:%{public}d, code:%{public}u", fullTokenId, callingPid, code);
+ return E_NOT_SYSTEM_APP;
+ }
+ code = code - DATA_SHARE_CMD_SYSTEM_CODE;
+ }
if (code != DATA_SHARE_SERVICE_CMD_QUERY && code != DATA_SHARE_SERVICE_CMD_GET_SILENT_PROXY_STATUS) {
- ZLOGI("code:%{public}u, callingPid:%{public}d", code, callingPid);
+ ZLOGI("code:%{public}u, callingPid:%{public}d, qosRet:%{public}d, curLevel:%{public}d",
+ code, callingPid, qosRet, curLevel);
}
if (!CheckInterfaceToken(data)) {
+ DataShareThreadLocal::CleanFromSystemApp();
return DATA_SHARE_ERROR;
}
int res = -1;
@@ -355,6 +396,7 @@ int DataShareServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Me
}
HiViewAdapter::GetInstance().ReportDataStatistic(callerInfo);
}
+ DataShareThreadLocal::CleanFromSystemApp();
return res;
}
diff --git a/services/distributeddataservice/service/data_share/data_share_service_stub.h b/services/distributeddataservice/service/data_share/data_share_service_stub.h
index d13b2099344894592e4804216ed2b2ef2a231625..47603e95941e975dec375523ecf6d7bbc25f0a81 100644
--- a/services/distributeddataservice/service/data_share/data_share_service_stub.h
+++ b/services/distributeddataservice/service/data_share/data_share_service_stub.h
@@ -27,6 +27,7 @@ public:
void SetServiceReady();
private:
+ class QosManager;
static constexpr std::chrono::milliseconds TIME_THRESHOLD = std::chrono::milliseconds(500);
static bool CheckInterfaceToken(MessageParcel& data);
int32_t OnQuery(MessageParcel& data, MessageParcel& reply);
diff --git a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp
index 6f8713521a0b4f483f70526afbd4c6dac0aa73aa..5b6bdc45b60f3850458c1137baab0981c54d2622 100644
--- a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp
+++ b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.cpp
@@ -86,19 +86,19 @@ std::pair HiViewFaultAdapter::GetCallingName(uint32_t callingT
return std::make_pair(callingName, result);
}
-void TimeoutReport::Report()
+void TimeoutReport::Report(const std::string &timeoutAppendix, const std::chrono::milliseconds timeoutms)
{
auto end = std::chrono::steady_clock::now();
std::chrono::milliseconds duration = std::chrono::duration_cast(end - start);
// Used to report DFX timeout faults
- if (needFaultReport && duration > DFX_TIME_OUT_MS) {
+ if (needFaultReport && duration > HiViewFaultAdapter::dfxTimeOutMs) {
DFXReport(duration);
}
// Used to report log timeout
- if (duration > TIME_OUT_MS) {
+ if (duration > timeoutms) {
int64_t milliseconds = duration.count();
- ZLOGE("over time when doing %{public}s, cost:%{public}" PRIi64 "ms", dfxInfo.businessType.c_str(),
- milliseconds);
+ ZLOGE("over time when doing %{public}s, %{public}s, cost:%{public}" PRIi64 "ms",
+ dfxInfo.businessType.c_str(), timeoutAppendix.c_str(), milliseconds);
}
}
@@ -107,11 +107,11 @@ void TimeoutReport::Report(const std::string &user, uint32_t callingPid, int32_t
auto end = std::chrono::steady_clock::now();
std::chrono::milliseconds duration = std::chrono::duration_cast(end - start);
// Used to report DFX timeout faults
- if (needFaultReport && duration > DFX_TIME_OUT_MS) {
+ if (needFaultReport && duration > HiViewFaultAdapter::dfxTimeOutMs) {
DFXReport(duration);
}
// Used to report log timeout
- if (duration > TIME_OUT_MS) {
+ if (duration > HiViewFaultAdapter::timeOutMs) {
int64_t milliseconds = duration.count();
std::string timeoutAppendix = "bundleName: " + dfxInfo.bundleName + ", user: " + user + ", callingPid: " +
std::to_string(callingPid);
@@ -134,8 +134,8 @@ void TimeoutReport::DFXReport(const std::chrono::milliseconds &duration)
int64_t milliseconds = duration.count();
std::string appendix = "callingName:" + HiViewFaultAdapter::GetCallingName(dfxInfo.callingTokenId).first;
appendix += ",cost:" + std::to_string(milliseconds) + "ms";
- DataShareFaultInfo faultInfo{TIME_OUT, dfxInfo.bundleName, dfxInfo.moduleName, dfxInfo.storeName,
- dfxInfo.businessType, errorCode, appendix};
+ DataShareFaultInfo faultInfo{HiViewFaultAdapter::timeOut, dfxInfo.bundleName, dfxInfo.moduleName,
+ dfxInfo.storeName, dfxInfo.businessType, errorCode, appendix};
HiViewFaultAdapter::ReportDataFault(faultInfo);
}
}
diff --git a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h
index 00cb42a5873f0e20605ad5d2a2946e706596c554..3b001e62d850779a3add7862037264bfe148d9cf 100644
--- a/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h
+++ b/services/distributeddataservice/service/data_share/dfx/hiview_fault_adapter.h
@@ -34,6 +34,17 @@ struct DataShareFaultInfo {
std::string appendix;
};
+class HiViewFaultAdapter {
+public:
+ static constexpr const std::chrono::milliseconds timeOutMs = std::chrono::milliseconds(300);
+ static constexpr const std::chrono::milliseconds dfxTimeOutMs = std::chrono::milliseconds(2000);
+ static constexpr const char* timeOut = "TIME_OUT";
+ static constexpr const char* resultsetFull = "RESULTSET_FULL";
+ static constexpr const char* curdFailed = "CURD_FAILED";
+ static void ReportDataFault(const DataShareFaultInfo &faultInfo);
+ static std::pair GetCallingName(uint32_t callingTokenid);
+};
+
// TimeoutReport is used for recording the time usage of multiple interfaces;
// It can set up a timeout threshold, and when the time usage exceeds this threshold, will print log;
// If want to record DFX fault report, need to set needFaultReport to true (default is false);
@@ -54,24 +65,12 @@ struct TimeoutReport {
explicit TimeoutReport(const DfxInfo &dfxInfo, bool needFaultReport = false)
: dfxInfo(dfxInfo), needFaultReport(needFaultReport)
{}
- void Report();
+ void Report(const std::string &timeoutAppendix = "",
+ const std::chrono::milliseconds timeoutms = HiViewFaultAdapter::timeOutMs);
void Report(const std::string &user, uint32_t callingPid, int32_t appIndex = -1, int32_t instanceId = -1);
void DFXReport(const std::chrono::milliseconds &duration);
~TimeoutReport() = default;
};
-
-
-class HiViewFaultAdapter {
-public:
- static void ReportDataFault(const DataShareFaultInfo &faultInfo);
- static std::pair GetCallingName(uint32_t callingTokenid);
-};
-
-inline const char* TIME_OUT = "TIME_OUT";
-inline const char* RESULTSET_FULL = "RESULTSET_FULL";
-inline const char* CURD_FAILED = "CURD_FAILED";
-inline const std::chrono::milliseconds TIME_OUT_MS = std::chrono::milliseconds(300);
-inline const std::chrono::milliseconds DFX_TIME_OUT_MS = std::chrono::milliseconds(2000);
}
}
#endif
\ No newline at end of file
diff --git a/services/distributeddataservice/service/data_share/idata_share_service.h b/services/distributeddataservice/service/data_share/idata_share_service.h
index e57489fecdeda12978ad666a1fd1518c064aacc6..05e1fd15542f7e286c0d6ba77b36ed1f005d52a1 100644
--- a/services/distributeddataservice/service/data_share/idata_share_service.h
+++ b/services/distributeddataservice/service/data_share/idata_share_service.h
@@ -29,6 +29,7 @@
namespace OHOS::DataShare {
class IDataShareService {
public:
+ static constexpr int DATA_SHARE_CMD_SYSTEM_CODE = 100;
enum {
DATA_SHARE_SERVICE_CMD_QUERY,
DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE,
@@ -52,7 +53,30 @@ public:
DATA_SHARE_SERVICE_CMD_INSERTEX,
DATA_SHARE_SERVICE_CMD_DELETEEX,
DATA_SHARE_SERVICE_CMD_UPDATEEX,
- DATA_SHARE_SERVICE_CMD_MAX
+ DATA_SHARE_SERVICE_CMD_MAX,
+ DATA_SHARE_SERVICE_CMD_QUERY_SYSTEM = DATA_SHARE_CMD_SYSTEM_CODE,
+ DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_DEL_TEMPLATE_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_PUBLISH_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_GET_DATA_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_SUBSCRIBE_RDB_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_RDB_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_RDB_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_RDB_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_SUBSCRIBE_PUBLISHED_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_PUBLISHED_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_PUBLISHED_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_PUBLISHED_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_NOTIFY_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_NOTIFY_OBSERVERS_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_SET_SILENT_SWITCH_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_GET_SILENT_PROXY_STATUS_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_REGISTER_OBSERVER_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_UNREGISTER_OBSERVER_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_INSERTEX_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_DELETEEX_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_UPDATEEX_SYSTEM,
+ DATA_SHARE_SERVICE_CMD_MAX_SYSTEM
};
enum { DATA_SHARE_ERROR = -1, DATA_SHARE_OK = 0 };
diff --git a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp
index c796152ca0fcd267f999c1d713a424cecacb7785..60d643d4b8145108b87d0783cc86d1de00f1e3e7 100644
--- a/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp
+++ b/services/distributeddataservice/service/data_share/strategies/data_proxy/load_config_from_data_proxy_node_strategy.cpp
@@ -30,9 +30,9 @@ bool LoadConfigFromDataProxyNodeStrategy::operator()(std::shared_ptr co
return false;
}
context->type = PUBLISHED_DATA_TYPE;
- if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS(
- context->calledBundleName, context->currentUserId, context->bundleInfo) != E_OK) {
- ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str());
+ if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck(
+ context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) {
+ ZLOGE("GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s", context->calledBundleName.c_str());
context->errCode = E_BUNDLE_NAME_NOT_EXIST;
return false;
}
@@ -40,10 +40,12 @@ bool LoadConfigFromDataProxyNodeStrategy::operator()(std::shared_ptr co
context->permission = "reject";
return true;
}
+ std::string uri = context->uri;
+ URIUtils::FormatUri(uri);
for (auto const &hapModuleInfo : context->bundleInfo.hapModuleInfos) {
auto proxyDatas = hapModuleInfo.proxyDatas;
for (auto const &proxyData : proxyDatas) {
- if (proxyData.uri != context->uri) {
+ if (proxyData.uri != uri) {
continue;
}
context->permission = context->isRead ? proxyData.requiredReadPermission
diff --git a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp
index 16fe91511f8148f17850e1acccb70dd233a305e5..cb4b331ac0b81cba9ec6862bd8f9068a80d8952e 100644
--- a/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp
+++ b/services/distributeddataservice/service/data_share/strategies/data_share/load_config_from_data_share_bundle_info_strategy.cpp
@@ -80,9 +80,9 @@ bool LoadConfigFromDataShareBundleInfoStrategy::operator()(std::shared_ptrcalledBundleName.c_str());
return false;
}
- if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMS(
- context->calledBundleName, context->currentUserId, context->bundleInfo) != E_OK) {
- ZLOGE("GetBundleInfoFromBMS failed! bundleName: %{public}s", context->calledBundleName.c_str());
+ if (BundleMgrProxy::GetInstance()->GetBundleInfoFromBMSWithCheck(
+ context->calledBundleName, context->visitedUserId, context->bundleInfo) != E_OK) {
+ ZLOGE("GetBundleInfoFromBMSWithCheck failed! bundleName: %{public}s", context->calledBundleName.c_str());
return false;
}
for (auto const &item : context->bundleInfo.extensionInfos) {
diff --git a/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp
index b8dece0fd2173572ea22fdba2f9e0bd8c833205f..9a64d37c7eec5db4b2b1e0530b9eff283ea278e1 100644
--- a/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp
+++ b/services/distributeddataservice/service/data_share/strategies/general/load_config_common_strategy.cpp
@@ -33,13 +33,14 @@ bool LoadConfigCommonStrategy::operator()(std::shared_ptr context)
context->callerTokenId = IPCSkeleton::GetCallingTokenID();
}
context->currentUserId = AccountDelegate::GetInstance()->GetUserByToken(context->callerTokenId);
+ context->visitedUserId = context->currentUserId;
if (!URIUtils::GetAppIndexFromProxyURI(context->uri, context->appIndex)) {
return false;
}
// sa, userId is in uri, caller token id is from first caller tokenId
if (context->currentUserId == 0) {
GetInfoFromProxyURI(
- context->uri, context->currentUserId, context->callerTokenId, context->calledBundleName);
+ context->uri, context->visitedUserId, context->callerTokenId, context->calledBundleName);
URIUtils::FormatUri(context->uri);
}
if (context->needAutoLoadCallerBundleName && context->callerBundleName.empty()) {
diff --git a/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp
index d5283e4d3a82bffd0cea72b2d3e3d5ab236f2e03..095a04bdb1f17f7d5a2f1e57f245c553af8bcb30 100644
--- a/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp
+++ b/services/distributeddataservice/service/data_share/strategies/general/load_config_data_info_strategy.cpp
@@ -53,12 +53,12 @@ bool LoadConfigNormalDataInfoStrategy::operator()(std::shared_ptr conte
}
DistributedData::StoreMetaData metaData;
if (!QueryMetaData(
- context->calledBundleName, context->calledStoreName, metaData, context->currentUserId, context->appIndex)) {
+ context->calledBundleName, context->calledStoreName, metaData, context->visitedUserId, context->appIndex)) {
// connect extension and retry
AAFwk::WantParams wantParams;
ExtensionConnectAdaptor::TryAndWait(context->uri, context->calledBundleName, wantParams);
if (!QueryMetaData(
- context->calledBundleName, context->calledStoreName, metaData, context->currentUserId, context->appIndex)) {
+ context->calledBundleName, context->calledStoreName, metaData, context->visitedUserId, context->appIndex)) {
ZLOGE("QueryMetaData fail, %{public}s", DistributedData::Anonymous::Change(context->uri).c_str());
context->errCode = NativeRdb::E_DB_NOT_EXIST;
return false;
diff --git a/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp
index c32d5daff4c916213c3a2740683989dcf96b56a3..b024369158a8c679f6daa55640b562821bdc6750 100644
--- a/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp
+++ b/services/distributeddataservice/service/data_share/strategies/get_data_strategy.cpp
@@ -36,7 +36,7 @@ Data GetDataStrategy::Execute(std::shared_ptr context, int &errorCode)
errorCode = context->errCode;
return Data();
}
- auto result = PublishedData::Query(context->calledBundleName, context->currentUserId);
+ auto result = PublishedData::Query(context->calledBundleName, context->visitedUserId);
Data data;
for (auto &item : result) {
if (!CheckPermission(context, item.value.key)) {
diff --git a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp
index 26b116d48aa72f13b7cd02ef3adaa4d144e59bf7..a23d516b026d911560b21b653b21b7dc63366184 100644
--- a/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp
+++ b/services/distributeddataservice/service/data_share/strategies/publish_strategy.cpp
@@ -42,10 +42,10 @@ int32_t PublishStrategy::Execute(std::shared_ptr