1 /*
2  * Copyright (c) 2022-2024 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 
16 /*
17  * 注意:
18  *     - 注意点1:本文件原则上只处理与IPC无关的业务逻辑
19  *     - 注意点2:This document, in principle, captures all exceptions.
20  *               Prevent exceptions from spreading to insecure modules.
21  */
22 #include "module_ipc/service.h"
23 
24 #include <algorithm>
25 #include <chrono>
26 #include <cerrno>
27 #include <cstddef>
28 #include <cstdint>
29 #include <cstring>
30 #include <regex>
31 
32 #include <fcntl.h>
33 #include <iomanip>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <sys/vfs.h>
37 
38 #include <directory_ex.h>
39 
40 #include "ability_manager_client.h"
41 #include "accesstoken_kit.h"
42 #include "b_anony/b_anony.h"
43 #include "b_error/b_error.h"
44 #include "b_error/b_excep_utils.h"
45 #include "b_file_info.h"
46 #include "b_hiaudit/hi_audit.h"
47 #include "b_json/b_json_cached_entity.h"
48 #include "b_jsonutil/b_jsonutil.h"
49 #include "b_ohos/startup/backup_para.h"
50 #include "b_process/b_multiuser.h"
51 #include "b_radar/b_radar.h"
52 #include "b_resources/b_constants.h"
53 #include "b_sa/b_sa_utils.h"
54 #include "bundle_mgr_client.h"
55 #include "filemgmt_libhilog.h"
56 #include "hisysevent.h"
57 #include "hitrace_meter.h"
58 #include "ipc_skeleton.h"
59 #include "access_token.h"
60 #include "tokenid_kit.h"
61 #include "module_app_gallery/app_gallery_dispose_proxy.h"
62 #include "module_external/bms_adapter.h"
63 #include "module_external/sms_adapter.h"
64 #include "module_ipc/svc_backup_connection.h"
65 #include "module_ipc/svc_restore_deps_manager.h"
66 #include "module_notify/notify_work_service.h"
67 #include "parameter.h"
68 #include "parameters.h"
69 #include "system_ability_definition.h"
70 
71 namespace OHOS::FileManagement::Backup {
72 using namespace std;
73 
74 REGISTER_SYSTEM_ABILITY_BY_ID(Service, FILEMANAGEMENT_BACKUP_SERVICE_SA_ID, false);
75 
76 namespace {
77 constexpr int32_t DEBUG_ID = 100;
78 constexpr int32_t INDEX = 3;
79 constexpr int32_t MS_1000 = 1000;
80 const static string BROADCAST_TYPE = "broadcast";
81 const std::string FILE_BACKUP_EVENTS = "FILE_BACKUP_EVENTS";
82 const static string UNICAST_TYPE = "unicast";
83 const int32_t CONNECT_WAIT_TIME_S = 15;
84 const std::string BACKUPSERVICE_WORK_STATUS_KEY = "persist.backupservice.workstatus";
85 const std::string BACKUPSERVICE_WORK_STATUS_ON = "true";
86 const std::string BACKUPSERVICE_WORK_STATUS_OFF = "false";
87 const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP";
88 const int32_t MAX_TRY_CLEAR_DISPOSE_NUM = 3;
89 } // namespace
90 
91 /* Shell/Xts user id equal to 0/1, we need set default 100 */
GetUserIdDefault()92 static inline int32_t GetUserIdDefault()
93 {
94     auto [isDebug, debugId] = BackupPara().GetBackupDebugOverrideAccount();
95     if (isDebug && debugId > DEBUG_ID) {
96         return debugId;
97     }
98     auto multiuser = BMultiuser::ParseUid(IPCSkeleton::GetCallingUid());
99     HILOGI("GetUserIdDefault userId=%{public}d.", multiuser.userId);
100     if ((multiuser.userId == BConstants::SYSTEM_UID) || (multiuser.userId == BConstants::XTS_UID)) {
101         return BConstants::DEFAULT_USER_ID;
102     }
103     return multiuser.userId;
104 }
105 
OnStart()106 void Service::OnStart()
107 {
108     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
109     HILOGI("SA OnStart Begin.");
110     std::vector<std::string> bundleNameList;
111     if (disposal_ != nullptr) {
112         bundleNameList = disposal_->GetBundleNameFromConfigFile();
113     }
114     std::vector<std::string> residualBundleNameList;
115     if (clearRecorder_ != nullptr) {
116         residualBundleNameList = clearRecorder_->GetAllClearBundleRecords();
117     }
118     if (!bundleNameList.empty() || !residualBundleNameList.empty()) {
119         SetOccupySession(true);
120         session_->Active(
121             {
122                 .clientToken = IPCSkeleton::GetCallingTokenID(),
123                 .scenario = IServiceReverse::Scenario::CLEAN,
124                 .clientProxy = nullptr,
125                 .userId = GetUserIdDefault(),
126             },
127             isOccupyingSession_.load());
128         HILOGI("SA OnStart, cleaning up backup data");
129     }
130     bool res = SystemAbility::Publish(sptr(this));
131     if (sched_ != nullptr) {
132         sched_->StartTimer();
133     }
134     ClearDisposalOnSaStart();
135     auto ret = AppendBundlesClearSession(residualBundleNameList);
136     if (isOccupyingSession_.load() && ret) {
137         SetOccupySession(false);
138         StopAll(nullptr, true);
139     }
140     HILOGI("SA OnStart End, res = %{public}d", res);
141 }
142 
SetOccupySession(bool isOccupyingSession)143 void Service::SetOccupySession(bool isOccupyingSession)
144 {
145     isOccupyingSession_.store(isOccupyingSession);
146 }
147 
OnStop()148 void Service::OnStop()
149 {
150     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
151     HILOGI("SA OnStop Begin.");
152     int32_t oldMemoryParaSize = BConstants::DEFAULT_VFS_CACHE_PRESSURE;
153     if (session_ != nullptr) {
154         oldMemoryParaSize = session_->GetMemParaCurSize();
155     }
156     StorageMgrAdapter::UpdateMemPara(oldMemoryParaSize);
157     HILOGI("SA OnStop End.");
158 }
159 
GetLocalCapabilities()160 UniqueFd Service::GetLocalCapabilities()
161 {
162     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
163     try {
164         /*
165          Only called by restore app before InitBackupSession,
166            so there must be set init userId.
167         */
168         HILOGI("Begin");
169         if (session_ == nullptr || isOccupyingSession_.load()) {
170             HILOGE("GetLocalCapabilities error, session is empty.");
171             return UniqueFd(-EPERM);
172         }
173         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
174         VerifyCaller();
175         string path = BConstants::GetSaBundleBackupRootDir(GetUserIdDefault());
176         BExcepUltils::VerifyPath(path, false);
177         UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR));
178         if (fd < 0) {
179             HILOGE("Failed to open config file = %{private}s, err = %{public}d", path.c_str(), errno);
180             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
181             return UniqueFd(-EPERM);
182         }
183         BJsonCachedEntity<BJsonEntityCaps> cachedEntity(std::move(fd));
184 
185         auto cache = cachedEntity.Structuralize();
186 
187         cache.SetSystemFullName(GetOSFullName());
188         cache.SetDeviceType(GetDeviceType());
189         auto bundleInfos = BundleMgrAdapter::GetFullBundleInfos(GetUserIdDefault());
190         cache.SetBundleInfos(bundleInfos);
191         cachedEntity.Persist();
192         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
193         HILOGI("End");
194         return move(cachedEntity.GetFd());
195     } catch (const BError &e) {
196         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
197         HILOGE("GetLocalCapabilities failed, errCode = %{public}d", e.GetCode());
198         return UniqueFd(-e.GetCode());
199     } catch (const exception &e) {
200         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
201         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
202         return UniqueFd(-EPERM);
203     } catch (...) {
204         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
205         HILOGI("Unexpected exception");
206         return UniqueFd(-EPERM);
207     }
208 }
209 
StopAll(const wptr<IRemoteObject> &obj, bool force)210 void Service::StopAll(const wptr<IRemoteObject> &obj, bool force)
211 {
212     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
213     session_->Deactive(obj, force);
214 }
215 
PermissionCheckFailRadar(const std::string &info, const std::string &func)216 static inline void PermissionCheckFailRadar(const std::string &info, const std::string &func)
217 {
218     std::string funcPos = "Service::";
219     AppRadar::Info resInfo("", "", info);
220     AppRadar::GetInstance().RecordDefaultFuncRes(resInfo, funcPos.append(func),
221                                                  GetUserIdDefault(), BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL,
222                                                  BError(BError::Codes::SA_REFUSED_ACT).GetCode());
223 }
224 
VerifyCallerAndGetCallerName()225 string Service::VerifyCallerAndGetCallerName()
226 {
227     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
228     uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID();
229     int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller);
230     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
231         Security::AccessToken::HapTokenInfo hapTokenInfo;
232         if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) {
233             PermissionCheckFailRadar("Get hap token info failed", "VerifyCallerAndGetCallerName");
234             throw BError(BError::Codes::SA_INVAL_ARG, "Get hap token info failed");
235         }
236         std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(hapTokenInfo.bundleName,
237             hapTokenInfo.instIndex);
238         session_->VerifyBundleName(bundleNameIndexInfo);
239         return bundleNameIndexInfo;
240     } else {
241         string str = to_string(tokenCaller);
242         HILOGE("tokenID = %{private}s", GetAnonyString(str).c_str());
243         std::string info = string("Invalid token type").append(to_string(tokenType)).append(string("\"}"));
244         PermissionCheckFailRadar(info, "VerifyCallerAndGetCallerName");
245         throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType)));
246     }
247 }
248 
VerifyCaller()249 void Service::VerifyCaller()
250 {
251     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
252     uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID();
253     int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller);
254     switch (tokenType) {
255         case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: { /* Update Service */
256             if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) !=
257                 Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
258                 std::string info = "Permission denied, token type is " + to_string(tokenType);
259                 PermissionCheckFailRadar(info, "VerifyCaller");
260                 throw BError(BError::Codes::SA_REFUSED_ACT,
261                     string("Permission denied, token type is ").append(to_string(tokenType)));
262             }
263             break;
264         }
265         case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: {
266             if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) !=
267                 Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
268                 std::string info = "Permission denied, token type is " + to_string(tokenType);
269                 PermissionCheckFailRadar(info, "VerifyCaller");
270                 throw BError(BError::Codes::SA_REFUSED_ACT,
271                     string("Permission denied, token type is ").append(to_string(tokenType)));
272             }
273             uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID();
274             if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) {
275                 std::string info = "Permission denied, token type is " + to_string(tokenType);
276                 PermissionCheckFailRadar(info, "VerifyCaller");
277                 throw BError(BError::Codes::SA_REFUSED_ACT,
278                     string("Permission denied, token type is ").append(to_string(tokenType)));
279             }
280             break;
281         }
282         case Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL:
283             if (IPCSkeleton::GetCallingUid() != BConstants::SYSTEM_UID) {
284                 std::string info = "invalid calling uid";
285                 PermissionCheckFailRadar(info, "VerifyCaller");
286                 throw BError(BError::Codes::SA_REFUSED_ACT, "Calling uid is invalid");
287             }
288             break;
289         default:
290             std::string info = "Permission denied, token type is " + to_string(tokenType);
291             PermissionCheckFailRadar(info, "VerifyCaller");
292             throw BError(BError::Codes::SA_REFUSED_ACT, string("Invalid token type ").append(to_string(tokenType)));
293             break;
294     }
295 }
296 
VerifyCaller(IServiceReverse::Scenario scenario)297 void Service::VerifyCaller(IServiceReverse::Scenario scenario)
298 {
299     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
300     session_->VerifyCallerAndScenario(IPCSkeleton::GetCallingTokenID(), scenario);
301     VerifyCaller();
302 }
303 
InitRestoreSession(sptr<IServiceReverse> remote)304 ErrCode Service::InitRestoreSession(sptr<IServiceReverse> remote)
305 {
306     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
307     try {
308         VerifyCaller();
309         return session_->Active({
310             .clientToken = IPCSkeleton::GetCallingTokenID(),
311             .scenario = IServiceReverse::Scenario::RESTORE,
312             .clientProxy = remote,
313             .userId = GetUserIdDefault(),
314         });
315     } catch (const BError &e) {
316         StopAll(nullptr, true);
317         return e.GetCode();
318     } catch (const exception &e) {
319         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
320         return EPERM;
321     } catch (...) {
322         HILOGI("Unexpected exception");
323         return EPERM;
324     }
325 }
326 
InitBackupSession(sptr<IServiceReverse> remote)327 ErrCode Service::InitBackupSession(sptr<IServiceReverse> remote)
328 {
329     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
330     try {
331         VerifyCaller();
332         int32_t oldSize = StorageMgrAdapter::UpdateMemPara(BConstants::BACKUP_VFS_CACHE_PRESSURE);
333         HILOGE("InitBackupSession oldSize %{public}d", oldSize);
334         session_->SetMemParaCurSize(oldSize);
335         return session_->Active({
336             .clientToken = IPCSkeleton::GetCallingTokenID(),
337             .scenario = IServiceReverse::Scenario::BACKUP,
338             .clientProxy = remote,
339             .userId = GetUserIdDefault(),
340         });
341     } catch (const BError &e) {
342         StopAll(nullptr, true);
343         return e.GetCode();
344     } catch (const exception &e) {
345         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
346         return EPERM;
347     } catch (...) {
348         HILOGI("Unexpected exception");
349         return EPERM;
350     }
351 }
352 
Start()353 ErrCode Service::Start()
354 {
355     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
356     try {
357         VerifyCaller(session_->GetScenario());
358         session_->Start();
359         OnStartSched();
360         return BError(BError::Codes::OK);
361     } catch (const BError &e) {
362         HILOGE("Failde to Start");
363         return e.GetCode();
364     }
365 }
366 
SpecialVersion(const string &versionName)367 static bool SpecialVersion(const string &versionName)
368 {
369     string versionNameFlag = versionName.substr(0, versionName.find_first_of(BConstants::VERSION_NAME_SEPARATOR_CHAR));
370     auto iter = find_if(BConstants::DEFAULT_VERSION_NAMES_VEC.begin(), BConstants::DEFAULT_VERSION_NAMES_VEC.end(),
371                         [&versionNameFlag](const auto &version) { return version == versionNameFlag; });
372     if (iter != BConstants::DEFAULT_VERSION_NAMES_VEC.end()) {
373         return true;
374     }
375     return false;
376 }
377 
OnBundleStarted(BError error, sptr<SvcSessionManager> session, const BundleName &bundleName)378 static void OnBundleStarted(BError error, sptr<SvcSessionManager> session, const BundleName &bundleName)
379 {
380     IServiceReverse::Scenario scenario = session->GetScenario();
381     if (scenario == IServiceReverse::Scenario::RESTORE && BackupPara().GetBackupOverrideIncrementalRestore() &&
382         session->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) {
383         session->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(error, bundleName);
384     } else if (scenario == IServiceReverse::Scenario::RESTORE) {
385         session->GetServiceReverseProxy()->RestoreOnBundleStarted(error, bundleName);
386     }
387 }
388 
GetRestoreBundleNames(UniqueFd fd, sptr<SvcSessionManager> session, const vector<BundleName> &bundleNames)389 static vector<BJsonEntityCaps::BundleInfo> GetRestoreBundleNames(UniqueFd fd,
390                                                                  sptr<SvcSessionManager> session,
391                                                                  const vector<BundleName> &bundleNames)
392 {
393     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
394     // BundleMgrAdapter::GetBundleInfos可能耗时
395     auto restoreInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session->GetSessionUserId());
396     BJsonCachedEntity<BJsonEntityCaps> cachedEntity(move(fd));
397     auto cache = cachedEntity.Structuralize();
398     auto bundleInfos = cache.GetBundleInfos();
399     if (!bundleInfos.size()) {
400         throw BError(BError::Codes::SA_INVAL_ARG, "Json entity caps is empty");
401     }
402     HILOGI("restoreInfos size is:%{public}zu", restoreInfos.size());
403     vector<BJsonEntityCaps::BundleInfo> restoreBundleInfos {};
404     for (auto &restoreInfo : restoreInfos) {
405         if (SAUtils::IsSABundleName(restoreInfo.name)) {
406             BJsonEntityCaps::BundleInfo info = {.name = restoreInfo.name,
407                                                 .appIndex = restoreInfo.appIndex,
408                                                 .versionCode = restoreInfo.versionCode,
409                                                 .versionName = restoreInfo.versionName,
410                                                 .spaceOccupied = restoreInfo.spaceOccupied,
411                                                 .allToBackup = restoreInfo.allToBackup,
412                                                 .fullBackupOnly = restoreInfo.fullBackupOnly,
413                                                 .extensionName = restoreInfo.extensionName,
414                                                 .restoreDeps = restoreInfo.restoreDeps};
415             restoreBundleInfos.emplace_back(info);
416             continue;
417         }
418         auto it = find_if(bundleInfos.begin(), bundleInfos.end(), [&restoreInfo](const auto &obj) {
419             return obj.name == restoreInfo.name && obj.appIndex == restoreInfo.appIndex;
420         });
421         if (it == bundleInfos.end()) {
422             HILOGE("Bundle not need restore, bundleName is %{public}s.", restoreInfo.name.c_str());
423             continue;
424         }
425         BJsonEntityCaps::BundleInfo info = {.name = (*it).name,
426                                             .appIndex = (*it).appIndex,
427                                             .versionCode = (*it).versionCode,
428                                             .versionName = (*it).versionName,
429                                             .spaceOccupied = (*it).spaceOccupied,
430                                             .allToBackup = (*it).allToBackup,
431                                             .fullBackupOnly = (*it).fullBackupOnly,
432                                             .extensionName = restoreInfo.extensionName,
433                                             .restoreDeps = restoreInfo.restoreDeps};
434         restoreBundleInfos.emplace_back(info);
435     }
436     HILOGI("restoreBundleInfos size is:%{public}zu", restoreInfos.size());
437     return restoreBundleInfos;
438 }
439 
HandleExceptionOnAppendBundles(sptr<SvcSessionManager> session, const vector<BundleName> &appendBundleNames, const vector<BundleName> &restoreBundleNames)440 static void HandleExceptionOnAppendBundles(sptr<SvcSessionManager> session,
441     const vector<BundleName> &appendBundleNames, const vector<BundleName> &restoreBundleNames)
442 {
443     if (appendBundleNames.size() != restoreBundleNames.size()) {
444         HILOGE("AppendBundleNames not equal restoreBundleNames, appendBundleNames size:%{public}zu,"
445             "restoreBundleNames size:%{public}zu", appendBundleNames.size(), restoreBundleNames.size());
446         for (auto bundleName : appendBundleNames) {
447             auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(),
448                 [&bundleName](const auto &obj) { return obj == bundleName; });
449             if (it == restoreBundleNames.end()) {
450                 HILOGE("AppendBundles failed, bundleName = %{public}s.", bundleName.c_str());
451                 OnBundleStarted(BError(BError::Codes::SA_BUNDLE_INFO_EMPTY), session, bundleName);
452             }
453         }
454     }
455 }
456 
AppendBundlesRestoreSession(UniqueFd fd, const vector<BundleName> &bundleNames, const std::vector<std::string> &bundleInfos, RestoreTypeEnum restoreType, int32_t userId)457 ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector<BundleName> &bundleNames,
458     const std::vector<std::string> &bundleInfos, RestoreTypeEnum restoreType, int32_t userId)
459 {
460     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
461     HILOGI("Begin");
462     try {
463         if (session_ == nullptr || isOccupyingSession_.load()) {
464             HILOGE("Init Incremental backup session error, session is empty");
465             return BError(BError::Codes::SA_INVAL_ARG);
466         }
467         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
468         session_->SetImplRestoreType(restoreType);
469         if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */
470             session_->SetSessionUserId(userId);
471         } else {
472             session_->SetSessionUserId(GetUserIdDefault());
473         }
474         VerifyCaller(IServiceReverse::Scenario::RESTORE);
475         std::vector<std::string> bundleNamesOnly;
476         std::map<std::string, bool> isClearDataFlags;
477         std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> bundleNameDetailMap =
478             BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly,
479                                         session_->GetSessionUserId(), isClearDataFlags);
480         auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames);
481         auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType);
482         HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames);
483         if (restoreBundleNames.empty()) {
484             HILOGE("AppendBundlesRestoreSession failed, restoreBundleNames is empty.");
485             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
486             return BError(BError::Codes::OK);
487         }
488         session_->AppendBundles(restoreBundleNames);
489         SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap,
490             isClearDataFlags, restoreType);
491         OnStartSched();
492         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
493         HILOGI("End");
494         return BError(BError::Codes::OK);
495     } catch (const BError &e) {
496         HILOGE("Catch exception");
497         HandleExceptionOnAppendBundles(session_, bundleNames, {});
498         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
499         return e.GetCode();
500     } catch (...) {
501         HILOGE("Unexpected exception");
502         HandleExceptionOnAppendBundles(session_, bundleNames, {});
503         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
504         return EPERM;
505     }
506 }
507 
SetCurrentSessProperties(std::vector<BJsonEntityCaps::BundleInfo> &restoreBundleInfos, std::vector<std::string> &restoreBundleNames, RestoreTypeEnum restoreType)508 void Service::SetCurrentSessProperties(std::vector<BJsonEntityCaps::BundleInfo> &restoreBundleInfos,
509     std::vector<std::string> &restoreBundleNames, RestoreTypeEnum restoreType)
510 {
511     HILOGI("Start");
512     for (auto restoreInfo : restoreBundleInfos) {
513         auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), [&restoreInfo](const auto &bundleName) {
514             std::string bundleNameIndex = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex);
515             return bundleName == bundleNameIndex;
516         });
517         if (it == restoreBundleNames.end()) {
518             throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name");
519         }
520         HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(),
521             restoreInfo.extensionName.c_str());
522         std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex);
523         if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) ||
524             (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) {
525             OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, bundleNameIndexInfo);
526             session_->RemoveExtInfo(bundleNameIndexInfo);
527             continue;
528         }
529         session_->SetBundleRestoreType(bundleNameIndexInfo, restoreType);
530         session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode);
531         session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName);
532         session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied);
533         session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName);
534         if (BundleMgrAdapter::IsUser0BundleName(bundleNameIndexInfo, session_->GetSessionUserId())) {
535             SendUserIdToApp(bundleNameIndexInfo, session_->GetSessionUserId());
536         }
537     }
538     HILOGI("End");
539 }
540 
AppendBundlesRestoreSession(UniqueFd fd, const vector<BundleName> &bundleNames, RestoreTypeEnum restoreType, int32_t userId)541 ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd,
542                                              const vector<BundleName> &bundleNames,
543                                              RestoreTypeEnum restoreType,
544                                              int32_t userId)
545 {
546     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
547     try {
548         if (session_ == nullptr || isOccupyingSession_.load()) {
549             HILOGE("Init Incremental backup session error, session is empty");
550             return BError(BError::Codes::SA_INVAL_ARG);
551         }
552         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
553         session_->SetImplRestoreType(restoreType);
554         if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */
555             session_->SetSessionUserId(userId);
556         } else {
557             session_->SetSessionUserId(GetUserIdDefault());
558         }
559         VerifyCaller(IServiceReverse::Scenario::RESTORE);
560         auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames);
561         auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType);
562         HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames);
563         if (restoreBundleNames.empty()) {
564             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
565             HILOGW("RestoreBundleNames is empty.");
566             return BError(BError::Codes::OK);
567         }
568         session_->AppendBundles(restoreBundleNames);
569         SetCurrentSessProperties(restoreInfos, restoreBundleNames, restoreType);
570         OnStartSched();
571         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
572         return BError(BError::Codes::OK);
573     } catch (const BError &e) {
574         HILOGE("Catch exception");
575         HandleExceptionOnAppendBundles(session_, bundleNames, {});
576         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
577         return e.GetCode();
578     } catch (...) {
579         HILOGE("Unexpected exception");
580         HandleExceptionOnAppendBundles(session_, bundleNames, {});
581         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
582         return EPERM;
583     }
584 }
585 
SetCurrentSessProperties(std::vector<BJsonEntityCaps::BundleInfo> &restoreBundleInfos, std::vector<std::string> &restoreBundleNames, std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> &bundleNameDetailMap, std::map<std::string, bool> &isClearDataFlags, RestoreTypeEnum restoreType)586 void Service::SetCurrentSessProperties(std::vector<BJsonEntityCaps::BundleInfo> &restoreBundleInfos,
587     std::vector<std::string> &restoreBundleNames,
588     std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> &bundleNameDetailMap,
589     std::map<std::string, bool> &isClearDataFlags, RestoreTypeEnum restoreType)
590 {
591     HILOGI("Start");
592     for (auto restoreInfo : restoreBundleInfos) {
593         auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(),
594             [&restoreInfo](const auto &bundleName) {
595             std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name,
596                 restoreInfo.appIndex);
597             return bundleName == bundleNameIndexInfo;
598         });
599         if (it == restoreBundleNames.end()) {
600             throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name");
601         }
602         HILOGD("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(),
603             restoreInfo.extensionName.c_str());
604         std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex);
605         if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) ||
606             (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) {
607             OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, bundleNameIndexInfo);
608             session_->RemoveExtInfo(bundleNameIndexInfo);
609             continue;
610         }
611         session_->SetBundleRestoreType(bundleNameIndexInfo, restoreType);
612         session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode);
613         session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName);
614         session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied);
615         session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName);
616         auto iter = isClearDataFlags.find(bundleNameIndexInfo);
617         if (iter != isClearDataFlags.end()) {
618             session_->SetClearDataFlag(bundleNameIndexInfo, iter->second);
619         }
620         BJsonUtil::BundleDetailInfo broadCastInfo;
621         BJsonUtil::BundleDetailInfo uniCastInfo;
622         bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE,
623             broadCastInfo);
624         if (broadCastRet) {
625             bool notifyRet =
626                     DelayedSingleton<NotifyWorkService>::GetInstance()->NotifyBundleDetail(broadCastInfo);
627             HILOGI("Publish event end, notify result is:%{public}d", notifyRet);
628         }
629         bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, UNICAST_TYPE,
630             uniCastInfo);
631         if (uniCastRet) {
632             HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str());
633             session_->SetBackupExtInfo(bundleNameIndexInfo, uniCastInfo.detail);
634         }
635     }
636     HILOGI("End");
637 }
638 
SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info, std::map<std::string, bool> &isClearDataFlags, const std::string &bundleNameIndexInfo)639 void Service::SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info,
640     std::map<std::string, bool> &isClearDataFlags, const std::string &bundleNameIndexInfo)
641 {
642     if (session_ == nullptr) {
643         HILOGE("Set currrent session properties error, session is empty");
644         return;
645     }
646     session_->SetBundleDataSize(bundleNameIndexInfo, info.spaceOccupied);
647     session_->SetBackupExtName(bundleNameIndexInfo, info.extensionName);
648     auto iter = isClearDataFlags.find(bundleNameIndexInfo);
649     if (iter != isClearDataFlags.end()) {
650         session_->SetClearDataFlag(bundleNameIndexInfo, iter->second);
651     }
652 }
653 
AppendBundlesBackupSession(const vector<BundleName> &bundleNames)654 ErrCode Service::AppendBundlesBackupSession(const vector<BundleName> &bundleNames)
655 {
656     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
657     try {
658         if (session_ == nullptr || isOccupyingSession_.load()) {
659             HILOGE("Init Incremental backup session error, session is empty");
660             return BError(BError::Codes::SA_INVAL_ARG);
661         }
662         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时
663         VerifyCaller(IServiceReverse::Scenario::BACKUP);
664         auto bundleDetails = MakeDetailList(bundleNames);
665         auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppend(bundleDetails, session_->GetSessionUserId());
666         session_->AppendBundles(bundleNames);
667         for (auto info : backupInfos) {
668             HILOGI("Current backupInfo bundleName:%{public}s, extName:%{public}s, appIndex:%{public}d",
669                 info.name.c_str(), info.extensionName.c_str(), info.appIndex);
670             std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(info.name, info.appIndex);
671             session_->SetBundleDataSize(bundleNameIndexInfo, info.spaceOccupied);
672             session_->SetBackupExtName(bundleNameIndexInfo, info.extensionName);
673             if (info.allToBackup == false) {
674                 session_->GetServiceReverseProxy()->BackupOnBundleStarted(
675                     BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), bundleNameIndexInfo);
676                 session_->RemoveExtInfo(bundleNameIndexInfo);
677             }
678         }
679         SetCurrentBackupSessProperties(bundleNames, session_->GetSessionUserId());
680         OnStartSched();
681         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
682         return BError(BError::Codes::OK);
683     } catch (const BError &e) {
684         HILOGE("Failed, errCode = %{public}d", e.GetCode());
685         HandleExceptionOnAppendBundles(session_, bundleNames, {});
686         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
687         return e.GetCode();
688     } catch (const exception &e) {
689         HILOGE("Catched an unexpected low-level exception %{public}s", e.what());
690         HandleExceptionOnAppendBundles(session_, bundleNames, {});
691         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
692         return EPERM;
693     } catch (...) {
694         HILOGE("Unexpected exception");
695         HandleExceptionOnAppendBundles(session_, bundleNames, {});
696         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
697         return EPERM;
698     }
699 }
700 
AppendBundlesDetailsBackupSession(const vector<BundleName> &bundleNames, const vector<std::string> &bundleInfos)701 ErrCode Service::AppendBundlesDetailsBackupSession(const vector<BundleName> &bundleNames,
702     const vector<std::string> &bundleInfos)
703 {
704     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
705     try {
706         if (session_ == nullptr || isOccupyingSession_.load()) {
707             HILOGE("Init Incremental backup session error, session is empty");
708             return BError(BError::Codes::SA_INVAL_ARG);
709         }
710         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时
711         VerifyCaller(IServiceReverse::Scenario::BACKUP);
712         std::vector<std::string> bundleNamesOnly;
713         std::map<std::string, bool> isClearDataFlags;
714         std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> bundleNameDetailMap =
715             BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly,
716             session_->GetSessionUserId(), isClearDataFlags);
717         auto bundleDetails = MakeDetailList(bundleNames);
718         auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppend(bundleDetails, session_->GetSessionUserId());
719         session_->AppendBundles(bundleNames);
720         HandleCurGroupBackupInfos(backupInfos, bundleNameDetailMap, isClearDataFlags);
721         OnStartSched();
722         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
723         return BError(BError::Codes::OK);
724     } catch (const BError &e) {
725         HILOGE("Failed, errCode = %{public}d", e.GetCode());
726         HandleExceptionOnAppendBundles(session_, bundleNames, {});
727         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
728         return e.GetCode();
729     } catch(...) {
730         HILOGE("Unexpected exception");
731         HandleExceptionOnAppendBundles(session_, bundleNames, {});
732         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
733         return EPERM;
734     }
735 }
736 
HandleCurGroupBackupInfos(std::vector<BJsonEntityCaps::BundleInfo> &backupInfos, std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> &bundleNameDetailMap, std::map<std::string, bool> &isClearDataFlags)737 void Service::HandleCurGroupBackupInfos(std::vector<BJsonEntityCaps::BundleInfo> &backupInfos,
738     std::map<std::string, std::vector<BJsonUtil::BundleDetailInfo>> &bundleNameDetailMap,
739     std::map<std::string, bool> &isClearDataFlags)
740 {
741     for (auto &info : backupInfos) {
742         HILOGI("Current backupInfo bundleName:%{public}s, extName:%{public}s, appIndex:%{public}d",
743             info.name.c_str(), info.extensionName.c_str(), info.appIndex);
744         std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(info.name, info.appIndex);
745         SetCurrentSessProperties(info, isClearDataFlags, bundleNameIndexInfo);
746         if (info.allToBackup == false) {
747             session_->GetServiceReverseProxy()->BackupOnBundleStarted(
748                 BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), bundleNameIndexInfo);
749             session_->RemoveExtInfo(bundleNameIndexInfo);
750         }
751         BJsonUtil::BundleDetailInfo uniCastInfo;
752         if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, UNICAST_TYPE, uniCastInfo)) {
753             HILOGI("current bundle:%{public}s, unicast info:%{public}s", bundleNameIndexInfo.c_str(),
754                 GetAnonyString(uniCastInfo.detail).c_str());
755             session_->SetBackupExtInfo(bundleNameIndexInfo, uniCastInfo.detail);
756         }
757     }
758 }
759 
ServiceResultReport(const std::string restoreRetInfo, BackupRestoreScenario sennario, ErrCode errCode)760 ErrCode Service::ServiceResultReport(const std::string restoreRetInfo,
761     BackupRestoreScenario sennario, ErrCode errCode)
762 {
763     string callerName = "";
764     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
765     try {
766         callerName = VerifyCallerAndGetCallerName();
767         if (sennario == BackupRestoreScenario::FULL_RESTORE) {
768             session_->GetServiceReverseProxy()->RestoreOnResultReport(restoreRetInfo, callerName, errCode);
769             NotifyCloneBundleFinish(callerName, sennario);
770         } else if (sennario == BackupRestoreScenario::INCREMENTAL_RESTORE) {
771             session_->GetServiceReverseProxy()->IncrementalRestoreOnResultReport(restoreRetInfo, callerName, errCode);
772             NotifyCloneBundleFinish(callerName, sennario);
773         } else if (sennario == BackupRestoreScenario::FULL_BACKUP) {
774             session_->GetServiceReverseProxy()->BackupOnResultReport(restoreRetInfo, callerName);
775         } else if (sennario == BackupRestoreScenario::INCREMENTAL_BACKUP) {
776             session_->GetServiceReverseProxy()->IncrementalBackupOnResultReport(restoreRetInfo, callerName);
777         }
778         return BError(BError::Codes::OK);
779     } catch (const BError &e) {
780         NotifyCloneBundleFinish(callerName, sennario);
781         return e.GetCode(); // 任意异常产生,终止监听该任务
782     } catch (const exception &e) {
783         NotifyCloneBundleFinish(callerName, sennario);
784         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
785         return EPERM;
786     } catch (...) {
787         NotifyCloneBundleFinish(callerName, sennario);
788         HILOGI("Unexpected exception");
789         return EPERM;
790     }
791 }
792 
SAResultReport(const std::string bundleName, const std::string restoreRetInfo, const ErrCode errCode, const BackupRestoreScenario sennario)793 ErrCode Service::SAResultReport(const std::string bundleName, const std::string restoreRetInfo,
794     const ErrCode errCode, const BackupRestoreScenario sennario)
795 {
796     if (sennario == BackupRestoreScenario::FULL_RESTORE) {
797         session_->GetServiceReverseProxy()->RestoreOnResultReport(restoreRetInfo, bundleName);
798     } else if (sennario == BackupRestoreScenario::INCREMENTAL_RESTORE) {
799         session_->GetServiceReverseProxy()->IncrementalRestoreOnResultReport(restoreRetInfo, bundleName);
800     } else if (sennario == BackupRestoreScenario::FULL_BACKUP) {
801         session_->GetServiceReverseProxy()->BackupOnResultReport(restoreRetInfo, bundleName);
802         session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, bundleName);
803     } else if (sennario == BackupRestoreScenario::INCREMENTAL_BACKUP) {
804         session_->GetServiceReverseProxy()->IncrementalBackupOnResultReport(restoreRetInfo, bundleName);
805     }
806     return SADone(errCode, bundleName);
807 }
808 
NotifyCloneBundleFinish(std::string bundleName, const BackupRestoreScenario sennario)809 void Service::NotifyCloneBundleFinish(std::string bundleName, const BackupRestoreScenario sennario)
810 {
811     try {
812         if (sennario != BackupRestoreScenario::FULL_RESTORE &&
813             sennario != BackupRestoreScenario::INCREMENTAL_RESTORE) {
814             return;
815         }
816         if (session_->OnBundleFileReady(bundleName)) {
817             std::shared_ptr<ExtensionMutexInfo> mutexPtr = GetExtensionMutex(bundleName);
818             if (mutexPtr == nullptr) {
819                 HILOGE("extension mutex ptr is nullptr");
820                 return;
821             }
822             std::lock_guard<std::mutex> lock(mutexPtr->callbackMutex);
823             auto backUpConnection = session_->GetExtConnection(bundleName);
824             if (backUpConnection == nullptr) {
825                 throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty");
826             }
827             auto proxy = backUpConnection->GetBackupExtProxy();
828             if (!proxy) {
829                 throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty");
830             }
831             proxy->HandleClear();
832             session_->StopFwkTimer(bundleName);
833             session_->StopExtTimer(bundleName);
834             backUpConnection->DisconnectBackupExtAbility();
835             ClearSessionAndSchedInfo(bundleName);
836         }
837         RemoveExtensionMutex(bundleName);
838         SendEndAppGalleryNotify(bundleName);
839         OnAllBundlesFinished(BError(BError::Codes::OK));
840     } catch (...) {
841         HILOGI("Unexpected exception");
842         ReleaseOnException();
843     }
844 }
845 
LaunchBackupSAExtension(const BundleName &bundleName)846 ErrCode Service::LaunchBackupSAExtension(const BundleName &bundleName)
847 {
848     string extInfo = session_->GetBackupExtInfo(bundleName);
849     IServiceReverse::Scenario scenario = session_->GetScenario();
850     if (SAUtils::IsSABundleName(bundleName)) {
851         auto saBackUpConnection = session_->GetSAExtConnection(bundleName);
852         std::shared_ptr<SABackupConnection> saConnection = saBackUpConnection.lock();
853         if (saConnection == nullptr) {
854             HILOGE("lock sa connection ptr is nullptr");
855             return BError(BError::Codes::SA_INVAL_ARG);
856         }
857         if (scenario == IServiceReverse::Scenario::BACKUP) {
858             return saConnection->ConnectBackupSAExt(bundleName, BConstants::EXTENSION_BACKUP, extInfo);
859         } else if (scenario == IServiceReverse::Scenario::RESTORE) {
860             return saConnection->ConnectBackupSAExt(bundleName, BConstants::EXTENSION_RESTORE, extInfo);
861         }
862     }
863     return BError(BError::Codes::OK);
864 }
865 
GetFileHandle(const string &bundleName, const string &fileName)866 ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName)
867 {
868     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
869     try {
870         VerifyCaller(IServiceReverse::Scenario::RESTORE);
871 
872         bool updateRes = SvcRestoreDepsManager::GetInstance().UpdateToRestoreBundleMap(bundleName, fileName);
873         if (updateRes) {
874             return BError(BError::Codes::OK);
875         }
876         auto action = session_->GetServiceSchedAction(bundleName);
877         if (action == BConstants::ServiceSchedAction::RUNNING) {
878             auto backUpConnection = session_->GetExtConnection(bundleName);
879             if (backUpConnection == nullptr) {
880                 HILOGE("GetFileHandle error, backUpConnection is empty");
881                 return BError(BError::Codes::SA_INVAL_ARG);
882             }
883             auto proxy = backUpConnection->GetBackupExtProxy();
884             if (!proxy) {
885                 HILOGE("GetFileHandle error, Extension backup Proxy is empty");
886                 return BError(BError::Codes::SA_INVAL_ARG);
887             }
888             int32_t errCode = 0;
889             UniqueFd fd = proxy->GetFileHandle(fileName, errCode);
890             if (errCode != ERR_OK) {
891                 AppRadar::Info info (bundleName, "", "");
892                 AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::GetFileHandle", GetUserIdDefault(),
893                     BizStageRestore::BIZ_STAGE_GET_FILE_HANDLE_FAIL, errCode);
894             }
895             session_->GetServiceReverseProxy()->RestoreOnFileReady(bundleName, fileName, move(fd), errCode);
896         } else {
897             session_->SetExtFileNameRequest(bundleName, fileName);
898         }
899         return BError(BError::Codes::OK);
900     } catch (const BError &e) {
901         return e.GetCode();
902     } catch (const exception &e) {
903         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
904         return EPERM;
905     } catch (...) {
906         HILOGI("Unexpected exception");
907         return EPERM;
908     }
909 }
910 
OnBackupExtensionDied(const string &&bundleName, bool isSecondCalled)911 void Service::OnBackupExtensionDied(const string &&bundleName, bool isSecondCalled)
912 {
913     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
914     if (isSecondCalled) {
915         HILOGE("Backup <%{public}s> Extension Process second Died", bundleName.c_str());
916         ClearSessionAndSchedInfo(bundleName);
917         OnAllBundlesFinished(BError(BError::Codes::OK));
918         return;
919     }
920     int32_t errCode = BError(BError::Codes::EXT_ABILITY_DIED).GetCode();
921     AppRadar::Info info (bundleName, "", "");
922     if (session_->GetScenario() == IServiceReverse::Scenario::BACKUP) {
923         AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::OnBackupExtensionDied", GetUserIdDefault(),
924                                                     BizStageBackup::BIZ_STAGE_EXTENSION_ABNORMAL_EXIT, errCode);
925     } else if (session_->GetScenario() == IServiceReverse::Scenario::RESTORE) {
926         AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::OnBackupExtensionDied", GetUserIdDefault(),
927                                                      BizStageRestore::BIZ_STAGE_EXTENSION_ABNORMAL_EXIT, errCode);
928     }
929     try {
930         string callName = move(bundleName);
931         HILOGE("Backup <%{public}s> Extension Process Died", callName.c_str());
932         session_->VerifyBundleName(callName);
933         // 重新连接清理缓存
934         HILOGI("Clear backup extension data, bundleName: %{public}s", callName.c_str());
935         ExtConnectDied(callName);
936     } catch (...) {
937         HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str());
938         ExtConnectDied(bundleName);
939         return;
940     }
941 }
942 
ExtConnectDied(const string &callName)943 void Service::ExtConnectDied(const string &callName)
944 {
945     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
946     try {
947         HILOGI("Begin, bundleName: %{public}s", callName.c_str());
948         std::shared_ptr<ExtensionMutexInfo> mutexPtr = GetExtensionMutex(callName);
949         if (mutexPtr == nullptr) {
950             HILOGE("extension mutex ptr is nullptr");
951             return;
952         }
953         std::lock_guard<std::mutex> lock(mutexPtr->callbackMutex);
954         /* Clear Timer */
955         session_->StopFwkTimer(callName);
956         session_->StopExtTimer(callName);
957         auto backUpConnection = session_->GetExtConnection(callName);
958         if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) {
959             backUpConnection->DisconnectBackupExtAbility();
960         }
961         session_->SetServiceSchedAction(callName, BConstants::ServiceSchedAction::CLEAN);
962         auto ret = LaunchBackupExtension(callName);
963         if (ret) {
964             /* Clear Session before notice client finish event */
965             ClearSessionAndSchedInfo(callName);
966         }
967         /* Notice Client Ext Ability Process Died */
968         NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED));
969     } catch (...) {
970         HILOGE("Unexpected exception, bundleName: %{public}s", callName.c_str());
971         ClearSessionAndSchedInfo(callName);
972         NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED));
973     }
974     RemoveExtensionMutex(callName);
975 }
976 
ExtStart(const string &bundleName)977 void Service::ExtStart(const string &bundleName)
978 {
979     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
980     try {
981         HILOGE("begin ExtStart, bundle name:%{public}s", bundleName.data());
982         if (SAUtils::IsSABundleName(bundleName)) {
983             BackupSA(bundleName);
984             return;
985         }
986         if (IncrementalBackup(bundleName)) {
987             return;
988         }
989         IServiceReverse::Scenario scenario = session_->GetScenario();
990         auto backUpConnection = session_->GetExtConnection(bundleName);
991         if (backUpConnection == nullptr) {
992             throw BError(BError::Codes::SA_INVAL_ARG, "ExtStart bundle task error, backUpConnection is empty");
993         }
994         auto proxy = backUpConnection->GetBackupExtProxy();
995         if (!proxy) {
996             throw BError(BError::Codes::SA_INVAL_ARG, "ExtStart bundle task error, Extension backup Proxy is empty");
997         }
998         if (scenario == IServiceReverse::Scenario::BACKUP) {
999             auto ret = proxy->HandleBackup(session_->GetClearDataFlag(bundleName));
1000             session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName);
1001             if (ret) {
1002                 ClearSessionAndSchedInfo(bundleName);
1003                 NoticeClientFinish(bundleName, BError(BError::Codes::SA_INVAL_ARG));
1004             }
1005             return;
1006         }
1007         if (scenario != IServiceReverse::Scenario::RESTORE) {
1008             throw BError(BError::Codes::SA_INVAL_ARG, "Failed to scenario");
1009         }
1010         auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName));
1011         session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName);
1012         auto fileNameVec = session_->GetExtFileNameRequest(bundleName);
1013         for (auto &fileName : fileNameVec) {
1014             int32_t errCode = 0;
1015             UniqueFd fd = proxy->GetFileHandle(fileName, errCode);
1016             session_->GetServiceReverseProxy()->RestoreOnFileReady(bundleName, fileName, move(fd), errCode);
1017         }
1018         return;
1019     } catch (...) {
1020         HILOGI("Unexpected exception, bundleName: %{public}s", bundleName.c_str());
1021         ClearSessionAndSchedInfo(bundleName);
1022         NoticeClientFinish(bundleName, BError(BError::Codes::SA_INVAL_ARG));
1023         return;
1024     }
1025 }
1026 
Dump(int fd, const vector<u16string> &args)1027 int Service::Dump(int fd, const vector<u16string> &args)
1028 {
1029     if (fd < 0) {
1030         HILOGI("HiDumper handle invalid");
1031         return -1;
1032     }
1033 
1034     session_->DumpInfo(fd, args);
1035     return 0;
1036 }
1037 
ReportOnExtConnectFailed(const IServiceReverse::Scenario scenario, const std::string &bundleName, const ErrCode ret)1038 void Service::ReportOnExtConnectFailed(const IServiceReverse::Scenario scenario,
1039     const std::string &bundleName, const ErrCode ret)
1040 {
1041     try {
1042         if (session_ == nullptr) {
1043             HILOGE("Report extConnectfailed error, session info is empty");
1044             return;
1045         }
1046         if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) {
1047             session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(ret, bundleName);
1048         } else if (scenario == IServiceReverse::Scenario::RESTORE &&
1049                    BackupPara().GetBackupOverrideIncrementalRestore() &&
1050                    session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) {
1051             session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(ret, bundleName);
1052 
1053             DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName);
1054             HILOGI("ExtConnectFailed EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr,
1055                    bundleName.c_str());
1056         } else if (scenario == IServiceReverse::Scenario::BACKUP) {
1057             session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName);
1058         } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1059             session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName);
1060             DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName);
1061             HILOGI("ExtConnectFailed EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr,
1062                    bundleName.c_str());
1063         }
1064     } catch (...) {
1065         HILOGE("Report extConnectfailed error");
1066     }
1067 }
1068 
ExtConnectFailed(const string &bundleName, ErrCode ret)1069 void Service::ExtConnectFailed(const string &bundleName, ErrCode ret)
1070 {
1071     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1072     IServiceReverse::Scenario scenario = IServiceReverse::Scenario::UNDEFINED;
1073     try {
1074         HILOGE("begin %{public}s", bundleName.data());
1075         scenario = session_->GetScenario();
1076         AppRadar::Info info (bundleName, "", "");
1077         if (scenario == IServiceReverse::Scenario::BACKUP) {
1078             AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::ExtConnectFailed", GetUserIdDefault(),
1079                                                         BizStageBackup::BIZ_STAGE_CONNECT_EXTENSION_FAIL, ret);
1080         } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1081             AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::ExtConnectFailed", GetUserIdDefault(),
1082                                                          BizStageRestore::BIZ_STAGE_CONNECT_EXTENSION_FAIL, ret);
1083         }
1084         ReportOnExtConnectFailed(scenario, bundleName, ret);
1085         ClearSessionAndSchedInfo(bundleName);
1086         NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_DIED));
1087         return;
1088     } catch (const BError &e) {
1089         return;
1090     } catch (const exception &e) {
1091         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
1092         return;
1093     } catch (...) {
1094         HILOGI("Unexpected exception");
1095         return;
1096     }
1097 }
1098 
NoticeClientFinish(const string &bundleName, ErrCode errCode)1099 void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode)
1100 {
1101     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1102     HILOGI("begin %{public}s", bundleName.c_str());
1103     try {
1104         auto scenario = session_->GetScenario();
1105         if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) {
1106             session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName);
1107         } else if (scenario == IServiceReverse::Scenario::RESTORE &&
1108                 BackupPara().GetBackupOverrideIncrementalRestore() &&
1109                 session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) {
1110             session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleFinished(errCode, bundleName);
1111         } else if (scenario == IServiceReverse::Scenario::BACKUP) {
1112             session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, bundleName);
1113         } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1114             session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, bundleName);
1115         };
1116         /* If all bundle ext process finish, notice client. */
1117         OnAllBundlesFinished(BError(BError::Codes::OK));
1118     } catch(const BError &e) {
1119         ReleaseOnException();
1120     } catch (...) {
1121         ReleaseOnException();
1122         HILOGI("Unexpected exception");
1123         return;
1124     }
1125 }
1126 
ExtConnectDone(string bundleName)1127 void Service::ExtConnectDone(string bundleName)
1128 {
1129     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1130     try {
1131         HILOGE("begin %{public}s", bundleName.data());
1132         auto timeoutCallback = TimeOutCallback(wptr<Service>(this), bundleName);
1133         auto scenario = session_->GetScenario();
1134         if (scenario == IServiceReverse::Scenario::BACKUP) {
1135             session_->StartExtTimer(bundleName, timeoutCallback);
1136         } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1137             session_->StartFwkTimer(bundleName, timeoutCallback);
1138         }
1139 
1140         BConstants::ServiceSchedAction curSchedAction = session_->GetServiceSchedAction(bundleName);
1141         if (curSchedAction == BConstants::ServiceSchedAction::CLEAN) {
1142             sched_->Sched(bundleName);
1143             return;
1144         }
1145         if (curSchedAction == BConstants::ServiceSchedAction::START &&
1146             clearRecorder_->FindClearBundleRecord(bundleName)) {
1147             session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::CLEAN);
1148         } else {
1149             session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::RUNNING);
1150             AddClearBundleRecord(bundleName);
1151         }
1152         sched_->Sched(bundleName);
1153     } catch (...) {
1154         HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str());
1155         ClearSessionAndSchedInfo(bundleName);
1156         NoticeClientFinish(bundleName, BError(BError::Codes::SDK_INVAL_ARG));
1157         return;
1158     }
1159 }
1160 
ClearSessionAndSchedInfo(const string &bundleName)1161 void Service::ClearSessionAndSchedInfo(const string &bundleName)
1162 {
1163     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1164     try {
1165         HILOGI("begin %{public}s", bundleName.c_str());
1166         session_->RemoveExtInfo(bundleName);
1167         sched_->RemoveExtConn(bundleName);
1168         HandleRestoreDepsBundle(bundleName);
1169         DelClearBundleRecord({bundleName});
1170         if (isOccupyingSession_.load() && session_->IsOnAllBundlesFinished()) {
1171             SetOccupySession(false);
1172             StopAll(nullptr, true);
1173             return;
1174         }
1175         sched_->Sched();
1176     } catch (const BError &e) {
1177         return;
1178     } catch (const exception &e) {
1179         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
1180         return;
1181     } catch (...) {
1182         HILOGI("Unexpected exception");
1183         return;
1184     }
1185 }
1186 
HandleRestoreDepsBundle(const string &bundleName)1187 void Service::HandleRestoreDepsBundle(const string &bundleName)
1188 {
1189     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1190     if (session_->GetScenario() != IServiceReverse::Scenario::RESTORE) {
1191         return;
1192     }
1193     HILOGI("Begin, bundleName: %{public}s", bundleName.c_str());
1194     SvcRestoreDepsManager::GetInstance().AddRestoredBundles(bundleName);
1195     // 该应用恢复完成,判断依赖hap的前置hap是否全部恢复完成,如果成了,追加该依赖hap
1196     auto restoreBundleMap = SvcRestoreDepsManager::GetInstance().GetRestoreBundleMap();
1197     if (restoreBundleMap.empty()) {
1198         HILOGI("restoreBundleMap is empty.");
1199         return;
1200     }
1201     // 启动恢复会话
1202     vector<string> restoreBundleNames {};
1203     for (const auto &bundle : restoreBundleMap) {
1204         HILOGI("Start restore session, bundle: %{public}s", bundle.first.c_str());
1205         restoreBundleNames.emplace_back(bundle.first);
1206     }
1207     session_->AppendBundles(restoreBundleNames);
1208     for (const auto &bundle : restoreBundleMap) {
1209         for (auto &bundleInfo : SvcRestoreDepsManager::GetInstance().GetAllBundles()) {
1210             if (bundle.first != bundleInfo.name) {
1211                 continue;
1212             }
1213             SvcRestoreDepsManager::RestoreInfo info = bundle.second;
1214             session_->SetBundleRestoreType(bundleInfo.name, info.restoreType_);
1215             session_->SetBundleVersionCode(bundleInfo.name, bundleInfo.versionCode);
1216             session_->SetBundleVersionName(bundleInfo.name, bundleInfo.versionName);
1217             session_->SetBundleDataSize(bundleInfo.name, bundleInfo.spaceOccupied);
1218             session_->SetBackupExtName(bundleInfo.name, bundleInfo.extensionName);
1219             for (auto &fileName : info.fileNames_) {
1220                 session_->SetExtFileNameRequest(bundleInfo.name, fileName);
1221             }
1222         }
1223     }
1224     HILOGI("End");
1225 }
1226 
OnAllBundlesFinished(ErrCode errCode)1227 void Service::OnAllBundlesFinished(ErrCode errCode)
1228 {
1229     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1230     HILOGI("called begin.");
1231     if (session_->IsOnAllBundlesFinished()) {
1232         IServiceReverse::Scenario scenario = session_->GetScenario();
1233         if (isInRelease_.load() && (scenario == IServiceReverse::Scenario::RESTORE)) {
1234             SessionDeactive();
1235         }
1236         if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) {
1237             session_->GetServiceReverseProxy()->IncrementalBackupOnAllBundlesFinished(errCode);
1238         } else if (scenario == IServiceReverse::Scenario::RESTORE &&
1239                    BackupPara().GetBackupOverrideIncrementalRestore() &&
1240                    session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) {
1241             session_->GetServiceReverseProxy()->IncrementalRestoreOnAllBundlesFinished(errCode);
1242         } else if (scenario == IServiceReverse::Scenario::BACKUP) {
1243             session_->GetServiceReverseProxy()->BackupOnAllBundlesFinished(errCode);
1244         } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1245             session_->GetServiceReverseProxy()->RestoreOnAllBundlesFinished(errCode);
1246         }
1247         if (!BackupPara().GetBackupOverrideBackupSARelease()) {
1248             sched_->TryUnloadServiceTimer(true);
1249         }
1250     }
1251     HILOGI("called end.");
1252 }
1253 
OnStartSched()1254 void Service::OnStartSched()
1255 {
1256     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1257     if (session_->IsOnOnStartSched()) {
1258         for (int num = 0; num < BConstants::EXT_CONNECT_MAX_COUNT; num++) {
1259             sched_->Sched();
1260         }
1261     }
1262 }
1263 
SendStartAppGalleryNotify(const BundleName &bundleName)1264 void Service::SendStartAppGalleryNotify(const BundleName &bundleName)
1265 {
1266     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1267     if (SAUtils::IsSABundleName(bundleName)) {
1268         HILOGI("SA does not need to StartRestore");
1269         return;
1270     }
1271     IServiceReverse::Scenario scenario = session_->GetScenario();
1272     if (scenario != IServiceReverse::Scenario::RESTORE) {
1273         return;
1274     }
1275     if (!disposal_->IfBundleNameInDisposalConfigFile(bundleName)) {
1276         HILOGE("WriteDisposalConfigFile Failed");
1277         return;
1278     }
1279     HILOGI("AppendIntoDisposalConfigFile OK, bundleName=%{public}s", bundleName.c_str());
1280     DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->StartRestore(bundleName);
1281     HILOGI("StartRestore, code=%{public}d, bundleName=%{public}s", disposeErr,
1282         bundleName.c_str());
1283 }
1284 
SendEndAppGalleryNotify(const BundleName &bundleName)1285 void Service::SendEndAppGalleryNotify(const BundleName &bundleName)
1286 {
1287     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1288     if (SAUtils::IsSABundleName(bundleName)) {
1289         HILOGI("SA does not need to EndRestore");
1290         return;
1291     }
1292     IServiceReverse::Scenario scenario = session_->GetScenario();
1293     if (scenario != IServiceReverse::Scenario::RESTORE) {
1294         return;
1295     }
1296     DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName);
1297     HILOGI("EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr,
1298         bundleName.c_str());
1299     if (disposeErr != DisposeErr::OK) {
1300         HILOGE("Error, disposal will be clear in the end");
1301         return;
1302     }
1303     if (!disposal_->DeleteFromDisposalConfigFile(bundleName)) {
1304         HILOGE("DeleteFromDisposalConfigFile Failed, bundleName=%{public}s", bundleName.c_str());
1305         return;
1306     }
1307     HILOGI("DeleteFromDisposalConfigFile OK, bundleName=%{public}s", bundleName.c_str());
1308 }
1309 
TryToClearDispose(const BundleName &bundleName)1310 void Service::TryToClearDispose(const BundleName &bundleName)
1311 {
1312     int32_t maxAtt = MAX_TRY_CLEAR_DISPOSE_NUM;
1313     int32_t att = 0;
1314     while (att < maxAtt) {
1315         DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName);
1316         HILOGI("EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr, bundleName.c_str());
1317         if (disposeErr == DisposeErr::OK) {
1318             break;
1319         }
1320         ++ att;
1321         HILOGI("Try to clear dispose, num = %{public}d", att);
1322     }
1323     if (!disposal_->DeleteFromDisposalConfigFile(bundleName)) {
1324         HILOGE("DeleteFromDisposalConfigFile Failed, bundleName=%{public}s", bundleName.c_str());
1325     }
1326 }
1327 
SendErrAppGalleryNotify()1328 void Service::SendErrAppGalleryNotify()
1329 {
1330     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1331     IServiceReverse::Scenario scenario = session_->GetScenario();
1332     if (scenario != IServiceReverse::Scenario::RESTORE) {
1333         return;
1334     }
1335     vector<string> bundleNameList = disposal_->GetBundleNameFromConfigFile();
1336     if (bundleNameList.empty()) {
1337         HILOGI("End, All disposal pasitions have been cleared");
1338         return;
1339     }
1340     for (vector<string>::iterator it = bundleNameList.begin(); it != bundleNameList.end(); ++it) {
1341         string bundleName = *it;
1342         TryToClearDispose(bundleName);
1343     }
1344 }
1345 
ClearDisposalOnSaStart()1346 void Service::ClearDisposalOnSaStart()
1347 {
1348     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1349     vector<string> bundleNameList = disposal_->GetBundleNameFromConfigFile();
1350     if (!bundleNameList.empty()) {
1351         for (vector<string>::iterator it = bundleNameList.begin(); it != bundleNameList.end(); ++it) {
1352             string bundleName = *it;
1353             TryToClearDispose(bundleName);
1354         }
1355     }
1356     HILOGI("SA start, All Errdisposal pasitions have been cleared");
1357 }
1358 
DeleteDisConfigFile()1359 void Service::DeleteDisConfigFile()
1360 {
1361     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1362     IServiceReverse::Scenario scenario = session_->GetScenario();
1363     if (scenario != IServiceReverse::Scenario::RESTORE) {
1364         return;
1365     }
1366     vector<string> bundleNameList = disposal_->GetBundleNameFromConfigFile();
1367     if (!bundleNameList.empty()) {
1368         HILOGE("DisposalConfigFile is not empty");
1369         return;
1370     }
1371     if (!disposal_->DeleteConfigFile()) {
1372         HILOGE("DeleteConfigFile failed");
1373     }
1374 }
1375 
SessionDeactive()1376 void Service::SessionDeactive()
1377 {
1378     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1379     try {
1380         HILOGI("Begin");
1381         isInRelease_.store(true);
1382         //清理处置状态
1383         if (session_ == nullptr) {
1384             HILOGE("Session deactive error, session is empty");
1385             return;
1386         }
1387         ErrCode ret = BError(BError::Codes::OK);
1388         std::vector<std::string> bundleNameList;
1389         if (session_->GetScenario() == IServiceReverse::Scenario::RESTORE &&
1390             session_->CleanAndCheckIfNeedWait(ret, bundleNameList)) {
1391             if (ret != ERR_OK) {
1392                 isRmConfigFile_.store(false);
1393             }
1394             if (!bundleNameList.empty()) {
1395                 DelClearBundleRecord(bundleNameList);
1396             }
1397             return;
1398         }
1399         isInRelease_.store(false);
1400         if (!bundleNameList.empty()) {
1401             DelClearBundleRecord(bundleNameList);
1402         }
1403         SendErrAppGalleryNotify();
1404         DeleteDisConfigFile();
1405         // 结束定时器
1406         if (sched_ == nullptr) {
1407             HILOGE("Session deactive error, sched is empty");
1408             return;
1409         }
1410         sched_->ClearSchedulerData();
1411         // 清除缓存数据
1412         if (session_ == nullptr) {
1413             HILOGE("Session deactive error, session is empty");
1414             return;
1415         }
1416         ret = session_->ClearSessionData();
1417         if (clearRecorder_ != nullptr && !ret && isRmConfigFile_.load()) {
1418             clearRecorder_->DeleteConfigFile();
1419         }
1420         // close session
1421         StopAll(nullptr, true);
1422         if (session_->GetSessionCnt() <= 0) {
1423             HILOGI("do unload Service.");
1424             sched_->TryUnloadService();
1425         }
1426     } catch (...) {
1427         HILOGE("Unexpected exception");
1428         return;
1429     }
1430 }
1431 
GetBackupInfoConnectDone(wptr<Service> obj, std::string &bundleName)1432 std::function<void(const std::string &&)> Service::GetBackupInfoConnectDone(wptr<Service> obj, std::string &bundleName)
1433 {
1434     return [obj](const string &&bundleName) {
1435         HILOGI("GetBackupInfoConnectDone, bundleName: %{public}s", bundleName.c_str());
1436         auto thisPtr = obj.promote();
1437         if (!thisPtr) {
1438             HILOGW("this pointer is null.");
1439             return;
1440         }
1441         thisPtr->getBackupInfoCondition_.notify_one();
1442     };
1443 }
1444 
GetBackupInfoConnectDied( wptr<Service> obj, std::string &bundleName)1445 std::function<void(const std::string &&, bool)> Service::GetBackupInfoConnectDied(
1446     wptr<Service> obj, std::string &bundleName)
1447 {
1448     return [obj](const string &&bundleName, bool isSecondCalled) {
1449         HILOGI("GetBackupInfoConnectDied, bundleName: %{public}s", bundleName.c_str());
1450         auto thisPtr = obj.promote();
1451         if (!thisPtr) {
1452             HILOGW("this pointer is null.");
1453             return;
1454         }
1455         thisPtr->isConnectDied_.store(true);
1456         thisPtr->getBackupInfoCondition_.notify_one();
1457     };
1458 }
1459 
1460 void Service::ClearResidualBundleData(const std::string &bundleName)
1461 {
1462     if (session_ == nullptr) {
1463         return;
1464     }
1465     auto backUpConnection = session_->GetExtConnection(bundleName);
1466     if (backUpConnection == nullptr) {
1467         throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty");
1468     }
1469     auto proxy = backUpConnection->GetBackupExtProxy();
1470     if (!proxy) {
1471         throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty");
1472     }
1473     // 通知ext清理
1474     proxy->HandleClear();
1475     if (backUpConnection->IsExtAbilityConnected()) {
1476         backUpConnection->DisconnectBackupExtAbility();
1477     }
1478     ClearSessionAndSchedInfo(bundleName);
1479     // 非清理任务,需要上报
1480     if (session_->GetScenario() != IServiceReverse::Scenario::CLEAN) {
1481         OnAllBundlesFinished(BError(BError::Codes::OK));
1482     }
1483 }
1484 
1485 ErrCode Service::GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result)
1486 {
1487     if (session_ == nullptr) {
1488         HILOGE("Get BackupInfo error, session is empty.");
1489         return BError(BError::Codes::SA_INVAL_ARG);
1490     }
1491     auto backupConnection = session_->CreateBackupConnection(bundleName);
1492     if (backupConnection == nullptr) {
1493         HILOGE("backupConnection is null. bundleName: %{public}s", bundleName.c_str());
1494         return BError(BError::Codes::SA_INVAL_ARG);
1495     }
1496     auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName);
1497     auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName);
1498     backupConnection->SetCallback(callConnected);
1499     backupConnection->SetCallDied(callDied);
1500     AAFwk::Want want = CreateConnectWant(bundleName);
1501     auto ret = backupConnection->ConnectBackupExtAbility(want, GetUserIdDefault());
1502     if (ret) {
1503         HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret);
1504         return BError(BError::Codes::SA_BOOT_EXT_FAIL);
1505     }
1506     std::unique_lock<std::mutex> lock(getBackupInfoSyncLock_);
1507     getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S));
1508     if (isConnectDied_.load()) {
1509         HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str());
1510         isConnectDied_.store(false);
1511         return BError(BError::Codes::EXT_ABILITY_DIED);
1512     }
1513     auto proxy = backupConnection->GetBackupExtProxy();
1514     if (!proxy) {
1515         HILOGE("Extension backup Proxy is empty.");
1516         return BError(BError::Codes::SA_INVAL_ARG);
1517     }
1518     ret = proxy->GetBackupInfo(result);
1519     backupConnection->DisconnectBackupExtAbility();
1520     if (ret != ERR_OK) {
1521         HILOGE("Call Ext GetBackupInfo faild.");
1522         AppRadar::Info info(bundleName, "", "Call Ext GetBackupInfo faild");
1523         Backup::AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::GetBackupInfoCmdHandle", GetUserIdDefault(),
1524                                                             BizStageBackup::BIZ_STAGE_GET_BACKUP_INFO_FAIL, ret);
1525         return BError(BError::Codes::SA_INVAL_ARG);
1526     }
1527 
1528     return BError(BError::Codes::OK);
1529 }
1530 
1531 ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result)
1532 {
1533     try {
1534         std::lock_guard<std::mutex> lock(getBackupInfoProcLock_);
1535         HILOGI("Service::GetBackupInfo begin.");
1536         if (session_ == nullptr || isOccupyingSession_.load()) {
1537             HILOGE("Get BackupInfo error, session is empty.");
1538             return BError(BError::Codes::SA_INVAL_ARG);
1539         }
1540         if (session_->GetImpl().clientToken) {
1541             return BError(BError::Codes::SA_REFUSED_ACT, "Already have an active session");
1542         }
1543         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1544         auto ret = GetBackupInfoCmdHandle(bundleName, result);
1545         HILOGI("Service::GetBackupInfo end. result: %{public}s", result.c_str());
1546         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1547         return ret;
1548     } catch (...) {
1549         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1550         HILOGI("Unexpected exception");
1551         return EPERM;
1552     }
1553 }
1554 
1555 ErrCode Service::StartExtTimer(bool &isExtStart)
1556 {
1557     try {
1558         HILOGI("Service::StartExtTimer begin.");
1559         string bundleName = VerifyCallerAndGetCallerName();
1560         if (session_ == nullptr) {
1561             HILOGE("StartExtTimer error, session_ is nullptr.");
1562             isExtStart = false;
1563             return BError(BError::Codes::SA_INVAL_ARG);
1564         }
1565         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1566         auto timeoutCallback = TimeOutCallback(wptr<Service>(this), bundleName);
1567         session_->StopFwkTimer(bundleName);
1568         isExtStart = session_->StartExtTimer(bundleName, timeoutCallback);
1569         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1570         return BError(BError::Codes::OK);
1571     } catch (...) {
1572         isExtStart = false;
1573         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1574         HILOGI("Unexpected exception");
1575         return EPERM;
1576     }
1577 }
1578 
1579 ErrCode Service::StartFwkTimer(bool &isFwkStart)
1580 {
1581     try {
1582         HILOGI("Service::StartFwkTimer begin.");
1583         string bundleName = VerifyCallerAndGetCallerName();
1584         if (session_ == nullptr) {
1585             HILOGE("StartFwkTimer error, session_ is nullptr.");
1586             isFwkStart = false;
1587             return BError(BError::Codes::SA_INVAL_ARG);
1588         }
1589         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1590         auto timeoutCallback = TimeOutCallback(wptr<Service>(this), bundleName);
1591         session_->StopExtTimer(bundleName);
1592         isFwkStart = session_->StartFwkTimer(bundleName, timeoutCallback);
1593         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1594         return BError(BError::Codes::OK);
1595     } catch (...) {
1596         isFwkStart = false;
1597         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1598         HILOGI("Unexpected exception");
1599         return EPERM;
1600     }
1601 }
1602 
1603 ErrCode Service::AppendBundlesClearSession(const std::vector<BundleName> &bundleNames)
1604 {
1605     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1606     try {
1607         if (bundleNames.empty() || session_ == nullptr) {
1608             HILOGE("Init Incremental backup session error, session is empty");
1609             return EPERM;
1610         }
1611         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时
1612         auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId());
1613         session_->AppendBundles(bundleNames);
1614         for (auto info : backupInfos) {
1615             session_->SetBackupExtName(info.name, info.extensionName);
1616         }
1617         OnStartSched();
1618         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1619         return BError(BError::Codes::OK);
1620     } catch (const BError &e) {
1621         HandleExceptionOnAppendBundles(session_, bundleNames, {});
1622         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1623         HILOGE("Failed, errCode = %{public}d", e.GetCode());
1624         return e.GetCode();
1625     } catch (const exception &e) {
1626         HandleExceptionOnAppendBundles(session_, bundleNames, {});
1627         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1628         HILOGE("Catched an unexpected low-level exception %{public}s", e.what());
1629         return EPERM;
1630     } catch (...) {
1631         HandleExceptionOnAppendBundles(session_, bundleNames, {});
1632         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1633         HILOGE("Unexpected exception");
1634         return EPERM;
1635     }
1636 }
1637 
1638 ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result)
1639 {
1640     try {
1641         HILOGI("Service::UpdateTimer begin.");
1642         if (session_ == nullptr || isOccupyingSession_.load()) {
1643             HILOGE("Update Timer error, session is empty.");
1644             result = false;
1645             return BError(BError::Codes::SA_INVAL_ARG);
1646         }
1647         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1648         VerifyCaller();
1649         auto timeoutCallback = TimeOutCallback(wptr<Service>(this), bundleName);
1650         result = session_->UpdateTimer(bundleName, timeout, timeoutCallback);
1651         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1652         return BError(BError::Codes::OK);
1653     } catch (...) {
1654         result = false;
1655         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1656         HILOGI("Unexpected exception");
1657         return EPERM;
1658     }
1659 }
1660 
1661 ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result)
1662 {
1663     try {
1664         HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate);
1665         if (session_ == nullptr || isOccupyingSession_.load()) {
1666             HILOGE("Update Send Rate error, session is empty.");
1667             result = false;
1668             return BError(BError::Codes::SA_INVAL_ARG);
1669         }
1670         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1671         VerifyCaller();
1672         IServiceReverse::Scenario scenario = session_ -> GetScenario();
1673         if (scenario != IServiceReverse::Scenario::BACKUP) {
1674             HILOGE("This method is applicable to the backup scenario");
1675             result = false;
1676             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1677             return BError(BError::Codes::SA_INVAL_ARG);
1678         }
1679         auto backupConnection  = session_->GetExtConnection(bundleName);
1680         auto proxy = backupConnection->GetBackupExtProxy();
1681         if (!proxy) {
1682             throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty");
1683         }
1684         auto ret = proxy->UpdateFdSendRate(bundleName, sendRate);
1685         if (ret != NO_ERROR) {
1686             result = false;
1687             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1688             return BError(BError::Codes::EXT_BROKEN_IPC);
1689         }
1690         result = true;
1691         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1692         return BError(BError::Codes::OK);
1693     } catch (...) {
1694         result = false;
1695         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1696         HILOGI("Unexpected exception");
1697         return EPERM;
1698     }
1699 }
1700 
1701 AAFwk::Want Service::CreateConnectWant (BundleName &bundleName)
1702 {
1703     BConstants::ExtensionAction action = BConstants::ExtensionAction::BACKUP;
1704     AAFwk::Want want;
1705     string backupExtName = BundleMgrAdapter::GetExtName(bundleName, session_->GetSessionUserId());
1706     want.SetElementName(bundleName, backupExtName);
1707     want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast<int>(action));
1708     return want;
1709 }
1710 
1711 ErrCode Service::BackupSA(std::string bundleName)
1712 {
1713     HILOGI("BackupSA begin %{public}s", bundleName.c_str());
1714     IServiceReverse::Scenario scenario = session_->GetScenario();
1715     auto backUpConnection = session_->GetSAExtConnection(bundleName);
1716     std::shared_ptr<SABackupConnection> saConnection = backUpConnection.lock();
1717     if (saConnection == nullptr) {
1718         HILOGE("lock sa connection ptr is nullptr");
1719         return BError(BError::Codes::SA_INVAL_ARG);
1720     }
1721     if (scenario == IServiceReverse::Scenario::BACKUP) {
1722         auto ret = saConnection->CallBackupSA();
1723         session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName);
1724         if (ret) {
1725             HILOGI("BackupSA ret is %{public}d", ret);
1726             ClearSessionAndSchedInfo(bundleName);
1727             NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_DIED));
1728             return BError(ret);
1729         }
1730     } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1731         session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(BError(BError::Codes::OK), bundleName);
1732     }
1733     return BError(BError::Codes::OK);
1734 }
1735 
1736 void Service::OnSABackup(const std::string &bundleName, const int &fd, const std::string &result,
1737     const ErrCode &errCode)
1738 {
1739     auto task = [bundleName, fd, result, errCode, this]() {
1740         HILOGI("OnSABackup bundleName: %{public}s, fd: %{public}d, result: %{public}s, err: %{public}d",
1741             bundleName.c_str(), fd, result.c_str(), errCode);
1742         session_->GetServiceReverseProxy()->BackupOnFileReady(bundleName, "", move(fd), errCode);
1743         SAResultReport(bundleName, result, errCode, BackupRestoreScenario::FULL_BACKUP);
1744     };
1745     threadPool_.AddTask([task]() {
1746         try {
1747             task();
1748         } catch (...) {
1749             HILOGE("Failed to add task to thread pool");
1750         }
1751     });
1752 }
1753 
1754 void Service::OnSARestore(const std::string &bundleName, const std::string &result, const ErrCode &errCode)
1755 {
1756     auto task = [bundleName, result, errCode, this]() {
1757         HILOGI("OnSARestore bundleName: %{public}s, result: %{public}s, err: %{public}d",
1758             bundleName.c_str(), result.c_str(), errCode);
1759         SAResultReport(bundleName, result, errCode, BackupRestoreScenario::INCREMENTAL_RESTORE);
1760     };
1761     threadPool_.AddTask([task]() {
1762         try {
1763             task();
1764         } catch (...) {
1765             HILOGE("Failed to add task to thread pool");
1766         }
1767     });
1768 }
1769 
1770 ErrCode Service::SADone(ErrCode errCode, std::string bundleName)
1771 {
1772     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1773     try {
1774         if (session_->OnBundleFileReady(bundleName)) {
1775             auto backupConnection = session_->GetSAExtConnection(bundleName);
1776             std::shared_ptr<SABackupConnection> saConnection = backupConnection.lock();
1777             if (saConnection == nullptr) {
1778                 HILOGE("lock sa connection ptr is nullptr");
1779                 return BError(BError::Codes::SA_INVAL_ARG);
1780             }
1781             session_->StopFwkTimer(bundleName);
1782             session_->StopExtTimer(bundleName);
1783             saConnection->DisconnectBackupSAExt();
1784             ClearSessionAndSchedInfo(bundleName);
1785         }
1786         OnAllBundlesFinished(BError(BError::Codes::OK));
1787         return BError(BError::Codes::OK);
1788     } catch (const BError &e) {
1789         ReleaseOnException();
1790         return e.GetCode(); // 任意异常产生,终止监听该任务
1791     } catch (const exception &e) {
1792         ReleaseOnException();
1793         HILOGE("Catched an unexpected low-level exception %{public}s", e.what());
1794         return EPERM;
1795     } catch(...) {
1796         ReleaseOnException();
1797         HILOGE("Unexpected exception");
1798         return EPERM;
1799     }
1800 }
1801 
1802 void Service::NotifyCallerCurAppDone(ErrCode errCode, const std::string &callerName)
1803 {
1804     IServiceReverse::Scenario scenario = session_->GetScenario();
1805     if (scenario == IServiceReverse::Scenario::BACKUP) {
1806         HILOGI("will notify clone data, scenario is Backup");
1807         session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, callerName);
1808         auto now = std::chrono::system_clock::now();
1809         auto time = std::chrono::system_clock::to_time_t(now);
1810         auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
1811         std::stringstream strTime;
1812         strTime << (std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S:")) << (std::setfill('0'))
1813             << (std::setw(INDEX)) << (ms.count() % MS_1000);
1814         HiSysEventWrite(
1815             OHOS::HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT,
1816             FILE_BACKUP_EVENTS,
1817             OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
1818             "PROC_NAME", "ohos.appfileservice",
1819             "BUNDLENAME", callerName,
1820             "PID", getpid(),
1821             "TIME", strTime.str()
1822         );
1823     } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1824         HILOGI("will notify clone data, scenario is Restore");
1825         session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, callerName);
1826     }
1827 }
1828 
1829 ErrCode Service::ReportAppProcessInfo(const std::string processInfo, BackupRestoreScenario sennario)
1830 {
1831     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1832     try {
1833         string bundleName = VerifyCallerAndGetCallerName();
1834         if (sennario == BackupRestoreScenario::FULL_RESTORE) {
1835             session_->GetServiceReverseProxy()->RestoreOnProcessInfo(bundleName, processInfo);
1836         } else if (sennario == BackupRestoreScenario::INCREMENTAL_RESTORE) {
1837             session_->GetServiceReverseProxy()->IncrementalRestoreOnProcessInfo(bundleName, processInfo);
1838         } else if (sennario == BackupRestoreScenario::FULL_BACKUP) {
1839             session_->GetServiceReverseProxy()->BackupOnProcessInfo(bundleName, processInfo);
1840         } else if (sennario == BackupRestoreScenario::INCREMENTAL_BACKUP) {
1841             session_->GetServiceReverseProxy()->IncrementalBackupOnProcessInfo(bundleName, processInfo);
1842         }
1843         return BError(BError::Codes::OK);
1844     } catch (const BError &e) {
1845         return e.GetCode(); // 任意异常产生,终止监听该任务
1846     } catch (const exception &e) {
1847         HILOGI("Catched an unexpected low-level exception %{public}s", e.what());
1848         return EPERM;
1849     }
1850 }
1851 
1852 std::function<void()> Service::TimeOutCallback(wptr<Service> ptr, std::string bundleName)
1853 {
1854     return [ptr, bundleName, this]() {
1855         HILOGI("begin timeoutCallback bundleName = %{public}s", bundleName.c_str());
1856         auto thisPtr = ptr.promote();
1857         if (!thisPtr) {
1858             HILOGE("ServicePtr is nullptr.");
1859             return;
1860         }
1861         try {
1862             DoTimeout(thisPtr, bundleName);
1863         } catch (...) {
1864             HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str());
1865             thisPtr->ClearSessionAndSchedInfo(bundleName);
1866             thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT));
1867         }
1868     };
1869 }
1870 
1871 void Service::TimeoutRadarReport(IServiceReverse::Scenario scenario, std::string &bundleName)
1872 {
1873     int32_t errCode = BError(BError::Codes::EXT_ABILITY_TIMEOUT).GetCode();
1874     if (scenario == IServiceReverse::Scenario::BACKUP) {
1875         AppRadar::Info info(bundleName, "", "on backup timeout");
1876         AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::TimeOutCallback", GetUserIdDefault(),
1877             BizStageBackup::BIZ_STAGE_ON_BACKUP, errCode);
1878     } else if (scenario == IServiceReverse::Scenario::RESTORE) {
1879         AppRadar::Info info(bundleName, "", "on restore timeout");
1880         AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::TimeOutCallback", GetUserIdDefault(),
1881             BizStageRestore::BIZ_STAGE_ON_RESTORE, errCode);
1882     }
1883 }
1884 
1885 void Service::DoTimeout(wptr<Service> ptr, std::string bundleName)
1886 {
1887     auto thisPtr = ptr.promote();
1888     if (!thisPtr) {
1889         HILOGE("ServicePtr is nullptr.");
1890         return;
1891     }
1892     auto sessionPtr = thisPtr->session_;
1893     if (sessionPtr == nullptr) {
1894         HILOGE("SessionPtr is nullptr.");
1895         return;
1896     }
1897     IServiceReverse::Scenario scenario = sessionPtr->GetScenario();
1898     TimeoutRadarReport(scenario, bundleName);
1899     try {
1900         std::shared_ptr<ExtensionMutexInfo> mutexPtr = GetExtensionMutex(bundleName);
1901         if (mutexPtr == nullptr) {
1902             HILOGE("extension mutex ptr is nullptr");
1903             return;
1904         }
1905         std::lock_guard<std::mutex> lock(mutexPtr->callbackMutex);
1906         if (SAUtils::IsSABundleName(bundleName)) {
1907             auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName);
1908             shared_ptr<SABackupConnection> saConnection = sessionConnection.lock();
1909             if (saConnection == nullptr) {
1910                 HILOGE("lock sa connection ptr is nullptr");
1911                 return;
1912             }
1913             saConnection->DisconnectBackupSAExt();
1914         } else {
1915             auto sessionConnection = sessionPtr->GetExtConnection(bundleName);
1916             sessionConnection->DisconnectBackupExtAbility();
1917         }
1918         sessionPtr->StopFwkTimer(bundleName);
1919         sessionPtr->StopExtTimer(bundleName);
1920         thisPtr->ClearSessionAndSchedInfo(bundleName);
1921         thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT));
1922     } catch (...) {
1923         HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str());
1924         thisPtr->ClearSessionAndSchedInfo(bundleName);
1925         thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT));
1926     }
1927     RemoveExtensionMutex(bundleName);
1928 }
1929 
1930 void Service::AddClearBundleRecord(const std::string &bundleName)
1931 {
1932     // 添加清理记录
1933     if (!clearRecorder_->InsertClearBundleRecord(bundleName)) {
1934         HILOGE("Failed to add clear bundle record, bundleName=%{public}s", bundleName.c_str());
1935         return;
1936     }
1937     HILOGI("Add clear bundle record OK, bundleName=%{public}s", bundleName.c_str());
1938 }
1939 
1940 void Service::DelClearBundleRecord(const std::vector<std::string> &bundleNames)
1941 {
1942     // 删除清理记录
1943     for (const auto &it : bundleNames) {
1944         if (!clearRecorder_->DeleteClearBundleRecord(it)) {
1945             HILOGE("Failed to delete clear bundle record, bundleName=%{public}s", it.c_str());
1946             continue;
1947         }
1948         HILOGI("Delete clear bundle record OK, bundleName=%{public}s", it.c_str());
1949     }
1950 }
1951 
1952 void Service::ReleaseOnException()
1953 {
1954     try {
1955         if (session_->IsOnAllBundlesFinished()) {
1956             IServiceReverse::Scenario scenario = session_->GetScenario();
1957             if (isInRelease_.load() && (scenario == IServiceReverse::Scenario::RESTORE)) {
1958                 SessionDeactive();
1959             }
1960         }
1961     } catch (...) {
1962         HILOGE("Unexpected exception");
1963     }
1964 }
1965 } // namespace OHOS::FileManagement::Backup
1966