• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <fcntl.h>
20 #include <fstream>
21 #include <ipc_skeleton.h>
22 #include <sys/sendfile.h>
23 #include <sys/stat.h>
24 #include <thread>
25 #include <unistd.h>
26 
27 #include "accesstoken_kit.h"
28 #include "app_id_mapping/app_id_mapping_config_manager.h"
29 #include "auth_delegate.h"
30 #include "auto_launch_export.h"
31 #include "bootstrap.h"
32 #include "checker/checker_manager.h"
33 #include "communication_provider.h"
34 #include "communicator_context.h"
35 #include "config_factory.h"
36 #include "crypto_manager.h"
37 #include "db_info_handle_impl.h"
38 #include "device_manager_adapter.h"
39 #include "device_matrix.h"
40 #include "dump/dump_manager.h"
41 #include "dump_helper.h"
42 #include "eventcenter/event_center.h"
43 #include "if_system_ability_manager.h"
44 #include "installer/installer.h"
45 #include "iservice_registry.h"
46 #include "kvstore_account_observer.h"
47 #include "kvstore_screen_observer.h"
48 #include "log_print.h"
49 #include "mem_mgr_client.h"
50 #include "mem_mgr_proxy.h"
51 #include "metadata/appid_meta_data.h"
52 #include "metadata/meta_data_manager.h"
53 #include "network/network_delegate.h"
54 #include "permission_validator.h"
55 #include "permit_delegate.h"
56 #include "process_communicator_impl.h"
57 #include "reporter.h"
58 #include "route_head_handler_impl.h"
59 #include "runtime_config.h"
60 #include "store/auto_cache.h"
61 #include "string_ex.h"
62 #include "system_ability_definition.h"
63 #include "task_manager.h"
64 #include "thread/thread_manager.h"
65 #include "upgrade.h"
66 #include "upgrade_manager.h"
67 #include "user_delegate.h"
68 #include "utils/anonymous.h"
69 #include "utils/base64_utils.h"
70 #include "utils/block_integer.h"
71 #include "utils/constant.h"
72 #include "utils/crypto.h"
73 
74 namespace OHOS::DistributedKv {
75 using namespace std::chrono;
76 using namespace OHOS::DistributedData;
77 using namespace OHOS::DistributedDataDfx;
78 using namespace OHOS::Security::AccessToken;
79 using KvStoreDelegateManager = DistributedDB::KvStoreDelegateManager;
80 using SecretKeyMeta = DistributedData::SecretKeyMetaData;
81 using DmAdapter = DistributedData::DeviceManagerAdapter;
82 constexpr const char* EXTENSION_BACKUP = "backup";
83 constexpr const char* EXTENSION_RESTORE = "restore";
84 constexpr const char* CLONE_KEY_ALIAS = "distributed_db_backup_key";
85 
86 REGISTER_SYSTEM_ABILITY_BY_ID(KvStoreDataService, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, true);
87 
88 constexpr char FOUNDATION_PROCESS_NAME[] = "foundation";
89 constexpr int MAX_DOWNLOAD_ASSETS_COUNT = 50;
90 constexpr int MAX_DOWNLOAD_TASK = 5;
91 constexpr int KEY_SIZE = 32;
92 constexpr int AES_256_NONCE_SIZE = 32;
93 
KvStoreDataService(bool runOnCreate)94 KvStoreDataService::KvStoreDataService(bool runOnCreate)
95     : SystemAbility(runOnCreate), clients_()
96 {
97     ZLOGI("begin.");
98 }
99 
KvStoreDataService(int32_t systemAbilityId,bool runOnCreate)100 KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate)
101     : SystemAbility(systemAbilityId, runOnCreate), clients_()
102 {
103     ZLOGI("begin");
104 }
105 
~KvStoreDataService()106 KvStoreDataService::~KvStoreDataService()
107 {
108     ZLOGI("begin.");
109     clients_.Clear();
110     features_.Clear();
111 }
112 
Initialize()113 void KvStoreDataService::Initialize()
114 {
115     ZLOGI("begin.");
116 #ifndef UT_TEST
117     KvStoreDelegateManager::SetProcessLabel(Bootstrap::GetInstance().GetProcessLabel(), "default");
118 #endif
119     CommunicatorContext::GetInstance().SetThreadPool(executors_);
120     auto communicator = std::shared_ptr<AppDistributedKv::ProcessCommunicatorImpl>(
121         AppDistributedKv::ProcessCommunicatorImpl::GetInstance());
122     communicator->SetRouteHeadHandlerCreator(RouteHeadHandlerImpl::Create);
123     DistributedDB::RuntimeConfig::SetDBInfoHandle(std::make_shared<DBInfoHandleImpl>());
124     DistributedDB::RuntimeConfig::SetAsyncDownloadAssetsConfig({ MAX_DOWNLOAD_TASK, MAX_DOWNLOAD_ASSETS_COUNT });
125     auto ret = KvStoreDelegateManager::SetProcessCommunicator(communicator);
126     ZLOGI("set communicator ret:%{public}d.", static_cast<int>(ret));
127 
128     AppDistributedKv::CommunicationProvider::GetInstance();
129     PermitDelegate::GetInstance().Init();
130     InitSecurityAdapter(executors_);
131     KvStoreMetaManager::GetInstance().BindExecutor(executors_);
132     KvStoreMetaManager::GetInstance().InitMetaParameter();
133     accountEventObserver_ = std::make_shared<KvStoreAccountObserver>(*this, executors_);
134     AccountDelegate::GetInstance()->Subscribe(accountEventObserver_);
135     screenEventObserver_ = std::make_shared<KvStoreScreenObserver>(*this, executors_);
136     ScreenManager::GetInstance()->Subscribe(screenEventObserver_);
137     deviceInnerListener_ = std::make_unique<KvStoreDeviceListener>(*this);
138     DmAdapter::GetInstance().StartWatchDeviceChange(deviceInnerListener_.get(), { "innerListener" });
139     CommunicatorContext::GetInstance().RegSessionListener(deviceInnerListener_.get());
140     auto translateCall = [](const std::string &oriDevId, const DistributedDB::StoreInfo &info) {
141         StoreMetaData meta;
142         AppIDMetaData appIdMeta;
143         MetaDataManager::GetInstance().LoadMeta(info.appId, appIdMeta, true);
144         meta.bundleName = appIdMeta.bundleName;
145         meta.storeId = info.storeId;
146         meta.user = info.userId;
147         meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
148         MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta, true);
149         std::string uuid;
150         if (OHOS::Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(meta.tokenId) ==
151             OHOS::Security::AccessToken::TOKEN_HAP) {
152             uuid = DmAdapter::GetInstance().CalcClientUuid(meta.appId, oriDevId);
153         } else {
154             uuid = DmAdapter::GetInstance().CalcClientUuid(" ", oriDevId);
155         }
156         return uuid;
157     };
158     DistributedDB::RuntimeConfig::SetTranslateToDeviceIdCallback(translateCall);
159 }
160 
GetFeatureInterface(const std::string & name)161 sptr<IRemoteObject> KvStoreDataService::GetFeatureInterface(const std::string &name)
162 {
163     sptr<FeatureStubImpl> feature;
164     bool isFirstCreate = false;
165     features_.Compute(name, [&feature, &isFirstCreate](const auto &key, auto &value) ->bool {
166         if (value != nullptr) {
167             feature = value;
168             return true;
169         }
170         auto creator = FeatureSystem::GetInstance().GetCreator(key);
171         if (!creator) {
172             return false;
173         }
174         auto impl = creator();
175         if (impl == nullptr) {
176             return false;
177         }
178 
179         value = new FeatureStubImpl(impl);
180         feature = value;
181         isFirstCreate = true;
182         return true;
183     });
184     if (isFirstCreate) {
185         feature->OnInitialize(executors_);
186     }
187     return feature != nullptr ? feature->AsObject() : nullptr;
188 }
189 
LoadFeatures()190 void KvStoreDataService::LoadFeatures()
191 {
192     ZLOGI("begin.");
193     auto features = FeatureSystem::GetInstance().GetFeatureName(FeatureSystem::BIND_NOW);
194     for (auto const &feature : features) {
195         GetFeatureInterface(feature);
196     }
197 }
198 
199 /* RegisterClientDeathObserver */
RegisterClientDeathObserver(const AppId & appId,sptr<IRemoteObject> observer)200 Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr<IRemoteObject> observer)
201 {
202     ZLOGD("begin.");
203     KVSTORE_ACCOUNT_EVENT_PROCESSING_CHECKER(Status::SYSTEM_ACCOUNT_EVENT_PROCESSING);
204     if (!appId.IsValid()) {
205         ZLOGE("invalid bundleName, name:%{public}s", appId.appId.c_str());
206         return Status::INVALID_ARGUMENT;
207     }
208 
209     CheckerManager::StoreInfo info;
210     info.uid = IPCSkeleton::GetCallingUid();
211     info.tokenId = IPCSkeleton::GetCallingTokenID();
212     info.bundleName = appId.appId;
213     info.storeId = "";
214     if (!CheckerManager::GetInstance().IsValid(info)) {
215         ZLOGW("check bundleName:%{public}s uid:%{public}d failed.", appId.appId.c_str(), info.uid);
216         return Status::PERMISSION_DENIED;
217     }
218     auto pid = IPCSkeleton::GetCallingPid();
219     clients_.Compute(
220         info.tokenId, [&appId, &info, pid, this, obs = std::move(observer)](const auto tokenId, auto &clients) {
221             auto res = clients.try_emplace(pid, appId, *this, std::move(obs));
222             ZLOGI("bundleName:%{public}s, uid:%{public}d, pid:%{public}d, inserted:%{public}s.", appId.appId.c_str(),
223                 info.uid, pid, res.second ? "success" : "failed");
224             return !clients.empty();
225         });
226     return Status::SUCCESS;
227 }
228 
AppExit(pid_t uid,pid_t pid,uint32_t token,const AppId & appId)229 Status KvStoreDataService::AppExit(pid_t uid, pid_t pid, uint32_t token, const AppId &appId)
230 {
231     ZLOGI("AppExit");
232     // memory of parameter appId locates in a member of clientDeathObserverMap_ and will be freed after
233     // clientDeathObserverMap_ erase, so we have to take a copy if we want to use this parameter after erase operation.
234     AppId appIdTmp = appId;
235     KvStoreClientDeathObserverImpl impl(*this);
236     clients_.ComputeIfPresent(token, [&impl, pid](auto &, auto &value) {
237         auto it = value.find(pid);
238         if (it == value.end()) {
239             return !value.empty();
240         }
241         impl = std::move(it->second);
242         value.erase(it);
243         return !value.empty();
244     });
245     return Status::SUCCESS;
246 }
247 
OnDump()248 void KvStoreDataService::OnDump()
249 {
250     ZLOGD("begin.");
251 }
252 
Dump(int fd,const std::vector<std::u16string> & args)253 int KvStoreDataService::Dump(int fd, const std::vector<std::u16string> &args)
254 {
255     int uid = static_cast<int>(IPCSkeleton::GetCallingUid());
256     const int maxUid = 10000;
257     if (uid > maxUid) {
258         return 0;
259     }
260 
261     std::vector<std::string> argsStr;
262     for (auto item : args) {
263         argsStr.emplace_back(Str16ToStr8(item));
264     }
265 
266     if (DumpHelper::GetInstance().Dump(fd, argsStr)) {
267         return 0;
268     }
269 
270     ZLOGE("DumpHelper failed");
271     return ERROR;
272 }
273 
InitExecutor()274 void KvStoreDataService::InitExecutor()
275 {
276     if (executors_ == nullptr) {
277         executors_ = std::make_shared<ExecutorPool>(ThreadManager::GetInstance().GetMaxThreadNum(),
278             ThreadManager::GetInstance().GetMinThreadNum());
279         DistributedDB::RuntimeConfig::SetThreadPool(std::make_shared<TaskManager>(executors_));
280     }
281     IPCSkeleton::SetMaxWorkThreadNum(ThreadManager::GetInstance().GetIpcThreadNum());
282 }
283 
OnStart()284 void KvStoreDataService::OnStart()
285 {
286     ZLOGI("distributeddata service onStart");
287     LoadConfigs();
288     EventCenter::Defer defer;
289     Reporter::GetInstance()->SetThreadPool(executors_);
290     AccountDelegate::GetInstance()->BindExecutor(executors_);
291     ScreenManager::GetInstance()->BindExecutor(executors_);
292     AccountDelegate::GetInstance()->RegisterHashFunc(Crypto::Sha256);
293     DmAdapter::GetInstance().Init(executors_);
294     AutoCache::GetInstance().Bind(executors_);
295     NetworkDelegate::GetInstance()->BindExecutor(executors_);
296     static constexpr int32_t RETRY_TIMES = 50;
297     static constexpr int32_t RETRY_INTERVAL = 500 * 1000; // unit is ms
298     for (BlockInteger retry(RETRY_INTERVAL); retry < RETRY_TIMES; ++retry) {
299         if (!DmAdapter::GetInstance().GetLocalDevice().uuid.empty()) {
300             break;
301         }
302         ZLOGW("GetLocalDeviceId failed, retry count:%{public}d", static_cast<int>(retry));
303     }
304     Initialize();
305     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
306     if (samgr != nullptr) {
307         ZLOGI("samgr exist.");
308         auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
309         auto kvDataServiceProxy = iface_cast<IKvStoreDataService>(remote);
310         if (kvDataServiceProxy != nullptr) {
311             ZLOGI("service has been registered.");
312             return;
313         }
314     }
315     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
316     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
317     AddSystemAbilityListener(COMM_NET_CONN_MANAGER_SYS_ABILITY_ID);
318     AddSystemAbilityListener(CONCURRENT_TASK_SERVICE_ID);
319     RegisterStoreInfo();
320     Handler handlerStoreInfo = std::bind(&KvStoreDataService::DumpStoreInfo, this, std::placeholders::_1,
321         std::placeholders::_2);
322     DumpManager::GetInstance().AddHandler("STORE_INFO", uintptr_t(this), handlerStoreInfo);
323     RegisterUserInfo();
324     Handler handlerUserInfo = std::bind(&KvStoreDataService::DumpUserInfo, this, std::placeholders::_1,
325         std::placeholders::_2);
326     DumpManager::GetInstance().AddHandler("USER_INFO", uintptr_t(this), handlerUserInfo);
327     RegisterBundleInfo();
328     Handler handlerBundleInfo = std::bind(&KvStoreDataService::DumpBundleInfo, this, std::placeholders::_1,
329         std::placeholders::_2);
330     DumpManager::GetInstance().AddHandler("BUNDLE_INFO", uintptr_t(this), handlerBundleInfo);
331     StartService();
332 }
333 
LoadConfigs()334 void KvStoreDataService::LoadConfigs()
335 {
336     ZLOGI("Bootstrap configs and plugins.");
337     Bootstrap::GetInstance().LoadThread();
338     InitExecutor();
339     Bootstrap::GetInstance().LoadComponents();
340     Bootstrap::GetInstance().LoadDirectory();
341     Bootstrap::GetInstance().LoadCheckers();
342     Bootstrap::GetInstance().LoadNetworks();
343     Bootstrap::GetInstance().LoadBackup(executors_);
344     Bootstrap::GetInstance().LoadCloud();
345     Bootstrap::GetInstance().LoadAppIdMappings();
346 }
347 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)348 void KvStoreDataService::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
349 {
350     ZLOGI("add system abilityid:%{public}d", systemAbilityId);
351     (void)deviceId;
352     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
353         AccountDelegate::GetInstance()->SubscribeAccountEvent();
354         Installer::GetInstance().Init(this, executors_);
355         ScreenManager::GetInstance()->SubscribeScreenEvent();
356     } else if (systemAbilityId == MEMORY_MANAGER_SA_ID) {
357         Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 1,
358                                                                 DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
359     } else if (systemAbilityId == COMM_NET_CONN_MANAGER_SYS_ABILITY_ID) {
360         NetworkDelegate::GetInstance()->RegOnNetworkChange();
361     }
362     return;
363 }
364 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)365 void KvStoreDataService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
366 {
367     ZLOGI("remove system abilityid:%{public}d", systemAbilityId);
368     (void)deviceId;
369     if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
370         return;
371     }
372     AccountDelegate::GetInstance()->UnsubscribeAccountEvent();
373     ScreenManager::GetInstance()->UnsubscribeScreenEvent();
374     Installer::GetInstance().UnsubscribeEvent();
375 }
376 
OnExtension(const std::string & extension,MessageParcel & data,MessageParcel & reply)377 int32_t KvStoreDataService::OnExtension(const std::string &extension, MessageParcel &data, MessageParcel &reply)
378 {
379     ZLOGI("extension is %{public}s, callingPid:%{public}d.", extension.c_str(), IPCSkeleton::GetCallingPid());
380     if (extension == EXTENSION_BACKUP) {
381         return KvStoreDataService::OnBackup(data, reply);
382     } else if (extension == EXTENSION_RESTORE) {
383         return KvStoreDataService::OnRestore(data, reply);
384     }
385     return 0;
386 }
387 
GetBackupReplyCode(int replyCode,const std::string & info)388 std::string KvStoreDataService::GetBackupReplyCode(int replyCode, const std::string &info)
389 {
390     CloneReplyCode reply;
391     CloneReplyResult result;
392     result.errorCode = std::to_string(replyCode);
393     result.errorInfo = info;
394     reply.resultInfo.push_back(std::move(result));
395     return Serializable::Marshall(reply);
396 }
397 
ConvertDecStrToVec(const std::string & inData)398 std::vector<uint8_t> ConvertDecStrToVec(const std::string &inData)
399 {
400     std::vector<uint8_t> outData;
401     auto splitedToken = Constant::Split(inData, ",");
402     outData.reserve(splitedToken.size());
403     for (auto &token : splitedToken) {
404         outData.push_back(static_cast<uint8_t>(atoi(token.c_str())));
405     }
406     return outData;
407 }
408 
ImportCloneKey(const std::string & keyStr)409 bool KvStoreDataService::ImportCloneKey(const std::string &keyStr)
410 {
411     auto key = ConvertDecStrToVec(keyStr);
412     if (key.size() != KEY_SIZE) {
413         ZLOGE("ImportKey failed, key size not correct, key size:%{public}zu", key.size());
414         key.assign(key.size(), 0);
415         return false;
416     }
417 
418     auto cloneKeyAlias = std::vector<uint8_t>(CLONE_KEY_ALIAS, CLONE_KEY_ALIAS + strlen(CLONE_KEY_ALIAS));
419     if (!CryptoManager::GetInstance().ImportKey(key, cloneKeyAlias)) {
420         key.assign(key.size(), 0);
421         return false;
422     }
423     key.assign(key.size(), 0);
424     return true;
425 }
426 
DeleteCloneKey()427 void KvStoreDataService::DeleteCloneKey()
428 {
429     auto cloneKeyAlias = std::vector<uint8_t>(CLONE_KEY_ALIAS, CLONE_KEY_ALIAS + strlen(CLONE_KEY_ALIAS));
430     CryptoManager::GetInstance().DeleteKey(cloneKeyAlias);
431 }
432 
WriteBackupInfo(const std::string & content,const std::string & backupPath)433 bool KvStoreDataService::WriteBackupInfo(const std::string &content, const std::string &backupPath)
434 {
435     FILE *fp = fopen(backupPath.c_str(), "w");
436 
437     if (!fp) {
438         ZLOGE("Secret key backup file fopen failed, path: %{public}s, errno: %{public}d", backupPath.c_str(), errno);
439         return false;
440     }
441     size_t ret = fwrite(content.c_str(), 1, content.length(), fp);
442     if (ret != content.length()) {
443         ZLOGE("Secret key backup file fwrite failed, path: %{public}s, errno: %{public}d", backupPath.c_str(), errno);
444         (void)fclose(fp);
445         return false;
446     }
447 
448     (void)fflush(fp);
449     (void)fsync(fileno(fp));
450     (void)fclose(fp);
451     return true;
452 }
453 
OnBackup(MessageParcel & data,MessageParcel & reply)454 int32_t KvStoreDataService::OnBackup(MessageParcel &data, MessageParcel &reply)
455 {
456     CloneBackupInfo backupInfo;
457     if (!backupInfo.Unmarshal(data.ReadString()) ||
458         backupInfo.bundleInfos.empty() || backupInfo.userId.empty()) {
459         std::fill(backupInfo.encryptionInfo.symkey.begin(), backupInfo.encryptionInfo.symkey.end(), '\0');
460         return -1;
461     }
462 
463     if (!ImportCloneKey(backupInfo.encryptionInfo.symkey)) {
464         std::fill(backupInfo.encryptionInfo.symkey.begin(), backupInfo.encryptionInfo.symkey.end(), '\0');
465         return -1;
466     }
467     std::fill(backupInfo.encryptionInfo.symkey.begin(), backupInfo.encryptionInfo.symkey.end(), '\0');
468 
469     auto iv = ConvertDecStrToVec(backupInfo.encryptionInfo.iv);
470     if (iv.size() != AES_256_NONCE_SIZE) {
471         ZLOGE("Iv size not correct, iv size:%{public}zu", iv.size());
472         iv.assign(iv.size(), 0);
473         return -1;
474     }
475 
476     std::string content;
477     if (!GetSecretKeyBackup(backupInfo.bundleInfos, backupInfo.userId, iv, content)) {
478         DeleteCloneKey();
479         return -1;
480     };
481     DeleteCloneKey();
482 
483     std::string backupPath = DirectoryManager::GetInstance().GetClonePath(backupInfo.userId);
484     if (backupPath.empty()) {
485         ZLOGE("GetClonePath failed, userId:%{public}s errno: %{public}d", backupInfo.userId.c_str(), errno);
486         return -1;
487     }
488     if (!WriteBackupInfo(content, backupPath)) {
489         return -1;
490     }
491 
492     UniqueFd fd(-1);
493     fd = UniqueFd(open(backupPath.c_str(), O_RDONLY));
494     std::string replyCode = GetBackupReplyCode(0);
495     if (!reply.WriteFileDescriptor(fd) || !reply.WriteString(replyCode)) {
496         close(fd.Release());
497         ZLOGE("OnBackup fail: reply wirte fail, fd:%{public}d", fd.Get());
498         return -1;
499     }
500 
501     close(fd.Release());
502     return 0;
503 }
504 
ReEncryptKey(const std::string & key,SecretKeyMetaData & secretKeyMeta,const StoreMetaData & metaData,const std::vector<uint8_t> & iv)505 std::vector<uint8_t> KvStoreDataService::ReEncryptKey(const std::string &key, SecretKeyMetaData &secretKeyMeta,
506     const StoreMetaData &metaData, const std::vector<uint8_t> &iv)
507 {
508     if (!MetaDataManager::GetInstance().LoadMeta(key, secretKeyMeta, true)) {
509         return {};
510     };
511     std::vector<uint8_t> password;
512     if (!CryptoManager::GetInstance().Decrypt(metaData, secretKeyMeta, password)) {
513         return {};
514     };
515 
516     auto cloneKeyAlias = std::vector<uint8_t>(CLONE_KEY_ALIAS, CLONE_KEY_ALIAS + strlen(CLONE_KEY_ALIAS));
517     CryptoManager::EncryptParams encryptParams = { .keyAlias = cloneKeyAlias, .nonce = iv };
518     auto reEncryptedKey = CryptoManager::GetInstance().Encrypt(password, encryptParams);
519     password.assign(password.size(), 0);
520     if (reEncryptedKey.size() == 0) {
521         return {};
522     };
523     return reEncryptedKey;
524 }
525 
GetSecretKeyBackup(const std::vector<DistributedData::CloneBundleInfo> & bundleInfos,const std::string & userId,const std::vector<uint8_t> & iv,std::string & content)526 bool KvStoreDataService::GetSecretKeyBackup(
527     const std::vector<DistributedData::CloneBundleInfo> &bundleInfos,
528     const std::string &userId, const std::vector<uint8_t> &iv, std::string &content)
529 {
530     SecretKeyBackupData backupInfos;
531     std::string deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
532     for (const auto& bundleInfo : bundleInfos) {
533         std::string metaPrefix = StoreMetaData::GetKey({ deviceId, userId, "default", bundleInfo.bundleName });
534         std::vector<StoreMetaData> StoreMetas;
535         if (!MetaDataManager::GetInstance().LoadMeta(metaPrefix, StoreMetas, true)) {
536             continue;
537         };
538         for (const auto &storeMeta : StoreMetas) {
539             if (!storeMeta.isEncrypt) {
540                 continue;
541             };
542             auto key = storeMeta.GetSecretKey();
543             SecretKeyMetaData secretKeyMeta;
544             auto reEncryptedKey = ReEncryptKey(key, secretKeyMeta, storeMeta, iv);
545             if (reEncryptedKey.size() == 0) {
546                 continue;
547             };
548             SecretKeyBackupData::BackupItem item;
549             item.time = secretKeyMeta.time;
550             item.bundleName = bundleInfo.bundleName;
551             item.dbName = storeMeta.storeId;
552             item.instanceId = storeMeta.instanceId;
553             item.sKey = DistributedData::Base64::Encode(reEncryptedKey);
554             item.storeType = secretKeyMeta.storeType;
555             item.user = userId;
556             item.area = storeMeta.area;
557             backupInfos.infos.push_back(std::move(item));
558         }
559     }
560     content = Serializable::Marshall(backupInfos);
561     return true;
562 }
563 
OnRestore(MessageParcel & data,MessageParcel & reply)564 int32_t KvStoreDataService::OnRestore(MessageParcel &data, MessageParcel &reply)
565 {
566     SecretKeyBackupData backupData;
567     if (!ParseSecretKeyFile(data, backupData) || backupData.infos.size() == 0) {
568         return ReplyForRestore(reply, -1);
569     }
570     CloneBackupInfo backupInfo;
571     bool ret = backupInfo.Unmarshal(data.ReadString());
572     if (!ret || backupInfo.userId.empty()) {
573         std::fill(backupInfo.encryptionInfo.symkey.begin(), backupInfo.encryptionInfo.symkey.end(), '\0');
574         return ReplyForRestore(reply, -1);
575     }
576 
577     auto iv = ConvertDecStrToVec(backupInfo.encryptionInfo.iv);
578     if (iv.size() != AES_256_NONCE_SIZE) {
579         ZLOGE("Iv size not correct, iv size:%{public}zu", iv.size());
580         std::fill(backupInfo.encryptionInfo.symkey.begin(), backupInfo.encryptionInfo.symkey.end(), '\0');
581         return ReplyForRestore(reply, -1);
582     }
583 
584     if (!ImportCloneKey(backupInfo.encryptionInfo.symkey)) {
585         std::fill(backupInfo.encryptionInfo.symkey.begin(), backupInfo.encryptionInfo.symkey.end(), '\0');
586         DeleteCloneKey();
587         return ReplyForRestore(reply, -1);
588     }
589     std::fill(backupInfo.encryptionInfo.symkey.begin(), backupInfo.encryptionInfo.symkey.end(), '\0');
590 
591     for (const auto &item : backupData.infos) {
592         if (!item.IsValid() || !RestoreSecretKey(item, backupInfo.userId, iv)) {
593             continue;
594         }
595     }
596     DeleteCloneKey();
597     return ReplyForRestore(reply, 0);
598 }
599 
ReplyForRestore(MessageParcel & reply,int32_t result)600 int32_t KvStoreDataService::ReplyForRestore(MessageParcel &reply, int32_t result)
601 {
602     std::string replyCode = GetBackupReplyCode(result);
603     if (!reply.WriteString(replyCode)) {
604         return -1;
605     }
606     return result;
607 }
608 
ParseSecretKeyFile(MessageParcel & data,SecretKeyBackupData & backupData)609 bool KvStoreDataService::ParseSecretKeyFile(MessageParcel &data, SecretKeyBackupData &backupData)
610 {
611     UniqueFd fd(data.ReadFileDescriptor());
612     struct stat statBuf;
613     if (fd.Get() < 0 || fstat(fd.Get(), &statBuf) < 0) {
614         ZLOGE("Parse backup secret key failed, fd:%{public}d, errno:%{public}d", fd.Get(), errno);
615         close(fd.Release());
616         return false;
617     }
618     char buffer[statBuf.st_size + 1];
619     if (read(fd.Get(), buffer, statBuf.st_size + 1) < 0) {
620         ZLOGE("Read backup secret key failed. errno:%{public}d", errno);
621         close(fd.Release());
622         return false;
623     }
624     close(fd.Release());
625     std::string secretKeyStr(buffer);
626     DistributedData::Serializable::Unmarshall(secretKeyStr, backupData);
627     return true;
628 }
629 
RestoreSecretKey(const SecretKeyBackupData::BackupItem & item,const std::string & userId,const std::vector<uint8_t> & iv)630 bool KvStoreDataService::RestoreSecretKey(const SecretKeyBackupData::BackupItem &item, const std::string &userId,
631     const std::vector<uint8_t> &iv)
632 {
633     StoreMetaData metaData;
634     metaData.bundleName = item.bundleName;
635     metaData.storeId = item.dbName;
636     metaData.user = item.user == "0" ? "0" : userId;
637     metaData.instanceId = item.instanceId;
638     auto sKey = DistributedData::Base64::Decode(item.sKey);
639     std::vector<uint8_t> rawKey;
640 
641     auto cloneKeyAlias = std::vector<uint8_t>(CLONE_KEY_ALIAS, CLONE_KEY_ALIAS + strlen(CLONE_KEY_ALIAS));
642     CryptoManager::EncryptParams encryptParams = { .keyAlias = cloneKeyAlias, .nonce = iv };
643     if (!CryptoManager::GetInstance().Decrypt(sKey, rawKey, encryptParams)) {
644         ZLOGE("Decrypt failed, bundleName:%{public}s, storeName:%{public}s, storeType:%{public}d",
645             item.bundleName.c_str(), Anonymous::Change(item.dbName).c_str(), item.storeType);
646         sKey.assign(sKey.size(), 0);
647         rawKey.assign(rawKey.size(), 0);
648         return false;
649     }
650     SecretKeyMetaData secretKey;
651     secretKey.storeType = item.storeType;
652     if (item.area < 0) {
653         secretKey.sKey = CryptoManager::GetInstance().Encrypt(rawKey, DEFAULT_ENCRYPTION_LEVEL, DEFAULT_USER);
654     } else {
655         secretKey.sKey = CryptoManager::GetInstance().Encrypt(rawKey, item.area, userId);
656         secretKey.area = item.area;
657     }
658     secretKey.time = { item.time.begin(), item.time.end() };
659     sKey.assign(sKey.size(), 0);
660     rawKey.assign(rawKey.size(), 0);
661     return MetaDataManager::GetInstance().SaveMeta(metaData.GetCloneSecretKey(), secretKey, true);
662 }
663 
StartService()664 void KvStoreDataService::StartService()
665 {
666     // register this to ServiceManager.
667     ZLOGI("begin.");
668     KvStoreMetaManager::GetInstance().InitMetaListener();
669     DeviceMatrix::GetInstance().Initialize(IPCSkeleton::GetCallingTokenID(), Bootstrap::GetInstance().GetMetaDBName());
670     LoadFeatures();
671     bool ret = SystemAbility::Publish(this);
672     if (!ret) {
673         DumpHelper::GetInstance().AddErrorInfo(SERVER_UNAVAILABLE, "StartService: Service publish failed.");
674     }
675     // Initialize meta db delegate manager.
676     KvStoreMetaManager::GetInstance().SubscribeMeta(StoreMetaData::GetKey({}),
677         [this](const std::vector<uint8_t> &key, const std::vector<uint8_t> &value, CHANGE_FLAG flag) {
678             OnStoreMetaChanged(key, value, flag);
679         });
680     UpgradeManager::GetInstance().Init(executors_);
681     UserDelegate::GetInstance().Init(executors_);
682 
683     // subscribe account event listener to EventNotificationMgr
684     auto autoLaunch = [this](const std::string &identifier, DistributedDB::AutoLaunchParam &param) -> bool {
685         features_.ForEachCopies([&identifier, &param](const auto &, sptr<DistributedData::FeatureStubImpl> &value) {
686             value->ResolveAutoLaunch(identifier, param);
687             return false;
688         });
689         return false;
690     };
691     KvStoreDelegateManager::SetAutoLaunchRequestCallback(autoLaunch);
692     ZLOGI("Start distributedata Success, Publish ret: %{public}d", static_cast<int>(ret));
693 }
694 
OnStoreMetaChanged(const std::vector<uint8_t> & key,const std::vector<uint8_t> & value,CHANGE_FLAG flag)695 void KvStoreDataService::OnStoreMetaChanged(
696     const std::vector<uint8_t> &key, const std::vector<uint8_t> &value, CHANGE_FLAG flag)
697 {
698     if (flag != CHANGE_FLAG::UPDATE) {
699         return;
700     }
701     StoreMetaData metaData;
702     metaData.Unmarshall({ value.begin(), value.end() });
703     ZLOGD("meta data info appType:%{public}s, storeId:%{public}s isDirty:%{public}d", metaData.appType.c_str(),
704         Anonymous::Change(metaData.storeId).c_str(), metaData.isDirty);
705     auto deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
706     if (metaData.deviceId != deviceId || metaData.deviceId.empty()) {
707         ZLOGD("ignore other device change or invalid meta device");
708         return;
709     }
710     static constexpr const char *HARMONY_APP = "harmony";
711     if (!metaData.isDirty || metaData.appType != HARMONY_APP) {
712         return;
713     }
714     ZLOGI("dirty kv store. storeId:%{public}s", Anonymous::Change(metaData.storeId).c_str());
715 }
716 
OnStop()717 void KvStoreDataService::OnStop()
718 {
719     ZLOGI("begin.");
720     Memory::MemMgrClient::GetInstance().NotifyProcessStatus(getpid(), 1, 0, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
721 }
722 
KvStoreClientDeathObserverImpl(const AppId & appId,KvStoreDataService & service,sptr<IRemoteObject> observer)723 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl(
724     const AppId &appId, KvStoreDataService &service, sptr<IRemoteObject> observer)
725     : appId_(appId), dataService_(service), observerProxy_(std::move(observer)),
726       deathRecipient_(new KvStoreDeathRecipient(*this))
727 {
728     ZLOGD("KvStoreClientDeathObserverImpl");
729     uid_ = IPCSkeleton::GetCallingUid();
730     pid_ = IPCSkeleton::GetCallingPid();
731     token_ = IPCSkeleton::GetCallingTokenID();
732     if (observerProxy_ != nullptr) {
733         ZLOGI("add death recipient");
734         observerProxy_->AddDeathRecipient(deathRecipient_);
735     } else {
736         ZLOGW("observerProxy_ is nullptr");
737     }
738 }
KvStoreClientDeathObserverImpl(KvStoreDataService & service)739 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl(KvStoreDataService &service)
740     : dataService_(service)
741 {
742     Reset();
743 }
744 
KvStoreClientDeathObserverImpl(KvStoreDataService::KvStoreClientDeathObserverImpl && impl)745 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreClientDeathObserverImpl(
746     KvStoreDataService::KvStoreClientDeathObserverImpl &&impl)
747     : uid_(impl.uid_), pid_(impl.pid_), token_(impl.token_), dataService_(impl.dataService_)
748 {
749     appId_.appId = std::move(impl.appId_.appId);
750     impl.Reset();
751 }
752 
operator =(KvStoreDataService::KvStoreClientDeathObserverImpl && impl)753 KvStoreDataService::KvStoreClientDeathObserverImpl &KvStoreDataService::KvStoreClientDeathObserverImpl::operator=(
754     KvStoreDataService::KvStoreClientDeathObserverImpl &&impl)
755 {
756     uid_ = impl.uid_;
757     pid_ = impl.pid_;
758     token_ = impl.token_;
759     appId_.appId = std::move(impl.appId_.appId);
760     impl.Reset();
761     return *this;
762 }
763 
~KvStoreClientDeathObserverImpl()764 KvStoreDataService::KvStoreClientDeathObserverImpl::~KvStoreClientDeathObserverImpl()
765 {
766     ZLOGI("~KvStoreClientDeathObserverImpl");
767     if (deathRecipient_ != nullptr && observerProxy_ != nullptr) {
768         ZLOGI("remove death recipient");
769         observerProxy_->RemoveDeathRecipient(deathRecipient_);
770     }
771     if (uid_ == INVALID_UID || pid_ == INVALID_PID || token_ == INVALID_TOKEN || !appId_.IsValid()) {
772         return;
773     }
774     dataService_.features_.ForEachCopies([this](const auto &, sptr<DistributedData::FeatureStubImpl> &value) {
775         value->OnAppExit(uid_, pid_, token_, appId_);
776         return false;
777     });
778 }
779 
NotifyClientDie()780 void KvStoreDataService::KvStoreClientDeathObserverImpl::NotifyClientDie()
781 {
782     ZLOGI("appId: %{public}s uid:%{public}d tokenId:%{public}u", appId_.appId.c_str(), uid_, token_);
783     dataService_.AppExit(uid_, pid_, token_, appId_);
784 }
785 
GetPid() const786 pid_t KvStoreDataService::KvStoreClientDeathObserverImpl::GetPid() const
787 {
788     return pid_;
789 }
790 
Reset()791 void KvStoreDataService::KvStoreClientDeathObserverImpl::Reset()
792 {
793     uid_ = INVALID_UID;
794     pid_ = INVALID_PID;
795     token_ = INVALID_TOKEN;
796     appId_.appId = "";
797 }
798 
KvStoreDeathRecipient(KvStoreClientDeathObserverImpl & kvStoreClientDeathObserverImpl)799 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::KvStoreDeathRecipient(
800     KvStoreClientDeathObserverImpl &kvStoreClientDeathObserverImpl)
801     : kvStoreClientDeathObserverImpl_(kvStoreClientDeathObserverImpl)
802 {
803     ZLOGI("KvStore Client Death Observer");
804 }
805 
~KvStoreDeathRecipient()806 KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::~KvStoreDeathRecipient()
807 {
808     ZLOGD("~KvStore Client Death Observer");
809 }
810 
OnRemoteDied(const wptr<IRemoteObject> & remote)811 void KvStoreDataService::KvStoreClientDeathObserverImpl::KvStoreDeathRecipient::OnRemoteDied(
812     const wptr<IRemoteObject> &remote)
813 {
814     (void) remote;
815     ZLOGI("begin");
816     kvStoreClientDeathObserverImpl_.NotifyClientDie();
817 }
818 
AccountEventChanged(const AccountEventInfo & eventInfo)819 void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo)
820 {
821     ZLOGI("account event %{public}d changed process, begin.", eventInfo.status);
822     NotifyAccountEvent(eventInfo);
823     switch (eventInfo.status) {
824         case AccountStatus::DEVICE_ACCOUNT_DELETE: {
825             g_kvStoreAccountEventStatus = 1;
826             // delete all kvstore meta belong to this user
827             std::vector<StoreMetaData> metaData;
828             MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({""}), metaData, true);
829             for (const auto &meta : metaData) {
830                 if (meta.user != eventInfo.userId) {
831                     continue;
832                 }
833                 ZLOGI("bundleName:%{public}s, user:%{public}s", meta.bundleName.c_str(), meta.user.c_str());
834                 MetaDataManager::GetInstance().DelMeta(meta.GetKey());
835                 MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true);
836                 MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true);
837                 MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true);
838                 MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey());
839                 MetaDataManager::GetInstance().DelMeta(meta.GetBackupSecretKey(), true);
840                 MetaDataManager::GetInstance().DelMeta(meta.GetAutoLaunchKey(), true);
841                 MetaDataManager::GetInstance().DelMeta(meta.appId, true);
842                 MetaDataManager::GetInstance().DelMeta(meta.GetDebugInfoKey(), true);
843                 MetaDataManager::GetInstance().DelMeta(meta.GetDfxInfoKey(), true);
844                 MetaDataManager::GetInstance().DelMeta(meta.GetCloneSecretKey(), true);
845                 PermitDelegate::GetInstance().DelCache(meta.GetKey());
846             }
847             g_kvStoreAccountEventStatus = 0;
848             break;
849         }
850         case AccountStatus::DEVICE_ACCOUNT_SWITCHED: {
851             auto ret = DistributedDB::KvStoreDelegateManager::NotifyUserChanged();
852             ZLOGI("notify delegate manager result:%{public}d", ret);
853             break;
854         }
855         default: {
856             break;
857         }
858     }
859     ZLOGI("account event %{public}d changed process, end.", eventInfo.status);
860 }
861 
NotifyAccountEvent(const AccountEventInfo & eventInfo)862 void KvStoreDataService::NotifyAccountEvent(const AccountEventInfo &eventInfo)
863 {
864     features_.ForEachCopies([&eventInfo](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
865         value->OnUserChange(uint32_t(eventInfo.status), eventInfo.userId, eventInfo.harmonyAccountId);
866         return false;
867     });
868     switch (eventInfo.status) {
869         case AccountStatus::DEVICE_ACCOUNT_SWITCHED:
870         case AccountStatus::DEVICE_ACCOUNT_DELETE:
871         case AccountStatus::DEVICE_ACCOUNT_STOPPED: {
872             std::vector<int32_t> users;
873             AccountDelegate::GetInstance()->QueryUsers(users);
874             std::set<int32_t> userIds(users.begin(), users.end());
875             userIds.insert(0);
876             AutoCache::GetInstance().CloseStore([&userIds](const StoreMetaData &meta) {
877                 if (userIds.count(atoi(meta.user.c_str())) == 0) {
878                     ZLOGW("Illegal use of database by user %{public}s, %{public}s:%{public}s", meta.user.c_str(),
879                           meta.bundleName.c_str(), meta.GetStoreAlias().c_str());
880                     return true;
881                 }
882                 return false;
883             });
884             break;
885         }
886         case AccountStatus::DEVICE_ACCOUNT_STOPPING:
887             AutoCache::GetInstance().CloseStore([&eventInfo](const StoreMetaData &meta) {
888                 return meta.user == eventInfo.userId;
889             });
890             break;
891         default:
892             break;
893     }
894 }
895 
InitSecurityAdapter(std::shared_ptr<ExecutorPool> executors)896 void KvStoreDataService::InitSecurityAdapter(std::shared_ptr<ExecutorPool> executors)
897 {
898     auto ret = DATASL_OnStart();
899     ZLOGI("datasl on start ret:%d", ret);
900     security_ = std::make_shared<Security>(executors);
901     if (security_ == nullptr) {
902         ZLOGE("security is nullptr.");
903         return;
904     }
905 
906     security_->InitLocalSecurity();
907     auto dbStatus = DistributedDB::RuntimeConfig::SetProcessSystemAPIAdapter(security_);
908     ZLOGD("set distributed db system api adapter: %d.", static_cast<int>(dbStatus));
909 
910     auto status = DmAdapter::GetInstance().StartWatchDeviceChange(security_.get(), {"security"});
911     if (status != Status::SUCCESS) {
912         ZLOGD("security register device change failed, status:%d", static_cast<int>(status));
913     }
914 }
915 
SetCompatibleIdentify(const AppDistributedKv::DeviceInfo & info) const916 void KvStoreDataService::SetCompatibleIdentify(const AppDistributedKv::DeviceInfo &info) const
917 {
918 }
919 
OnDeviceOnline(const AppDistributedKv::DeviceInfo & info)920 void KvStoreDataService::OnDeviceOnline(const AppDistributedKv::DeviceInfo &info)
921 {
922     if (info.uuid.empty()) {
923         return;
924     }
925     features_.ForEachCopies([&info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
926         value->Online(info.uuid);
927         return false;
928     });
929 }
930 
OnDeviceOffline(const AppDistributedKv::DeviceInfo & info)931 void KvStoreDataService::OnDeviceOffline(const AppDistributedKv::DeviceInfo &info)
932 {
933     if (info.uuid.empty()) {
934         return;
935     }
936     features_.ForEachCopies([&info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
937         value->Offline(info.uuid);
938         return false;
939     });
940 }
941 
OnDeviceOnReady(const AppDistributedKv::DeviceInfo & info)942 void KvStoreDataService::OnDeviceOnReady(const AppDistributedKv::DeviceInfo &info)
943 {
944     if (info.uuid.empty()) {
945         return;
946     }
947     features_.ForEachCopies([&info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
948         value->OnReady(info.uuid);
949         return false;
950     });
951 }
952 
OnSessionReady(const AppDistributedKv::DeviceInfo & info)953 void KvStoreDataService::OnSessionReady(const AppDistributedKv::DeviceInfo &info)
954 {
955     if (info.uuid.empty()) {
956         return;
957     }
958     features_.ForEachCopies([info](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
959         value->OnSessionReady(info.uuid);
960         return false;
961     });
962 }
963 
OnUninstall(const std::string & bundleName,int32_t user,int32_t index)964 int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t user, int32_t index)
965 {
966     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
967     staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr<StaticActs>& acts) {
968         acts->OnAppUninstall(bundleName, user, index);
969         return false;
970     });
971     return SUCCESS;
972 }
973 
OnUpdate(const std::string & bundleName,int32_t user,int32_t index)974 int32_t KvStoreDataService::OnUpdate(const std::string &bundleName, int32_t user, int32_t index)
975 {
976     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
977     staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr<StaticActs>& acts) {
978         acts->OnAppUpdate(bundleName, user, index);
979         return false;
980     });
981     return SUCCESS;
982 }
983 
OnInstall(const std::string & bundleName,int32_t user,int32_t index)984 int32_t KvStoreDataService::OnInstall(const std::string &bundleName, int32_t user, int32_t index)
985 {
986     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
987     staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr<StaticActs>& acts) {
988         acts->OnAppInstall(bundleName, user, index);
989         return false;
990     });
991     return SUCCESS;
992 }
993 
OnScreenUnlocked(int32_t user)994 int32_t KvStoreDataService::OnScreenUnlocked(int32_t user)
995 {
996     features_.ForEachCopies([user](const auto &key, sptr<DistributedData::FeatureStubImpl> &value) {
997         value->OnScreenUnlocked(user);
998         return false;
999     });
1000     return SUCCESS;
1001 }
1002 
ClearAppStorage(const std::string & bundleName,int32_t userId,int32_t appIndex,int32_t tokenId)1003 int32_t KvStoreDataService::ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex,
1004     int32_t tokenId)
1005 {
1006     auto callerToken = IPCSkeleton::GetCallingTokenID();
1007     NativeTokenInfo nativeTokenInfo;
1008     if (AccessTokenKit::GetNativeTokenInfo(callerToken, nativeTokenInfo) != RET_SUCCESS ||
1009         nativeTokenInfo.processName != FOUNDATION_PROCESS_NAME) {
1010         ZLOGE("passed wrong, tokenId: %{public}u, bundleName:%{public}s, user:%{public}d, appIndex:%{public}d",
1011             tokenId, bundleName.c_str(), userId, appIndex);
1012         return ERROR;
1013     }
1014 
1015     auto staticActs = FeatureSystem::GetInstance().GetStaticActs();
1016     staticActs.ForEachCopies(
1017         [bundleName, userId, appIndex, tokenId](const auto &, const std::shared_ptr<StaticActs> &acts) {
1018             acts->OnClearAppStorage(bundleName, userId, appIndex, tokenId);
1019             return false;
1020         });
1021 
1022     std::vector<StoreMetaData> metaData;
1023     std::string prefix = StoreMetaData::GetPrefix(
1024         { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName });
1025     if (!MetaDataManager::GetInstance().LoadMeta(prefix, metaData, true)) {
1026         ZLOGE("Clear data load meta failed, bundleName:%{public}s, user:%{public}d, appIndex:%{public}d",
1027             bundleName.c_str(), userId, appIndex);
1028         return ERROR;
1029     }
1030 
1031     for (auto &meta : metaData) {
1032         if (meta.instanceId == appIndex && !meta.appId.empty() && !meta.storeId.empty()) {
1033             ZLOGI("data cleared bundleName:%{public}s, stordId:%{public}s, appIndex:%{public}d", bundleName.c_str(),
1034                 Anonymous::Change(meta.storeId).c_str(), appIndex);
1035             MetaDataManager::GetInstance().DelMeta(meta.GetKey());
1036             MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true);
1037             MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true);
1038             MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true);
1039             MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey());
1040             MetaDataManager::GetInstance().DelMeta(meta.GetBackupSecretKey(), true);
1041             MetaDataManager::GetInstance().DelMeta(meta.appId, true);
1042             MetaDataManager::GetInstance().DelMeta(meta.GetDebugInfoKey(), true);
1043             MetaDataManager::GetInstance().DelMeta(meta.GetDfxInfoKey(), true);
1044             MetaDataManager::GetInstance().DelMeta(meta.GetAutoLaunchKey(), true);
1045             PermitDelegate::GetInstance().DelCache(meta.GetKey());
1046         }
1047     }
1048     return SUCCESS;
1049 }
1050 
RegisterStoreInfo()1051 void KvStoreDataService::RegisterStoreInfo()
1052 {
1053     OHOS::DistributedData::DumpManager::Config storeInfoConfig;
1054     storeInfoConfig.fullCmd = "--store-info";
1055     storeInfoConfig.abbrCmd = "-s";
1056     storeInfoConfig.dumpName = "STORE_INFO";
1057     storeInfoConfig.countPrintf = PRINTF_COUNT_2;
1058     storeInfoConfig.infoName = " <StoreId>";
1059     storeInfoConfig.minParamsNum = 0;
1060     storeInfoConfig.maxParamsNum = MAXIMUM_PARAMETER_LIMIT; // Store contains no more than three parameters
1061     storeInfoConfig.parentNode = "BUNDLE_INFO";
1062     storeInfoConfig.dumpCaption = { "| Display all the store statistics", "| Display the store statistics  by "
1063                                                                           "StoreID" };
1064     DumpManager::GetInstance().AddConfig(storeInfoConfig.dumpName, storeInfoConfig);
1065 }
1066 
DumpStoreInfo(int fd,std::map<std::string,std::vector<std::string>> & params)1067 void KvStoreDataService::DumpStoreInfo(int fd, std::map<std::string, std::vector<std::string>> &params)
1068 {
1069     std::vector<StoreMetaData> metas;
1070     std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
1071     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) {
1072         ZLOGE("get full meta failed");
1073         return;
1074     }
1075     FilterData(metas, params);
1076     PrintfInfo(fd, metas);
1077 }
1078 
FilterData(std::vector<StoreMetaData> & metas,std::map<std::string,std::vector<std::string>> & filterInfo)1079 void KvStoreDataService::FilterData(std::vector<StoreMetaData> &metas,
1080     std::map<std::string, std::vector<std::string>> &filterInfo)
1081 {
1082     for (auto iter = metas.begin(); iter != metas.end();) {
1083         if ((IsExist("USER_INFO", filterInfo, iter->user)) || (IsExist("BUNDLE_INFO", filterInfo, iter->bundleName)) ||
1084             (IsExist("STORE_INFO", filterInfo, iter->storeId))) {
1085             iter = metas.erase(iter);
1086         } else {
1087             iter++;
1088         }
1089     }
1090 }
1091 
IsExist(const std::string & infoName,std::map<std::string,std::vector<std::string>> & filterInfo,std::string & metaParam)1092 bool KvStoreDataService::IsExist(const std::string &infoName,
1093     std::map<std::string, std::vector<std::string>> &filterInfo, std::string &metaParam)
1094 {
1095     auto info = filterInfo.find(infoName);
1096     if (info != filterInfo.end()) {
1097         if (!info->second.empty()) {
1098             auto it = find(info->second.begin(), info->second.end(), metaParam);
1099             if (it == info->second.end()) {
1100                 return true;
1101             }
1102         }
1103     }
1104     return false;
1105 }
1106 
PrintfInfo(int fd,const std::vector<StoreMetaData> & metas)1107 void KvStoreDataService::PrintfInfo(int fd, const std::vector<StoreMetaData> &metas)
1108 {
1109     std::string info;
1110     int indentation = 0;
1111     if (metas.size() > 1) {
1112         info.append("Stores: ").append(std::to_string(metas.size())).append("\n");
1113         indentation++;
1114     }
1115     for (auto &data : metas) {
1116         char version[VERSION_WIDTH];
1117         auto flag = sprintf_s(version, sizeof(version), "0x%08X", data.version);
1118         if (flag < 0) {
1119             ZLOGE("get version failed");
1120             return;
1121         }
1122         info.append(GetIndentation(indentation))
1123             .append("--------------------------------------------------------------------------\n")
1124             .append(GetIndentation(indentation)).append("StoreID           : ").append(data.storeId).append("\n")
1125             .append(GetIndentation(indentation)).append("UId               : ").append(data.user).append("\n")
1126             .append(GetIndentation(indentation)).append("BundleName        : ").append(data.bundleName).append("\n")
1127             .append(GetIndentation(indentation)).append("AppID             : ").append(data.appId).append("\n")
1128             .append(GetIndentation(indentation)).append("StorePath         : ").append(data.dataDir).append("\n")
1129             .append(GetIndentation(indentation)).append("StoreType         : ")
1130             .append(std::to_string(data.storeType)).append("\n")
1131             .append(GetIndentation(indentation)).append("encrypt           : ")
1132             .append(std::to_string(data.isEncrypt)).append("\n")
1133             .append(GetIndentation(indentation)).append("autoSync          : ")
1134             .append(std::to_string(data.isAutoSync)).append("\n")
1135             .append(GetIndentation(indentation)).append("schema            : ").append(data.schema).append("\n")
1136             .append(GetIndentation(indentation)).append("securityLevel     : ")
1137             .append(std::to_string(data.securityLevel)).append("\n")
1138             .append(GetIndentation(indentation)).append("area              : ")
1139             .append(std::to_string(data.area)).append("\n")
1140             .append(GetIndentation(indentation)).append("instanceID        : ")
1141             .append(std::to_string(data.instanceId)).append("\n")
1142             .append(GetIndentation(indentation)).append("version           : ").append(version).append("\n");
1143     }
1144     dprintf(fd, "--------------------------------------StoreInfo-------------------------------------\n%s\n",
1145         info.c_str());
1146 }
1147 
GetIndentation(int size)1148 std::string KvStoreDataService::GetIndentation(int size)
1149 {
1150     std::string indentation;
1151     for (int i = 0; i < size; i++) {
1152         indentation.append(INDENTATION);
1153     }
1154     return indentation;
1155 }
1156 
RegisterUserInfo()1157 void KvStoreDataService::RegisterUserInfo()
1158 {
1159     DumpManager::Config userInfoConfig;
1160     userInfoConfig.fullCmd = "--user-info";
1161     userInfoConfig.abbrCmd = "-u";
1162     userInfoConfig.dumpName = "USER_INFO";
1163     userInfoConfig.countPrintf = PRINTF_COUNT_2;
1164     userInfoConfig.infoName = " <UId>";
1165     userInfoConfig.minParamsNum = 0;
1166     userInfoConfig.maxParamsNum = MAXIMUM_PARAMETER_LIMIT; // User contains no more than three parameters
1167     userInfoConfig.childNode = "BUNDLE_INFO";
1168     userInfoConfig.dumpCaption = { "| Display all the user statistics", "| Display the user statistics by UserId" };
1169     DumpManager::GetInstance().AddConfig(userInfoConfig.dumpName, userInfoConfig);
1170 }
1171 
BuildData(std::map<std::string,UserInfo> & datas,const std::vector<StoreMetaData> & metas)1172 void KvStoreDataService::BuildData(std::map<std::string, UserInfo> &datas, const std::vector<StoreMetaData> &metas)
1173 {
1174     for (auto &meta : metas) {
1175         auto it = datas.find(meta.user);
1176         if (it == datas.end()) {
1177             UserInfo userInfo;
1178             userInfo.userId = meta.user;
1179             userInfo.bundles.insert(meta.bundleName);
1180             datas[meta.user] = userInfo;
1181         } else {
1182             std::set<std::string> bundles_ = datas[meta.user].bundles;
1183             auto iter = std::find(bundles_.begin(), bundles_.end(), meta.bundleName);
1184             if (iter == bundles_.end()) {
1185                 datas[meta.user].bundles.insert(meta.bundleName);
1186             }
1187         }
1188     }
1189 }
1190 
PrintfInfo(int fd,const std::map<std::string,UserInfo> & datas)1191 void KvStoreDataService::PrintfInfo(int fd, const std::map<std::string, UserInfo> &datas)
1192 {
1193     std::string info;
1194     int indentation = 0;
1195     if (datas.size() > 1) {
1196         info.append("Users : ").append(std::to_string(datas.size())).append("\n");
1197         indentation++;
1198     }
1199 
1200     for (auto &data : datas) {
1201         info.append(GetIndentation(indentation))
1202             .append("------------------------------------------------------------------------------\n")
1203             .append("UID        : ")
1204             .append(data.second.userId)
1205             .append("\n");
1206         info.append(GetIndentation(indentation))
1207             .append("Bundles       : ")
1208             .append(std::to_string(data.second.bundles.size()))
1209             .append("\n");
1210         indentation++;
1211         info.append("------------------------------------------------------------------------------\n");
1212         for (auto &bundle : data.second.bundles) {
1213             info.append(GetIndentation(indentation)).append("BundleName    : ").append(bundle).append("\n");
1214         }
1215         indentation--;
1216     }
1217     dprintf(fd, "--------------------------------------UserInfo--------------------------------------\n%s\n",
1218         info.c_str());
1219 }
1220 
DumpUserInfo(int fd,std::map<std::string,std::vector<std::string>> & params)1221 void KvStoreDataService::DumpUserInfo(int fd, std::map<std::string, std::vector<std::string>> &params)
1222 {
1223     std::vector<StoreMetaData> metas;
1224     std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
1225     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) {
1226         ZLOGE("get full meta failed");
1227         return;
1228     }
1229     FilterData(metas, params);
1230     std::map<std::string, UserInfo> datas;
1231     BuildData(datas, metas);
1232     PrintfInfo(fd, datas);
1233 }
1234 
RegisterBundleInfo()1235 void KvStoreDataService::RegisterBundleInfo()
1236 {
1237     DumpManager::Config bundleInfoConfig;
1238     bundleInfoConfig.fullCmd = "--bundle-info";
1239     bundleInfoConfig.abbrCmd = "-b";
1240     bundleInfoConfig.dumpName = "BUNDLE_INFO";
1241     bundleInfoConfig.countPrintf = PRINTF_COUNT_2;
1242     bundleInfoConfig.infoName = " <BundleName>";
1243     bundleInfoConfig.minParamsNum = 0;
1244     bundleInfoConfig.maxParamsNum = MAXIMUM_PARAMETER_LIMIT; // Bundle contains no more than three parameters
1245     bundleInfoConfig.parentNode = "USER_INFO";
1246     bundleInfoConfig.childNode = "STORE_INFO";
1247     bundleInfoConfig.dumpCaption = { "| Display all the bundle statistics", "| Display the bundle statistics by "
1248                                                                             "BundleName" };
1249     DumpManager::GetInstance().AddConfig(bundleInfoConfig.dumpName, bundleInfoConfig);
1250 }
1251 
BuildData(std::map<std::string,BundleInfo> & datas,const std::vector<StoreMetaData> & metas)1252 void KvStoreDataService::BuildData(std::map<std::string, BundleInfo> &datas, const std::vector<StoreMetaData> &metas)
1253 {
1254     for (auto &meta : metas) {
1255         auto it = datas.find(meta.bundleName);
1256         if (it == datas.end()) {
1257             BundleInfo bundleInfo;
1258             bundleInfo.bundleName = meta.bundleName;
1259             bundleInfo.appId = meta.appId;
1260             bundleInfo.type = meta.appType;
1261             bundleInfo.uid = meta.uid;
1262             bundleInfo.tokenId = meta.tokenId;
1263             bundleInfo.userId = meta.user;
1264             std::string storeId = meta.storeId;
1265             storeId.resize(FORMAT_BLANK_SIZE, FORMAT_BLANK_SPACE);
1266             bundleInfo.storeIDs.insert(storeId);
1267             datas[meta.bundleName] = bundleInfo;
1268         } else {
1269             std::set<std::string> storeIDs_ = datas[meta.bundleName].storeIDs;
1270             std::string storeId = meta.storeId;
1271             storeId.resize(FORMAT_BLANK_SIZE, FORMAT_BLANK_SPACE);
1272             auto iter = std::find(storeIDs_.begin(), storeIDs_.end(), storeId);
1273             if (iter == storeIDs_.end()) {
1274                 datas[meta.bundleName].storeIDs.insert(storeId);
1275             }
1276         }
1277     }
1278 }
1279 
PrintfInfo(int fd,const std::map<std::string,BundleInfo> & datas)1280 void KvStoreDataService::PrintfInfo(int fd, const std::map<std::string, BundleInfo> &datas)
1281 {
1282     std::string info;
1283     int indentation = 0;
1284     if (datas.size() > 1) {
1285         info.append("Bundles: ").append(std::to_string(datas.size())).append("\n");
1286         indentation++;
1287     }
1288     for (auto &data : datas) {
1289         info.append(GetIndentation(indentation))
1290             .append("--------------------------------------------------------------------------\n");
1291         info.append(GetIndentation(indentation)).append("BundleName     : ")
1292             .append(data.second.bundleName).append("\n");
1293         info.append(GetIndentation(indentation)).append("AppID          : ")
1294             .append(data.second.appId).append("\n");
1295         info.append(GetIndentation(indentation)).append("Type           : ")
1296             .append(data.second.type).append("\n");
1297         info.append(GetIndentation(indentation))
1298             .append("UId            : ")
1299             .append(std::to_string(data.second.uid))
1300             .append("\n");
1301         info.append(GetIndentation(indentation))
1302             .append("TokenID        : ")
1303             .append(std::to_string(data.second.tokenId))
1304             .append("\n");
1305         info.append(GetIndentation(indentation)).append("UserID         : ").append(data.second.userId).append("\n");
1306         info.append(GetIndentation(indentation))
1307             .append("Stores         : ")
1308             .append(std::to_string(data.second.storeIDs.size()))
1309             .append("\n");
1310         indentation++;
1311         info.append("----------------------------------------------------------------------\n");
1312         for (auto &store : data.second.storeIDs) {
1313             info.append(GetIndentation(indentation)).append("StoreID    : ").append(store).append("\n");
1314         }
1315         indentation--;
1316     }
1317     dprintf(fd, "-------------------------------------BundleInfo-------------------------------------\n%s\n",
1318         info.c_str());
1319 }
1320 
DumpBundleInfo(int fd,std::map<std::string,std::vector<std::string>> & params)1321 void KvStoreDataService::DumpBundleInfo(int fd, std::map<std::string, std::vector<std::string>> &params)
1322 {
1323     std::vector<StoreMetaData> metas;
1324     std::string localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
1325     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ localDeviceId }), metas, true)) {
1326         ZLOGE("get full meta failed");
1327         return;
1328     }
1329     FilterData(metas, params);
1330     std::map<std::string, BundleInfo> datas;
1331     BuildData(datas, metas);
1332     PrintfInfo(fd, datas);
1333 }
1334 } // namespace OHOS::DistributedKv