• 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 #include "module_ipc/service.h"
17 
18 #include <algorithm>
19 #include <cerrno>
20 #include <chrono>
21 #include <cinttypes>
22 #include <cstddef>
23 #include <cstdint>
24 #include <cstring>
25 #include <regex>
26 
27 #include <fcntl.h>
28 #include <iomanip>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/vfs.h>
32 
33 #include <directory_ex.h>
34 
35 #include "ability_manager_client.h"
36 #include "accesstoken_kit.h"
37 #include "b_anony/b_anony.h"
38 #include "b_error/b_error.h"
39 #include "b_error/b_excep_utils.h"
40 #include "b_filesystem/b_dir.h"
41 #include "b_file_info.h"
42 #include "b_hiaudit/hi_audit.h"
43 #include "b_json/b_json_cached_entity.h"
44 #include "b_jsonutil/b_jsonutil.h"
45 #include "b_ohos/startup/backup_para.h"
46 #include "b_process/b_multiuser.h"
47 #include "b_radar/b_radar.h"
48 #include "b_radar/radar_app_statistic.h"
49 #include "b_resources/b_constants.h"
50 #include "b_sa/b_sa_utils.h"
51 #include "b_utils/b_time.h"
52 #include "bundle_mgr_client.h"
53 #include "filemgmt_libhilog.h"
54 #include "hisysevent.h"
55 #include "hitrace_meter.h"
56 #include "ipc_skeleton.h"
57 #include "access_token.h"
58 #include "tokenid_kit.h"
59 #include "module_app_gallery/app_gallery_dispose_proxy.h"
60 #include "module_external/bms_adapter.h"
61 #include "module_external/sms_adapter.h"
62 #include "module_ipc/svc_backup_connection.h"
63 #include "module_ipc/svc_restore_deps_manager.h"
64 #include "module_notify/notify_work_service.h"
65 #include "parameter.h"
66 #include "parameters.h"
67 #include "system_ability_definition.h"
68 
69 namespace OHOS::FileManagement::Backup {
70 using namespace std;
71 
72 namespace {
73 const int32_t MAX_FILE_READY_REPORT_TIME = 2;
74 const int32_t WAIT_SCANNING_INFO_SEND_TIME = 5;
75 const int ERR_SIZE = -1;
76 } // namespace
77 
AppendBundles(const std::vector<std::string> & bundleNames)78 void Service::AppendBundles(const std::vector<std::string> &bundleNames)
79 {
80     std::vector<std::string> failedBundles;
81     session_->AppendBundles(bundleNames, failedBundles);
82     if (!failedBundles.empty()) {
83         HILOGE("Handle exception on failed bundles, size = %{public}zu", failedBundles.size());
84         HandleExceptionOnAppendBundles(session_, failedBundles, {});
85     }
86 }
87 
ReportOnBundleStarted(IServiceReverseType::Scenario scenario,const std::string & bundleName)88 void Service::ReportOnBundleStarted(IServiceReverseType::Scenario scenario, const std::string &bundleName)
89 {
90     if (scenario == IServiceReverseType::Scenario::BACKUP) {
91         session_->GetServiceReverseProxy()->BackupOnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), bundleName);
92     } else if (scenario == IServiceReverseType::Scenario::RESTORE) {
93         session_->GetServiceReverseProxy()->RestoreOnBundleStarted(BError(BError::Codes::SA_INVAL_ARG), bundleName);
94     }
95 }
96 
BundleNameWithUserId(const string & bundleName,const int32_t userId)97 string Service::BundleNameWithUserId(const string& bundleName, const int32_t userId)
98 {
99     return to_string(userId) + "-" + bundleName;
100 }
101 
SplitBundleName(const string & bundleNameWithId)102 std::tuple<std::string, int32_t> Service::SplitBundleName(const string& bundleNameWithId)
103 {
104     size_t found = bundleNameWithId.find('-');
105     if (found == std::string::npos) {
106         HILOGE("Can not split bundleName = %{public}s", bundleNameWithId.c_str());
107         return { "", -1 };
108     }
109     std::string bundleName = bundleNameWithId.substr(found + 1, bundleNameWithId.length());
110     int32_t userId = std::atoi(bundleNameWithId.substr(0, found).c_str());
111     return { bundleName, userId };
112 }
113 
MakeDetailList(const vector<BundleName> & bundleNames)114 vector<BIncrementalData> Service::MakeDetailList(const vector<BundleName> &bundleNames)
115 {
116     vector<BIncrementalData> bundleDetails {};
117     for (const auto &bundleName : bundleNames) {
118         bundleDetails.emplace_back(BIncrementalData {bundleName, 0});
119     }
120     return bundleDetails;
121 }
122 
UpdateBundleRadarReport(const std::string & bundleName)123 void Service::UpdateBundleRadarReport(const std::string &bundleName)
124 {
125     std::unique_lock<std::mutex> lock(bundleExecRadarLock_);
126     bundleExecRadarSet_.insert(bundleName);
127 }
128 
ClearBundleRadarReport()129 void Service::ClearBundleRadarReport()
130 {
131     std::unique_lock<std::mutex> lock(bundleExecRadarLock_);
132     bundleExecRadarSet_.clear();
133 }
134 
IsReportBundleExecFail(const std::string & bundleName)135 bool Service::IsReportBundleExecFail(const std::string &bundleName)
136 {
137     std::unique_lock<std::mutex> lock(bundleExecRadarLock_);
138     auto it = bundleExecRadarSet_.find(bundleName);
139     if (it != bundleExecRadarSet_.end()) {
140         HILOGI("BundleName %{public}s has already been reported", bundleName.c_str());
141         return false;
142     }
143     return true;
144 }
145 
ClearFileReadyRadarReport()146 void Service::ClearFileReadyRadarReport()
147 {
148     std::unique_lock<std::mutex> lock(fileReadyRadarLock_);
149     fileReadyRadarMap_.clear();
150 }
151 
IsReportFileReadyFail(const std::string & bundleName)152 bool Service::IsReportFileReadyFail(const std::string &bundleName)
153 {
154     std::unique_lock<std::mutex> lock(fileReadyRadarLock_);
155     auto it = fileReadyRadarMap_.find(bundleName);
156     if (it != fileReadyRadarMap_.end()) {
157         it->second++;
158     } else {
159         fileReadyRadarMap_[bundleName] = 1;
160     }
161     if (it->second > MAX_FILE_READY_REPORT_TIME) {
162         HILOGI("FileReady radar report more than %{public}d times, bundleName = %{public}s",
163             MAX_FILE_READY_REPORT_TIME, bundleName.c_str());
164         return false;
165     }
166     return true;
167 }
168 
TimeoutRadarReport(IServiceReverseType::Scenario scenario,std::string & bundleName)169 void Service::TimeoutRadarReport(IServiceReverseType::Scenario scenario, std::string &bundleName)
170 {
171     if (!IsReportBundleExecFail(bundleName)) {
172         return;
173     }
174     UpdateBundleRadarReport(bundleName);
175     int32_t errCode = BError::BackupErrorCode::E_ETO;
176     if (session_->GetTimeoutValue(bundleName) == 0) {
177         errCode = BError::BackupErrorCode::E_FORCE_TIMEOUT;
178     }
179     if (scenario == IServiceReverseType::Scenario::BACKUP) {
180         AppRadar::Info info(bundleName, "", "on backup timeout");
181         AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::TimeOutCallback", GetUserIdDefault(),
182             BizStageBackup::BIZ_STAGE_ON_BACKUP, errCode);
183     } else if (scenario == IServiceReverseType::Scenario::RESTORE) {
184         AppRadar::Info info(bundleName, "", "on restore timeout");
185         AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::TimeOutCallback", GetUserIdDefault(),
186             BizStageRestore::BIZ_STAGE_ON_RESTORE, errCode);
187     }
188 }
189 
Finish()190 ErrCode Service::Finish()
191 {
192     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
193     try {
194         ErrCode ret = VerifyCaller(session_->GetScenario());
195         if (ret != ERR_OK) {
196             HILOGE("Failde to Finish, verify caller failed, ret:%{public}d", ret);
197             ReleaseOnException();
198             return ret;
199         }
200         ret = session_->Finish();
201         if (ret != ERR_OK) {
202             HILOGE("Failde to Finish, session finish failed, ret:%{public}d", ret);
203             ReleaseOnException();
204             return ret;
205         }
206         OnAllBundlesFinished(BError(BError::Codes::OK));
207         return BError(BError::Codes::OK);
208     } catch (const BError &e) {
209         ReleaseOnException();
210         HILOGE("Failde to Finish");
211         return e.GetCode();
212     }
213 }
214 
GetFileHandle(const string & bundleName,const string & fileName)215 ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName)
216 {
217     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
218     try {
219         if (session_ == nullptr) {
220             HILOGE("GetFileHandle error, session is empty");
221             return BError(BError::Codes::SA_INVAL_ARG);
222         }
223         ErrCode ret = VerifyCaller(IServiceReverseType::Scenario::RESTORE);
224         if (ret != ERR_OK) {
225             HILOGE("verify caller failed, bundleName:%{public}s", bundleName.c_str());
226             return ret;
227         }
228         if (!BDir::IsFilePathValid(fileName)) {
229             HILOGE("path is forbidden, path : %{public}s", GetAnonyPath(fileName).c_str());
230             return BError(BError::Codes::SA_INVAL_ARG);
231         }
232         bool updateRes = SvcRestoreDepsManager::GetInstance().UpdateToRestoreBundleMap(bundleName, fileName);
233         if (updateRes) {
234             return BError(BError::Codes::OK);
235         }
236         auto action = session_->GetServiceSchedAction(bundleName);
237         if (action == BConstants::ServiceSchedAction::UNKNOWN) {
238             HILOGE("action is unknown, bundleName:%{public}s", bundleName.c_str());
239             return BError(BError::Codes::SA_INVAL_ARG);
240         }
241         if (action == BConstants::ServiceSchedAction::RUNNING) {
242             auto err = SendFileHandle(bundleName, fileName);
243             if (err != ERR_OK) {
244                 HILOGE("SendFileHandle failed, bundle:%{public}s", bundleName.c_str());
245                 return err;
246             }
247         } else {
248             session_->SetExtFileNameRequest(bundleName, fileName);
249         }
250         return BError(BError::Codes::OK);
251     } catch (const BError &e) {
252         return e.GetCode();
253     }
254 }
255 
SendFileHandle(const std::string & bundleName,const std::string & fileName)256 ErrCode Service::SendFileHandle(const std::string &bundleName, const std::string &fileName)
257 {
258     auto backUpConnection = session_->GetExtConnection(bundleName);
259     if (backUpConnection == nullptr) {
260         HILOGE("backUpConnection is empty, bundle:%{public}s", bundleName.c_str());
261         return BError(BError::Codes::SA_INVAL_ARG);
262     }
263     auto proxy = backUpConnection->GetBackupExtProxy();
264     if (!proxy) {
265         HILOGE("GetFileHandle failed, bundleName:%{public}s", bundleName.c_str());
266         return BError(BError::Codes::SA_INVAL_ARG);
267     }
268     int32_t errCode = 0;
269     int32_t fdCode = 0;
270     proxy->GetFileHandleWithUniqueFd(fileName, errCode, fdCode);
271     UniqueFd fd(fdCode);
272     if (errCode != ERR_OK) {
273         AppRadar::Info info(bundleName, "", "");
274         AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::GetFileHandle", GetUserIdDefault(),
275                                                      BizStageRestore::BIZ_STAGE_GET_FILE_HANDLE_FAIL, errCode);
276     }
277     session_->GetServiceReverseProxy()->RestoreOnFileReady(bundleName, fileName, move(fd), errCode);
278     FileReadyRadarReport(bundleName, fileName, errCode, IServiceReverseType::Scenario::RESTORE);
279     return BError(BError::Codes::OK);
280 }
281 
PublishFile(const BFileInfo & fileInfo)282 ErrCode Service::PublishFile(const BFileInfo &fileInfo)
283 {
284     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
285     if (session_ == nullptr) {
286         HILOGE("PublishFile error, session is empty");
287         return BError(BError::Codes::SA_INVAL_ARG);
288     }
289     ErrCode ret = VerifyCaller(IServiceReverseType::Scenario::RESTORE);
290     if (ret != ERR_OK) {
291         HILOGE("PublishFile error, verify caller by scenario failed, ret:%{public}d", ret);
292         return ret;
293     }
294     if (!fileInfo.fileName.empty()) {
295         HILOGE("Forbit to use publishFile with fileName for App");
296         return EPERM;
297     }
298     auto backUpConnection = session_->GetExtConnection(fileInfo.owner);
299     if (backUpConnection == nullptr) {
300         HILOGE("backUpConnection is empty, bundle:%{public}s", fileInfo.owner.c_str());
301         return BError(BError::Codes::SA_INVAL_ARG);
302     }
303     auto proxy = backUpConnection->GetBackupExtProxy();
304     if (!proxy) {
305         HILOGE("PublishFile error, Extension backup Proxy is empty");
306         return BError(BError::Codes::SA_INVAL_ARG);
307     }
308     ret = proxy->PublishFile(fileInfo.fileName);
309     if (ret != ERR_OK) {
310         HILOGE("Failed to publish file for backup extension, ret:%{public}d", ret);
311         return ret;
312     }
313     return BError(BError::Codes::OK);
314 }
315 
AppFileReady(const std::string & fileName,int fd,int32_t errCode)316 ErrCode Service::AppFileReady(const std::string &fileName, int fd, int32_t errCode)
317 {
318     HILOGI("Begin fileName =%{public}s, fd = %{public}d, errCode = %{public}d", fileName.c_str(), fd, errCode);
319     UniqueFd fdUnique(fd);
320     return AppFileReady(fileName, std::move(fdUnique), errCode);
321 }
322 
AppFileReadyWithoutFd(const std::string & fileName,int32_t errCode)323 ErrCode Service::AppFileReadyWithoutFd(const std::string &fileName, int32_t errCode)
324 {
325     return AppFileReady(fileName, UniqueFd(INVALID_FD), errCode);
326 }
327 
AppFileReady(const string & fileName,UniqueFd fd,int32_t errCode)328 ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd, int32_t errCode)
329 {
330     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
331     try {
332         if (session_ == nullptr) {
333             HILOGE("AppFileReady error, session is empty");
334             return BError(BError::Codes::SA_INVAL_ARG);
335         }
336         string callerName;
337         ErrCode ret = VerifyCallerAndGetCallerName(callerName);
338         if (ret != ERR_OK) {
339             HILOGE("AppFileReady error, Get bundle name failed, ret:%{public}d", ret);
340             return ret;
341         }
342         if (fileName.find('/') != string::npos) {
343             HILOGE("AppFileReady error, filename is not valid, fileName:%{public}s", GetAnonyPath(fileName).c_str());
344             return BError(BError::Codes::SA_INVAL_ARG);
345         }
346         if (fileName == BConstants::EXT_BACKUP_MANAGE) {
347             fd = session_->OnBundleExtManageInfo(callerName, move(fd));
348         }
349         bool fdFlag = fd < 0 ? true : false;
350         fdFlag ? session_->GetServiceReverseProxy()->BackupOnFileReadyWithoutFd(callerName, fileName, errCode) :
351                  session_->GetServiceReverseProxy()->BackupOnFileReady(callerName, fileName, move(fd), errCode);
352         FileReadyRadarReport(callerName, fileName, errCode, session_->GetScenario());
353         if (session_->OnBundleFileReady(callerName, fileName)) {
354             ret = HandleCurBundleFileReady(callerName, fileName, false);
355             if (ret != ERR_OK) {
356                 HILOGE("Handle current bundle file failed, bundleName:%{public}s, fileName:%{public}s",
357                     callerName.c_str(),  GetAnonyPath(fileName).c_str());
358                 return ret;
359             }
360         }
361         OnAllBundlesFinished(BError(BError::Codes::OK));
362         return BError(BError::Codes::OK);
363     } catch (const BError &e) {
364         return e.GetCode(); // 任意异常产生,终止监听该任务
365     } catch (...) {
366         HILOGE("Unexpected exception");
367         return EPERM;
368     }
369 }
370 
AppDone(ErrCode errCode)371 ErrCode Service::AppDone(ErrCode errCode)
372 {
373     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
374     try {
375         if (session_ == nullptr) {
376             HILOGE("App finish error, session info is empty");
377             return BError(BError::Codes::SA_INVAL_ARG);
378         }
379         string callerName;
380         ErrCode ret = VerifyCallerAndGetCallerName(callerName);
381         if (ret != ERR_OK) {
382             HILOGE("App done failed, Get bundle name failed, ret:%{public}d", ret);
383             return ret;
384         }
385         HILOGI("Begin, callerName is: %{public}s, errCode: %{public}d", callerName.c_str(), errCode);
386         if (session_->OnBundleFileReady(callerName) || errCode != BError(BError::Codes::OK)) {
387             std::shared_ptr<ExtensionMutexInfo> mutexPtr = GetExtensionMutex(callerName);
388             if (mutexPtr == nullptr) {
389                 HILOGE("extension mutex ptr is nullptr, bundleName:%{public}s", callerName.c_str());
390                 return BError(BError::Codes::SA_INVAL_ARG);
391             }
392             std::lock_guard<std::mutex> lock(mutexPtr->callbackMutex);
393             SetExtOnRelease(callerName, true);
394             return BError(BError::Codes::OK);
395         }
396         RemoveExtensionMutex(callerName);
397         OnAllBundlesFinished(BError(BError::Codes::OK));
398         return BError(BError::Codes::OK);
399     } catch (const BError &e) {
400         ReleaseOnException();
401         HILOGE("AppDone error, err code is: %{public}d", e.GetCode());
402         return e.GetCode(); // 任意异常产生,终止监听该任务
403     } catch (...) {
404         HILOGE("Unexpected exception");
405         ReleaseOnException();
406         return EPERM;
407     }
408 }
409 
LaunchBackupExtension(const BundleName & bundleName)410 ErrCode Service::LaunchBackupExtension(const BundleName &bundleName)
411 {
412     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
413     HILOGI("begin %{public}s", bundleName.data());
414     IServiceReverseType::Scenario scenario = session_->GetScenario();
415     BConstants::ExtensionAction action;
416     if (scenario == IServiceReverseType::Scenario::BACKUP || scenario == IServiceReverseType::Scenario::CLEAN) {
417         action = BConstants::ExtensionAction::BACKUP;
418     } else if (scenario == IServiceReverseType::Scenario::RESTORE) {
419         action = BConstants::ExtensionAction::RESTORE;
420     } else {
421         action = BConstants::ExtensionAction::INVALID;
422         HILOGE("Launch current bundle backupExtension failed, action is unknown, bundleName:%{public}s",
423             bundleName.c_str());
424         return BError(BError::Codes::SA_INVAL_ARG);
425     }
426     if (SAUtils::IsSABundleName(bundleName)) {
427         return LaunchBackupSAExtension(bundleName);
428     }
429     AAFwk::Want want;
430     SetWant(want, bundleName, action);
431     auto backUpConnection = session_->GetExtConnection(bundleName);
432     if (backUpConnection == nullptr) {
433         HILOGE("LaunchBackupExtension error, backUpConnection is empty");
434         return BError(BError::Codes::SA_INVAL_ARG);
435     }
436     if (backUpConnection->IsExtAbilityConnected() && !backUpConnection->WaitDisconnectDone()) {
437         HILOGE("LaunchBackupExtension error, WaitDisconnectDone failed");
438         return BError(BError::Codes::SA_INVAL_ARG);
439     }
440     BConstants::ServiceSchedAction bundleAction = session_->GetServiceSchedAction(bundleName);
441     if (bundleAction == BConstants::ServiceSchedAction::UNKNOWN) {
442         HILOGE("action is unknown, bundleName:%{public}s", bundleName.c_str());
443         return BError(BError::Codes::SA_INVAL_ARG);
444     }
445     ErrCode ret = backUpConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId(),
446         bundleAction == BConstants::ServiceSchedAction::CLEAN);
447     if (ret != ERR_OK) {
448         HILOGE("ConnectBackupExtAbility failed, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret);
449         ExtensionConnectFailRadarReport(bundleName, ret, scenario);
450         return BError(BError::Codes::SA_BOOT_EXT_FAIL);
451     }
452     return BError(BError::Codes::OK);
453 }
454 
SetWant(AAFwk::Want & want,const BundleName & bundleName,const BConstants::ExtensionAction & action)455 void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action)
456 {
457     BJsonUtil::BundleDetailInfo bundleDetail = BJsonUtil::ParseBundleNameIndexStr(bundleName);
458     string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */
459     HILOGI("BackupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data());
460     string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */
461     int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */
462     RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */
463     string bundleExtInfo = session_->GetBackupExtInfo(bundleName);
464     HILOGI("BundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str());
465     string oldBackupVersion = session_->GetOldBackupVersion(); /* old device backup version */
466     if (oldBackupVersion.empty()) {
467         HILOGE("Failed to get backupVersion of old device");
468     }
469     want.SetElementName(bundleDetail.bundleName, backupExtName);
470     want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast<int>(action));
471     want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast<long>(versionCode));
472     want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast<int>(restoreType));
473     want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName);
474     want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo);
475     want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo);
476     want.SetParam(BConstants::EXTENSION_APP_CLONE_INDEX_PARA, bundleDetail.bundleIndex);
477     want.SetParam(BConstants::EXTENSION_OLD_BACKUP_VERSION_PARA, oldBackupVersion);
478 }
479 
GetSupportBackupBundleNames(vector<BJsonEntityCaps::BundleInfo> & backupInfos,bool isIncBackup,const std::vector<std::string> & srcBundleNames)480 std::vector<std::string> Service::GetSupportBackupBundleNames(vector<BJsonEntityCaps::BundleInfo> &backupInfos,
481     bool isIncBackup, const std::vector<std::string> &srcBundleNames)
482 {
483     HILOGI("Begin");
484     std::vector<std::string> supportBackupNames;
485     for (const auto &info : backupInfos) {
486         HILOGI("Current backupInfo bundleName:%{public}s, index:%{public}d, extName:%{public}s", info.name.c_str(),
487             info.appIndex, info.extensionName.c_str());
488         std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(info.name, info.appIndex);
489         if (!info.allToBackup) {
490             if (isIncBackup) {
491                 session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(
492                     BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), bundleNameIndexInfo);
493             } else {
494                 session_->GetServiceReverseProxy()->BackupOnBundleStarted(
495                     BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), bundleNameIndexInfo);
496             }
497             BundleBeginRadarReport(bundleNameIndexInfo, BError(BError::Codes::SA_FORBID_BACKUP_RESTORE).GetCode(),
498                 IServiceReverseType::Scenario::BACKUP);
499             continue;
500         }
501         supportBackupNames.emplace_back(bundleNameIndexInfo);
502     }
503     HandleNotSupportBundleNames(srcBundleNames, supportBackupNames, isIncBackup);
504     HILOGI("End");
505     return supportBackupNames;
506 }
507 
SetCurrentSessProperties(BJsonEntityCaps::BundleInfo & info,std::map<std::string,bool> & isClearDataFlags,const std::string & bundleNameIndexInfo)508 void Service::SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info,
509     std::map<std::string, bool> &isClearDataFlags, const std::string &bundleNameIndexInfo)
510 {
511     HILOGI("Begin");
512     if (session_ == nullptr) {
513         HILOGE("Set currrent session properties error, session is empty");
514         return;
515     }
516     session_->SetBundleDataSize(bundleNameIndexInfo, info.spaceOccupied);
517     auto iter = isClearDataFlags.find(bundleNameIndexInfo);
518     if (iter != isClearDataFlags.end()) {
519         session_->SetClearDataFlag(bundleNameIndexInfo, iter->second);
520     }
521     HILOGI("End");
522 }
523 
RefreshDataSize(int64_t totalDataSize)524 ErrCode Service::RefreshDataSize(int64_t totalDataSize)
525 {
526     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
527     try {
528         if (session_ == nullptr) {
529             HILOGE("session is nullptr");
530             return BError(BError::Codes::SA_INVAL_ARG);
531         }
532         std::string bundleName;
533         ErrCode ret = VerifyCallerAndGetCallerName(bundleName);
534         if (ret != ERR_OK) {
535             HILOGE("Refresh data size failed, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret);
536             return ret;
537         }
538         session_->SetBundleDataSize(bundleName, totalDataSize);
539         HILOGI("RefreshDataSize, bundleName:%{public}s ,datasize = %{public}" PRId64 "",
540             bundleName.c_str(), totalDataSize);
541         return BError(BError::Codes::OK);
542     } catch (const BError &e) {
543         return e.GetCode();
544     }
545 }
546 
547 
HandleNotSupportBundleNames(const std::vector<std::string> & srcBundleNames,std::vector<std::string> & supportBundleNames,bool isIncBackup)548 void Service::HandleNotSupportBundleNames(const std::vector<std::string> &srcBundleNames,
549     std::vector<std::string> &supportBundleNames, bool isIncBackup)
550 {
551     for (const auto &bundleName : srcBundleNames) {
552         auto it = std::find(supportBundleNames.begin(), supportBundleNames.end(), bundleName);
553         if (it != supportBundleNames.end()) {
554             continue;
555         }
556         HILOGE("bundleName:%{public}s, can not find from supportBundleNames", bundleName.c_str());
557         AppStatReportErr(bundleName, "HandleNotSupportBundleNames",
558             RadarError(MODULE_HAP, BError(BError::Codes::SA_BUNDLE_INFO_EMPTY)));
559         if (isIncBackup) {
560             session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(
561                 BError(BError::Codes::SA_BUNDLE_INFO_EMPTY), bundleName);
562         } else {
563             session_->GetServiceReverseProxy()->BackupOnBundleStarted(
564                 BError(BError::Codes::SA_BUNDLE_INFO_EMPTY), bundleName);
565         }
566     }
567 }
568 
StopExtTimer(bool & isExtStop)569 ErrCode Service::StopExtTimer(bool &isExtStop)
570 {
571     try {
572         HILOGI("Service::StopExtTimer begin.");
573         if (session_ == nullptr) {
574             HILOGE("StopExtTimer error, session_ is nullptr.");
575             isExtStop = false;
576             return BError(BError::Codes::SA_INVAL_ARG);
577         }
578         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
579         string bundleName;
580         ErrCode ret = VerifyCallerAndGetCallerName(bundleName);
581         if (ret != ERR_OK) {
582             HILOGE("Stop extension error, ret:%{public}d", ret);
583             isExtStop = false;
584             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
585             return ret;
586         }
587         isExtStop = session_->StopExtTimer(bundleName);
588         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
589         return BError(BError::Codes::OK);
590     } catch (...) {
591         HILOGE("Unexpected exception");
592         isExtStop = false;
593         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
594         return EPERM;
595     }
596 }
597 
ClearFailedBundles()598 void Service::ClearFailedBundles()
599 {
600     std::lock_guard<std::mutex> lock(failedBundlesLock_);
601     failedBundles_.clear();
602 }
603 
UpdateFailedBundles(const std::string & bundleName,BundleTaskInfo taskInfo)604 void Service::UpdateFailedBundles(const std::string &bundleName, BundleTaskInfo taskInfo)
605 {
606     std::lock_guard<std::mutex> lock(failedBundlesLock_);
607     failedBundles_[bundleName] = taskInfo;
608 }
609 
GetOldDeviceBackupVersion()610 void Service::GetOldDeviceBackupVersion()
611 {
612     std::string oldBackupVersion = session_->GetOldBackupVersion();
613     if (oldBackupVersion.empty()) {
614         HILOGE("Failed to get backupVersion of old device");
615     }
616     HILOGI("backupVersion of old device = %{public}s", oldBackupVersion.c_str());
617 }
618 
AppStatReportErr(const string & bundleName,const string & func,RadarError error)619 void Service::AppStatReportErr(const string &bundleName, const string &func, RadarError error)
620 {
621     if (totalStatistic_ == nullptr) {
622         HILOGE("totalStat is null. appStatReport func:%{public}s, err: %{public}s", func.c_str(),
623             error.errMsg_.c_str());
624         return;
625     }
626     RadarAppStatistic appStatistic(bundleName, totalStatistic_->GetUniqId(), totalStatistic_->GetBizScene());
627     appStatistic.ReportError(func, error);
628 }
629 
SaStatReport(const string & bundleName,const string & func,RadarError err)630 void Service::SaStatReport(const string &bundleName, const string &func, RadarError err)
631 {
632     if (totalStatistic_ == nullptr) {
633         HILOGE("totalStat is null. appStatReport func:%{public}s, err: %{public}s", func.c_str(),
634             err.errMsg_.c_str());
635         return;
636     }
637 
638     std::shared_ptr<RadarAppStatistic> saStatistic = nullptr;
639     {
640         std::shared_lock<std::shared_mutex> mapLock(statMapMutex_);
641         if (saStatisticMap_.count(bundleName) > 0) {
642             saStatistic = saStatisticMap_[bundleName];
643             saStatistic->doBackupSpend_.End();
644             saStatistic->doRestoreSpend_ = TimeUtils::GetSpendMS(saStatistic->doRestoreStart_);
645         } else {
646             saStatistic = std::make_shared<RadarAppStatistic>(bundleName, totalStatistic_->GetUniqId(),
647                 totalStatistic_->GetBizScene());
648         }
649     }
650     saStatistic->ReportSA(func, err);
651 }
652 
ExtConnectDied(const string & callName)653 void Service::ExtConnectDied(const string &callName)
654 {
655     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
656     try {
657         HILOGI("Begin, bundleName: %{public}s", callName.c_str());
658         std::shared_ptr<ExtensionMutexInfo> mutexPtr = GetExtensionMutex(callName);
659         if (mutexPtr == nullptr) {
660             HILOGE("extension mutex ptr is nullptr");
661             return;
662         }
663         std::lock_guard<std::mutex> lock(mutexPtr->callbackMutex);
664         /* Clear Timer */
665         sched_->RemoveExtConn(callName);
666         session_->StopFwkTimer(callName);
667         session_->StopExtTimer(callName);
668         auto backUpConnection = session_->GetExtConnection(callName);
669         if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) {
670             backUpConnection->DisconnectBackupExtAbility();
671             AppStatReportErr(callName, "ExtConnectDied", RadarError(MODULE_ABILITY_MGR_SVC,
672                 backUpConnection->GetError()));
673         }
674         bool needCleanData = session_->GetClearDataFlag(callName);
675         if (!needCleanData || SAUtils::IsSABundleName(callName)) {
676             HILOGE("Current extension is died, but not need clean data, bundleName:%{public}s", callName.c_str());
677             SendEndAppGalleryNotify(callName);
678             ClearSessionAndSchedInfo(callName);
679             NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED));
680             return;
681         }
682         session_->SetServiceSchedAction(callName, BConstants::ServiceSchedAction::CLEAN);
683         auto ret = LaunchBackupExtension(callName);
684         if (ret) {
685             /* Clear Session before notice client finish event */
686             HILOGE("Current bundle launch extension failed, bundleName:%{public}s", callName.c_str());
687             SendEndAppGalleryNotify(callName);
688             bool isRestoreEnd = session_->GetIsRestoreEnd(callName);
689             ClearSessionAndSchedInfo(callName);
690             /* Notice Client Ext Ability Process Died */
691             DoNoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED), isRestoreEnd);
692         }
693     } catch (...) {
694         HILOGE("Unexpected exception, bundleName: %{public}s", callName.c_str());
695         SendEndAppGalleryNotify(callName);
696         bool isRestoreEnd = session_->GetIsRestoreEnd(callName);
697         ClearSessionAndSchedInfo(callName);
698         DoNoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED), isRestoreEnd);
699     }
700     RemoveExtensionMutex(callName);
701 }
702 
OnBackupExtensionDied(const string && bundleName,bool isCleanCalled)703 void Service::OnBackupExtensionDied(const string &&bundleName, bool isCleanCalled)
704 {
705     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
706     if (isCleanCalled) {
707         HILOGE("Backup <%{public}s> Extension Process second Died", bundleName.c_str());
708         bool isRestoreEnd = session_->GetIsRestoreEnd(bundleName);
709         ClearSessionAndSchedInfo(bundleName);
710         DoNoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_DIED), isRestoreEnd);
711         OnAllBundlesFinished(BError(BError::Codes::OK));
712         return;
713     }
714     try {
715         string callName = move(bundleName);
716         HILOGE("Backup <%{public}s> Extension Process Died", callName.c_str());
717         ErrCode ret = session_->VerifyBundleName(callName);
718         if (ret != ERR_OK) {
719             HILOGE("Backup Extension died error, verify bundleName failed, bundleName:%{public}s, ret:%{public}d",
720                 bundleName.c_str(), ret);
721             ExtConnectDied(bundleName);
722             return;
723         }
724         // 重新连接清理缓存
725         HILOGI("Clear backup extension data, bundleName: %{public}s", callName.c_str());
726         ExtConnectDied(callName);
727     } catch (...) {
728         HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str());
729         ExtConnectDied(bundleName);
730         return;
731     }
732 }
733 
NoticeClientFinish(const string & bundleName,ErrCode errCode)734 void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode)
735 {
736     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
737     HILOGI("begin %{public}s", bundleName.c_str());
738     try {
739         auto scenario = session_->GetScenario();
740         if (scenario == IServiceReverseType::Scenario::BACKUP && session_->GetIsIncrementalBackup()) {
741             session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName);
742         } else if (scenario == IServiceReverseType::Scenario::RESTORE &&
743                 BackupPara().GetBackupOverrideIncrementalRestore() &&
744                 session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) {
745             session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleFinished(errCode, bundleName);
746         } else if (scenario == IServiceReverseType::Scenario::BACKUP) {
747             session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, bundleName);
748         } else if (scenario == IServiceReverseType::Scenario::RESTORE) {
749             session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, bundleName);
750         };
751         BundleEndRadarReport(bundleName, errCode, scenario);
752         /* If all bundle ext process finish, notice client. */
753         OnAllBundlesFinished(BError(BError::Codes::OK));
754     } catch(const BError &e) {
755         HILOGE("NoticeClientFinish exception, bundleName:%{public}s", bundleName.c_str());
756         ReleaseOnException();
757         return;
758     } catch (...) {
759         HILOGE("Unexpected exception");
760         ReleaseOnException();
761         return;
762     }
763 }
764 
TotalStatReport(ErrCode errCode)765 void Service::TotalStatReport(ErrCode errCode)
766 {
767     if (totalStatistic_ == nullptr) {
768         HILOGE("totalStat is null");
769         return;
770     }
771     totalStatistic_->totalSpendTime_.End();
772     totalStatistic_->Report("OnAllBundlesFinished", errCode);
773 }
774 
OnAllBundlesFinished(ErrCode errCode)775 void Service::OnAllBundlesFinished(ErrCode errCode)
776 {
777     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
778     HILOGI("called begin.");
779     if (session_->IsOnAllBundlesFinished()) {
780         IServiceReverseType::Scenario scenario = session_->GetScenario();
781         TotalStatReport(errCode);
782         if (isInRelease_.load() && (scenario == IServiceReverseType::Scenario::RESTORE)) {
783             HILOGI("Will destory session info");
784             SessionDeactive();
785         }
786         if (scenario == IServiceReverseType::Scenario::BACKUP && session_->GetIsIncrementalBackup()) {
787             session_->GetServiceReverseProxy()->IncrementalBackupOnAllBundlesFinished(errCode);
788         } else if (scenario == IServiceReverseType::Scenario::RESTORE &&
789                    BackupPara().GetBackupOverrideIncrementalRestore() &&
790                    session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) {
791             session_->GetServiceReverseProxy()->IncrementalRestoreOnAllBundlesFinished(errCode);
792         } else if (scenario == IServiceReverseType::Scenario::BACKUP) {
793             session_->GetServiceReverseProxy()->BackupOnAllBundlesFinished(errCode);
794         } else if (scenario == IServiceReverseType::Scenario::RESTORE) {
795             session_->GetServiceReverseProxy()->RestoreOnAllBundlesFinished(errCode);
796         }
797         if (!BackupPara().GetBackupOverrideBackupSARelease()) {
798             HILOGI("Will unload backup sa");
799             sched_->TryUnloadServiceTimer(true);
800         }
801     }
802     HILOGI("called end.");
803 }
804 
VerifySendRateParam()805 ErrCode Service::VerifySendRateParam()
806 {
807     ErrCode ret = VerifyCaller();
808     if (ret != ERR_OK) {
809         HILOGE("Update send rate fail, verify caller failed, ret:%{public}d", ret);
810         return ret;
811     }
812     IServiceReverseType::Scenario scenario = session_ -> GetScenario();
813     if (scenario != IServiceReverseType::Scenario::BACKUP) {
814         HILOGE("This method is applicable to the backup scenario");
815         return BError(BError::Codes::SA_INVAL_ARG);
816     }
817     return BError(BError::Codes::OK);
818 }
819 
HandleCurBundleFileReady(const std::string & bundleName,const std::string & fileName,bool isIncBackup)820 ErrCode Service::HandleCurBundleFileReady(const std::string &bundleName, const std::string &fileName, bool isIncBackup)
821 {
822     auto backUpConnection = session_->GetExtConnection(bundleName);
823     if (backUpConnection == nullptr) {
824         HILOGE("AppFileReady error, backUpConnection is empty, bundleName:%{public}s", bundleName.c_str());
825         return BError(BError::Codes::SA_INVAL_ARG);
826     }
827     auto proxy = backUpConnection->GetBackupExtProxy();
828     if (!proxy) {
829         HILOGE("AppFileReady error, Extension backup Proxy is empty, bundleName:%{public}s", bundleName.c_str());
830         return BError(BError::Codes::SA_INVAL_ARG);
831     }
832     // 通知extension清空缓存
833     proxy->HandleClear();
834     // 清除Timer
835     session_->StopFwkTimer(bundleName);
836     session_->StopExtTimer(bundleName);
837     // 通知TOOL 备份完成
838     if (isIncBackup) {
839         session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(BError(BError::Codes::OK),
840             bundleName);
841         BundleEndRadarReport(bundleName, BError(BError::Codes::OK), IServiceReverseType::Scenario::BACKUP);
842     } else {
843         session_->GetServiceReverseProxy()->BackupOnBundleFinished(BError(BError::Codes::OK), bundleName);
844         BundleEndRadarReport(bundleName, BError(BError::Codes::OK), session_->GetScenario());
845     }
846     // 断开extension
847     backUpConnection->DisconnectBackupExtAbility();
848     ClearSessionAndSchedInfo(bundleName);
849     return BError(BError::Codes::OK);
850 }
851 
HandleCurAppDone(ErrCode errCode,const std::string & bundleName,bool isIncBackup)852 ErrCode Service::HandleCurAppDone(ErrCode errCode, const std::string &bundleName, bool isIncBackup)
853 {
854     auto backUpConnection = session_->GetExtConnection(bundleName);
855     if (backUpConnection == nullptr) {
856         HILOGE("App finish error, backUpConnection is empty, bundleName:%{public}s", bundleName.c_str());
857         return BError(BError::Codes::SA_INVAL_ARG);
858     }
859     auto proxy = backUpConnection->GetBackupExtProxy();
860     if (!proxy) {
861         HILOGE("App finish error, extension backup Proxy is empty, bundleName:%{public}s", bundleName.c_str());
862         return BError(BError::Codes::SA_INVAL_ARG);
863     }
864     proxy->HandleClear();
865     session_->StopFwkTimer(bundleName);
866     session_->StopExtTimer(bundleName);
867     SendEndAppGalleryNotify(bundleName);
868     backUpConnection->DisconnectBackupExtAbility();
869     ClearSessionAndSchedInfo(bundleName);
870     if (isIncBackup) {
871         HILOGI("Incremental backup or restore app done, bundleName:%{public}s, errCode:%{public}d",
872             bundleName.c_str(), errCode);
873         NotifyCallerCurAppIncrementDone(errCode, bundleName);
874     } else {
875         HILOGI("Full backup or restore app done, bundleName:%{public}s, errCode:%{public}d",
876             bundleName.c_str(), errCode);
877         NotifyCallerCurAppDone(errCode, bundleName);
878     }
879     return BError(BError::Codes::OK);
880 }
881 
CallOnBundleEndByScenario(const std::string & bundleName,BackupRestoreScenario scenario,ErrCode errCode)882 void Service::CallOnBundleEndByScenario(const std::string &bundleName, BackupRestoreScenario scenario, ErrCode errCode)
883 {
884     if (session_ == nullptr) {
885         HILOGE("Session is empty, bundleName:%{public}s", bundleName.c_str());
886         return;
887     }
888     HILOGI("Begin");
889     try {
890         if (scenario == BackupRestoreScenario::FULL_RESTORE) {
891             session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, bundleName);
892         } else if (scenario == BackupRestoreScenario::INCREMENTAL_RESTORE) {
893             session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleFinished(errCode, bundleName);
894         } else if (scenario == BackupRestoreScenario::FULL_BACKUP) {
895             session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, bundleName);
896         } else if (scenario == BackupRestoreScenario::INCREMENTAL_BACKUP) {
897             session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName);
898         }
899     } catch (const BError &e) {
900         HILOGE("Call onBundleFinished error, client is died");
901         return;
902     }
903 }
904 
GetCallerName()905 std::string Service::GetCallerName()
906 {
907     std::string callerName;
908     uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID();
909     int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller);
910     switch (tokenType) {
911         case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: { /* Update Service */
912             Security::AccessToken::NativeTokenInfo nativeTokenInfo;
913             if (Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenCaller, nativeTokenInfo) != 0) {
914                 HILOGE("Failed to get native token info");
915                 break;
916             }
917             callerName = nativeTokenInfo.processName;
918             break;
919         }
920         case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: {
921             Security::AccessToken::HapTokenInfo hapTokenInfo;
922             if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) {
923                 HILOGE("Failed to get hap token info");
924                 break;
925             }
926             callerName = hapTokenInfo.bundleName;
927             break;
928         }
929         default:
930             HILOGE("Invalid token type, %{public}s", to_string(tokenType).c_str());
931             break;
932     }
933     return callerName;
934 }
935 
InitRestoreSessionWithErrMsg(const sptr<IServiceReverse> & remote,int32_t & errCodeForMsg,std::string & errMsg)936 ErrCode Service::InitRestoreSessionWithErrMsg(const sptr<IServiceReverse> &remote,
937                                               int32_t &errCodeForMsg, std::string &errMsg)
938 {
939     errCodeForMsg = InitRestoreSession(remote, errMsg);
940     HILOGI("Start InitRestoreSessionWithErrMsg, errCode:%{public}d, Msg :%{public}s",
941            errCodeForMsg,
942            errMsg.c_str());
943     return ERR_OK;
944 }
945 
InitRestoreSession(const sptr<IServiceReverse> & remote,std::string & errMsg)946 ErrCode Service::InitRestoreSession(const sptr<IServiceReverse>& remote, std::string &errMsg)
947 {
948     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
949     totalStatistic_ = std::make_shared<RadarTotalStatistic>(BizScene::RESTORE, GetCallerName());
950     ErrCode ret = VerifyCaller();
951     if (ret != ERR_OK) {
952         HILOGE("Init restore session failed, verify caller failed");
953         totalStatistic_->Report("InitRestoreSession", MODULE_INIT, ret);
954         return ret;
955     }
956     ret = session_->Active({
957         .clientToken = IPCSkeleton::GetCallingTokenID(),
958         .scenario = IServiceReverseType::Scenario::RESTORE,
959         .clientProxy = remote,
960         .userId = GetUserIdDefault(),
961         .callerName = GetCallerName(),
962         .activeTime = TimeUtils::GetCurrentTime(),
963     });
964     if (ret == ERR_OK) {
965         ClearFailedBundles();
966         successBundlesNum_ = 0;
967         ClearBundleRadarReport();
968         ClearFileReadyRadarReport();
969         return ret;
970     }
971     totalStatistic_->Report("InitRestoreSession", MODULE_INIT, ret);
972     if (ret == BError(BError::Codes::SA_SESSION_CONFLICT)) {
973         errMsg = BJsonUtil::BuildInitSessionErrInfo(session_->GetSessionUserId(),
974                                                     session_->GetSessionCallerName(),
975                                                     session_->GetSessionActiveTime());
976         HILOGE("Active restore session error, Already have a session");
977         return ret;
978     }
979     HILOGE("Active restore session error");
980     StopAll(nullptr, true);
981     return ret;
982 }
983 
InitBackupSessionWithErrMsg(const sptr<IServiceReverse> & remote,int32_t & errCodeForMsg,std::string & errMsg)984 ErrCode Service::InitBackupSessionWithErrMsg(const sptr<IServiceReverse>& remote,
985                                              int32_t &errCodeForMsg, std::string &errMsg)
986 {
987     errCodeForMsg = InitBackupSession(remote, errMsg);
988     HILOGI("Start InitBackupSessionWithErrMsg, errCode:%{public}d, Msg :%{public}s",
989            errCodeForMsg,
990            errMsg.c_str());
991     return ERR_OK;
992 }
993 
InitBackupSession(const sptr<IServiceReverse> & remote,std::string & errMsg)994 ErrCode Service::InitBackupSession(const sptr<IServiceReverse>& remote, std::string &errMsg)
995 {
996     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
997     totalStatistic_ = std::make_shared<RadarTotalStatistic>(BizScene::BACKUP, GetCallerName());
998     ErrCode ret = VerifyCaller();
999     if (ret != ERR_OK) {
1000         HILOGE("Init full backup session fail, verify caller failed");
1001         totalStatistic_->Report("InitBackupSessionWithErrMsg", MODULE_INIT, ret);
1002         return ret;
1003     }
1004     int32_t oldSize = StorageMgrAdapter::UpdateMemPara(BConstants::BACKUP_VFS_CACHE_PRESSURE);
1005     HILOGI("InitBackupSession oldSize %{public}d", oldSize);
1006     session_->SetMemParaCurSize(oldSize);
1007     ret = session_->Active({
1008         .clientToken = IPCSkeleton::GetCallingTokenID(),
1009         .scenario = IServiceReverseType::Scenario::BACKUP,
1010         .clientProxy = remote,
1011         .userId = GetUserIdDefault(),
1012         .callerName = GetCallerName(),
1013         .activeTime = TimeUtils::GetCurrentTime(),
1014     });
1015     if (ret == ERR_OK) {
1016         ClearFailedBundles();
1017         successBundlesNum_ = 0;
1018         ClearBundleRadarReport();
1019         ClearFileReadyRadarReport();
1020         return ret;
1021     }
1022     totalStatistic_->Report("InitBackupSessionWithErrMsg", MODULE_INIT, ret);
1023     if (ret == BError(BError::Codes::SA_SESSION_CONFLICT)) {
1024         errMsg = BJsonUtil::BuildInitSessionErrInfo(session_->GetSessionUserId(),
1025                                                     session_->GetSessionCallerName(),
1026                                                     session_->GetSessionActiveTime());
1027         HILOGE("Active backup session error, Already have a session");
1028         return ret;
1029     }
1030     HILOGE("Active backup session error");
1031     StopAll(nullptr, true);
1032     return ret;
1033 }
1034 
GetLocalCapabilitiesForBundleInfos(int & fd)1035 ErrCode Service::GetLocalCapabilitiesForBundleInfos(int &fd)
1036 {
1037     UniqueFd uniqueFd(GetLocalCapabilitiesForBundleInfos());
1038     fd = uniqueFd.Release();
1039     return ErrCode(BError::Codes::OK);
1040 }
1041 
GetLocalCapabilitiesForBundleInfos()1042 UniqueFd Service::GetLocalCapabilitiesForBundleInfos()
1043 {
1044     try {
1045         HILOGI("start GetLocalCapabilitiesForBundleInfos");
1046         if (session_ == nullptr) {
1047             HILOGE("GetLocalCapabilitiesForBundleInfos failed, session is nullptr");
1048             return UniqueFd(-EPERM);
1049         }
1050         ErrCode ret = VerifyCaller();
1051         if (ret != ERR_OK) {
1052             HILOGE("GetLocalCapabilitiesForBundleInfos failed, verify caller failed");
1053             return UniqueFd(-EPERM);
1054         }
1055         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1056         string path = BConstants::GetSaBundleBackupRootDir(GetUserIdDefault());
1057         BExcepUltils::VerifyPath(path, false);
1058         CreateDirIfNotExist(path);
1059         UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR));
1060         if (fd < 0) {
1061             HILOGE("Failed to open config file = %{private}s, err = %{public}d", path.c_str(), errno);
1062             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1063             return UniqueFd(-EPERM);
1064         }
1065         BJsonCachedEntity<BJsonEntityCaps> cachedEntity(std::move(fd));
1066         auto cache = cachedEntity.Structuralize();
1067         cache.SetSystemFullName(GetOSFullName());
1068         cache.SetDeviceType(GetDeviceType());
1069         auto bundleInfos = BundleMgrAdapter::GetBundleInfosForLocalCapabilities(GetUserIdDefault());
1070         if (bundleInfos.size() == 0) {
1071             HILOGE("getBundleInfos failed, size = 0");
1072             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1073             return UniqueFd(-EPERM);
1074         }
1075         cache.SetBundleInfos(bundleInfos);
1076         cachedEntity.Persist();
1077         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1078         HILOGI("End");
1079         return move(cachedEntity.GetFd());
1080     } catch (const BError &e) {
1081         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1082         HILOGE("GetLocalCapabilitiesForBundleInfos failed, errCode = %{public}d", e.GetCode());
1083         return UniqueFd(-e.GetCode());
1084     } catch (...) {
1085         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1086         HILOGI("Unexpected exception");
1087         return UniqueFd(-EPERM);
1088     }
1089 }
1090 
GetBackupDataSize(bool isPreciseScan,const std::vector<BIncrementalData> & bundleNameList)1091 ErrCode Service::GetBackupDataSize(bool isPreciseScan, const std::vector<BIncrementalData>& bundleNameList)
1092 {
1093     try {
1094         HILOGI("start GetBackupDataSize");
1095         if (session_ == nullptr || onScanning_.load()) {
1096             HILOGE("GetBackupDataSize error 1.session is nullptr 2.onScanning_ = %{public}d", onScanning_.load());
1097             return BError(BError::Codes::SA_INVAL_ARG);
1098         }
1099         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1100         onScanning_.store(true);
1101         ErrCode ret = VerifyCaller();
1102         if (ret != ERR_OK) {
1103             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1104             return BError(BError::Codes::SA_INVAL_ARG, "verify caller failed");
1105         }
1106         CyclicSendScannedInfo(isPreciseScan, bundleNameList);
1107         return BError(BError::Codes::OK);
1108     } catch (...) {
1109         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1110         return BError(BError::Codes::SA_INVAL_ARG);
1111     }
1112 }
1113 
CyclicSendScannedInfo(bool isPreciseScan,vector<BIncrementalData> bundleNameList)1114 void Service::CyclicSendScannedInfo(bool isPreciseScan, vector<BIncrementalData> bundleNameList)
1115 {
1116     auto task = [isPreciseScan {isPreciseScan}, bundleNameList {move(bundleNameList)},
1117         obj {wptr<Service>(this)}, session {session_}]() {
1118         auto ptr = obj.promote();
1119         if (ptr == nullptr) {
1120             HILOGE("ptr is nullptr");
1121             session->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1122             return;
1123         }
1124         size_t listSize = bundleNameList.size();
1125         HILOGI("need scanf num = %{public}zu", listSize);
1126         string scanning;
1127         size_t allScannedSize = 0;
1128         ptr->GetDataSizeStepByStep(isPreciseScan, bundleNameList, scanning);
1129         while (!ptr->isScannedEnd_.load()) {
1130             std::unique_lock<mutex> lock(ptr->getDataSizeLock_);
1131             ptr->getDataSizeCon_.wait_for(lock, std::chrono::seconds(WAIT_SCANNING_INFO_SEND_TIME),
1132                 [ptr] { return ptr->isScannedEnd_.load(); });
1133             auto scannedSize = ptr->bundleDataSizeList_.size();
1134             allScannedSize += scannedSize;
1135             HILOGI("ScannedSize = %{public}zu, allScannedSize = %{public}zu", scannedSize, allScannedSize);
1136             if (!ptr->GetScanningInfo(obj, scannedSize, scanning)) {
1137                 ptr->SendScannedInfo("", session);
1138                 continue;
1139             }
1140             ptr->DeleteFromList(scannedSize);
1141             ptr->SendScannedInfo(ptr->scannedInfo_, session);
1142         }
1143         ptr->isScannedEnd_.store(false);
1144         session->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1145     };
1146 
1147     callbackScannedInfoThreadPool_.AddTask([task, session {session_}]() {
1148         try {
1149             task();
1150         } catch (...) {
1151             session->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1152             HILOGE("Failed to add task to thread pool");
1153         }
1154     });
1155 }
1156 
GetDataSizeStepByStep(bool isPreciseScan,vector<BIncrementalData> bundleNameList,string & scanning)1157 void Service::GetDataSizeStepByStep(bool isPreciseScan, vector<BIncrementalData> bundleNameList, string &scanning)
1158 {
1159     auto task = [isPreciseScan {isPreciseScan}, bundleNameList {move(bundleNameList)},
1160         &scanning, obj {wptr<Service>(this)}]() {
1161         auto ptr = obj.promote();
1162         if (ptr == nullptr) {
1163             HILOGE("ptr is nullptr");
1164             return;
1165         }
1166         if (!isPreciseScan) {
1167             HILOGI("start GetPresumablySize");
1168             ptr->GetPresumablySize(bundleNameList, scanning);
1169         } else {
1170             HILOGI("start GetPrecisesSize");
1171             ptr->GetPrecisesSize(bundleNameList, scanning);
1172         }
1173         std::lock_guard lock(ptr->getDataSizeLock_);
1174         ptr->isScannedEnd_.store(true);
1175         ptr->getDataSizeCon_.notify_all();
1176         ptr->onScanning_.store(false);
1177     };
1178 
1179     getDataSizeThreadPool_.AddTask([task]() {
1180         try {
1181             task();
1182         } catch (...) {
1183             HILOGE("Failed to add task to thread pool");
1184         }
1185     });
1186 }
1187 
GetPresumablySize(vector<BIncrementalData> bundleNameList,string & scanning)1188 void Service::GetPresumablySize(vector<BIncrementalData> bundleNameList, string &scanning)
1189 {
1190     int32_t userId = GetUserIdDefault();
1191     for (const auto &bundleData : bundleNameList) {
1192         string name = bundleData.bundleName;
1193         SetScanningInfo(scanning, name);
1194         if (SAUtils::IsSABundleName(name)) {
1195             WriteScannedInfoToList(name, 0, ERR_SIZE);
1196             continue;
1197         }
1198         int64_t dataSize = BundleMgrAdapter::GetBundleDataSize(name, userId);
1199         if (dataSize == 0) {
1200             WriteScannedInfoToList(name, ERR_SIZE, ERR_SIZE);
1201             continue;
1202         }
1203         WriteScannedInfoToList(name, dataSize, ERR_SIZE);
1204     }
1205     SetScanningInfo(scanning, "");
1206     HILOGI("GetPresumablySize end");
1207 }
1208 
GetPrecisesSize(vector<BIncrementalData> bundleNameList,string & scanning)1209 void Service::GetPrecisesSize(vector<BIncrementalData> bundleNameList, string &scanning)
1210 {
1211     for (const auto &bundleData : bundleNameList) {
1212         vector<string> bundleNames;
1213         vector<int64_t> lastBackTimes;
1214         string name = bundleData.bundleName;
1215         SetScanningInfo(scanning, name);
1216         BJsonUtil::BundleDetailInfo bundleDetail = BJsonUtil::ParseBundleNameIndexStr(name);
1217         if (bundleDetail.bundleIndex > 0) {
1218             std::string bundleNameIndex  = "+clone-" + std::to_string(bundleDetail.bundleIndex) + "+" +
1219             bundleDetail.bundleName;
1220             bundleNames.push_back(bundleNameIndex);
1221         } else {
1222             bundleNames.push_back(name);
1223         }
1224         int64_t lastTime = bundleData.lastIncrementalTime;
1225         lastBackTimes.push_back(lastTime);
1226         vector<int64_t> pkgFileSizes {};
1227         vector<int64_t> incPkgFileSizes {};
1228         int32_t err = StorageMgrAdapter::GetBundleStatsForIncrease(GetUserIdDefault(), bundleNames, lastBackTimes,
1229             pkgFileSizes, incPkgFileSizes);
1230         if (err != 0) {
1231             HILOGE("filed to get datasize from storage, err =%{public}d, bundlename = %{public}s, index = %{public}d",
1232                 err, name.c_str(), bundleDetail.bundleIndex);
1233             WriteScannedInfoToList(name, ERR_SIZE, ERR_SIZE);
1234             continue;
1235         }
1236         if (lastTime == 0 && pkgFileSizes.size() > 0) {
1237             WriteScannedInfoToList(name, pkgFileSizes[0], ERR_SIZE);
1238         } else if (pkgFileSizes.size() > 0 && incPkgFileSizes.size() > 0) {
1239             WriteScannedInfoToList(name, pkgFileSizes[0], incPkgFileSizes[0]);
1240         } else {
1241             HILOGE ("pkgFileSizes or incPkgFileSizes error, %{public}zu, %{public}zu",
1242                 pkgFileSizes.size(), incPkgFileSizes.size());
1243         }
1244     }
1245     SetScanningInfo(scanning, "");
1246     HILOGI("GetPrecisesSize end");
1247 }
1248 
WriteToList(BJsonUtil::BundleDataSize bundleDataSize)1249 void Service::WriteToList(BJsonUtil::BundleDataSize bundleDataSize)
1250 {
1251     std::lock_guard<std::mutex> lock(scannedListLock_);
1252     bundleDataSizeList_.push_back(bundleDataSize);
1253 }
1254 
DeleteFromList(size_t scannedSize)1255 void Service::DeleteFromList(size_t scannedSize)
1256 {
1257     std::lock_guard<std::mutex> lock(scannedListLock_);
1258     bundleDataSizeList_.erase(bundleDataSizeList_.begin(), bundleDataSizeList_.begin() + scannedSize);
1259 }
1260 
GetScanningInfo(wptr<Service> obj,size_t scannedSize,string & scanning)1261 bool Service::GetScanningInfo(wptr<Service> obj, size_t scannedSize, string &scanning)
1262 {
1263     auto ptr = obj.promote();
1264     if (ptr == nullptr) {
1265         HILOGE("ptr is nullptr");
1266         return false;
1267     }
1268     std::lock_guard<std::mutex> lock(scannedListLock_);
1269     if (!BJsonUtil::WriteToStr(ptr->bundleDataSizeList_, scannedSize, scanning, ptr->scannedInfo_)) {
1270         return false;
1271     }
1272     return true;
1273 }
1274 
SetScanningInfo(string & scanning,string name)1275 void Service::SetScanningInfo(string &scanning, string name)
1276 {
1277     std::lock_guard<std::mutex> lock(scannedListLock_);
1278     scanning = name;
1279 }
1280 
WriteScannedInfoToList(const string & bundleName,int64_t dataSize,int64_t incDataSize)1281 void Service::WriteScannedInfoToList(const string &bundleName, int64_t dataSize, int64_t incDataSize)
1282 {
1283     BJsonUtil::BundleDataSize bundleDataSize;
1284     bundleDataSize.bundleName = bundleName;
1285     bundleDataSize.dataSize = dataSize;
1286     bundleDataSize.incDataSize = incDataSize;
1287     HILOGI("name = %{public}s, size = %{public}" PRId64 ", incSize = %{public}" PRId64 "",
1288         bundleName.c_str(), dataSize, incDataSize);
1289     WriteToList(bundleDataSize);
1290 }
1291 
SendScannedInfo(const string & scannendInfos,sptr<SvcSessionManager> session)1292 void Service::SendScannedInfo(const string&scannendInfos, sptr<SvcSessionManager> session)
1293 {
1294     if (scannendInfos.empty()) {
1295         HILOGE("write json failed , info is null");
1296     }
1297     if (session == nullptr) {
1298         HILOGE("session is nullptr");
1299         return;
1300     }
1301     HILOGI("start send scanned info");
1302     auto task = [session {session}, scannendInfos {scannendInfos}]() {
1303         if (session->GetScenario() == IServiceReverseType::Scenario::BACKUP && session->GetIsIncrementalBackup()) {
1304             HILOGI("this is incremental backup sending info");
1305             session->GetServiceReverseProxy()->IncrementalBackupOnScanningInfo(scannendInfos);
1306             return;
1307         }
1308         HILOGI("this is full backup sending info");
1309         session->GetServiceReverseProxy()->BackupOnScanningInfo(scannendInfos);
1310     };
1311 
1312     sendScannendResultThreadPool_.AddTask([task]() {
1313         try {
1314             task();
1315         } catch (...) {
1316             HILOGE("Failed to add task to thread pool");
1317         }
1318     });
1319 }
1320 
StartExtTimer(bool & isExtStart)1321 ErrCode Service::StartExtTimer(bool &isExtStart)
1322 {
1323     try {
1324         HILOGI("Service::StartExtTimer begin.");
1325         if (session_ == nullptr) {
1326             HILOGE("StartExtTimer error, session_ is nullptr.");
1327             isExtStart = false;
1328             return BError(BError::Codes::SA_INVAL_ARG);
1329         }
1330         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1331         string bundleName;
1332         ErrCode ret = VerifyCallerAndGetCallerName(bundleName);
1333         if (ret != ERR_OK) {
1334             HILOGE("Start extension timer fail, get bundleName failed, ret:%{public}d", ret);
1335             isExtStart = false;
1336             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1337             return ret;
1338         }
1339         auto timeoutCallback = TimeOutCallback(wptr<Service>(this), bundleName);
1340         session_->StopFwkTimer(bundleName);
1341         isExtStart = session_->StartExtTimer(bundleName, timeoutCallback);
1342         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1343         return BError(BError::Codes::OK);
1344     } catch (...) {
1345         HILOGE("Unexpected exception");
1346         isExtStart = false;
1347         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1348         return EPERM;
1349     }
1350 }
1351 
StartFwkTimer(bool & isFwkStart)1352 ErrCode Service::StartFwkTimer(bool &isFwkStart)
1353 {
1354     try {
1355         HILOGI("Service::StartFwkTimer begin.");
1356         if (session_ == nullptr) {
1357             HILOGE("StartFwkTimer error, session_ is nullptr.");
1358             isFwkStart = false;
1359             return BError(BError::Codes::SA_INVAL_ARG);
1360         }
1361         session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1362         std::string bundleName;
1363         ErrCode ret = VerifyCallerAndGetCallerName(bundleName);
1364         if (ret != ERR_OK) {
1365             HILOGE("Start fwk timer fail, get bundleName failed, ret:%{public}d", ret);
1366             isFwkStart = false;
1367             session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1368             return ret;
1369         }
1370         auto timeoutCallback = TimeOutCallback(wptr<Service>(this), bundleName);
1371         session_->StopExtTimer(bundleName);
1372         isFwkStart = session_->StartFwkTimer(bundleName, timeoutCallback);
1373         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1374         return BError(BError::Codes::OK);
1375     } catch (...) {
1376         HILOGE("Unexpected exception");
1377         isFwkStart = false;
1378         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1379         return EPERM;
1380     }
1381 }
1382 
TryToConnectExt(const std::string & bundleName,sptr<SvcBackupConnection> & extConnection)1383 ErrCode Service::TryToConnectExt(const std::string& bundleName, sptr<SvcBackupConnection>& extConnection)
1384 {
1385     extConnection = session_->GetExtConnection(bundleName);
1386     if (extConnection != nullptr && extConnection->IsExtAbilityConnected()) {
1387         return BError(BError::Codes::OK);
1388     }
1389     if (extConnection == nullptr) {
1390         extConnection = session_->CreateBackupConnection(bundleName);
1391         if (extConnection == nullptr) {
1392             HILOGE("backupConnection is null, bundleName: %{public}s", bundleName.c_str());
1393             return BError(BError::Codes::SA_INVAL_ARG);
1394         }
1395     }
1396     auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName);
1397     auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName);
1398     extConnection->SetCallback(callConnected);
1399     extConnection->SetCallDied(callDied);
1400     AAFwk::Want want = CreateConnectWant(bundleName);
1401     ErrCode err = extConnection->ConnectBackupExtAbility(want, GetUserIdDefault(), false);
1402     if (err != BError(BError::Codes::OK)) {
1403         HILOGE("ConnectBackupExtAbility failed, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), err);
1404         return BError(BError::Codes::SA_BOOT_EXT_FAIL);
1405     }
1406     return BError(BError::Codes::OK);
1407 }
1408 
CleanBundleTempDir(const string & bundleName)1409 ErrCode Service::CleanBundleTempDir(const string &bundleName)
1410 {
1411     HILOGI("Service::CleanBundleTempDir");
1412     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1413     ErrCode err = VerifyCaller();
1414     if (err != ERR_OK) {
1415         HILOGE("VerifyCaller failed");
1416         return err;
1417     }
1418     if (session_ == nullptr) {
1419         HILOGE("session is empty.");
1420         return BError(BError::Codes::SA_INVAL_ARG);
1421     }
1422     sptr<SvcBackupConnection> backupConnection;
1423     err = TryToConnectExt(bundleName, backupConnection);
1424     if (err != BError(BError::Codes::OK)) {return err;}
1425 
1426     std::unique_lock<std::mutex> lock(getBackupInfoSyncLock_);
1427     getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S));
1428     if (isConnectDied_.load()) {
1429         HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str());
1430         isConnectDied_.store(false);
1431         return BError(BError::Codes::EXT_ABILITY_DIED);
1432     }
1433 
1434     session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1435     if (backupConnection == nullptr) {
1436         HILOGE("backupConnection is empty.");
1437         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1438         return BError(BError::Codes::SA_INVAL_ARG);
1439     }
1440     auto proxy = backupConnection->GetBackupExtProxy();
1441     if (!proxy) {
1442         HILOGE("Extension backup Proxy is empty.");
1443         backupConnection->DisconnectBackupExtAbility();
1444         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1445         return BError(BError::Codes::SA_INVAL_ARG);
1446     }
1447     proxy->CleanBundleTempDir();
1448     backupConnection->DisconnectBackupExtAbility();
1449     session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1450     return BError(BError::Codes::OK);
1451 }
1452 
HandleExtDisconnect(BackupRestoreScenario scenario,bool isAppResultReport,ErrCode errCode)1453 ErrCode Service::HandleExtDisconnect(BackupRestoreScenario scenario, bool isAppResultReport, ErrCode errCode)
1454 {
1455     HILOGI("begin, scenario: %{public}d, isAppResultReport:%{public}d, errCode:%{public}d", scenario,
1456         isAppResultReport, errCode);
1457     std::string callerName;
1458     auto ret = VerifyCallerAndGetCallerName(callerName);
1459     if (ret != ERR_OK) {
1460         HILOGE("HandleExtDisconnect VerifyCaller failed, get bundle failed, ret:%{public}d", ret);
1461         if (isAppResultReport) {
1462             HandleCurBundleEndWork(callerName, scenario);
1463             OnAllBundlesFinished(BError(BError::Codes::OK));
1464         }
1465         return ret;
1466     }
1467     if (isAppResultReport && (scenario == BackupRestoreScenario::FULL_RESTORE ||
1468         scenario == BackupRestoreScenario::INCREMENTAL_RESTORE)) {
1469         HandleCurBundleEndWork(callerName, scenario);
1470         OnAllBundlesFinished(BError(BError::Codes::OK));
1471     } else if (!isAppResultReport) {
1472         bool isIncBackup = true;
1473         if (scenario == BackupRestoreScenario::FULL_BACKUP || scenario == BackupRestoreScenario::FULL_RESTORE) {
1474             isIncBackup = false;
1475         }
1476         std::shared_ptr<ExtensionMutexInfo> mutexPtr = GetExtensionMutex(callerName);
1477         if (mutexPtr == nullptr) {
1478             HILOGE("extension mutex ptr is nullptr, bundleName:%{public}s", callerName.c_str());
1479             return BError(BError::Codes::SA_INVAL_ARG);
1480         }
1481         std::lock_guard<std::mutex> lock(mutexPtr->callbackMutex);
1482         ret = HandleCurAppDone(errCode, callerName, isIncBackup);
1483         if (ret != ERR_OK) {
1484             HILOGE("Handle current app done error, bundleName:%{public}s", callerName.c_str());
1485             return ret;
1486         }
1487         RemoveExtensionMutex(callerName);
1488         RemoveExtOnRelease(callerName);
1489         OnAllBundlesFinished(BError(BError::Codes::OK));
1490     }
1491     return ret;
1492 }
1493 
GetExtOnRelease(bool & isExtOnRelease)1494 ErrCode Service::GetExtOnRelease(bool &isExtOnRelease)
1495 {
1496     std::string bundleName;
1497     auto ret = VerifyCallerAndGetCallerName(bundleName);
1498     if (ret != ERR_OK) {
1499         HILOGE("GetExtOnRelease VerifyCaller failed, get bundle failed, ret:%{public}d", ret);
1500         return ret;
1501     }
1502     auto it = backupExtOnReleaseMap_.find(bundleName);
1503     if (it == backupExtOnReleaseMap_.end()) {
1504         HILOGI("BackupExtOnReleaseMap not contain %{public}s", bundleName.c_str());
1505         backupExtOnReleaseMap_[bundleName] = false;
1506         isExtOnRelease = backupExtOnReleaseMap_[bundleName].load();
1507         return ret;
1508     }
1509     HILOGI("BackupExtOnReleaseMap contain %{public}s", bundleName.c_str());
1510     isExtOnRelease = backupExtOnReleaseMap_[bundleName].load();
1511     return ret;
1512 }
1513 
SetExtOnRelease(const BundleName & bundleName,bool isOnRelease)1514 void Service::SetExtOnRelease(const BundleName &bundleName, bool isOnRelease)
1515 {
1516     HILOGI("Set bundleName:%{public}s isOnRelease:%{public}d", bundleName.c_str(), isOnRelease);
1517     auto it = backupExtOnReleaseMap_.find(bundleName);
1518     if (it == backupExtOnReleaseMap_.end()) {
1519         backupExtOnReleaseMap_[bundleName] = isOnRelease;
1520         return;
1521     }
1522     it->second.store(isOnRelease);
1523 }
1524 
RemoveExtOnRelease(const BundleName & bundleName)1525 void Service::RemoveExtOnRelease(const BundleName &bundleName)
1526 {
1527     auto it = backupExtOnReleaseMap_.find(bundleName);
1528     if (it == backupExtOnReleaseMap_.end()) {
1529         HILOGI("BackupExtOnReleaseMap not contain %{public}s", bundleName.c_str());
1530         return;
1531     }
1532     backupExtOnReleaseMap_.erase(it);
1533 }
1534 
HandleOnReleaseAndDisconnect(sptr<SvcSessionManager> sessionPtr,const std::string & bundleName)1535 void Service::HandleOnReleaseAndDisconnect(sptr<SvcSessionManager> sessionPtr, const std::string &bundleName)
1536 {
1537     if (sessionPtr == nullptr) {
1538         HILOGE("SessionPtr is nullptr.");
1539         return;
1540     }
1541     auto sessionConnection = sessionPtr->GetExtConnection(bundleName);
1542     if (sessionConnection == nullptr) {
1543         HILOGE("Error, sessionConnection is empty, bundleName:%{public}s", bundleName.c_str());
1544         return;
1545     }
1546     auto proxy = sessionConnection->GetBackupExtProxy();
1547     if (!proxy) {
1548         HILOGE("Extension backup Proxy is empty");
1549         return;
1550     }
1551     sessionPtr->HandleOnRelease(proxy);
1552     sessionConnection->DisconnectBackupExtAbility();
1553 }
1554 
GetCompatibilityInfo(const std::string & bundleName,const std::string & extInfo,std::string & compatInfo)1555 ErrCode Service::GetCompatibilityInfo(const std::string &bundleName, const std::string &extInfo,
1556     std::string &compatInfo)
1557 {
1558     HILOGI("Service::GetCompatibilityInfo begin bundleName: %{public}s", bundleName.c_str());
1559     HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__);
1560     ErrCode err = VerifyCaller();
1561     if (err != ERR_OK) {
1562         HILOGE("VerifyCaller failed");
1563         return err;
1564     }
1565     if (SAUtils::IsSABundleName(bundleName)) {
1566         HILOGE("SA not support");
1567         return BError(BError::Codes::SA_INVAL_ARG);
1568     }
1569     if (session_ == nullptr) {
1570         HILOGE("session is empty or busy");
1571         return BError(BError::Codes::SA_INVAL_ARG);
1572     }
1573     sptr<SvcBackupConnection> backupConnection;
1574     err = TryToConnectExt(bundleName, backupConnection);
1575     if (err != BError(BError::Codes::OK)) {
1576         return err;
1577     }
1578     std::unique_lock<std::mutex> lock(getBackupInfoSyncLock_);
1579     getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S));
1580     if (isConnectDied_.load()) {
1581         HILOGE("backupConnection connect timeout");
1582         isConnectDied_.store(false);
1583         return BError(BError::Codes::EXT_ABILITY_DIED);
1584     }
1585     session_->IncreaseSessionCnt(__PRETTY_FUNCTION__);
1586     auto proxy = backupConnection->GetBackupExtProxy();
1587     if (!proxy) {
1588         HILOGE("Extension backup Proxy is empty.");
1589         backupConnection->DisconnectBackupExtAbility();
1590         session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1591         return BError(BError::Codes::SA_INVAL_ARG);
1592     }
1593     err = proxy->HandleGetCompatibilityInfo(extInfo, static_cast<int32_t>(session_->GetScenario()), compatInfo);
1594     if (err != BError(BError::Codes::OK)) {
1595         HILOGE("HandleGetCompatibilityInfo failed");
1596     }
1597     backupConnection->DisconnectBackupExtAbility();
1598     session_->DecreaseSessionCnt(__PRETTY_FUNCTION__);
1599     return err;
1600 }
1601 
DoNoticeClientFinish(const std::string & bundleName,ErrCode errCode,bool isRestoreEnd)1602 void Service::DoNoticeClientFinish(const std::string &bundleName, ErrCode errCode, bool isRestoreEnd)
1603 {
1604     if (!isRestoreEnd) {
1605         NoticeClientFinish(bundleName, errCode);
1606     }
1607 }
1608 }