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