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