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