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