1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #define LOG_TAG "KvStoreDataService"
16 #include "kvstore_data_service.h"
17
18 #include <chrono>
19 #include <directory_ex.h>
20 #include <file_ex.h>
21 #include <ipc_skeleton.h>
22 #include <thread>
23 #include <unistd.h>
24
25 #include "accesstoken_kit.h"
26 #include "auth_delegate.h"
27 #include "auto_launch_export.h"
28 #include "bootstrap.h"
29 #include "checker/checker_manager.h"
30 #include "communication_provider.h"
31 #include "config_factory.h"
32 #include "constant.h"
33 #include "dds_trace.h"
34 #include "device_manager_adapter.h"
35 #include "device_matrix.h"
36 #include "eventcenter/event_center.h"
37 #include "executor_factory.h"
38 #include "hap_token_info.h"
39 #include "if_system_ability_manager.h"
40 #include "iservice_registry.h"
41 #include "kvstore_account_observer.h"
42 #include "kvstore_app_accessor.h"
43 #include "log_print.h"
44 #include "metadata/appid_meta_data.h"
45 #include "metadata/meta_data_manager.h"
46 #include "metadata/secret_key_meta_data.h"
47 #include "metadata/strategy_meta_data.h"
48 #include "permission_validator.h"
49 #include "permit_delegate.h"
50 #include "process_communicator_impl.h"
51 #include "route_head_handler_impl.h"
52 #include "runtime_config.h"
53 #include "string_ex.h"
54 #include "system_ability_definition.h"
55 #include "uninstaller/uninstaller.h"
56 #include "upgrade_manager.h"
57 #include "user_delegate.h"
58 #include "utils/block_integer.h"
59 #include "utils/converter.h"
60 #include "utils/crypto.h"
61
62 namespace OHOS::DistributedKv {
63 using namespace std::chrono;
64 using namespace OHOS::DistributedData;
65 using namespace OHOS::DistributedDataDfx;
66 using namespace OHOS::Security::AccessToken;
67 using KvStoreDelegateManager = DistributedDB::KvStoreDelegateManager;
68 using SecretKeyMeta = DistributedData::SecretKeyMetaData;
69 using StrategyMetaData = DistributedData::StrategyMeta;
70 using DmAdapter = DistributedData::DeviceManagerAdapter;
71
72 REGISTER_SYSTEM_ABILITY_BY_ID(KvStoreDataService, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, true);
73
KvStoreDataService(bool runOnCreate)74 KvStoreDataService::KvStoreDataService(bool runOnCreate)
75 : SystemAbility(runOnCreate), mutex_(), clients_()
76 {
77 ZLOGI("begin.");
78 }
79
KvStoreDataService(int32_t systemAbilityId,bool runOnCreate)80 KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate)
81 : SystemAbility(systemAbilityId, runOnCreate), mutex_(), clients_()
82 {
83 ZLOGI("begin");
84 }
85
~KvStoreDataService()86 KvStoreDataService::~KvStoreDataService()
87 {
88 ZLOGI("begin.");
89 clients_.clear();
90 features_.Clear();
91 }
92
Initialize()93 void KvStoreDataService::Initialize()
94 {
95 ZLOGI("begin.");
96 #ifndef UT_TEST
97 KvStoreDelegateManager::SetProcessLabel(Bootstrap::GetInstance().GetProcessLabel(), "default");
98 #endif
99 auto communicator = std::make_shared<AppDistributedKv::ProcessCommunicatorImpl>(RouteHeadHandlerImpl::Create);
100 auto ret = KvStoreDelegateManager::SetProcessCommunicator(communicator);
101 ZLOGI("set communicator ret:%{public}d.", static_cast<int>(ret));
102
103 PermitDelegate::GetInstance().Init();
104 InitSecurityAdapter();
105 KvStoreMetaManager::GetInstance().InitMetaParameter();
106 accountEventObserver_ = std::make_shared<KvStoreAccountObserver>(*this);
107 AccountDelegate::GetInstance()->Subscribe(accountEventObserver_);
108 deviceInnerListener_ = std::make_unique<KvStoreDeviceListener>(*this);
109 AppDistributedKv::CommunicationProvider::GetInstance().StartWatchDeviceChange(
110 deviceInnerListener_.get(), { "innerListener" });
111 }
112
GetFeatureInterface(const std::string & name)113 sptr<IRemoteObject> KvStoreDataService::GetFeatureInterface(const std::string &name)
114 {
115 sptr<DistributedData::FeatureStubImpl> feature;
116 bool isFirstCreate = false;
117 features_.Compute(name, [&feature, &isFirstCreate](const auto &key, auto &value) ->bool {
118 if (value != nullptr) {
119 feature = value;
120 return true;
121 }
122 auto creator = FeatureSystem::GetInstance().GetCreator(key);
123 if (!creator) {
124 return false;
125 }
126 auto impl = creator();
127 if (impl == nullptr) {
128 return false;
129 }
130
131 value = new DistributedData::FeatureStubImpl(impl);
132 feature = value;
133 isFirstCreate = true;
134 return true;
135 });
136 if (isFirstCreate) {
137 feature->OnInitialize();
138 }
139 return feature != nullptr ? feature->AsObject() : nullptr;
140 }
141
InitObjectStore()142 void KvStoreDataService::InitObjectStore()
143 {
144 ZLOGI("begin.");
145 auto feature = GetFeatureInterface("data_object");
146 }
147
148 /* RegisterClientDeathObserver */
RegisterClientDeathObserver(const AppId & appId,sptr<IRemoteObject> observer)149 Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer)
150 {
151 ZLOGD("begin.");
152 KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING);
153 if (!appId.IsValid()) {
154 ZLOGE("invalid bundleName.");
155 return Status::INVALID_ARGUMENT;
156 }
157
158 CheckerManager::StoreInfo info;
159 info.uid = IPCSkeleton::GetCallingUid();
160 info.tokenId = IPCSkeleton::GetCallingTokenID();
161 info.bundleName = appId.appId;
162 info.storeId = "";
163 if (!CheckerManager::GetInstance().IsValid(info)) {
164 ZLOGW("check bundleName:%{public}s uid:%{public}d failed.", appId.appId.c_str(), info.uid);
165 return Status::PERMISSION_DENIED;
166 }
167
168 std::lock_guard<decltype(mutex_)> lg(mutex_);
169 auto iter = clients_.find(info.tokenId);
170 // Ignore register with same tokenId and pid
171 if (iter != clients_.end() && IPCSkeleton::GetCallingPid() == iter->second.GetPid()) {
172 ZLOGW("bundleName:%{public}s, uid:%{public}d, pid:%{public}d has already registered.",
173 appId.appId.c_str(), info.uid, IPCSkeleton::GetCallingPid());
174 return Status::SUCCESS;
175 }
176
177 clients_.erase(info.tokenId);
178 auto it = clients_.emplace(std::piecewise_construct, std::forward_as_tuple(info.tokenId),
179 std::forward_as_tuple(appId, *this, std::move(observer)));
180 ZLOGI("bundleName:%{public}s, uid:%{public}d, pid:%{public}d inserted:%{public}s.",
181 appId.appId.c_str(), info.uid, IPCSkeleton::GetCallingPid(), it.second ? "success" : "failed");
182 return it.second ? Status::SUCCESS : Status::ERROR;
183 }
184
AppExit(pid_t uid,pid_t pid,uint32_t token,const AppId & appId)185 Status KvStoreDataService::AppExit(pid_t uid, pid_t pid, uint32_t token, const AppId &appId)
186 {
187 ZLOGI("AppExit");
188 // memory of parameter appId locates in a member of clientDeathObserverMap_ and will be freed after
189 // clientDeathObserverMap_ erase, so we have to take a copy if we want to use this parameter after erase operation.
190 AppId appIdTmp = appId;
191 std::lock_guard<decltype(mutex_)> lg(mutex_);
192 clients_.erase(token);
193 return Status::SUCCESS;
194 }
195
OnDump()196 void KvStoreDataService::OnDump()
197 {
198 ZLOGD("begin.");
199 }
200
Dump(int fd,const std::vector<std::u16string> & args)201 int KvStoreDataService::Dump(int fd, const std::vector<std::u16string> &args)
202 {
203 int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
204 const int maxUid = 10000;
205 if (uid > maxUid) {
206 return 0;
207 }
208
209 std::vector<std::string> argsStr;
210 for (auto item : args) {
211 argsStr.emplace_back(Str16ToStr8(item));
212 }
213
214 if (DumpHelper::GetInstance().Dump(fd, argsStr)) {
215 return 0;
216 }
217
218 ZLOGE("DumpHelper failed");
219 return ERROR;
220 }
221
OnStart()222 void KvStoreDataService::OnStart()
223 {
224 ZLOGI("distributeddata service onStart");
225 EventCenter::Defer defer;
226 AccountDelegate::GetInstance()->RegisterHashFunc(Crypto::Sha256);
227 static constexpr int32_t RETRY_TIMES = 50;
228 static constexpr int32_t RETRY_INTERVAL = 500 * 1000; // unit is ms
229 for (BlockInteger retry(RETRY_INTERVAL); retry < RETRY_TIMES; ++retry) {
230 if (!AppDistributedKv::CommunicationProvider::GetInstance().GetLocalDevice().uuid.empty()) {
231 break;
232 }
233 ZLOGE("GetLocalDeviceId failed, retry count:%{public}d", static_cast<int>(retry));
234 }
235 ZLOGI("Bootstrap configs and plugins.");
236 Bootstrap::GetInstance().LoadComponents();
237 Bootstrap::GetInstance().LoadDirectory();
238 Bootstrap::GetInstance().LoadCheckers();
239 Bootstrap::GetInstance().LoadNetworks();
240 Bootstrap::GetInstance().LoadBackup();
241 Initialize();
242 auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
243 if (samgr != nullptr) {
244 ZLOGI("samgr exist.");
245 auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
246 auto kvDataServiceProxy = iface_cast<IKvStoreDataService>(remote);
247 if (kvDataServiceProxy != nullptr) {
248 ZLOGI("service has been registered.");
249 return;
250 }
251 }
252 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
253 StartService();
254 }
255
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)256 void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
257 {
258 ZLOGI("add system abilityid:%d", systemAbilityId);
259 (void)deviceId;
260 if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
261 return;
262 }
263 AccountDelegate::GetInstance()->SubscribeAccountEvent();
264 Uninstaller::GetInstance().Init(this);
265 }
266
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)267 void KvStoreDataService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
268 {
269 ZLOGI("remove system abilityid:%d", systemAbilityId);
270 (void)deviceId;
271 if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
272 return;
273 }
274 AccountDelegate::GetInstance()->UnsubscribeAccountEvent();
275 Uninstaller::GetInstance().UnsubscribeEvent();
276 }
277
StartService()278 void KvStoreDataService::StartService()
279 {
280 // register this to ServiceManager.
281 KvStoreMetaManager::GetInstance().InitMetaListener();
282 DeviceMatrix::GetInstance().Initialize(IPCSkeleton::GetCallingTokenID(), Bootstrap::GetInstance().GetMetaDBName());
283 InitObjectStore();
284 bool ret = SystemAbility::Publish(this);
285 if (!ret) {
286 DumpHelper::GetInstance().AddErrorInfo("StartService: Service publish failed.");
287 }
288 Uninstaller::GetInstance().Init(this);
289 // Initialize meta db delegate manager.
290 KvStoreMetaManager::GetInstance().SubscribeMeta(KvStoreMetaRow::KEY_PREFIX,
291 [this](const std::vector<uint8_t> &key, const std::vector<uint8_t> &value, CHANGE_FLAG flag) {
292 OnStoreMetaChanged(key, value, flag);
293 });
294 UpgradeManager::GetInstance().Init();
295 UserDelegate::GetInstance().Init();
296
297 // subscribe account event listener to EventNotificationMgr
298 AccountDelegate::GetInstance()->SubscribeAccountEvent();
299 auto autoLaunch = [this](const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) -> bool {
300 auto status = ResolveAutoLaunchParamByIdentifier(identifier, param);
301 features_.ForEachCopies([&identifier, ¶m](const auto &, sptr<DistributedData::FeatureStubImpl> &value) {
302 value->ResolveAutoLaunch(identifier, param);
303 return false;
304 });
305 return status;
306 };
307 KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunch);
308 ZLOGI("Publish ret: %{public}d", static_cast<int>(ret));
309 }
310
OnStoreMetaChanged(const std::vector<uint8_t> & key,const std::vector<uint8_t> & value,CHANGE_FLAG flag)311 void KvStoreDataService::OnStoreMetaChanged(
312 const std::vector<uint8_t> &key, const std::vector<uint8_t> &value, CHANGE_FLAG flag)
313 {
314 if (flag != CHANGE_FLAG::UPDATE) {
315 return;
316 }
317 StoreMetaData metaData;
318 metaData.Unmarshall({ value.begin(), value.end() });
319 ZLOGD("meta data info appType:%{public}s, storeId:%{public}s isDirty:%{public}d", metaData.appType.c_str(),
320 metaData.storeId.c_str(), metaData.isDirty);
321 auto deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
322 if (metaData.deviceId != deviceId || metaData.deviceId.empty()) {
323 ZLOGD("ignore other device change or invalid meta device");
324 return;
325 }
326 static constexpr const char *HARMONY_APP = "harmony";
327 if (!metaData.isDirty || metaData.appType != HARMONY_APP) {
328 return;
329 }
330 ZLOGI("dirty kv store. storeId:%{public}s", metaData.storeId.c_str());
331 }
332
ResolveAutoLaunchParamByIdentifier(const std::string & identifier,DistributedDB::AutoLaunchParam & param)333 bool KvStoreDataService::ResolveAutoLaunchParamByIdentifier(
334 const std::string &identifier, DistributedDB::AutoLaunchParam ¶m)
335 {
336 ZLOGI("start");
337 std::map<std::string, MetaData> entries;
338 if (!KvStoreMetaManager::GetInstance().GetFullMetaData(entries)) {
339 ZLOGE("get full meta failed");
340 return false;
341 }
342 std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
343 for (const auto &entry : entries) {
344 auto &storeMeta = entry.second.kvStoreMetaData;
345 if ((!param.userId.empty() && (param.userId != storeMeta.deviceAccountId))
346 || (localDeviceId != storeMeta.deviceId)) {
347 // judge local userid and local meta
348 continue;
349 }
350 const std::string &itemTripleIdentifier = DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier(
351 storeMeta.userId, storeMeta.appId, storeMeta.storeId, false);
352 const std::string &itemDualIdentifier =
353 DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier("", storeMeta.appId, storeMeta.storeId, true);
354 if (identifier == itemTripleIdentifier && storeMeta.bundleName != Bootstrap::GetInstance().GetProcessLabel()) {
355 // old triple tuple identifier, should SetEqualIdentifier
356 ResolveAutoLaunchCompatible(entry.second, identifier);
357 }
358 if (identifier == itemDualIdentifier || identifier == itemTripleIdentifier) {
359 ZLOGI("identifier find");
360 DistributedDB::AutoLaunchOption option;
361 option.createIfNecessary = false;
362 option.isEncryptedDb = storeMeta.isEncrypt;
363 DistributedDB::CipherPassword password;
364 const std::vector<uint8_t> &secretKey = entry.second.secretKeyMetaData.secretKey;
365 if (password.SetValue(secretKey.data(), secretKey.size()) != DistributedDB::CipherPassword::OK) {
366 ZLOGE("Get secret key failed.");
367 }
368 if (storeMeta.bundleName == Bootstrap::GetInstance().GetProcessLabel()) {
369 param.userId = storeMeta.deviceAccountId;
370 }
371 option.passwd = password;
372 option.schema = storeMeta.schema;
373 option.createDirByStoreIdOnly = true;
374 option.dataDir = storeMeta.dataDir;
375 option.secOption = ConvertSecurity(storeMeta.securityLevel);
376 option.isAutoSync = storeMeta.isAutoSync;
377 option.syncDualTupleMode = true; // dual tuple flag
378 param.appId = storeMeta.appId;
379 param.storeId = storeMeta.storeId;
380 param.option = option;
381 return true;
382 }
383 }
384 ZLOGI("not find identifier");
385 return false;
386 }
387
ConvertSecurity(int securityLevel)388 DistributedDB::SecurityOption KvStoreDataService::ConvertSecurity(int securityLevel)
389 {
390 if (securityLevel < SecurityLevel::NO_LABEL || securityLevel > SecurityLevel::S4) {
391 return {DistributedDB::NOT_SET, DistributedDB::ECE};
392 }
393 switch (securityLevel) {
394 case SecurityLevel::S3:
395 return {DistributedDB::S3, DistributedDB::SECE};
396 case SecurityLevel::S4:
397 return {DistributedDB::S4, DistributedDB::ECE};
398 default:
399 return {securityLevel, DistributedDB::ECE};
400 }
401 }
402
ResolveAutoLaunchCompatible(const MetaData & meta,const std::string & identifier)403 void KvStoreDataService::ResolveAutoLaunchCompatible(const MetaData &meta, const std::string &identifier)
404 {
405 ZLOGI("AutoLaunch:peer device is old tuple, begin to open store");
406 if (meta.kvStoreType > KvStoreType::SINGLE_VERSION || meta.kvStoreMetaData.version > STORE_VERSION) {
407 ZLOGW("no longer support multi or higher version store type");
408 return;
409 }
410
411 // open store and SetEqualIdentifier, then close store after 60s
412 auto &storeMeta = meta.kvStoreMetaData;
413 auto *delegateManager = new (std::nothrow)
414 DistributedDB::KvStoreDelegateManager(storeMeta.appId, storeMeta.deviceAccountId);
415 if (delegateManager == nullptr) {
416 ZLOGE("get store delegate manager failed");
417 return;
418 }
419 delegateManager->SetKvStoreConfig({ storeMeta.dataDir });
420 Options options = {
421 .createIfMissing = false,
422 .encrypt = storeMeta.isEncrypt,
423 .autoSync = storeMeta.isAutoSync,
424 .securityLevel = storeMeta.securityLevel,
425 .kvStoreType = static_cast<KvStoreType>(storeMeta.kvStoreType),
426 };
427 DistributedDB::KvStoreNbDelegate::Option dbOptions;
428 InitNbDbOption(options, meta.secretKeyMetaData.secretKey, dbOptions);
429 DistributedDB::KvStoreNbDelegate *store = nullptr;
430 delegateManager->GetKvStore(storeMeta.storeId, dbOptions,
431 [&identifier, &store, &storeMeta](int status, DistributedDB::KvStoreNbDelegate *delegate) {
432 ZLOGI("temporary open db for equal identifier, ret:%{public}d", status);
433 if (delegate != nullptr) {
434 KvStoreTuple tuple = { storeMeta.deviceAccountId, storeMeta.appId, storeMeta.storeId };
435 UpgradeManager::SetCompatibleIdentifyByType(delegate, tuple, IDENTICAL_ACCOUNT_GROUP);
436 UpgradeManager::SetCompatibleIdentifyByType(delegate, tuple, PEER_TO_PEER_GROUP);
437 store = delegate;
438 }
439 });
440 KvStoreTask delayTask([delegateManager, store]() {
441 constexpr const int CLOSE_STORE_DELAY_TIME = 60; // unit: seconds
442 std::this_thread::sleep_for(std::chrono::seconds(CLOSE_STORE_DELAY_TIME));
443 ZLOGI("AutoLaunch:close store after 60s while autolaunch finishied");
444 delegateManager->CloseKvStore(store);
445 delete delegateManager;
446 });
447 ExecutorFactory::GetInstance().Execute(std::move(delayTask));
448 }
449
InitNbDbOption(const Options & options,const std::vector<uint8_t> & cipherKey,DistributedDB::KvStoreNbDelegate::Option & dbOption)450 Status KvStoreDataService::InitNbDbOption(const Options &options, const std::vector<uint8_t> &cipherKey,
451 DistributedDB::KvStoreNbDelegate::Option &dbOption)
452 {
453 DistributedDB::CipherPassword password;
454 auto status = password.SetValue(cipherKey.data(), cipherKey.size());
455 if (status != DistributedDB::CipherPassword::ErrorCode::OK) {
456 ZLOGE("Failed to set the passwd.");
457 return Status::DB_ERROR;
458 }
459
460 dbOption.syncDualTupleMode = true; // tuple of (appid+storeid)
461 dbOption.createIfNecessary = options.createIfMissing;
462 dbOption.isMemoryDb = (!options.persistent);
463 dbOption.isEncryptedDb = options.encrypt;
464 if (options.encrypt) {
465 dbOption.cipher = DistributedDB::CipherType::AES_256_GCM;
466 dbOption.passwd = password;
467 }
468
469 if (options.kvStoreType == KvStoreType::SINGLE_VERSION) {
470 dbOption.conflictResolvePolicy = DistributedDB::LAST_WIN;
471 } else if (options.kvStoreType == KvStoreType::DEVICE_COLLABORATION) {
472 dbOption.conflictResolvePolicy = DistributedDB::DEVICE_COLLABORATION;
473 } else {
474 ZLOGE("kvStoreType is invalid");
475 return Status::INVALID_ARGUMENT;
476 }
477
478 dbOption.schema = options.schema;
479 dbOption.createDirByStoreIdOnly = true;
480 dbOption.secOption = ConvertSecurity(options.securityLevel);
481 return Status::SUCCESS;
482 }
483
OnStop()484 void KvStoreDataService::OnStop()
485 {
486 ZLOGI("begin.");
487 }
488
KvStoreClientDeathObserverImpl(const AppId & appId,KvStoreDataService & service,sptr<IRemoteObject> observer)489 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl(
490 const AppId &appId, KvStoreDataService &service, sptr<IRemoteObject> observer)
491 : appId_(appId), dataService_(service), observerProxy_(std::move(observer)),
492 deathRecipient_(new KvStoreDeathRecipient(*this))
493 {
494 ZLOGI("KvStoreClientDeathObserverImpl");
495 uid_ = IPCSkeleton::GetCallingUid();
496 pid_ = IPCSkeleton::GetCallingPid();
497 token_ = IPCSkeleton::GetCallingTokenID();
498 if (observerProxy_ != nullptr) {
499 ZLOGI("add death recipient");
500 observerProxy_->AddDeathRecipient(deathRecipient_);
501 } else {
502 ZLOGW("observerProxy_ is nullptr");
503 }
504 }
505
~KvStoreClientDeathObserverImpl()506 KvStoreDataService::KvStoreClientDeathObserverImpl::~KvStoreClientDeathObserverImpl()
507 {
508 ZLOGI("~KvStoreClientDeathObserverImpl");
509 if (deathRecipient_ != nullptr && observerProxy_ != nullptr) {
510 ZLOGI("remove death recipient");
511 observerProxy_->RemoveDeathRecipient(deathRecipient_);
512 }
513 dataService_.features_.ForEachCopies([this](const auto &, sptr<DistributedData::FeatureStubImpl> &value) {
514 value->OnAppExit(uid_, pid_, token_, appId_);
515 return false;
516 });
517 }
518
NotifyClientDie()519 void KvStoreDataService::KvStoreClientDeathObserverImpl::NotifyClientDie()
520 {
521 ZLOGI("appId: %{public}s uid:%{public}d tokenId:%{public}u", appId_.appId.c_str(), uid_, token_);
522 dataService_.AppExit(uid_, pid_, token_, appId_);
523 }
524
GetPid() const525 pid_t KvStoreDataService::KvStoreClientDeathObserverImpl::GetPid() const
526 {
527 return pid_;
528 }
529
KvStoreDeathRecipient(KvStoreClientDeathObserverImpl & kvStoreClientDeathObserverImpl)530 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::KvStoreDeathRecipient(
531 KvStoreClientDeathObserverImpl &kvStoreClientDeathObserverImpl)
532 : kvStoreClientDeathObserverImpl_(kvStoreClientDeathObserverImpl)
533 {
534 ZLOGI("KvStore Client Death Observer");
535 }
536
~KvStoreDeathRecipient()537 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::~KvStoreDeathRecipient()
538 {
539 ZLOGI("KvStore Client Death Observer");
540 }
541
OnRemoteDied(const wptr<IRemoteObject> & remote)542 void KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::OnRemoteDied(
543 const wptr<IRemoteObject> &remote)
544 {
545 (void) remote;
546 ZLOGI("begin");
547 kvStoreClientDeathObserverImpl_.NotifyClientDie();
548 }
549
AccountEventChanged(const AccountEventInfo & eventInfo)550 void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo)
551 {
552 ZLOGI("account event %{public}d changed process, begin.", eventInfo.status);
553 NotifyAccountEvent(eventInfo);
554 switch (eventInfo.status) {
555 case AccountStatus::DEVICE_ACCOUNT_DELETE: {
556 g_kvStoreAccountEventStatus = 1;
557 // delete all kvstore meta belong to this user
558 std::vector<StoreMetaData> metaData;
559 MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({""}), metaData);
560 for (const auto &meta : metaData) {
561 if (meta.user != eventInfo.userId) {
562 continue;
563 }
564 ZLOGI("bundlname:%s, user:%s", meta.bundleName.c_str(), meta.user.c_str());
565 MetaDataManager::GetInstance().DelMeta(meta.GetKey());
566 MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey());
567 MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true);
568 MetaDataManager::GetInstance().DelMeta(meta.appId, true);
569 MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true);
570 }
571 g_kvStoreAccountEventStatus = 0;
572 break;
573 }
574 case AccountStatus::DEVICE_ACCOUNT_SWITCHED: {
575 auto ret = DistributedDB::KvStoreDelegateManager::NotifyUserChanged();
576 ZLOGI("notify delegate manager result:%{public}d", ret);
577 break;
578 }
579 default: {
580 break;
581 }
582 }
583 ZLOGI("account event %{public}d changed process, end.", eventInfo.status);
584 }
585
NotifyAccountEvent(const AccountEventInfo & eventInfo)586 void KvStoreDataService::NotifyAccountEvent(const AccountEventInfo &eventInfo)
587 {
588 features_.ForEachCopies([&eventInfo](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
589 value->OnUserChange(uint32_t(eventInfo.status), eventInfo.userId, eventInfo.harmonyAccountId);
590 return false;
591 });
592
593 if (eventInfo.status == AccountStatus::DEVICE_ACCOUNT_SWITCHED) {
594 features_.Erase("data_share");
595 }
596 }
597
InitSecurityAdapter()598 void KvStoreDataService::InitSecurityAdapter()
599 {
600 auto ret = DATASL_OnStart();
601 ZLOGI("datasl on start ret:%d", ret);
602 security_ = std::make_shared<Security>();
603 if (security_ == nullptr) {
604 ZLOGD("Security is nullptr.");
605 return;
606 }
607
608 auto dbStatus = DistributedDB::RuntimeConfig::SetProcessSystemAPIAdapter(security_);
609 ZLOGD("set distributed db system api adapter: %d.", static_cast<int>(dbStatus));
610
611 auto status = AppDistributedKv::CommunicationProvider::GetInstance().StartWatchDeviceChange(
612 security_.get(), {"security"});
613 if (status != AppDistributedKv::Status::SUCCESS) {
614 ZLOGD("security register device change failed, status:%d", static_cast<int>(status));
615 }
616 }
617
SetCompatibleIdentify(const AppDistributedKv::DeviceInfo & info) const618 void KvStoreDataService::SetCompatibleIdentify(const AppDistributedKv::DeviceInfo &info) const
619 {
620 }
621
OnDeviceOnline(const AppDistributedKv::DeviceInfo & info)622 void KvStoreDataService::OnDeviceOnline(const AppDistributedKv::DeviceInfo &info)
623 {
624 if (info.uuid.empty()) {
625 return;
626 }
627 features_.ForEachCopies([&info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
628 value->Online(info.uuid);
629 return false;
630 });
631 }
632
GetKvStoreDiskSize(const std::string & storeId,uint64_t & size)633 bool DbMetaCallbackDelegateMgr::GetKvStoreDiskSize(const std::string &storeId, uint64_t &size)
634 {
635 if (IsDestruct()) {
636 return false;
637 }
638 DistributedDB::DBStatus ret = delegate_->GetKvStoreDiskSize(storeId, size);
639 return (ret == DistributedDB::DBStatus::OK);
640 }
641
GetKvStoreKeys(std::vector<StoreInfo> & dbStats)642 void DbMetaCallbackDelegateMgr::GetKvStoreKeys(std::vector<StoreInfo> &dbStats)
643 {
644 if (IsDestruct()) {
645 return;
646 }
647 DistributedDB::DBStatus dbStatusTmp;
648 Option option {.createIfNecessary = true, .isMemoryDb = false, .isEncryptedDb = false};
649 DistributedDB::KvStoreNbDelegate *nbDelegate = nullptr;
650 delegate_->GetKvStore(Bootstrap::GetInstance().GetMetaDBName(), option,
651 [&nbDelegate, &dbStatusTmp](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreNbDelegate *delegate) {
652 nbDelegate = delegate;
653 dbStatusTmp = dbStatus;
654 });
655
656 if (dbStatusTmp != DistributedDB::DBStatus::OK) {
657 return;
658 }
659 DistributedDB::Key dbKey = KvStoreMetaRow::GetKeyFor("");
660 std::vector<DistributedDB::Entry> entries;
661 nbDelegate->GetEntries(dbKey, entries);
662 if (entries.empty()) {
663 delegate_->CloseKvStore(nbDelegate);
664 return;
665 }
666 for (auto const &entry : entries) {
667 std::string key = std::string(entry.key.begin(), entry.key.end());
668 std::vector<std::string> out;
669 Split(key, Constant::KEY_SEPARATOR, out);
670 if (out.size() >= VECTOR_SIZE) {
671 StoreInfo storeInfo = {out[USER_ID], out[APP_ID], out[STORE_ID]};
672 dbStats.push_back(std::move(storeInfo));
673 }
674 }
675 delegate_->CloseKvStore(nbDelegate);
676 }
677
OnUninstall(const std::string & bundleName,int32_t user,int32_t index,uint32_t tokenId)678 int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t user, int32_t index, uint32_t tokenId)
679 {
680 features_.ForEachCopies(
681 [bundleName, user, index, tokenId](const auto &, sptr<DistributedData::FeatureStubImpl> &value) {
682 value->OnAppUninstall(bundleName, user, index, tokenId);
683 return false;
684 });
685 return 0;
686 }
687 } // namespace OHOS::DistributedKv
688