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 <ipc_skeleton.h>
20 #include <thread>
21 
22 #include "accesstoken_kit.h"
23 #include "auth_delegate.h"
24 #include "auto_launch_export.h"
25 #include "bootstrap.h"
26 #include "checker/checker_manager.h"
27 #include "communication_provider.h"
28 #include "communicator_context.h"
29 #include "config_factory.h"
30 #include "crypto_manager.h"
31 #include "db_info_handle_impl.h"
32 #include "device_manager_adapter.h"
33 #include "device_matrix.h"
34 #include "dump/dump_manager.h"
35 #include "dump_helper.h"
36 #include "eventcenter/event_center.h"
37 #include "if_system_ability_manager.h"
38 #include "iservice_registry.h"
39 #include "kvstore_account_observer.h"
40 #include "log_print.h"
41 #include "mem_mgr_client.h"
42 #include "mem_mgr_proxy.h"
43 #include "metadata/appid_meta_data.h"
44 #include "metadata/meta_data_manager.h"
45 #include "metadata/secret_key_meta_data.h"
46 #include "permission_validator.h"
47 #include "permit_delegate.h"
48 #include "process_communicator_impl.h"
49 #include "reporter.h"
50 #include "route_head_handler_impl.h"
51 #include "runtime_config.h"
52 #include "store/auto_cache.h"
53 #include "string_ex.h"
54 #include "system_ability_definition.h"
55 #include "task_manager.h"
56 #include "installer/installer.h"
57 #include "upgrade.h"
58 #include "upgrade_manager.h"
59 #include "user_delegate.h"
60 #include "utils/anonymous.h"
61 #include "utils/block_integer.h"
62 #include "utils/crypto.h"
63 #include "water_version_manager.h"
64 #include "app_id_mapping/app_id_mapping_config_manager.h"
65 
66 namespace OHOS::DistributedKv {
67 using namespace std::chrono;
68 using namespace OHOS::DistributedData;
69 using namespace OHOS::DistributedDataDfx;
70 using namespace OHOS::Security::AccessToken;
71 using KvStoreDelegateManager = DistributedDB::KvStoreDelegateManager;
72 using SecretKeyMeta = DistributedData::SecretKeyMetaData;
73 using DmAdapter = DistributedData::DeviceManagerAdapter;
74 using DBConfig = DistributedDB::RuntimeConfig;
75 
76 REGISTER_SYSTEM_ABILITY_BY_ID(KvStoreDataService, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, true);
77 
78 constexpr char FOUNDATION_PROCESS_NAME[] = "foundation";
79 
KvStoreDataService(bool runOnCreate)80 KvStoreDataService::KvStoreDataService(bool runOnCreate)
81     : SystemAbility(runOnCreate), clients_()
82 {
83     ZLOGI("begin.");
84     if (executors_ == nullptr) {
85         constexpr size_t MAX = 12;
86         constexpr size_t MIN = 5;
87         executors_ = std::make_shared<ExecutorPool>(MAX, MIN);
88         DistributedDB::RuntimeConfig::SetThreadPool(std::make_shared<TaskManager>(executors_));
89     }
90 }
91 
KvStoreDataService(int32_t systemAbilityId,bool runOnCreate)92 KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate)
93     : SystemAbility(systemAbilityId, runOnCreate), clients_()
94 {
95     ZLOGI("begin");
96     if (executors_ == nullptr) {
97         constexpr size_t MAX = 12;
98         constexpr size_t MIN = 5;
99         executors_ = std::make_shared<ExecutorPool>(MAX, MIN);
100         DistributedDB::RuntimeConfig::SetThreadPool(std::make_shared<TaskManager>(executors_));
101     }
102 }
103 
~KvStoreDataService()104 KvStoreDataService::~KvStoreDataService()
105 {
106     ZLOGI("begin.");
107     clients_.Clear();
108     features_.Clear();
109 }
110 
Initialize()111 void KvStoreDataService::Initialize()
112 {
113     ZLOGI("begin.");
114 #ifndef UT_TEST
115     KvStoreDelegateManager::SetProcessLabel(Bootstrap::GetInstance().GetProcessLabel(), "default");
116 #endif
117     CommunicatorContext::GetInstance().SetThreadPool(executors_);
118     auto communicator = std::make_shared<AppDistributedKv::ProcessCommunicatorImpl>(RouteHeadHandlerImpl::Create);
119     DistributedDB::RuntimeConfig::SetDBInfoHandle(std::make_shared<DBInfoHandleImpl>());
120     auto ret = KvStoreDelegateManager::SetProcessCommunicator(communicator);
121     ZLOGI("set communicator ret:%{public}d.", static_cast<int>(ret));
122 
123     AppDistributedKv::CommunicationProvider::GetInstance();
124     PermitDelegate::GetInstance().Init();
125     InitSecurityAdapter(executors_);
126     KvStoreMetaManager::GetInstance().BindExecutor(executors_);
127     KvStoreMetaManager::GetInstance().InitMetaParameter();
128     accountEventObserver_ = std::make_shared<KvStoreAccountObserver>(*this, executors_);
129     AccountDelegate::GetInstance()->Subscribe(accountEventObserver_);
130     deviceInnerListener_ = std::make_unique<KvStoreDeviceListener>(*this);
131     DmAdapter::GetInstance().StartWatchDeviceChange(deviceInnerListener_.get(), { "innerListener" });
132     CommunicatorContext::GetInstance().RegSessionListener(deviceInnerListener_.get());
133     auto translateCall = [](const std::string &oriDevId, const DistributedDB::StoreInfo &info) {
134         StoreMetaData meta;
135         AppIDMetaData appIdMeta;
136         MetaDataManager::GetInstance().LoadMeta(info.appId, appIdMeta, true);
137         meta.bundleName = appIdMeta.bundleName;
138         meta.storeId = info.storeId;
139         meta.user = info.userId;
140         meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
141         MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true);
142         std::string uuid;
143         if (OHOS::Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(meta.tokenId) ==
144             OHOS::Security::AccessToken::TOKEN_HAP) {
145             uuid = DmAdapter::GetInstance().CalcClientUuid(meta.appId, oriDevId);
146         } else {
147             uuid = DmAdapter::GetInstance().CalcClientUuid(" ", oriDevId);
148         }
149         return uuid;
150     };
151     DBConfig::SetTranslateToDeviceIdCallback(translateCall);
152 }
153 
GetFeatureInterface(const std::string & name)154 sptr<IRemoteObject> KvStoreDataService::GetFeatureInterface(const std::string &name)
155 {
156     sptr<FeatureStubImpl> feature;
157     bool isFirstCreate = false;
158     features_.Compute(name, [&feature, &isFirstCreate](const auto &key, auto &value) ->bool {
159         if (value != nullptr) {
160             feature = value;
161             return true;
162         }
163         auto creator = FeatureSystem::GetInstance().GetCreator(key);
164         if (!creator) {
165             return false;
166         }
167         auto impl = creator();
168         if (impl == nullptr) {
169             return false;
170         }
171 
172         value = new FeatureStubImpl(impl);
173         feature = value;
174         isFirstCreate = true;
175         return true;
176     });
177     if (isFirstCreate) {
178         feature->OnInitialize(executors_);
179     }
180     return feature != nullptr ? feature->AsObject() : nullptr;
181 }
182 
LoadFeatures()183 void KvStoreDataService::LoadFeatures()
184 {
185     ZLOGI("begin.");
186     auto features = FeatureSystem::GetInstance().GetFeatureName(FeatureSystem::BIND_NOW);
187     for (auto const &feature : features) {
188         GetFeatureInterface(feature);
189     }
190 }
191 
192 /* RegisterClientDeathObserver */
RegisterClientDeathObserver(const AppId & appId,sptr<IRemoteObject> observer)193 Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer)
194 {
195     ZLOGD("begin.");
196     KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING);
197     if (!appId.IsValid()) {
198         ZLOGE("invalid bundleName, name:%{public}s", appId.appId.c_str());
199         return Status::INVALID_ARGUMENT;
200     }
201 
202     CheckerManager::StoreInfo info;
203     info.uid = IPCSkeleton::GetCallingUid();
204     info.tokenId = IPCSkeleton::GetCallingTokenID();
205     info.bundleName = appId.appId;
206     info.storeId = "";
207     if (!CheckerManager::GetInstance().IsValid(info)) {
208         ZLOGW("check bundleName:%{public}s uid:%{public}d failed.", appId.appId.c_str(), info.uid);
209         return Status::PERMISSION_DENIED;
210     }
211     auto pid = IPCSkeleton::GetCallingPid();
212     clients_.Compute(
213         info.tokenId, [&appId, &info, pid, this, obs = std::move(observer)](const auto tokenId, auto &clients) {
214             auto res = clients.try_emplace(pid, appId, *this, std::move(obs));
215             ZLOGI("bundleName:%{public}s, uid:%{public}d, pid:%{public}d, inserted:%{public}s.", appId.appId.c_str(),
216                 info.uid, pid, res.second ? "success" : "failed");
217             return !clients.empty();
218         });
219     return Status::SUCCESS;
220 }
221 
AppExit(pid_t uid,pid_t pid,uint32_t token,const AppId & appId)222 Status KvStoreDataService::AppExit(pid_t uid, pid_t pid, uint32_t token, const AppId &appId)
223 {
224     ZLOGI("AppExit");
225     // memory of parameter appId locates in a member of clientDeathObserverMap_ and will be freed after
226     // clientDeathObserverMap_ erase, so we have to take a copy if we want to use this parameter after erase operation.
227     AppId appIdTmp = appId;
228     KvStoreClientDeathObserverImpl impl(*this);
229     clients_.ComputeIfPresent(token, [&impl, pid](auto &, auto &value) {
230         auto it = value.find(pid);
231         if (it == value.end()) {
232             return !value.empty();
233         }
234         impl = std::move(it->second);
235         value.erase(it);
236         return !value.empty();
237     });
238     return Status::SUCCESS;
239 }
240 
OnDump()241 void KvStoreDataService::OnDump()
242 {
243     ZLOGD("begin.");
244 }
245 
Dump(int fd,const std::vector<std::u16string> & args)246 int KvStoreDataService::Dump(int fd, const std::vector<std::u16string> &args)
247 {
248     int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
249     const int maxUid = 10000;
250     if (uid > maxUid) {
251         return 0;
252     }
253 
254     std::vector<std::string> argsStr;
255     for (auto item : args) {
256         argsStr.emplace_back(Str16ToStr8(item));
257     }
258 
259     if (DumpHelper::GetInstance().Dump(fd, argsStr)) {
260         return 0;
261     }
262 
263     ZLOGE("DumpHelper failed");
264     return ERROR;
265 }
266 
OnStart()267 void KvStoreDataService::OnStart()
268 {
269     ZLOGI("distributeddata service onStart");
270     EventCenter::Defer defer;
271     Reporter::GetInstance()->SetThreadPool(executors_);
272     AccountDelegate::GetInstance()->BindExecutor(executors_);
273     AccountDelegate::GetInstance()->RegisterHashFunc(Crypto::Sha256);
274     DmAdapter::GetInstance().Init(executors_);
275     AutoCache::GetInstance().Bind(executors_);
276     static constexpr int32_t RETRY_TIMES = 50;
277     static constexpr int32_t RETRY_INTERVAL = 500 * 1000; // unit is ms
278     for (BlockInteger retry(RETRY_INTERVAL); retry < RETRY_TIMES; ++retry) {
279         if (!DmAdapter::GetInstance().GetLocalDevice().uuid.empty()) {
280             break;
281         }
282         ZLOGW("GetLocalDeviceId failed, retry count:%{public}d", static_cast<int>(retry));
283     }
284     ZLOGI("Bootstrap configs and plugins.");
285     LoadConfigs();
286     Initialize();
287     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
288     if (samgr != nullptr) {
289         ZLOGI("samgr exist.");
290         auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
291         auto kvDataServiceProxy = iface_cast<IKvStoreDataService>(remote);
292         if (kvDataServiceProxy != nullptr) {
293             ZLOGI("service has been registered.");
294             return;
295         }
296     }
297     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
298     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
299     RegisterStoreInfo();
300     Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1,
301         std::placeholders::_2);
302     DumpManager::GetInstance().AddHandler("STORE_INFO", uintptr_t(this), handlerStoreInfo);
303     RegisterUserInfo();
304     Handler handlerUserInfo = std::bind(&KvStoreDataService::DumpUserInfo, this, std::placeholders::_1,
305         std::placeholders::_2);
306     DumpManager::GetInstance().AddHandler("USER_INFO", uintptr_t(this), handlerUserInfo);
307     RegisterBundleInfo();
308     Handler handlerBundleInfo = std::bind(&KvStoreDataService::DumpBundleInfo, this, std::placeholders::_1,
309         std::placeholders::_2);
310     DumpManager::GetInstance().AddHandler("BUNDLE_INFO", uintptr_t(this), handlerBundleInfo);
311     StartService();
312 }
313 
LoadConfigs()314 void KvStoreDataService::LoadConfigs()
315 {
316     Bootstrap::GetInstance().LoadComponents();
317     Bootstrap::GetInstance().LoadDirectory();
318     Bootstrap::GetInstance().LoadCheckers();
319     Bootstrap::GetInstance().LoadNetworks();
320     Bootstrap::GetInstance().LoadBackup(executors_);
321     Bootstrap::GetInstance().LoadCloud();
322     Bootstrap::GetInstance().LoadAppIdMappings();
323 }
324 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)325 void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
326 {
327     ZLOGI("add system abilityid:%{public}d", systemAbilityId);
328     (void)deviceId;
329     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
330         AccountDelegate::GetInstance()->SubscribeAccountEvent();
331         Installer::GetInstance().Init(this, executors_);
332     } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
333         Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 1,
334                                                                 DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
335     }
336     return;
337 }
338 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)339 void KvStoreDataService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
340 {
341     ZLOGI("remove system abilityid:%{public}d", systemAbilityId);
342     (void)deviceId;
343     if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
344         return;
345     }
346     AccountDelegate::GetInstance()->UnsubscribeAccountEvent();
347     Installer::GetInstance().UnsubscribeEvent();
348 }
349 
StartService()350 void KvStoreDataService::StartService()
351 {
352     // register this to ServiceManager.
353     ZLOGI("begin.");
354     KvStoreMetaManager::GetInstance().InitMetaListener();
355     DeviceMatrix::GetInstance().Initialize(IPCSkeleton::GetCallingTokenID(), Bootstrap::GetInstance().GetMetaDBName());
356     WaterVersionManager::GetInstance().Init();
357     LoadFeatures();
358     bool ret = SystemAbility::Publish(this);
359     if (!ret) {
360         DumpHelper::GetInstance().AddErrorInfo(SERVER_UNAVAILABLE, "StartService: Service publish failed.");
361     }
362     // Initialize meta db delegate manager.
363     KvStoreMetaManager::GetInstance().SubscribeMeta(StoreMetaData::GetKey({}),
364         [this](const std::vector<uint8_t> &key, const std::vector<uint8_t> &value, CHANGE_FLAG flag) {
365             OnStoreMetaChanged(key, value, flag);
366         });
367     UpgradeManager::GetInstance().Init(executors_);
368     UserDelegate::GetInstance().Init(executors_);
369 
370     // subscribe account event listener to EventNotificationMgr
371     auto autoLaunch = [this](const std::string &identifier, DistributedDB::AutoLaunchParam &param) -> bool {
372         features_.ForEachCopies([&identifier, &param](const auto &, sptr<DistributedData::FeatureStubImpl> &value) {
373             value->ResolveAutoLaunch(identifier, param);
374             return false;
375         });
376         return false;
377     };
378     KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunch);
379     ZLOGI("Start distributedata Success, Publish ret: %{public}d", static_cast<int>(ret));
380 }
381 
OnStoreMetaChanged(const std::vector<uint8_t> & key,const std::vector<uint8_t> & value,CHANGE_FLAG flag)382 void KvStoreDataService::OnStoreMetaChanged(
383     const std::vector<uint8_t> &key, const std::vector<uint8_t> &value, CHANGE_FLAG flag)
384 {
385     if (flag != CHANGE_FLAG::UPDATE) {
386         return;
387     }
388     StoreMetaData metaData;
389     metaData.Unmarshall({ value.begin(), value.end() });
390     ZLOGD("meta data info appType:%{public}s, storeId:%{public}s isDirty:%{public}d", metaData.appType.c_str(),
391         Anonymous::Change(metaData.storeId).c_str(), metaData.isDirty);
392     auto deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
393     if (metaData.deviceId != deviceId || metaData.deviceId.empty()) {
394         ZLOGD("ignore other device change or invalid meta device");
395         return;
396     }
397     static constexpr const char *HARMONY_APP = "harmony";
398     if (!metaData.isDirty || metaData.appType != HARMONY_APP) {
399         return;
400     }
401     ZLOGI("dirty kv store. storeId:%{public}s", Anonymous::Change(metaData.storeId).c_str());
402 }
403 
OnStop()404 void KvStoreDataService::OnStop()
405 {
406     ZLOGI("begin.");
407     Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 0, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
408 }
409 
KvStoreClientDeathObserverImpl(const AppId & appId,KvStoreDataService & service,sptr<IRemoteObject> observer)410 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl(
411     const AppId &appId, KvStoreDataService &service, sptr<IRemoteObject> observer)
412     : appId_(appId), dataService_(service), observerProxy_(std::move(observer)),
413       deathRecipient_(new KvStoreDeathRecipient(*this))
414 {
415     ZLOGD("KvStoreClientDeathObserverImpl");
416     uid_ = IPCSkeleton::GetCallingUid();
417     pid_ = IPCSkeleton::GetCallingPid();
418     token_ = IPCSkeleton::GetCallingTokenID();
419     if (observerProxy_ != nullptr) {
420         ZLOGI("add death recipient");
421         observerProxy_->AddDeathRecipient(deathRecipient_);
422     } else {
423         ZLOGW("observerProxy_ is nullptr");
424     }
425 }
KvStoreClientDeathObserverImpl(KvStoreDataService & service)426 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl(KvStoreDataService &service)
427     : dataService_(service)
428 {
429     Reset();
430 }
431 
KvStoreClientDeathObserverImpl(KvStoreDataService::KvStoreClientDeathObserverImpl && impl)432 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl(
433     KvStoreDataService::KvStoreClientDeathObserverImpl &&impl)
434     : uid_(impl.uid_), pid_(impl.pid_), token_(impl.token_), dataService_(impl.dataService_)
435 {
436     appId_.appId = std::move(impl.appId_.appId);
437     impl.Reset();
438 }
439 
operator =(KvStoreDataService::KvStoreClientDeathObserverImpl && impl)440 KvStoreDataService::KvStoreClientDeathObserverImpl &KvStoreDataService::KvStoreClientDeathObserverImpl::operator=(
441     KvStoreDataService::KvStoreClientDeathObserverImpl &&impl)
442 {
443     uid_ = impl.uid_;
444     pid_ = impl.pid_;
445     token_ = impl.token_;
446     appId_.appId = std::move(impl.appId_.appId);
447     impl.Reset();
448     return *this;
449 }
450 
~KvStoreClientDeathObserverImpl()451 KvStoreDataService::KvStoreClientDeathObserverImpl::~KvStoreClientDeathObserverImpl()
452 {
453     ZLOGI("~KvStoreClientDeathObserverImpl");
454     if (deathRecipient_ != nullptr && observerProxy_ != nullptr) {
455         ZLOGI("remove death recipient");
456         observerProxy_->RemoveDeathRecipient(deathRecipient_);
457     }
458     if (uid_ == INVALID_UID || pid_ == INVALID_PID || token_ == INVALID_TOKEN || !appId_.IsValid()) {
459         return;
460     }
461     dataService_.features_.ForEachCopies([this](const auto &, sptr<DistributedData::FeatureStubImpl> &value) {
462         value->OnAppExit(uid_, pid_, token_, appId_);
463         return false;
464     });
465 }
466 
NotifyClientDie()467 void KvStoreDataService::KvStoreClientDeathObserverImpl::NotifyClientDie()
468 {
469     ZLOGI("appId: %{public}s uid:%{public}d tokenId:%{public}u", appId_.appId.c_str(), uid_, token_);
470     dataService_.AppExit(uid_, pid_, token_, appId_);
471 }
472 
GetPid() const473 pid_t KvStoreDataService::KvStoreClientDeathObserverImpl::GetPid() const
474 {
475     return pid_;
476 }
477 
Reset()478 void KvStoreDataService::KvStoreClientDeathObserverImpl::Reset()
479 {
480     uid_ = INVALID_UID;
481     pid_ = INVALID_PID;
482     token_ = INVALID_TOKEN;
483     appId_.appId = "";
484 }
485 
KvStoreDeathRecipient(KvStoreClientDeathObserverImpl & kvStoreClientDeathObserverImpl)486 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::KvStoreDeathRecipient(
487     KvStoreClientDeathObserverImpl &kvStoreClientDeathObserverImpl)
488     : kvStoreClientDeathObserverImpl_(kvStoreClientDeathObserverImpl)
489 {
490     ZLOGI("KvStore Client Death Observer");
491 }
492 
~KvStoreDeathRecipient()493 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::~KvStoreDeathRecipient()
494 {
495     ZLOGD("~KvStore Client Death Observer");
496 }
497 
OnRemoteDied(const wptr<IRemoteObject> & remote)498 void KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::OnRemoteDied(
499     const wptr<IRemoteObject> &remote)
500 {
501     (void) remote;
502     ZLOGI("begin");
503     kvStoreClientDeathObserverImpl_.NotifyClientDie();
504 }
505 
AccountEventChanged(const AccountEventInfo & eventInfo)506 void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo)
507 {
508     ZLOGI("account event %{public}d changed process, begin.", eventInfo.status);
509     NotifyAccountEvent(eventInfo);
510     switch (eventInfo.status) {
511         case AccountStatus::DEVICE_ACCOUNT_DELETE: {
512             g_kvStoreAccountEventStatus = 1;
513             // delete all kvstore meta belong to this user
514             std::vector<StoreMetaData> metaData;
515             MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({""}), metaData, true);
516             for (const auto &meta : metaData) {
517                 if (meta.user != eventInfo.userId) {
518                     continue;
519                 }
520                 ZLOGI("bundleName:%{public}s, user:%{public}s", meta.bundleName.c_str(), meta.user.c_str());
521                 MetaDataManager::GetInstance().DelMeta(meta.GetKey());
522                 MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true);
523                 MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true);
524                 MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true);
525                 MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey());
526                 MetaDataManager::GetInstance().DelMeta(meta.GetBackupSecretKey(), true);
527                 MetaDataManager::GetInstance().DelMeta(meta.GetAutoLaunchKey(), true);
528                 MetaDataManager::GetInstance().DelMeta(meta.appId, true);
529                 MetaDataManager::GetInstance().DelMeta(meta.GetDebugInfoKey(), true);
530                 PermitDelegate::GetInstance().DelCache(meta.GetKey());
531             }
532             g_kvStoreAccountEventStatus = 0;
533             break;
534         }
535         case AccountStatus::DEVICE_ACCOUNT_SWITCHED: {
536             auto ret = DistributedDB::KvStoreDelegateManager::NotifyUserChanged();
537             ZLOGI("notify delegate manager result:%{public}d", ret);
538             break;
539         }
540         default: {
541             break;
542         }
543     }
544     ZLOGI("account event %{public}d changed process, end.", eventInfo.status);
545 }
546 
NotifyAccountEvent(const AccountEventInfo & eventInfo)547 void KvStoreDataService::NotifyAccountEvent(const AccountEventInfo &eventInfo)
548 {
549     features_.ForEachCopies([&eventInfo](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
550         value->OnUserChange(uint32_t(eventInfo.status), eventInfo.userId, eventInfo.harmonyAccountId);
551         return false;
552     });
553 }
554 
InitSecurityAdapter(std::shared_ptr<ExecutorPool> executors)555 void KvStoreDataService::InitSecurityAdapter(std::shared_ptr<ExecutorPool> executors)
556 {
557     auto ret = DATASL_OnStart();
558     ZLOGI("datasl on start ret:%d", ret);
559     security_ = std::make_shared<Security>(executors);
560     if (security_ == nullptr) {
561         ZLOGE("security is nullptr.");
562         return;
563     }
564 
565     security_->InitLocalSecurity();
566     auto dbStatus = DistributedDB::RuntimeConfig::SetProcessSystemAPIAdapter(security_);
567     ZLOGD("set distributed db system api adapter: %d.", static_cast<int>(dbStatus));
568 
569     auto status = DmAdapter::GetInstance().StartWatchDeviceChange(security_.get(), {"security"});
570     if (status != Status::SUCCESS) {
571         ZLOGD("security register device change failed, status:%d", static_cast<int>(status));
572     }
573 }
574 
SetCompatibleIdentify(const AppDistributedKv::DeviceInfo & info) const575 void KvStoreDataService::SetCompatibleIdentify(const AppDistributedKv::DeviceInfo &info) const
576 {
577 }
578 
OnDeviceOnline(const AppDistributedKv::DeviceInfo & info)579 void KvStoreDataService::OnDeviceOnline(const AppDistributedKv::DeviceInfo &info)
580 {
581     if (info.uuid.empty()) {
582         return;
583     }
584     features_.ForEachCopies([&info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
585         value->Online(info.uuid);
586         return false;
587     });
588 }
589 
OnDeviceOffline(const AppDistributedKv::DeviceInfo & info)590 void KvStoreDataService::OnDeviceOffline(const AppDistributedKv::DeviceInfo &info)
591 {
592     if (info.uuid.empty()) {
593         return;
594     }
595     features_.ForEachCopies([&info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
596         value->Offline(info.uuid);
597         return false;
598     });
599 }
600 
OnDeviceOnReady(const AppDistributedKv::DeviceInfo & info)601 void KvStoreDataService::OnDeviceOnReady(const AppDistributedKv::DeviceInfo &info)
602 {
603     if (info.uuid.empty()) {
604         return;
605     }
606     features_.ForEachCopies([&info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
607         value->OnReady(info.uuid);
608         return false;
609     });
610 }
611 
OnSessionReady(const AppDistributedKv::DeviceInfo & info)612 void KvStoreDataService::OnSessionReady(const AppDistributedKv::DeviceInfo &info)
613 {
614     if (info.uuid.empty()) {
615         return;
616     }
617     features_.ForEachCopies([info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
618         value->OnSessionReady(info.uuid);
619         return false;
620     });
621 }
622 
OnUninstall(const std::string & bundleName,int32_t user,int32_t index)623 int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t user, int32_t index)
624 {
625     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
626     staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr<StaticActs>& acts) {
627         acts->OnAppUninstall(bundleName, user, index);
628         return false;
629     });
630     return SUCCESS;
631 }
632 
OnUpdate(const std::string & bundleName,int32_t user,int32_t index)633 int32_t KvStoreDataService::OnUpdate(const std::string &bundleName, int32_t user, int32_t index)
634 {
635     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
636     staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr<StaticActs>& acts) {
637         acts->OnAppUpdate(bundleName, user, index);
638         return false;
639     });
640     return SUCCESS;
641 }
642 
OnInstall(const std::string & bundleName,int32_t user,int32_t index)643 int32_t KvStoreDataService::OnInstall(const std::string &bundleName, int32_t user, int32_t index)
644 {
645     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
646     staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr<StaticActs>& acts) {
647         acts->OnAppInstall(bundleName, user, index);
648         return false;
649     });
650     return SUCCESS;
651 }
652 
OnScreenUnlocked(int32_t user)653 int32_t KvStoreDataService::OnScreenUnlocked(int32_t user)
654 {
655     features_.ForEachCopies([user](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
656         value->OnScreenUnlocked(user);
657         return false;
658     });
659     return SUCCESS;
660 }
661 
ClearAppStorage(const std::string & bundleName,int32_t userId,int32_t appIndex,int32_t tokenId)662 int32_t KvStoreDataService::ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex,
663     int32_t tokenId)
664 {
665     auto callerToken = IPCSkeleton::GetCallingTokenID();
666     NativeTokenInfo nativeTokenInfo;
667     if (AccessTokenKit::GetNativeTokenInfo(callerToken, nativeTokenInfo) != RET_SUCCESS ||
668         nativeTokenInfo.processName != FOUNDATION_PROCESS_NAME) {
669         ZLOGE("passed wrong, tokenId: %{public}u, bundleName:%{public}s, user:%{public}d, appIndex:%{public}d",
670             tokenId, bundleName.c_str(), userId, appIndex);
671         return ERROR;
672     }
673 
674     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
675     staticActs.ForEachCopies(
676         [bundleName, userId, appIndex, tokenId](const auto &, const std::shared_ptr<StaticActs> &acts) {
677             acts->OnClearAppStorage(bundleName, userId, appIndex, tokenId);
678             return false;
679         });
680 
681     std::vector<StoreMetaData> metaData;
682     std::string prefix = StoreMetaData::GetPrefix(
683         { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName });
684     if (!MetaDataManager::GetInstance().LoadMeta(prefix, metaData, true)) {
685         ZLOGE("Clear data load meta failed, bundleName:%{public}s, user:%{public}d, appIndex:%{public}d",
686             bundleName.c_str(), userId, appIndex);
687         return ERROR;
688     }
689 
690     for (auto &meta : metaData) {
691         if (meta.instanceId == appIndex && !meta.appId.empty() && !meta.storeId.empty()) {
692             ZLOGI("data cleared bundleName:%{public}s, stordId:%{public}s, appIndex:%{public}d", bundleName.c_str(),
693                 Anonymous::Change(meta.storeId).c_str(), appIndex);
694             MetaDataManager::GetInstance().DelMeta(meta.GetKey());
695             MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true);
696             MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true);
697             MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true);
698             MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey());
699             MetaDataManager::GetInstance().DelMeta(meta.GetBackupSecretKey(), true);
700             MetaDataManager::GetInstance().DelMeta(meta.appId, true);
701             MetaDataManager::GetInstance().DelMeta(meta.GetDebugInfoKey(), true);
702             MetaDataManager::GetInstance().DelMeta(meta.GetAutoLaunchKey(), true);
703             PermitDelegate::GetInstance().DelCache(meta.GetKey());
704         }
705     }
706     return SUCCESS;
707 }
708 
RegisterStoreInfo()709 void KvStoreDataService::RegisterStoreInfo()
710 {
711     OHOS::DistributedData::DumpManager::Config storeInfoConfig;
712     storeInfoConfig.fullCmd = "--store-info";
713     storeInfoConfig.abbrCmd = "-s";
714     storeInfoConfig.dumpName = "STORE_INFO";
715     storeInfoConfig.countPrintf = PRINTF_COUNT_2;
716     storeInfoConfig.infoName = " <StoreId>";
717     storeInfoConfig.minParamsNum = 0;
718     storeInfoConfig.maxParamsNum = MAXIMUM_PARAMETER_LIMIT; // Store contains no more than three parameters
719     storeInfoConfig.parentNode = "BUNDLE_INFO";
720     storeInfoConfig.dumpCaption = { "| Display all the store statistics", "| Display the store statistics  by "
721                                                                           "StoreID" };
722     DumpManager::GetInstance().AddConfig(storeInfoConfig.dumpName, storeInfoConfig);
723 }
724 
DumpStoreInfo(int fd,std::map<std::string,std::vector<std::string>> & params)725 void KvStoreDataService::DumpStoreInfo(int fd, std::map<std::string, std::vector<std::string>> &params)
726 {
727     std::vector<StoreMetaData> metas;
728     std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
729     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) {
730         ZLOGE("get full meta failed");
731         return;
732     }
733     FilterData(metas, params);
734     PrintfInfo(fd, metas);
735 }
736 
FilterData(std::vector<StoreMetaData> & metas,std::map<std::string,std::vector<std::string>> & filterInfo)737 void KvStoreDataService::FilterData(std::vector<StoreMetaData> &metas,
738     std::map<std::string, std::vector<std::string>> &filterInfo)
739 {
740     for (auto iter = metas.begin(); iter != metas.end();) {
741         if ((IsExist("USER_INFO", filterInfo, iter->user)) || (IsExist("BUNDLE_INFO", filterInfo, iter->bundleName)) ||
742             (IsExist("STORE_INFO", filterInfo, iter->storeId))) {
743             iter = metas.erase(iter);
744         } else {
745             iter++;
746         }
747     }
748 }
749 
IsExist(const std::string & infoName,std::map<std::string,std::vector<std::string>> & filterInfo,std::string & metaParam)750 bool KvStoreDataService::IsExist(const std::string &infoName,
751     std::map<std::string, std::vector<std::string>> &filterInfo, std::string &metaParam)
752 {
753     auto info = filterInfo.find(infoName);
754     if (info != filterInfo.end()) {
755         if (!info->second.empty()) {
756             auto it = find(info->second.begin(), info->second.end(), metaParam);
757             if (it == info->second.end()) {
758                 return true;
759             }
760         }
761     }
762     return false;
763 }
764 
PrintfInfo(int fd,const std::vector<StoreMetaData> & metas)765 void KvStoreDataService::PrintfInfo(int fd, const std::vector<StoreMetaData> &metas)
766 {
767     std::string info;
768     int indentation = 0;
769     if (metas.size() > 1) {
770         info.append("Stores: ").append(std::to_string(metas.size())).append("\n");
771         indentation++;
772     }
773     for (auto &data : metas) {
774         char version[VERSION_WIDTH];
775         auto flag = sprintf_s(version, sizeof(version), "0x%08X", data.version);
776         if (flag < 0) {
777             ZLOGE("get version failed");
778             return;
779         }
780         info.append(GetIndentation(indentation))
781             .append("--------------------------------------------------------------------------\n")
782             .append(GetIndentation(indentation)).append("StoreID           : ").append(data.storeId).append("\n")
783             .append(GetIndentation(indentation)).append("UId               : ").append(data.user).append("\n")
784             .append(GetIndentation(indentation)).append("BundleName        : ").append(data.bundleName).append("\n")
785             .append(GetIndentation(indentation)).append("AppID             : ").append(data.appId).append("\n")
786             .append(GetIndentation(indentation)).append("StorePath         : ").append(data.dataDir).append("\n")
787             .append(GetIndentation(indentation)).append("StoreType         : ")
788             .append(std::to_string(data.storeType)).append("\n")
789             .append(GetIndentation(indentation)).append("encrypt           : ")
790             .append(std::to_string(data.isEncrypt)).append("\n")
791             .append(GetIndentation(indentation)).append("autoSync          : ")
792             .append(std::to_string(data.isAutoSync)).append("\n")
793             .append(GetIndentation(indentation)).append("schema            : ").append(data.schema).append("\n")
794             .append(GetIndentation(indentation)).append("securityLevel     : ")
795             .append(std::to_string(data.securityLevel)).append("\n")
796             .append(GetIndentation(indentation)).append("area              : ")
797             .append(std::to_string(data.area)).append("\n")
798             .append(GetIndentation(indentation)).append("instanceID        : ")
799             .append(std::to_string(data.instanceId)).append("\n")
800             .append(GetIndentation(indentation)).append("version           : ").append(version).append("\n");
801     }
802     dprintf(fd, "--------------------------------------StoreInfo-------------------------------------\n%s\n",
803         info.c_str());
804 }
805 
GetIndentation(int size)806 std::string KvStoreDataService::GetIndentation(int size)
807 {
808     std::string indentation;
809     for (int i = 0; i < size; i++) {
810         indentation.append(INDENTATION);
811     }
812     return indentation;
813 }
814 
RegisterUserInfo()815 void KvStoreDataService::RegisterUserInfo()
816 {
817     DumpManager::Config userInfoConfig;
818     userInfoConfig.fullCmd = "--user-info";
819     userInfoConfig.abbrCmd = "-u";
820     userInfoConfig.dumpName = "USER_INFO";
821     userInfoConfig.countPrintf = PRINTF_COUNT_2;
822     userInfoConfig.infoName = " <UId>";
823     userInfoConfig.minParamsNum = 0;
824     userInfoConfig.maxParamsNum = MAXIMUM_PARAMETER_LIMIT; // User contains no more than three parameters
825     userInfoConfig.childNode = "BUNDLE_INFO";
826     userInfoConfig.dumpCaption = { "| Display all the user statistics", "| Display the user statistics by UserId" };
827     DumpManager::GetInstance().AddConfig(userInfoConfig.dumpName, userInfoConfig);
828 }
829 
BuildData(std::map<std::string,UserInfo> & datas,const std::vector<StoreMetaData> & metas)830 void KvStoreDataService::BuildData(std::map<std::string, UserInfo> &datas, const std::vector<StoreMetaData> &metas)
831 {
832     for (auto &meta : metas) {
833         auto it = datas.find(meta.user);
834         if (it == datas.end()) {
835             UserInfo userInfo;
836             userInfo.userId = meta.user;
837             userInfo.bundles.insert(meta.bundleName);
838             datas[meta.user] = userInfo;
839         } else {
840             std::set<std::string> bundles_ = datas[meta.user].bundles;
841             auto iter = std::find(bundles_.begin(), bundles_.end(), meta.bundleName);
842             if (iter == bundles_.end()) {
843                 datas[meta.user].bundles.insert(meta.bundleName);
844             }
845         }
846     }
847 }
848 
PrintfInfo(int fd,const std::map<std::string,UserInfo> & datas)849 void KvStoreDataService::PrintfInfo(int fd, const std::map<std::string, UserInfo> &datas)
850 {
851     std::string info;
852     int indentation = 0;
853     if (datas.size() > 1) {
854         info.append("Users : ").append(std::to_string(datas.size())).append("\n");
855         indentation++;
856     }
857 
858     for (auto &data : datas) {
859         info.append(GetIndentation(indentation))
860             .append("------------------------------------------------------------------------------\n")
861             .append("UID        : ")
862             .append(data.second.userId)
863             .append("\n");
864         info.append(GetIndentation(indentation))
865             .append("Bundles       : ")
866             .append(std::to_string(data.second.bundles.size()))
867             .append("\n");
868         indentation++;
869         info.append("------------------------------------------------------------------------------\n");
870         for (auto &bundle : data.second.bundles) {
871             info.append(GetIndentation(indentation)).append("BundleName    : ").append(bundle).append("\n");
872         }
873         indentation--;
874     }
875     dprintf(fd, "--------------------------------------UserInfo--------------------------------------\n%s\n",
876         info.c_str());
877 }
878 
DumpUserInfo(int fd,std::map<std::string,std::vector<std::string>> & params)879 void KvStoreDataService::DumpUserInfo(int fd, std::map<std::string, std::vector<std::string>> &params)
880 {
881     std::vector<StoreMetaData> metas;
882     std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
883     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) {
884         ZLOGE("get full meta failed");
885         return;
886     }
887     FilterData(metas, params);
888     std::map<std::string, UserInfo> datas;
889     BuildData(datas, metas);
890     PrintfInfo(fd, datas);
891 }
892 
RegisterBundleInfo()893 void KvStoreDataService::RegisterBundleInfo()
894 {
895     DumpManager::Config bundleInfoConfig;
896     bundleInfoConfig.fullCmd = "--bundle-info";
897     bundleInfoConfig.abbrCmd = "-b";
898     bundleInfoConfig.dumpName = "BUNDLE_INFO";
899     bundleInfoConfig.countPrintf = PRINTF_COUNT_2;
900     bundleInfoConfig.infoName = " <BundleName>";
901     bundleInfoConfig.minParamsNum = 0;
902     bundleInfoConfig.maxParamsNum = MAXIMUM_PARAMETER_LIMIT; // Bundle contains no more than three parameters
903     bundleInfoConfig.parentNode = "USER_INFO";
904     bundleInfoConfig.childNode = "STORE_INFO";
905     bundleInfoConfig.dumpCaption = { "| Display all the bundle statistics", "| Display the bundle statistics by "
906                                                                             "BundleName" };
907     DumpManager::GetInstance().AddConfig(bundleInfoConfig.dumpName, bundleInfoConfig);
908 }
909 
BuildData(std::map<std::string,BundleInfo> & datas,const std::vector<StoreMetaData> & metas)910 void KvStoreDataService::BuildData(std::map<std::string, BundleInfo> &datas, const std::vector<StoreMetaData> &metas)
911 {
912     for (auto &meta : metas) {
913         auto it = datas.find(meta.bundleName);
914         if (it == datas.end()) {
915             BundleInfo bundleInfo;
916             bundleInfo.bundleName = meta.bundleName;
917             bundleInfo.appId = meta.appId;
918             bundleInfo.type = meta.appType;
919             bundleInfo.uid = meta.uid;
920             bundleInfo.tokenId = meta.tokenId;
921             bundleInfo.userId = meta.user;
922             std::string storeId = meta.storeId;
923             storeId.resize(FORMAT_BLANK_SIZE, FORMAT_BLANK_SPACE);
924             bundleInfo.storeIDs.insert(storeId);
925             datas[meta.bundleName] = bundleInfo;
926         } else {
927             std::set<std::string> storeIDs_ = datas[meta.bundleName].storeIDs;
928             std::string storeId = meta.storeId;
929             storeId.resize(FORMAT_BLANK_SIZE, FORMAT_BLANK_SPACE);
930             auto iter = std::find(storeIDs_.begin(), storeIDs_.end(), storeId);
931             if (iter == storeIDs_.end()) {
932                 datas[meta.bundleName].storeIDs.insert(storeId);
933             }
934         }
935     }
936 }
937 
PrintfInfo(int fd,const std::map<std::string,BundleInfo> & datas)938 void KvStoreDataService::PrintfInfo(int fd, const std::map<std::string, BundleInfo> &datas)
939 {
940     std::string info;
941     int indentation = 0;
942     if (datas.size() > 1) {
943         info.append("Bundles: ").append(std::to_string(datas.size())).append("\n");
944         indentation++;
945     }
946     for (auto &data : datas) {
947         info.append(GetIndentation(indentation))
948             .append("--------------------------------------------------------------------------\n");
949         info.append(GetIndentation(indentation)).append("BundleName     : ")
950             .append(data.second.bundleName).append("\n");
951         info.append(GetIndentation(indentation)).append("AppID          : ")
952             .append(data.second.appId).append("\n");
953         info.append(GetIndentation(indentation)).append("Type           : ")
954             .append(data.second.type).append("\n");
955         info.append(GetIndentation(indentation))
956             .append("UId            : ")
957             .append(std::to_string(data.second.uid))
958             .append("\n");
959         info.append(GetIndentation(indentation))
960             .append("TokenID        : ")
961             .append(std::to_string(data.second.tokenId))
962             .append("\n");
963         info.append(GetIndentation(indentation)).append("UserID         : ").append(data.second.userId).append("\n");
964         info.append(GetIndentation(indentation))
965             .append("Stores         : ")
966             .append(std::to_string(data.second.storeIDs.size()))
967             .append("\n");
968         indentation++;
969         info.append("----------------------------------------------------------------------\n");
970         for (auto &store : data.second.storeIDs) {
971             info.append(GetIndentation(indentation)).append("StoreID    : ").append(store).append("\n");
972         }
973         indentation--;
974     }
975     dprintf(fd, "-------------------------------------BundleInfo-------------------------------------\n%s\n",
976         info.c_str());
977 }
978 
DumpBundleInfo(int fd,std::map<std::string,std::vector<std::string>> & params)979 void KvStoreDataService::DumpBundleInfo(int fd, std::map<std::string, std::vector<std::string>> &params)
980 {
981     std::vector<StoreMetaData> metas;
982     std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
983     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) {
984         ZLOGE("get full meta failed");
985         return;
986     }
987     FilterData(metas, params);
988     std::map<std::string, BundleInfo> datas;
989     BuildData(datas, metas);
990     PrintfInfo(fd, datas);
991 }
992 } // namespace OHOS::DistributedKv
993