From 6986c372ad72cdd91667ff05a74b45167245eeb0 Mon Sep 17 00:00:00 2001 From: "yaoruozi1@huawei.com" Date: Wed, 25 Dec 2024 09:06:11 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81=EF=BC=8C?= =?UTF-8?q?=E5=8E=BB=E9=99=A4throw=20part1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yaoruozi1@huawei.com --- .../backup_sa/include/module_ipc/service.h | 16 +- .../include/module_ipc/svc_session_manager.h | 12 +- services/backup_sa/src/module_ipc/service.cpp | 515 ++++++++---------- .../src/module_ipc/service_incremental.cpp | 293 +++++----- .../backup_sa/src/module_ipc/sub_service.cpp | 336 ++++++++---- .../src/module_ipc/svc_session_manager.cpp | 85 ++- tests/mock/module_ipc/service_mock.cpp | 14 +- .../src/svc_session_manager_mock.cpp | 31 +- .../module_ipc/svc_session_manager_mock.cpp | 22 +- .../svc_session_manager_throw_mock.cpp | 24 +- .../svc_session_manager_throw_mock.h | 24 +- tests/unittests/backup_sa/module_ipc/BUILD.gn | 8 +- .../module_ipc/service_incremental_test.cpp | 20 +- .../module_ipc/service_other_test.cpp | 142 +++-- .../module_ipc/service_throw_test.cpp | 449 ++++++++------- .../backup_sa/module_ipc/sub_service_test.cpp | 4 + .../module_ipc/svc_session_manager_test.cpp | 254 ++++----- 17 files changed, 1201 insertions(+), 1048 deletions(-) diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index d877ad4a6..d539c3840 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -325,21 +325,21 @@ private: * @brief 验证调用者 * */ - void VerifyCaller(); + ErrCode VerifyCaller(); /** * @brief 验证调用者 * * @param scenario Scenario状态 */ - void VerifyCaller(IServiceReverse::Scenario scenario); + ErrCode VerifyCaller(IServiceReverse::Scenario scenario); /** * @brief 验证调用者并返回名称 * - * @return std::string + * @return ErrCode */ - std::string VerifyCallerAndGetCallerName(); + ErrCode VerifyCallerAndGetCallerName(std::string &bundleName); /** * @brief 清除Session Sched相关资源 @@ -554,7 +554,7 @@ private: void ClearFailedBundles(); void CreateDirIfNotExist(const std::string &path); - + void GetOldDeviceBackupVersion(); std::vector GetSupportBackupBundleNames(vector &bundleInfos, @@ -568,8 +568,12 @@ private: void SetBundleIncDataInfo(const std::vector &bundlesToBackup, std::vector &supportBundleNames); - + void CancelTask(std::string bundleName, wptr ptr); + + void SetUserIdAndRestoreType(RestoreTypeEnum restoreType, int32_t userId); + + ErrCode VerifySendRateParam(); private: static sptr instance_; static std::mutex instanceLock_; diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h index 1d63fdf2b..51b13b07e 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -103,7 +103,7 @@ public: * @throw BError::Codes::SA_REFUSED_ACT 调用者不是会话所有者 * @throw BError::Codes::SDK_MIXED_SCENARIO 调用者在备份/恢复场景使用了不匹配的函数 */ - void VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const; + ErrCode VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const; /** * @brief 激活会话 @@ -119,7 +119,7 @@ public: * @param remoteInAction 尝试关闭会话的客户端代理。只有激活会话的客户端代理有权关闭会话 * @param force 强制关闭 */ - void Deactive(const wptr &remoteInAction, bool force = false); + ErrCode Deactive(const wptr &remoteInAction, bool force = false); /** * @brief 检验调用者给定的bundleName是否是有效的 @@ -127,7 +127,7 @@ public: * @param bundleName 调用者名称 * @throw BError::Codes::SA_REFUSED_ACT 调用者不是会话所有者 */ - void VerifyBundleName(std::string &bundleName); + ErrCode VerifyBundleName(std::string &bundleName); /** * @brief 获取IServiceReverse @@ -301,14 +301,14 @@ public: * * @return ErrCode */ - void Start(); + ErrCode Start(); /** * @brief 结束追加应用 * * @return ErrCode */ - void Finish(); + ErrCode Finish(); /** * @brief 整个备份恢复流程是否结束 @@ -552,7 +552,7 @@ private: * * @param newImpl */ - void InitClient(Impl &newImpl); + ErrCode InitClient(Impl &newImpl); /** * @brief 获取BackupExtNameMap iterator diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 5cc8e65cd..335987159 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -268,13 +268,18 @@ UniqueFd Service::GetLocalCapabilities() return UniqueFd(-EPERM); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); - VerifyCaller(); + ErrCode errCode = VerifyCaller(); + if (errCode != ERR_OK) { + HILOGE("Get local abilities failed, Verify caller failed, errCode:%{public}d", errCode); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return UniqueFd(-EPERM); + } string path = BConstants::GetSaBundleBackupRootDir(GetUserIdDefault()); BExcepUltils::VerifyPath(path, false); CreateDirIfNotExist(path); UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR)); if (fd < 0) { - HILOGE("Failed to open config file = %{private}s, err = %{public}d", path.c_str(), errno); + HILOGE("Failed to open config file = %{public}s, err = %{public}d", GetAnonyPath(path).c_str(), errno); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return UniqueFd(-EPERM); } @@ -295,13 +300,9 @@ UniqueFd Service::GetLocalCapabilities() session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetLocalCapabilities failed, errCode = %{public}d", e.GetCode()); return UniqueFd(-e.GetCode()); - } catch (const exception &e) { - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return UniqueFd(-EPERM); } catch (...) { + HILOGE("Unexpected exception"); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGI("Unexpected exception"); return UniqueFd(-EPERM); } } @@ -345,7 +346,7 @@ static inline void PermissionCheckFailRadar(const std::string &info, const std:: BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } -string Service::VerifyCallerAndGetCallerName() +ErrCode Service::VerifyCallerAndGetCallerName(std::string &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); @@ -354,147 +355,157 @@ string Service::VerifyCallerAndGetCallerName() Security::AccessToken::HapTokenInfo hapTokenInfo; if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) { PermissionCheckFailRadar("Get hap token info failed", "VerifyCallerAndGetCallerName"); - throw BError(BError::Codes::SA_INVAL_ARG, "Get hap token info failed"); + HILOGE("Verify and get caller name failed, Get hap token info failed"); + return BError(BError::Codes::SA_INVAL_ARG); } std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(hapTokenInfo.bundleName, hapTokenInfo.instIndex); - session_->VerifyBundleName(bundleNameIndexInfo); - return bundleNameIndexInfo; + ErrCode ret = session_->VerifyBundleName(bundleNameIndexInfo); + if (ret != ERR_OK) { + HILOGE("Verify bundle name failed, bundleNameIndexInfo:%{public}s", bundleNameIndexInfo.c_str()); + return ret; + } + bundleName = bundleNameIndexInfo; + return BError(BError::Codes::OK); } else { string str = to_string(tokenCaller); HILOGE("tokenID = %{private}s", GetAnonyString(str).c_str()); std::string info = string("Invalid token type").append(to_string(tokenType)).append(string("\"}")); PermissionCheckFailRadar(info, "VerifyCallerAndGetCallerName"); - throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType))); + HILOGE("Verify and get caller name failed, Invalid token type"); + return BError(BError::Codes::SA_INVAL_ARG); } } -void Service::VerifyCaller() +ErrCode Service::VerifyCaller() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); + ErrCode ret = BError(BError::Codes::OK); switch (tokenType) { case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: { /* Update Service */ if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + HILOGE("Permission denied, token type is token native"); std::string info = "Permission denied, token type is " + to_string(tokenType); PermissionCheckFailRadar(info, "VerifyCaller"); - throw BError(BError::Codes::SA_REFUSED_ACT, - string("Permission denied, token type is ").append(to_string(tokenType))); + ret = BError(BError::Codes::SA_REFUSED_ACT); } break; } case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: { if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + HILOGE("Permission denied, token type is token hap"); std::string info = "Permission denied, token type is " + to_string(tokenType); PermissionCheckFailRadar(info, "VerifyCaller"); - throw BError(BError::Codes::SA_REFUSED_ACT, - string("Permission denied, token type is ").append(to_string(tokenType))); + ret = BError(BError::Codes::SA_REFUSED_ACT); } uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) { + HILOGE("Permission denied, token type is token hap, full tokenId is error"); std::string info = "Permission denied, token type is " + to_string(tokenType); PermissionCheckFailRadar(info, "VerifyCaller"); - throw BError(BError::Codes::SA_REFUSED_ACT, - string("Permission denied, token type is ").append(to_string(tokenType))); + ret = BError(BError::Codes::SA_REFUSED_ACT); } break; } case Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL: if (IPCSkeleton::GetCallingUid() != BConstants::SYSTEM_UID) { + HILOGE("Permission denied, token type is token shell"); std::string info = "invalid calling uid"; PermissionCheckFailRadar(info, "VerifyCaller"); - throw BError(BError::Codes::SA_REFUSED_ACT, "Calling uid is invalid"); + ret = BError(BError::Codes::SA_REFUSED_ACT); } break; default: std::string info = "Permission denied, token type is " + to_string(tokenType); PermissionCheckFailRadar(info, "VerifyCaller"); - throw BError(BError::Codes::SA_REFUSED_ACT, string("Invalid token type ").append(to_string(tokenType))); + HILOGE("Permission denied, token type is default"); + ret = BError(BError::Codes::SA_REFUSED_ACT); break; } + return ret; } -void Service::VerifyCaller(IServiceReverse::Scenario scenario) +ErrCode Service::VerifyCaller(IServiceReverse::Scenario scenario) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - session_->VerifyCallerAndScenario(IPCSkeleton::GetCallingTokenID(), scenario); - VerifyCaller(); + ErrCode ret = session_->VerifyCallerAndScenario(IPCSkeleton::GetCallingTokenID(), scenario); + if (ret != ERR_OK) { + HILOGE("Verify bundle by scenario failed, ret:%{public}d", ret); + return ret; + } + return VerifyCaller(); } ErrCode Service::InitRestoreSession(sptr remote) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - VerifyCaller(); - ErrCode errCode = session_->Active({ - .clientToken = IPCSkeleton::GetCallingTokenID(), - .scenario = IServiceReverse::Scenario::RESTORE, - .clientProxy = remote, - .userId = GetUserIdDefault(), - }); - if (errCode == 0) { - ClearFailedBundles(); - successBundlesNum_ = 0; - } - return errCode; - } catch (const BError &e) { + ErrCode ret = VerifyCaller(); + if (ret != ERR_OK) { + HILOGE("Init restore session failed, verify caller failed"); + return ret; + } + ret = session_->Active({ + .clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::RESTORE, + .clientProxy = remote, + .userId = GetUserIdDefault(), + }); + if (ret != ERR_OK) { + HILOGE("Active restore session error, Already have a session"); StopAll(nullptr, true); - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; + return ret; } + ClearFailedBundles(); + successBundlesNum_ = 0; + return BError(BError::Codes::OK); } ErrCode Service::InitBackupSession(sptr remote) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - VerifyCaller(); - int32_t oldSize = StorageMgrAdapter::UpdateMemPara(BConstants::BACKUP_VFS_CACHE_PRESSURE); - HILOGE("InitBackupSession oldSize %{public}d", oldSize); - session_->SetMemParaCurSize(oldSize); - ErrCode errCode = session_->Active({ - .clientToken = IPCSkeleton::GetCallingTokenID(), - .scenario = IServiceReverse::Scenario::BACKUP, - .clientProxy = remote, - .userId = GetUserIdDefault(), - }); - if (errCode == 0) { - ClearFailedBundles(); - successBundlesNum_ = 0; - } - return errCode; - } catch (const BError &e) { + ErrCode ret = VerifyCaller(); + if (ret != ERR_OK) { + HILOGE("Init full backup session fail, verify caller failed"); + return ret; + } + int32_t oldSize = StorageMgrAdapter::UpdateMemPara(BConstants::BACKUP_VFS_CACHE_PRESSURE); + HILOGI("InitBackupSession oldSize %{public}d", oldSize); + session_->SetMemParaCurSize(oldSize); + ret = session_->Active({ + .clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::BACKUP, + .clientProxy = remote, + .userId = GetUserIdDefault(), + }); + if (ret != ERR_OK) { + HILOGE("Active backup session error, Already have a session"); StopAll(nullptr, true); - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; + return ret; } + ClearFailedBundles(); + successBundlesNum_ = 0; + return BError(BError::Codes::OK); } ErrCode Service::Start() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - VerifyCaller(session_->GetScenario()); - session_->Start(); - OnStartSched(); - return BError(BError::Codes::OK); - } catch (const BError &e) { - HILOGE("Failde to Start"); - return e.GetCode(); + ErrCode ret = VerifyCaller(session_->GetScenario()); + if (ret != ERR_OK) { + HILOGE("Service start failed, Verify caller failed, ret:%{public}d", ret); + return ret; + } + ret = session_->Start(); + if (ret != ERR_OK) { + HILOGE("Service start failed, session is invalid, ret:%{public}d", ret); + return ret; } + OnStartSched(); + return BError(BError::Codes::OK); } static bool SpecialVersion(const string &versionName) @@ -604,13 +615,14 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vectorIncreaseSessionCnt(__PRETTY_FUNCTION__); - session_->SetImplRestoreType(restoreType); - if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */ - session_->SetSessionUserId(userId); - } else { - session_->SetSessionUserId(GetUserIdDefault()); + SetUserIdAndRestoreType(restoreType, userId); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::RESTORE); + if (ret != ERR_OK) { + HILOGE("AppendBundles restore session with infos error, verify caller failed, ret:%{public}d", ret); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; } - VerifyCaller(IServiceReverse::Scenario::RESTORE); std::vector bundleNamesOnly; std::map isClearDataFlags; std::map> bundleNameDetailMap = @@ -656,7 +668,9 @@ void Service::SetCurrentSessProperties(std::vector return bundleName == bundleNameIndex; }); if (it == restoreBundleNames.end()) { - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); + HILOGE("Can not find current bundle, bundleName:%{public}s, appIndex:%{public}d", restoreInfo.name.c_str(), + restoreInfo.appIndex); + continue; } HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), restoreInfo.extensionName.c_str()); @@ -692,13 +706,14 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); - session_->SetImplRestoreType(restoreType); - if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */ - session_->SetSessionUserId(userId); - } else { - session_->SetSessionUserId(GetUserIdDefault()); + SetUserIdAndRestoreType(restoreType, userId); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::RESTORE); + if (ret != ERR_OK) { + HILOGE("AppendBundles restore session with infos error, verify caller failed, ret:%{public}d", ret); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; } - VerifyCaller(IServiceReverse::Scenario::RESTORE); std::string oldBackupVersion; auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames, oldBackupVersion); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); @@ -741,10 +756,10 @@ void Service::SetCurrentSessProperties(std::vector return bundleName == bundleNameIndexInfo; }); if (it == restoreBundleNames.end()) { - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); + HILOGE("Can not find current bundle, bundleName:%{public}s, appIndex:%{public}d", restoreInfo.name.c_str(), + restoreInfo.appIndex); + continue; } - HILOGD("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), - restoreInfo.extensionName.c_str()); std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex); if ((!restoreInfo.allToBackup && !SpecialVersion(restoreInfo.versionName)) || (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { @@ -790,7 +805,13 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 - VerifyCaller(IServiceReverse::Scenario::BACKUP); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::BACKUP); + if (ret != ERR_OK) { + HILOGE("AppendBundles backup session error, verify caller failed, ret:%{public}d", ret); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } auto bundleDetails = MakeDetailList(bundleNames); auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppend(bundleDetails, session_->GetSessionUserId()); std::vector supportBackupNames = GetSupportBackupBundleNames(backupInfos, false, bundleNames); @@ -804,11 +825,6 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return e.GetCode(); - } catch (const exception &e) { - HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); - HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - return EPERM; } catch (...) { HILOGE("Unexpected exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); @@ -827,7 +843,13 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 - VerifyCaller(IServiceReverse::Scenario::BACKUP); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::BACKUP); + if (ret != ERR_OK) { + HILOGE("AppendBundles backup session with infos error, verify caller failed, ret:%{public}d", ret); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } std::vector bundleNamesOnly; std::map isClearDataFlags; std::map> bundleNameDetailMap = @@ -877,10 +899,15 @@ void Service::HandleCurGroupBackupInfos(std::vector ErrCode Service::ServiceResultReport(const std::string restoreRetInfo, BackupRestoreScenario sennario, ErrCode errCode) { - string callerName = ""; + string callerName; HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - callerName = VerifyCallerAndGetCallerName(); + ErrCode ret = VerifyCallerAndGetCallerName(callerName); + if (ret != ERR_OK) { + HILOGE("Result report fail, bundleName:%{public}s, ret:%{public}d", callerName.c_str(), ret); + NotifyCloneBundleFinish(callerName, sennario); + return ret; + } SendEndAppGalleryNotify(callerName); if (sennario == BackupRestoreScenario::FULL_RESTORE) { session_->GetServiceReverseProxy()->RestoreOnResultReport(restoreRetInfo, callerName, errCode); @@ -897,13 +924,9 @@ ErrCode Service::ServiceResultReport(const std::string restoreRetInfo, } catch (const BError &e) { NotifyCloneBundleFinish(callerName, sennario); return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - NotifyCloneBundleFinish(callerName, sennario); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; } catch (...) { NotifyCloneBundleFinish(callerName, sennario); - HILOGI("Unexpected exception"); + HILOGE("Unexpected exception"); return EPERM; } } @@ -946,11 +969,13 @@ void Service::NotifyCloneBundleFinish(std::string bundleName, const BackupRestor std::lock_guard lock(mutexPtr->callbackMutex); auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { - throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty"); + HILOGE("backUpConnection is empty, bundle:%{public}s", bundleName.c_str()); + return; } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + HILOGE("Extension backup Proxy is empty, bundle:%{public}s", bundleName.c_str()); + return; } proxy->HandleClear(); session_->StopFwkTimer(bundleName); @@ -994,8 +1019,11 @@ ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) HILOGE("GetFileHandle error, session is empty"); return BError(BError::Codes::SA_INVAL_ARG); } - VerifyCaller(IServiceReverse::Scenario::RESTORE); - + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::RESTORE); + if (ret != ERR_OK) { + HILOGE("verify caller failed, bundleName:%{public}s", bundleName.c_str()); + return ret; + } bool updateRes = SvcRestoreDepsManager::GetInstance().UpdateToRestoreBundleMap(bundleName, fileName); if (updateRes) { return BError(BError::Codes::OK); @@ -1004,7 +1032,7 @@ ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) if (action == BConstants::ServiceSchedAction::RUNNING) { auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { - HILOGE("GetFileHandle error, backUpConnection is empty"); + HILOGE("backUpConnection is empty, bundle:%{public}s", bundleName.c_str()); return BError(BError::Codes::SA_INVAL_ARG); } auto proxy = backUpConnection->GetBackupExtProxy(); @@ -1027,70 +1055,7 @@ ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } -} - -void Service::OnBackupExtensionDied(const string &&bundleName, bool isCleanCalled) -{ - HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (isCleanCalled) { - HILOGE("Backup <%{public}s> Extension Process second Died", bundleName.c_str()); - ClearSessionAndSchedInfo(bundleName); - OnAllBundlesFinished(BError(BError::Codes::OK)); - return; - } - try { - string callName = move(bundleName); - HILOGE("Backup <%{public}s> Extension Process Died", callName.c_str()); - session_->VerifyBundleName(callName); - // 重新连接清理缓存 - HILOGI("Clear backup extension data, bundleName: %{public}s", callName.c_str()); - ExtConnectDied(callName); - } catch (...) { - HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); - ExtConnectDied(bundleName); - return; - } -} - -void Service::ExtConnectDied(const string &callName) -{ - HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - HILOGI("Begin, bundleName: %{public}s", callName.c_str()); - std::shared_ptr mutexPtr = GetExtensionMutex(callName); - if (mutexPtr == nullptr) { - HILOGE("extension mutex ptr is nullptr"); - return; - } - std::lock_guard lock(mutexPtr->callbackMutex); - /* Clear Timer */ - session_->StopFwkTimer(callName); - session_->StopExtTimer(callName); - auto backUpConnection = session_->GetExtConnection(callName); - if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) { - backUpConnection->DisconnectBackupExtAbility(); - } - session_->SetServiceSchedAction(callName, BConstants::ServiceSchedAction::CLEAN); - auto ret = LaunchBackupExtension(callName); - if (ret) { - /* Clear Session before notice client finish event */ - ClearSessionAndSchedInfo(callName); - } - /* Notice Client Ext Ability Process Died */ - NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED)); - } catch (...) { - HILOGE("Unexpected exception, bundleName: %{public}s", callName.c_str()); - ClearSessionAndSchedInfo(callName); - NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED)); } - RemoveExtensionMutex(callName); } void Service::ExtStart(const string &bundleName) @@ -1212,36 +1177,6 @@ void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) } } -void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) -{ - HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - HILOGI("begin %{public}s", bundleName.c_str()); - try { - SendEndAppGalleryNotify(bundleName); - auto scenario = session_->GetScenario(); - if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { - session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName); - } else if (scenario == IServiceReverse::Scenario::RESTORE && - BackupPara().GetBackupOverrideIncrementalRestore() && - session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) { - session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleFinished(errCode, bundleName); - } else if (scenario == IServiceReverse::Scenario::BACKUP) { - session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, bundleName); - } else if (scenario == IServiceReverse::Scenario::RESTORE) { - session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, bundleName); - }; - BundleEndRadarReport(bundleName, errCode, scenario); - /* If all bundle ext process finish, notice client. */ - OnAllBundlesFinished(BError(BError::Codes::OK)); - } catch(const BError &e) { - ReleaseOnException(); - } catch (...) { - ReleaseOnException(); - HILOGI("Unexpected exception"); - return; - } -} - void Service::StartRunningTimer(const std::string &bundleName) { auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); @@ -1350,33 +1285,6 @@ void Service::HandleRestoreDepsBundle(const string &bundleName) HILOGI("End"); } -void Service::OnAllBundlesFinished(ErrCode errCode) -{ - HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - HILOGI("called begin."); - if (session_->IsOnAllBundlesFinished()) { - IServiceReverse::Scenario scenario = session_->GetScenario(); - if (isInRelease_.load() && (scenario == IServiceReverse::Scenario::RESTORE)) { - SessionDeactive(); - } - if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { - session_->GetServiceReverseProxy()->IncrementalBackupOnAllBundlesFinished(errCode); - } else if (scenario == IServiceReverse::Scenario::RESTORE && - BackupPara().GetBackupOverrideIncrementalRestore() && - session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) { - session_->GetServiceReverseProxy()->IncrementalRestoreOnAllBundlesFinished(errCode); - } else if (scenario == IServiceReverse::Scenario::BACKUP) { - session_->GetServiceReverseProxy()->BackupOnAllBundlesFinished(errCode); - } else if (scenario == IServiceReverse::Scenario::RESTORE) { - session_->GetServiceReverseProxy()->RestoreOnAllBundlesFinished(errCode); - } - if (!BackupPara().GetBackupOverrideBackupSARelease()) { - sched_->TryUnloadServiceTimer(true); - } - } - HILOGI("called end."); -} - void Service::OnStartSched() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -1591,11 +1499,13 @@ ErrCode Service::ClearResidualBundleData(const std::string &bundleName) } auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { - throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty"); + HILOGE("BackUpConnection is empty, bundle:%{public}s", bundleName.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + HILOGE("Extension backup Proxy is empty, bundle:%{public}s", bundleName.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); } // 通知ext清理 ErrCode res = proxy->HandleClear(); @@ -1690,7 +1600,14 @@ ErrCode Service::StartExtTimer(bool &isExtStart) return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); - string bundleName = VerifyCallerAndGetCallerName(); + string bundleName; + ErrCode ret = VerifyCallerAndGetCallerName(bundleName); + if (ret != ERR_OK) { + HILOGE("Start extension timer fail, get bundleName failed, ret:%{public}d", ret); + isExtStart = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); session_->StopFwkTimer(bundleName); isExtStart = session_->StartExtTimer(bundleName, timeoutCallback); @@ -1714,7 +1631,14 @@ ErrCode Service::StartFwkTimer(bool &isFwkStart) return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); - string bundleName = VerifyCallerAndGetCallerName(); + std::string bundleName; + ErrCode ret = VerifyCallerAndGetCallerName(bundleName); + if (ret != ERR_OK) { + HILOGE("Start fwk timer fail, get bundleName failed, ret:%{public}d", ret); + isFwkStart = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); session_->StopExtTimer(bundleName); isFwkStart = session_->StartFwkTimer(bundleName, timeoutCallback); @@ -1771,9 +1695,9 @@ ErrCode Service::AppendBundlesClearSession(const std::vector &bundle HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { + HILOGE("Unexpected exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGE("Unexpected exception"); return EPERM; } } @@ -1788,7 +1712,13 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &res return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); - VerifyCaller(); + ErrCode ret = VerifyCaller(); + if (ret != ERR_OK) { + HILOGE("Update timer failed, verify caller failed"); + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); result = session_->UpdateTimer(bundleName, timeout, timeoutCallback); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); @@ -1803,54 +1733,54 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &res ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) { - try { - HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); - if (session_ == nullptr || isOccupyingSession_.load()) { - HILOGE("Update Send Rate error, session is empty."); - result = false; - return BError(BError::Codes::SA_INVAL_ARG); - } - session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); - std::shared_ptr mutexPtr = GetExtensionMutex(bundleName); - if (mutexPtr == nullptr) { - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - return BError(BError::Codes::SA_INVAL_ARG, "Extension mutex ptr is null."); - } + HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); + if (session_ == nullptr || isOccupyingSession_.load()) { + HILOGE("Update Send Rate error, session is empty."); + result = false; + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); + ErrCode ret = VerifySendRateParam(); + if (ret != ERR_OK) { + HILOGE("Verify sendRate param failed, bundleName:%{public}s", bundleName.c_str()); + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } + std::shared_ptr mutexPtr = GetExtensionMutex(bundleName); + if (mutexPtr == nullptr) { + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::SA_INVAL_ARG, "Extension mutex ptr is null."); + } + do { std::lock_guard lock(mutexPtr->callbackMutex); - VerifyCaller(); - IServiceReverse::Scenario scenario = session_ -> GetScenario(); - if (scenario != IServiceReverse::Scenario::BACKUP) { - HILOGE("This method is applicable to the backup scenario"); + result = true; + auto backUpConnection = session_->GetExtConnection(bundleName); + if (backUpConnection == nullptr) { + HILOGE("backUpConnection is empty, bundle:%{public}s", bundleName.c_str()); result = false; - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto backupConnection = session_->GetExtConnection(bundleName); - if (backupConnection == nullptr) { - HILOGE("backUpConnection is null. bundleName: %{public}s", bundleName.c_str()); - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - return BError(BError::Codes::SA_INVAL_ARG); + ret = BError(BError::Codes::SA_INVAL_ARG); + break; } - auto proxy = backupConnection->GetBackupExtProxy(); + auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + HILOGE("Update send rate fail, extension proxy is empty"); + result = false; + ret = BError(BError::Codes::SA_INVAL_ARG); + break; } - auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); + ret = proxy->UpdateFdSendRate(bundleName, sendRate); if (ret != NO_ERROR) { + HILOGE("Extension do updateSendRate failed, ret:%{public}d", ret); result = false; - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - return BError(BError::Codes::EXT_BROKEN_IPC); + ret = BError(BError::Codes::EXT_BROKEN_IPC); + break; } - result = true; - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - } catch (...) { - result = false; - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGE("Unexpected exception"); - return EPERM; - } + } while (0); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); RemoveExtensionMutex(bundleName); - return BError(BError::Codes::OK); + return ret; } AAFwk::Want Service::CreateConnectWant (BundleName &bundleName) @@ -1945,13 +1875,9 @@ ErrCode Service::SADone(ErrCode errCode, std::string bundleName) } catch (const BError &e) { ReleaseOnException(); return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - ReleaseOnException(); - HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; } catch(...) { - ReleaseOnException(); HILOGE("Unexpected exception"); + ReleaseOnException(); return EPERM; } } @@ -1989,7 +1915,12 @@ ErrCode Service::ReportAppProcessInfo(const std::string processInfo, BackupResto { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - string bundleName = VerifyCallerAndGetCallerName(); + string bundleName; + ErrCode ret = VerifyCallerAndGetCallerName(bundleName); + if (ret != ERR_OK) { + HILOGE("Report app process info failed, Get bundle name failed, ret:%{public}d", ret); + return ret; + } if (sennario == BackupRestoreScenario::FULL_RESTORE) { session_->GetServiceReverseProxy()->RestoreOnProcessInfo(bundleName, processInfo); } else if (sennario == BackupRestoreScenario::INCREMENTAL_RESTORE) { @@ -2058,7 +1989,7 @@ void Service::DoTimeout(wptr ptr, std::string bundleName) try { std::shared_ptr mutexPtr = GetExtensionMutex(bundleName); if (mutexPtr == nullptr) { - HILOGE("extension mutex ptr is nullptr"); + HILOGE("extension mutex ptr is nullptr, bundleName:%{public}s", bundleName.c_str()); return; } std::lock_guard lock(mutexPtr->callbackMutex); @@ -2066,12 +1997,16 @@ void Service::DoTimeout(wptr ptr, std::string bundleName) auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName); shared_ptr saConnection = sessionConnection.lock(); if (saConnection == nullptr) { - HILOGE("lock sa connection ptr is nullptr"); + HILOGE("Error, saConnection is empty, bundleName:%{public}s", bundleName.c_str()); return; } saConnection->DisconnectBackupSAExt(); } else { auto sessionConnection = sessionPtr->GetExtConnection(bundleName); + if (sessionConnection == nullptr) { + HILOGE("Error, sessionConnection is empty, bundleName:%{public}s", bundleName.c_str()); + return; + } sessionConnection->DisconnectBackupExtAbility(); } sessionPtr->StopFwkTimer(bundleName); @@ -2121,4 +2056,14 @@ void Service::ReleaseOnException() HILOGE("Unexpected exception"); } } + +void Service::SetUserIdAndRestoreType(RestoreTypeEnum restoreType, int32_t userId) +{ + session_->SetImplRestoreType(restoreType); + if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */ + session_->SetSessionUserId(userId); + } else { + session_->SetSessionUserId(GetUserIdDefault()); + } +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index d3a9a67ae..37f306372 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -150,7 +150,12 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorIncreaseSessionCnt(__PRETTY_FUNCTION__); - VerifyCaller(); + ErrCode errCode = VerifyCaller(); + if (errCode != ERR_OK) { + HILOGE("Get local abilities info failed, Verify caller failed, errCode:%{public}d", errCode); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return UniqueFd(-ENOENT); + } string path = BConstants::GetSaBundleBackupRootDir(GetUserIdDefault()); BExcepUltils::VerifyPath(path, false); CreateDirIfNotExist(path); @@ -177,10 +182,6 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorDecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetLocalCapabilitiesIncremental failed, errCode = %{public}d", e.GetCode()); return UniqueFd(-e.GetCode()); - } catch (const exception &e) { - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return UniqueFd(-EPERM); } catch (...) { session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); @@ -273,7 +274,13 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); session_->SetSessionUserId(GetUserIdDefault()); - std::string bundleName = VerifyCallerAndGetCallerName(); + std::string bundleName; + ErrCode ret = VerifyCallerAndGetCallerName(bundleName); + if (ret != ERR_OK) { + HILOGE("Get AppLocalList failed, Get bundle failed, ret:%{public}d", ret); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } auto task = [this, bundleName]() { StartGetFdTask(bundleName, wptr(this)); }; @@ -294,13 +301,9 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetAppLocalListAndDoIncrementalBackup failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); - } catch (const exception &e) { - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; } catch (...) { + HILOGE("Unexpected exception"); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGI("Unexpected exception"); return EPERM; } } @@ -308,26 +311,28 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() ErrCode Service::InitIncrementalBackupSession(sptr remote) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - VerifyCaller(); - if (session_ == nullptr) { - HILOGE("Init Incremental backup session error, session is empty"); - return BError(BError::Codes::SA_INVAL_ARG); - } - ErrCode errCode = session_->Active({.clientToken = IPCSkeleton::GetCallingTokenID(), - .scenario = IServiceReverse::Scenario::BACKUP, - .clientProxy = remote, - .userId = GetUserIdDefault(), - .isIncrementalBackup = true}); - if (errCode == 0) { - ClearFailedBundles(); - successBundlesNum_ = 0; - } + ErrCode errCode = VerifyCaller(); + if (errCode != ERR_OK) { + HILOGE("Init incremental backup session fail, Verify caller failed, errCode:%{public}d", errCode); return errCode; - } catch (const BError &e) { + } + if (session_ == nullptr) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + errCode = session_->Active({.clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::BACKUP, + .clientProxy = remote, + .userId = GetUserIdDefault(), + .isIncrementalBackup = true}); + if (errCode != ERR_OK) { + HILOGE("Active incremental backup session error, Already have a session"); StopAll(nullptr, true); - return e.GetCode(); + return errCode; } + ClearFailedBundles(); + successBundlesNum_ = 0; + return BError(BError::Codes::OK); } vector Service::GetBundleNameByDetails(const std::vector &bundlesToBackup) @@ -342,14 +347,21 @@ vector Service::GetBundleNameByDetails(const std::vector &bundlesToBackup) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + vector bundleNames; try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("Init Incremental backup session error, session is empty"); return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 - VerifyCaller(IServiceReverse::Scenario::BACKUP); - vector bundleNames = GetBundleNameByDetails(bundlesToBackup); + bundleNames = GetBundleNameByDetails(bundlesToBackup); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::BACKUP); + if (ret != ERR_OK) { + HILOGE("Append bundles incremental session failed, verify caller failed, ret:%{public}d", ret); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppend(bundlesToBackup, session_->GetSessionUserId()); std::vector supportBackupNames = GetSupportBackupBundleNames(backupInfos, true, bundleNames); @@ -360,10 +372,12 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorDecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (...) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; @@ -374,14 +388,21 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector &infos) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + vector bundleNames; try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("Init Incremental backup session error, session is empty"); return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 - VerifyCaller(IServiceReverse::Scenario::BACKUP); - vector bundleNames = GetBundleNameByDetails(bundlesToBackup); + bundleNames = GetBundleNameByDetails(bundlesToBackup); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::BACKUP); + if (ret != ERR_OK) { + HILOGE("Append bundles incremental session with infos failed, verify caller failed, ret:%{public}d", ret); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + return ret; + } std::vector bundleNamesOnly; std::map isClearDataFlags; std::map> bundleNameDetailMap = @@ -397,10 +418,12 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorDecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (...) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; @@ -431,40 +454,37 @@ void Service::HandleCurGroupIncBackupInfos(vector & ErrCode Service::PublishIncrementalFile(const BFileInfo &fileInfo) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - VerifyCaller(IServiceReverse::Scenario::RESTORE); - HILOGI("Start get ExtConnection, bundleName:%{public}s", fileInfo.owner.c_str()); - if (!fileInfo.fileName.empty()) { - HILOGE("Forbit to use PublishIncrementalFile with fileName for App"); - return EPERM; - } - if (session_ != nullptr) { - session_->SetPublishFlag(fileInfo.owner); - } - auto backUpConnection = session_->GetExtConnection(fileInfo.owner); - if (backUpConnection == nullptr) { - HILOGE("PublishIncrementalFile error, backUpConnection is empty"); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto proxy = backUpConnection->GetBackupExtProxy(); - if (!proxy) { - HILOGE("PublishIncrementalFile error, Extension backup Proxy is empty"); - return BError(BError::Codes::SA_INVAL_ARG); - } - ErrCode res = proxy->PublishIncrementalFile(fileInfo.fileName); - if (res) { - HILOGE("Failed to publish file for backup extension"); - } - return res; - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::RESTORE); + if (ret != ERR_OK) { + HILOGE("Publish incremental file failed, bundleName:%{public}s", fileInfo.owner.c_str()); + return ret; + } + HILOGI("Start get ExtConnection, bundleName:%{public}s", fileInfo.owner.c_str()); + if (!fileInfo.fileName.empty()) { + HILOGE("Forbit to use PublishIncrementalFile with fileName for App"); return EPERM; } + if (session_ == nullptr) { + HILOGE("session is empty, bundleName:%{public}s", fileInfo.owner.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->SetPublishFlag(fileInfo.owner); + auto backUpConnection = session_->GetExtConnection(fileInfo.owner); + if (backUpConnection == nullptr) { + HILOGE("backUpConnection is empty, bundle:%{public}s", fileInfo.owner.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + HILOGE("Publish Incremental file failed, bundleName:%{public}s", fileInfo.owner.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + ret = proxy->PublishIncrementalFile(fileInfo.fileName); + if (ret != ERR_OK) { + HILOGE("Failed to publish file for backup extension, bundleName:%{public}s", fileInfo.owner.c_str()); + return ret; + } + return BError(BError::Codes::OK); } ErrCode Service::PublishSAIncrementalFile(const BFileInfo &fileInfo, UniqueFd fd) @@ -498,18 +518,17 @@ ErrCode Service::AppIncrementalFileReady(const std::string &bundleName, const st if (fileName == BConstants::EXT_BACKUP_MANAGE) { fd = session_->OnBundleExtManageInfo(bundleName, move(fd)); } - HILOGD("reverse: Will notify IncrementalBackupOnFileReady"); session_->GetServiceReverseProxy()->IncrementalBackupOnFileReady(bundleName, fileName, move(fd), move(manifestFd), errCode); FileReadyRadarReport(bundleName, fileName, errCode, IServiceReverse::Scenario::BACKUP); - AuditLog auditLog = { false, "Backup File Ready", "ADD", "", 1, "SUCCESS", "AppIncrementalFileReady", - bundleName, GetAnonyPath(fileName) }; - HiAudit::GetInstance(true).Write(auditLog); if (session_->OnBundleFileReady(bundleName, fileName)) { auto backUpConnection = session_->GetExtConnection(bundleName); + if (backUpConnection == nullptr) { + return BError(BError::Codes::SA_INVAL_ARG, "backup connection is empty"); + } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + return BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } // 通知extension清空缓存 proxy->HandleClear(); @@ -529,9 +548,6 @@ ErrCode Service::AppIncrementalFileReady(const std::string &bundleName, const st return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; } catch (...) { HILOGI("Unexpected exception"); return EPERM; @@ -542,7 +558,12 @@ ErrCode Service::AppIncrementalFileReady(const std::string &fileName, UniqueFd f { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - string callerName = VerifyCallerAndGetCallerName(); + string callerName; + ErrCode ret = VerifyCallerAndGetCallerName(callerName); + if (ret != ERR_OK) { + HILOGE("Verify caller failed, ret:%{public}d", ret); + return ret; + } if (session_->GetScenario() == IServiceReverse::Scenario::RESTORE) { session_->GetServiceReverseProxy()->IncrementalRestoreOnFileReady(callerName, fileName, move(fd), move(manifestFd), errCode); @@ -552,15 +573,14 @@ ErrCode Service::AppIncrementalFileReady(const std::string &fileName, UniqueFd f if (fileName == BConstants::EXT_BACKUP_MANAGE) { fd = session_->OnBundleExtManageInfo(callerName, move(fd)); } - HILOGD("reverse: Will notify IncrementalBackupOnFileReady"); session_->GetServiceReverseProxy()->IncrementalBackupOnFileReady(callerName, fileName, move(fd), move(manifestFd), errCode); FileReadyRadarReport(callerName, fileName, errCode, IServiceReverse::Scenario::BACKUP); - AuditLog auditLog = { false, "Backup File Ready", "ADD", "", 1, "SUCCESS", "AppIncrementalFileReady", - callerName, GetAnonyPath(fileName) }; - HiAudit::GetInstance(true).Write(auditLog); if (session_->OnBundleFileReady(callerName, fileName)) { auto backUpConnection = session_->GetExtConnection(callerName); + if (backUpConnection == nullptr) { + return BError(BError::Codes::SA_INVAL_ARG, "Extension backup connection is empty"); + } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); @@ -583,12 +603,6 @@ ErrCode Service::AppIncrementalFileReady(const std::string &fileName, UniqueFd f return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; } } @@ -600,18 +614,20 @@ ErrCode Service::AppIncrementalDone(ErrCode errCode) HILOGE("AppIncrementalDone error, session is null"); return BError(BError::Codes::SA_INVAL_ARG); } - string callerName = VerifyCallerAndGetCallerName(); - HILOGI("Service AppIncrementalDone start, callerName is %{public}s, errCode is: %{public}d", - callerName.c_str(), errCode); + string callerName; + ErrCode ret = VerifyCallerAndGetCallerName(callerName); + if (ret != ERR_OK) { + HILOGE("App incremental done fail, ret:%{public}d", ret); + return ret; + } + HILOGI("Begin, callerName is %{public}s, errCode is: %{public}d", callerName.c_str(), errCode); if (session_->OnBundleFileReady(callerName) || errCode != BError(BError::Codes::OK)) { std::shared_ptr mutexPtr = GetExtensionMutex(callerName); if (mutexPtr == nullptr) { - HILOGE("extension mutex ptr is nullptr"); return BError(BError::Codes::SA_INVAL_ARG, "Extension mutex ptr is null."); } std::lock_guard lock(mutexPtr->callbackMutex); - auto tempBackUpConnection = session_->GetExtConnection(callerName); - auto backUpConnection = tempBackUpConnection.promote(); + auto backUpConnection = session_->GetExtConnection(callerName); if (backUpConnection == nullptr) { return BError(BError::Codes::SA_INVAL_ARG, "Promote backUpConnection ptr is null."); } @@ -648,17 +664,22 @@ ErrCode Service::GetIncrementalFileHandle(const std::string &bundleName, const s HILOGE("GetIncrementalFileHandle error, session is empty"); return BError(BError::Codes::SA_INVAL_ARG); } - VerifyCaller(IServiceReverse::Scenario::RESTORE); + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::RESTORE); + if (ret != ERR_OK) { + HILOGE("Error, bundleName:%{public}s, fileName:%{public}s", bundleName.c_str(), + GetAnonyPath(fileName).c_str()); + return ret; + } auto action = session_->GetServiceSchedAction(bundleName); if (action == BConstants::ServiceSchedAction::RUNNING) { auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { - HILOGE("GetIncrementalFileHandle error, backUpConnection is empty"); + HILOGE("backUpConnection is empty, bundle:%{public}s", bundleName.c_str()); return BError(BError::Codes::SA_INVAL_ARG); } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - HILOGE("GetIncrementalFileHandle error, Extension backup Proxy is empty"); + HILOGE("GetIncrementalFileHandle failed, bundleName:%{public}s", bundleName.c_str()); return BError(BError::Codes::SA_INVAL_ARG); } auto[errCode, fd, reportFd] = proxy->GetIncrementalFileHandle(fileName); @@ -676,9 +697,6 @@ ErrCode Service::GetIncrementalFileHandle(const std::string &bundleName, const s return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; } catch (...) { HILOGI("Unexpected exception"); return EPERM; @@ -691,11 +709,15 @@ bool Service::IncrementalBackup(const string &bundleName) IServiceReverse::Scenario scenario = session_->GetScenario(); auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { - throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty"); + HILOGE("backUpConnection is empty, bundle:%{public}s", bundleName.c_str()); + NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_DIED)); + return true; } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + HILOGE("Increment backup error, extension proxy is empty, bundleName:%{public}s", bundleName.c_str()); + NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_DIED)); + return true; } if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { auto ret = proxy->IncrementalOnBackup(session_->GetClearDataFlag(bundleName)); @@ -843,8 +865,7 @@ void Service::CancelTask(std::string bundleName, wptr ptr) } do { std::lock_guard lock(mutexPtr->callbackMutex); - auto tempBackUpConnection = session->GetExtConnection(bundleName); - auto backUpConnection = tempBackUpConnection.promote(); + auto backUpConnection = session->GetExtConnection(bundleName); if (backUpConnection == nullptr) { HILOGE("Promote backUpConnection ptr is null."); break; @@ -876,46 +897,42 @@ ErrCode Service::Cancel(std::string bundleName, int32_t &result) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin, bundle name:%{public}s", bundleName.c_str()); - try { - if (session_ == nullptr) { - HILOGE("Cancel error, session is null"); - return BError(BError::BackupErrorCode::E_CANCEL_UNSTARTED_TASK); - } - IServiceReverse::Scenario scenario = session_->GetScenario(); - VerifyCaller(scenario); - auto impl = session_->GetImpl(); - auto it = impl.backupExtNameMap.find(bundleName); - if (it == impl.backupExtNameMap.end()) { - result = BError::BackupErrorCode::E_CANCEL_NO_TASK; - return BError(BError::Codes::OK); - } - auto action = session_->GetServiceSchedAction(bundleName); - auto task = [this, bundleName]() { - try { - CancelTask(bundleName, wptr(this)); - } catch (const BError &e) { - HILOGE("CancelTask failed, errCode = %{public}d", e.GetCode()); - } catch (...) { - HILOGI("Unexpected exception"); - } - }; - if (action == BConstants::ServiceSchedAction::RUNNING) { - threadPool_.AddTask(task); - result = BError(BError::Codes::OK); - return BError(BError::Codes::OK); - } - if (action == BConstants::ServiceSchedAction::CLEAN) { - result = BError::BackupErrorCode::E_CANCEL_NO_TASK; - } else { - result = BError::BackupErrorCode::E_CANCEL_UNSTARTED_TASK; - } + if (session_ == nullptr) { + HILOGE("Cancel error, session is null"); + return BError(BError::BackupErrorCode::E_CANCEL_UNSTARTED_TASK); + } + IServiceReverse::Scenario scenario = session_->GetScenario(); + ErrCode ret = VerifyCaller(scenario); + if (ret != ERR_OK) { + HILOGE("Verify caller failed, bundleName:%{public}s, scenario:%{public}d", bundleName.c_str(), scenario); + return BError(BError::BackupErrorCode::E_CANCEL_UNSTARTED_TASK); + } + auto impl = session_->GetImpl(); + auto it = impl.backupExtNameMap.find(bundleName); + if (it == impl.backupExtNameMap.end()) { + result = BError::BackupErrorCode::E_CANCEL_NO_TASK; return BError(BError::Codes::OK); - } catch (const BError &e) { - HILOGE("Cancel failed, errCode = %{public}d", e.GetCode()); - return e.GetCode(); - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; } + auto action = session_->GetServiceSchedAction(bundleName); + auto task = [this, bundleName]() { + try { + CancelTask(bundleName, wptr(this)); + } catch (const BError &e) { + HILOGE("CancelTask failed, errCode = %{public}d", e.GetCode()); + } catch (...) { + HILOGE("Unexpected exception"); + } + }; + if (action == BConstants::ServiceSchedAction::RUNNING) { + threadPool_.AddTask(task); + result = BError(BError::Codes::OK); + return BError(BError::Codes::OK); + } + if (action == BConstants::ServiceSchedAction::CLEAN) { + result = BError::BackupErrorCode::E_CANCEL_NO_TASK; + } else { + result = BError::BackupErrorCode::E_CANCEL_UNSTARTED_TASK; + } + return BError(BError::Codes::OK); } } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index c6dc5dd4e..23e3a9d86 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -78,8 +78,18 @@ ErrCode Service::Finish() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - VerifyCaller(session_->GetScenario()); - session_->Finish(); + ErrCode ret = VerifyCaller(session_->GetScenario()); + if (ret != ERR_OK) { + HILOGE("Failde to Finish, verify caller failed, ret:%{public}d", ret); + ReleaseOnException(); + return ret; + } + ret = session_->Finish(); + if (ret != ERR_OK) { + HILOGE("Failde to Finish, session finish failed, ret:%{public}d", ret); + ReleaseOnException(); + return ret; + } OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); } catch (const BError &e) { @@ -92,40 +102,35 @@ ErrCode Service::Finish() ErrCode Service::PublishFile(const BFileInfo &fileInfo) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - if (session_ == nullptr) { - HILOGE("PublishFile error, session is empty"); - return BError(BError::Codes::SA_INVAL_ARG); - } - VerifyCaller(IServiceReverse::Scenario::RESTORE); - if (!fileInfo.fileName.empty()) { - HILOGE("Forbit to use publishFile with fileName for App"); - return EPERM; - } - auto backUpConnection = session_->GetExtConnection(fileInfo.owner); - if (backUpConnection == nullptr) { - HILOGE("PublishFile error, backUpConnection is empty"); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto proxy = backUpConnection->GetBackupExtProxy(); - if (!proxy) { - HILOGE("PublishFile error, Extension backup Proxy is empty"); - return BError(BError::Codes::SA_INVAL_ARG); - } - ErrCode res = proxy->PublishFile(fileInfo.fileName); - if (res) { - HILOGE("Failed to publish file for backup extension"); - } - return res; - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); + if (session_ == nullptr) { + HILOGE("PublishFile error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + ErrCode ret = VerifyCaller(IServiceReverse::Scenario::RESTORE); + if (ret != ERR_OK) { + HILOGE("PublishFile error, verify caller by scenario failed, ret:%{public}d", ret); + return ret; + } + if (!fileInfo.fileName.empty()) { + HILOGE("Forbit to use publishFile with fileName for App"); return EPERM; } + auto backUpConnection = session_->GetExtConnection(fileInfo.owner); + if (backUpConnection == nullptr) { + HILOGE("backUpConnection is empty, bundle:%{public}s", fileInfo.owner.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + HILOGE("PublishFile error, Extension backup Proxy is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + ret = proxy->PublishFile(fileInfo.fileName); + if (ret != ERR_OK) { + HILOGE("Failed to publish file for backup extension, ret:%{public}d", ret); + return ret; + } + return BError(BError::Codes::OK); } ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd, int32_t errCode) @@ -136,18 +141,21 @@ ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd, int32_t errCo HILOGE("AppFileReady error, session is empty"); return BError(BError::Codes::SA_INVAL_ARG); } - string callerName = VerifyCallerAndGetCallerName(); + string callerName; + ErrCode ret = VerifyCallerAndGetCallerName(callerName); + if (ret != ERR_OK) { + HILOGE("AppFileReady error, Get bundle name failed, ret:%{public}d", ret); + return ret; + } if (fileName.find('/') != string::npos) { - throw BError(BError::Codes::SA_INVAL_ARG, "Filename is not valid"); + HILOGE("AppFileReady error, Filename is not valid, fileName:%{public}s", GetAnonyPath(fileName).c_str()); + return BError(BError::Codes::SA_INVAL_ARG); } if (fileName == BConstants::EXT_BACKUP_MANAGE) { fd = session_->OnBundleExtManageInfo(callerName, move(fd)); } session_->GetServiceReverseProxy()->BackupOnFileReady(callerName, fileName, move(fd), errCode); FileReadyRadarReport(callerName, fileName, errCode, session_->GetScenario()); - AuditLog auditLog = { false, "Backup File Ready", "ADD", "", 1, "SUCCESS", "AppFileReady", - callerName, GetAnonyPath(fileName) }; - HiAudit::GetInstance(true).Write(auditLog); if (session_->OnBundleFileReady(callerName, fileName)) { auto backUpConnection = session_->GetExtConnection(callerName); if (backUpConnection == nullptr) { @@ -175,9 +183,6 @@ ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd, int32_t errCo return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; } catch (...) { HILOGI("Unexpected exception"); return EPERM; @@ -192,7 +197,12 @@ ErrCode Service::AppDone(ErrCode errCode) HILOGE("App finish error, session info is empty"); return BError(BError::Codes::SA_INVAL_ARG); } - string callerName = VerifyCallerAndGetCallerName(); + string callerName; + ErrCode ret = VerifyCallerAndGetCallerName(callerName); + if (ret != ERR_OK) { + HILOGE("App done failed, Get bundle name failed, ret:%{public}d", ret); + return ret; + } HILOGI("Begin, callerName is: %{public}s, errCode: %{public}d", callerName.c_str(), errCode); if (session_->OnBundleFileReady(callerName) || errCode != BError(BError::Codes::OK)) { std::shared_ptr mutexPtr = GetExtensionMutex(callerName); @@ -203,12 +213,11 @@ ErrCode Service::AppDone(ErrCode errCode) std::lock_guard lock(mutexPtr->callbackMutex); auto backUpConnection = session_->GetExtConnection(callerName); if (backUpConnection == nullptr) { - HILOGE("App finish error, backUpConnection is empty"); - return BError(BError::Codes::SA_INVAL_ARG); + return BError(BError::Codes::SA_INVAL_ARG, "App finish error, backUpConnection is empty"); } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + return BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } proxy->HandleClear(); session_->StopFwkTimer(callerName); @@ -224,12 +233,9 @@ ErrCode Service::AppDone(ErrCode errCode) ReleaseOnException(); HILOGE("AppDone error, err code is: %{public}d", e.GetCode()); return e.GetCode(); // 任意异常产生,终止监听该任务 - } catch (const exception &e) { - ReleaseOnException(); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; } catch (...) { - HILOGI("Unexpected exception"); + HILOGE("Unexpected exception"); + ReleaseOnException(); return EPERM; } } @@ -237,49 +243,42 @@ ErrCode Service::AppDone(ErrCode errCode) ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - try { - HILOGI("begin %{public}s", bundleName.data()); - IServiceReverse::Scenario scenario = session_->GetScenario(); - BConstants::ExtensionAction action; - if (scenario == IServiceReverse::Scenario::BACKUP || scenario == IServiceReverse::Scenario::CLEAN) { - action = BConstants::ExtensionAction::BACKUP; - } else if (scenario == IServiceReverse::Scenario::RESTORE) { - action = BConstants::ExtensionAction::RESTORE; - } else { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to scenario"); - } - if (SAUtils::IsSABundleName(bundleName)) { - return LaunchBackupSAExtension(bundleName); - } - AAFwk::Want want; - SetWant(want, bundleName, action); - auto backUpConnection = session_->GetExtConnection(bundleName); - if (backUpConnection == nullptr) { - HILOGE("LaunchBackupExtension error, backUpConnection is empty"); - return BError(BError::Codes::SA_INVAL_ARG); - } - if (backUpConnection->IsExtAbilityConnected() && !backUpConnection->WaitDisconnectDone()) { - HILOGE("LaunchBackupExtension error, WaitDisconnectDone failed"); - return BError(BError::Codes::SA_INVAL_ARG); - } - BConstants::ServiceSchedAction bundleAction = session_->GetServiceSchedAction(bundleName); - ErrCode ret = backUpConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId(), - bundleAction == BConstants::ServiceSchedAction::CLEAN); - if (ret) { - HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); - ExtensionConnectFailRadarReport(bundleName, ret, scenario); - return BError(BError::Codes::SA_BOOT_EXT_FAIL); - } - return BError(BError::Codes::OK); - } catch (const BError &e) { - return e.GetCode(); - } catch (const exception &e) { - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); - return EPERM; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; + HILOGI("begin %{public}s", bundleName.data()); + IServiceReverse::Scenario scenario = session_->GetScenario(); + BConstants::ExtensionAction action; + if (scenario == IServiceReverse::Scenario::BACKUP || scenario == IServiceReverse::Scenario::CLEAN) { + action = BConstants::ExtensionAction::BACKUP; + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + action = BConstants::ExtensionAction::RESTORE; + } else { + action = BConstants::ExtensionAction::INVALID; + HILOGE("Launch current bundle backupExtension failed, action is unknown, bundleName:%{public}s", + bundleName.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + if (SAUtils::IsSABundleName(bundleName)) { + return LaunchBackupSAExtension(bundleName); + } + AAFwk::Want want; + SetWant(want, bundleName, action); + auto backUpConnection = session_->GetExtConnection(bundleName); + if (backUpConnection == nullptr) { + HILOGE("LaunchBackupExtension error, backUpConnection is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + if (backUpConnection->IsExtAbilityConnected() && !backUpConnection->WaitDisconnectDone()) { + HILOGE("LaunchBackupExtension error, WaitDisconnectDone failed"); + return BError(BError::Codes::SA_INVAL_ARG); + } + BConstants::ServiceSchedAction bundleAction = session_->GetServiceSchedAction(bundleName); + ErrCode ret = backUpConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId(), + bundleAction == BConstants::ServiceSchedAction::CLEAN); + if (ret != ERR_OK) { + HILOGE("ConnectBackupExtAbility failed, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + ExtensionConnectFailRadarReport(bundleName, ret, scenario); + return BError(BError::Codes::SA_BOOT_EXT_FAIL); } + return BError(BError::Codes::OK); } void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action) @@ -359,7 +358,12 @@ ErrCode Service::RefreshDataSize(int64_t totalDataSize) HILOGE("session is nullptr"); return BError(BError::Codes::SA_INVAL_ARG); } - std::string bundleName = VerifyCallerAndGetCallerName(); + std::string bundleName; + ErrCode ret = VerifyCallerAndGetCallerName(bundleName); + if (ret != ERR_OK) { + HILOGE("Refresh data size failed, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + return ret; + } session_->SetBundleDataSize(bundleName, totalDataSize); HILOGI("RefreshDataSize, bundleName:%{public}s ,datasize = %{public}" PRId64 "", bundleName.c_str(), totalDataSize); @@ -399,7 +403,14 @@ ErrCode Service::StopExtTimer(bool &isExtStop) return BError(BError::Codes::SA_INVAL_ARG); } session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); - string bundleName = VerifyCallerAndGetCallerName(); + string bundleName; + ErrCode ret = VerifyCallerAndGetCallerName(bundleName); + if (ret != ERR_OK) { + HILOGE("Stop extension error, ret:%{public}d", ret); + isExtStop = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } isExtStop = session_->StopExtTimer(bundleName); session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); @@ -431,4 +442,139 @@ void Service::GetOldDeviceBackupVersion() } HILOGI("backupVersion of old device = %{public}s", oldBackupVersion.c_str()); } + +void Service::ExtConnectDied(const string &callName) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + try { + HILOGI("Begin, bundleName: %{public}s", callName.c_str()); + std::shared_ptr mutexPtr = GetExtensionMutex(callName); + if (mutexPtr == nullptr) { + HILOGE("extension mutex ptr is nullptr"); + return; + } + std::lock_guard lock(mutexPtr->callbackMutex); + /* Clear Timer */ + session_->StopFwkTimer(callName); + session_->StopExtTimer(callName); + auto backUpConnection = session_->GetExtConnection(callName); + if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) { + backUpConnection->DisconnectBackupExtAbility(); + } + session_->SetServiceSchedAction(callName, BConstants::ServiceSchedAction::CLEAN); + auto ret = LaunchBackupExtension(callName); + if (ret) { + /* Clear Session before notice client finish event */ + ClearSessionAndSchedInfo(callName); + } + /* Notice Client Ext Ability Process Died */ + NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED)); + } catch (...) { + HILOGE("Unexpected exception, bundleName: %{public}s", callName.c_str()); + ClearSessionAndSchedInfo(callName); + NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED)); + } + RemoveExtensionMutex(callName); +} + +void Service::OnBackupExtensionDied(const string &&bundleName, bool isCleanCalled) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (isCleanCalled) { + HILOGE("Backup <%{public}s> Extension Process second Died", bundleName.c_str()); + ClearSessionAndSchedInfo(bundleName); + OnAllBundlesFinished(BError(BError::Codes::OK)); + return; + } + try { + string callName = move(bundleName); + HILOGE("Backup <%{public}s> Extension Process Died", callName.c_str()); + ErrCode ret = session_->VerifyBundleName(callName); + if (ret != ERR_OK) { + HILOGE("Backup Extension died error, verify bundleName failed, bundleName:%{public}s, ret:%{public}d", + bundleName.c_str(), ret); + ExtConnectDied(bundleName); + return; + } + // 重新连接清理缓存 + HILOGI("Clear backup extension data, bundleName: %{public}s", callName.c_str()); + ExtConnectDied(callName); + } catch (...) { + HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); + ExtConnectDied(bundleName); + return; + } +} + +void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + HILOGI("begin %{public}s", bundleName.c_str()); + try { + SendEndAppGalleryNotify(bundleName); + auto scenario = session_->GetScenario(); + if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { + session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName); + } else if (scenario == IServiceReverse::Scenario::RESTORE && + BackupPara().GetBackupOverrideIncrementalRestore() && + session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleFinished(errCode, bundleName); + } else if (scenario == IServiceReverse::Scenario::BACKUP) { + session_->GetServiceReverseProxy()->BackupOnBundleFinished(errCode, bundleName); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, bundleName); + }; + BundleEndRadarReport(bundleName, errCode, scenario); + /* If all bundle ext process finish, notice client. */ + OnAllBundlesFinished(BError(BError::Codes::OK)); + } catch(const BError &e) { + ReleaseOnException(); + } catch (...) { + ReleaseOnException(); + HILOGI("Unexpected exception"); + return; + } +} + +void Service::OnAllBundlesFinished(ErrCode errCode) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + HILOGI("called begin."); + if (session_->IsOnAllBundlesFinished()) { + IServiceReverse::Scenario scenario = session_->GetScenario(); + if (isInRelease_.load() && (scenario == IServiceReverse::Scenario::RESTORE)) { + SessionDeactive(); + } + if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { + session_->GetServiceReverseProxy()->IncrementalBackupOnAllBundlesFinished(errCode); + } else if (scenario == IServiceReverse::Scenario::RESTORE && + BackupPara().GetBackupOverrideIncrementalRestore() && + session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnAllBundlesFinished(errCode); + } else if (scenario == IServiceReverse::Scenario::BACKUP) { + session_->GetServiceReverseProxy()->BackupOnAllBundlesFinished(errCode); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + session_->GetServiceReverseProxy()->RestoreOnAllBundlesFinished(errCode); + } + if (!BackupPara().GetBackupOverrideBackupSARelease()) { + sched_->TryUnloadServiceTimer(true); + } + } + HILOGI("called end."); +} + +ErrCode Service::VerifySendRateParam() +{ + ErrCode ret = VerifyCaller(); + if (ret != ERR_OK) { + HILOGE("Update send rate fail, verify caller failed, ret:%{public}d", ret); + return ret; + } + IServiceReverse::Scenario scenario = session_ -> GetScenario(); + if (scenario != IServiceReverse::Scenario::BACKUP) { + HILOGE("This method is applicable to the backup scenario"); + return BError(BError::Codes::SA_INVAL_ARG); + } + return BError(BError::Codes::OK); +} } \ No newline at end of file diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index 9fec17ab3..8b79408c3 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -39,25 +39,28 @@ namespace OHOS::FileManagement::Backup { using namespace std; -void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const +ErrCode SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const { shared_lock lock(lock_); if (impl_.scenario != scenario) { - HILOGE("Inconsistent scenario, impl scenario:%{public}d", impl_.scenario); + HILOGE("Verify caller failed, Inconsistent scenario, impl scenario:%{public}d", impl_.scenario); AppRadar::Info info("", "", "Inconsistent scenario"); AppRadar::GetInstance().RecordDefaultFuncRes(info, "SvcSessionManager::VerifyCallerAndScenario", impl_.userId, BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL, BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode()); - throw BError(BError::Codes::SDK_MIXED_SCENARIO); + return BError(BError::Codes::SDK_MIXED_SCENARIO); } if (impl_.clientToken != clientToken) { + HILOGE("Verify caller failed, Caller mismatched"); AppRadar::Info info2("", "", "Caller mismatched"); AppRadar::GetInstance().RecordDefaultFuncRes(info2, "SvcSessionManager::VerifyCallerAndScenario", impl_.userId, BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL, BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode()); - throw BError(BError::Codes::SA_REFUSED_ACT, "Caller mismatched"); + + return BError(BError::Codes::SA_REFUSED_ACT); } HILOGD("Succeed to verify the caller"); + return BError(BError::Codes::OK); } SvcSessionManager::Impl SvcSessionManager::GetImpl() @@ -80,32 +83,40 @@ ErrCode SvcSessionManager::Active(Impl newImpl, bool isOccupyingSession) } if (!isOccupyingSession && !newImpl.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("Active session fail, No caller token was specified"); + return BError(BError::Codes::SA_INVAL_ARG); } if (!isOccupyingSession && newImpl.scenario == IServiceReverse::Scenario::UNDEFINED) { - throw BError(BError::Codes::SA_INVAL_ARG, "No scenario was specified"); + HILOGE("Active session fail, No scenario was specified"); + return BError(BError::Codes::SA_INVAL_ARG); } if (!isOccupyingSession) { - InitClient(newImpl); + ErrCode ret = InitClient(newImpl); + if (ret != BError(BError::Codes::OK)) { + HILOGE("Active session failed, init client error"); + return ret; + } } impl_ = newImpl; IncreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } -void SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) +ErrCode SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) { unique_lock lock(lock_); if (!impl_.clientToken) { - HILOGI("Empty session"); - return; + HILOGE("Deactive session fail, caller token is invalid"); + return BError(BError::Codes::SA_INVAL_ARG); } if (!force && (!impl_.clientToken || !impl_.clientProxy)) { - return; + HILOGE("Deactive session fail, client proxy is invalid"); + return BError(BError::Codes::SA_INVAL_ARG); } if (!force && (remoteInAction != impl_.clientProxy->AsObject())) { - throw BError(BError::Codes::SA_INVAL_ARG, "Only the client actived the session can deactive it"); + HILOGE("Deactive session fail, Only the client actived the session can deactive it"); + return BError(BError::Codes::SA_INVAL_ARG); } deathRecipient_ = nullptr; @@ -121,21 +132,23 @@ void SvcSessionManager::Deactive(const wptr &remoteInAction, bool impl_ = {}; extConnectNum_ = 0; DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::OK); } -void SvcSessionManager::VerifyBundleName(string &bundleName) +ErrCode SvcSessionManager::VerifyBundleName(string &bundleName) { shared_lock lock(lock_); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("Verify bundle name failed, No caller token was specified, bundleName:%{public}s", bundleName.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); } auto asVerify = [&bundleName](const auto &it) { return it.first == bundleName; }; if (none_of(impl_.backupExtNameMap.begin(), impl_.backupExtNameMap.end(), asVerify)) { - stringstream ss; - ss << "Could not find the " << bundleName << " from current session"; - throw BError(BError::Codes::SA_REFUSED_ACT, ss.str()); + HILOGE("Could not find the bundle from current session, bundleName:%{public}s", bundleName.c_str()); + return BError(BError::Codes::SA_REFUSED_ACT); } HILOGD("Succeed to verify the bundleName"); + return BError(BError::Codes::OK); } sptr SvcSessionManager::GetServiceReverseProxy() @@ -151,7 +164,8 @@ IServiceReverse::Scenario SvcSessionManager::GetScenario() { shared_lock lock(lock_); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("Get scenario failed, No caller token was specified"); + return IServiceReverse::Scenario::UNDEFINED; } return impl_.scenario; } @@ -252,14 +266,18 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & HILOGD("svcMrg:GetExt, bundleName:%{public}s", bundleName.c_str()); shared_lock lock(lock_); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("GetExt connection failed, No caller token was specified, bundleName:%{public}s", bundleName.c_str()); + return nullptr; + } + auto it = impl_.backupExtNameMap.find(bundleName); + if (it == impl_.backupExtNameMap.end()) { + HILOGE("Could not find the bundle from current session, bundleName:%{public}s", bundleName.c_str()); + return nullptr; } - - auto it = GetBackupExtNameMap(bundleName); if (!it->second.backUpConnection) { - throw BError(BError::Codes::SA_INVAL_ARG, "Svc backup connection is empty"); + HILOGE("Current bundle extension connection is empty, bundleName:%{public}s", bundleName.c_str()); + return nullptr; } - return wptr(it->second.backUpConnection); } @@ -357,14 +375,16 @@ void SvcSessionManager::DumpInfo(const int fd, const std::vector dprintf(fd, "Scenario: %d\n", impl_.scenario); } -void SvcSessionManager::InitClient(Impl &newImpl) +ErrCode SvcSessionManager::InitClient(Impl &newImpl) { if (!newImpl.clientProxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Invalid client"); + HILOGE("Init client error, Invalid client"); + return BError(BError::Codes::SA_INVAL_ARG); } auto remoteObj = newImpl.clientProxy->AsObject(); if (!remoteObj) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Proxy's remote object can't be nullptr"); + HILOGE("Init client error, Proxy's remote object can't be nullptr"); + return BError(BError::Codes::SA_BROKEN_IPC); } auto callback = [revPtr {reversePtr_}](const wptr &obj) { @@ -389,6 +409,7 @@ void SvcSessionManager::InitClient(Impl &newImpl) BizStageBackup::BIZ_STAGE_ACTIVE_SESSION, ERR_OK); } HILOGI("Succeed to active a session"); + return BError(BError::Codes::OK); } void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &fileName) @@ -556,22 +577,26 @@ sptr SvcSessionManager::CreateBackupConnection(BundleName & return GetBackupAbilityExt(bundleName); } -void SvcSessionManager::Start() +ErrCode SvcSessionManager::Start() { unique_lock lock(lock_); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("Start error, No caller token was specified"); + return BError(BError::Codes::SA_INVAL_ARG); } impl_.isBackupStart = true; + return BError(BError::Codes::OK); } -void SvcSessionManager::Finish() +ErrCode SvcSessionManager::Finish() { unique_lock lock(lock_); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("Finish error, No caller token was specified"); + return BError(BError::Codes::SA_INVAL_ARG); } impl_.isAppendFinish = true; + return BError(BError::Codes::OK); } bool SvcSessionManager::IsOnAllBundlesFinished() diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index 786a66bcc..2661aa56c 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -37,9 +37,9 @@ UniqueFd Service::GetLocalCapabilities() void Service::StopAll(const wptr &obj, bool force) {} -string Service::VerifyCallerAndGetCallerName() +ErrCode Service::VerifyCallerAndGetCallerName(std::string &bundleName) { - return ""; + return BError(BError::Codes::OK); } ErrCode Service::InitRestoreSession(sptr remote) @@ -143,9 +143,15 @@ void Service::ExtConnectDone(string bundleName) {} void Service::ClearSessionAndSchedInfo(const string &bundleName) {} -void Service::VerifyCaller() {} +ErrCode Service::VerifyCaller() +{ + return BError(BError::Codes::OK); +} -void Service::VerifyCaller(IServiceReverse::Scenario scenario) {} +ErrCode Service::VerifyCaller(IServiceReverse::Scenario scenario) +{ + return BError(BError::Codes::OK); +} void Service::OnAllBundlesFinished(ErrCode errCode) {} diff --git a/tests/mock/module_ipc/src/svc_session_manager_mock.cpp b/tests/mock/module_ipc/src/svc_session_manager_mock.cpp index b4aa9f283..8739d1da4 100644 --- a/tests/mock/module_ipc/src/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/src/svc_session_manager_mock.cpp @@ -15,21 +15,31 @@ #include "module_ipc/svc_session_manager.h" +#include "b_error/b_error.h" #include "svc_session_manager_mock.h" namespace OHOS::FileManagement::Backup { using namespace std; -void SvcSessionManager::VerifyCallerAndScenario(uint32_t, IServiceReverse::Scenario) const {} +ErrCode SvcSessionManager::VerifyCallerAndScenario(uint32_t, IServiceReverse::Scenario) const +{ + return BError(BError::Codes::OK); +} ErrCode SvcSessionManager::Active(Impl newImpl, bool force) { return BSvcSessionManager::sessionManager->Active(newImpl, force); } -void SvcSessionManager::Deactive(const wptr &, bool) {} +ErrCode SvcSessionManager::Deactive(const wptr &, bool) +{ + return BError(BError::Codes::OK); +} -void SvcSessionManager::VerifyBundleName(string &bundleName) {} +ErrCode SvcSessionManager::VerifyBundleName(string &bundleName) +{ + return BError(BError::Codes::OK); +} sptr SvcSessionManager::GetServiceReverseProxy() { @@ -65,7 +75,10 @@ sptr SvcSessionManager::GetBackupAbilityExt(const string &b void SvcSessionManager::DumpInfo(const int, const std::vector &) {} -void SvcSessionManager::InitClient(Impl &) {} +ErrCode SvcSessionManager::InitClient(Impl &) +{ + return BError(BError::Codes::OK); +} void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &) {} @@ -117,9 +130,15 @@ sptr SvcSessionManager::CreateBackupConnection(BundleName & return BSvcSessionManager::sessionManager->CreateBackupConnection(bundleName); } -void SvcSessionManager::Start() {} +ErrCode SvcSessionManager::Start() +{ + return BError(BError::Codes::OK); +} -void SvcSessionManager::Finish() {} +ErrCode SvcSessionManager::Finish() +{ + return BError(BError::Codes::OK); +} bool SvcSessionManager::IsOnAllBundlesFinished() { diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 1e9e265b8..bb61902f8 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -36,9 +36,10 @@ static int32_t g_nFileReadyNum = 0; static int32_t g_nAllBundlesFinished = 0; } // namespace -void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const +ErrCode SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const { GTEST_LOG_(INFO) << "VerifyCallerAndScenario"; + return BError(BError::Codes::OK); } ErrCode SvcSessionManager::Active(Impl newImpl, bool force) @@ -49,14 +50,16 @@ ErrCode SvcSessionManager::Active(Impl newImpl, bool force) return BError(BError::Codes::OK); } -void SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) +ErrCode SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) { GTEST_LOG_(INFO) << "Deactive"; + return BError(BError::Codes::OK); } -void SvcSessionManager::VerifyBundleName(string &bundleName) +ErrCode SvcSessionManager::VerifyBundleName(string &bundleName) { GTEST_LOG_(INFO) << "VerifyBundleName " << bundleName; + return BError(BError::Codes::OK); } sptr SvcSessionManager::GetServiceReverseProxy() @@ -123,9 +126,10 @@ void SvcSessionManager::DumpInfo(const int fd, const std::vector GTEST_LOG_(INFO) << "DumpInfo"; } -void SvcSessionManager::InitClient(Impl &newImpl) +ErrCode SvcSessionManager::InitClient(Impl &newImpl) { GTEST_LOG_(INFO) << "InitClient"; + return BError(BError::Codes::OK); } void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &fileName) @@ -255,9 +259,15 @@ sptr SvcSessionManager::CreateBackupConnection(BundleName & return GetBackupAbilityExt(bundleName); } -void SvcSessionManager::Start() {} +ErrCode SvcSessionManager::Start() +{ + return BError(BError::Codes::OK); +} -void SvcSessionManager::Finish() {} +ErrCode SvcSessionManager::Finish() +{ + return BError(BError::Codes::OK); +} bool SvcSessionManager::IsOnAllBundlesFinished() { diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp index c76234055..bfdf4a3d5 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -19,9 +19,9 @@ namespace OHOS::FileManagement::Backup { using namespace std; -void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const +ErrCode SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const { - BackupSvcSessionManager::session->VerifyCallerAndScenario(clientToken, scenario); + return BackupSvcSessionManager::session->VerifyCallerAndScenario(clientToken, scenario); } ErrCode SvcSessionManager::Active(Impl newImpl, bool force) @@ -29,14 +29,14 @@ ErrCode SvcSessionManager::Active(Impl newImpl, bool force) return BackupSvcSessionManager::session->Active(newImpl); } -void SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) +ErrCode SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) { - BackupSvcSessionManager::session->Deactive(remoteInAction, force); + return BackupSvcSessionManager::session->Deactive(remoteInAction, force); } -void SvcSessionManager::VerifyBundleName(string &bundleName) +ErrCode SvcSessionManager::VerifyBundleName(string &bundleName) { - BackupSvcSessionManager::session->VerifyBundleName(bundleName); + return BackupSvcSessionManager::session->VerifyBundleName(bundleName); } sptr SvcSessionManager::GetServiceReverseProxy() @@ -79,9 +79,9 @@ void SvcSessionManager::DumpInfo(const int fd, const std::vector BackupSvcSessionManager::session->DumpInfo(fd, args); } -void SvcSessionManager::InitClient(Impl &newImpl) +ErrCode SvcSessionManager::InitClient(Impl &newImpl) { - BackupSvcSessionManager::session->InitClient(newImpl); + return BackupSvcSessionManager::session->InitClient(newImpl); } void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const string &fileName) @@ -149,14 +149,14 @@ sptr SvcSessionManager::CreateBackupConnection(BundleName & return BackupSvcSessionManager::session->CreateBackupConnection(bundleName); } -void SvcSessionManager::Start() +ErrCode SvcSessionManager::Start() { - BackupSvcSessionManager::session->Start(); + return BackupSvcSessionManager::session->Start(); } -void SvcSessionManager::Finish() +ErrCode SvcSessionManager::Finish() { - BackupSvcSessionManager::session->Finish(); + return BackupSvcSessionManager::session->Finish(); } bool SvcSessionManager::IsOnAllBundlesFinished() diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.h b/tests/mock/module_ipc/svc_session_manager_throw_mock.h index 60113e1d7..2b3154b1a 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -27,10 +27,10 @@ class BackupSvcSessionManager { public: virtual ~BackupSvcSessionManager() = default; public: - virtual void VerifyCallerAndScenario(uint32_t, IServiceReverse::Scenario) = 0; + virtual ErrCode VerifyCallerAndScenario(uint32_t, IServiceReverse::Scenario) = 0; virtual ErrCode Active(SvcSessionManager::Impl) = 0; - virtual void Deactive(const wptr &, bool) = 0; - virtual void VerifyBundleName(std::string &) = 0; + virtual ErrCode Deactive(const wptr &, bool) = 0; + virtual ErrCode VerifyBundleName(std::string &) = 0; virtual sptr GetServiceReverseProxy() = 0; virtual IServiceReverse::Scenario GetScenario() = 0; virtual bool OnBundleFileReady(const std::string &, const std::string &) = 0; @@ -39,7 +39,7 @@ public: virtual wptr GetExtConnection(const BundleName &) = 0; virtual sptr GetBackupAbilityExt(const std::string &) = 0; virtual void DumpInfo(const int, const std::vector &) = 0; - virtual void InitClient(SvcSessionManager::Impl &) = 0; + virtual ErrCode InitClient(SvcSessionManager::Impl &) = 0; virtual void SetExtFileNameRequest(const std::string &, const std::string &) = 0; virtual std::set GetExtFileNameRequest(const std::string &) = 0; virtual std::map::iterator GetBackupExtNameMap(const std::string &) = 0; @@ -53,8 +53,8 @@ public: virtual std::weak_ptr GetSAExtConnection(const BundleName &) = 0; virtual void AppendBundles(const std::vector &) = 0; virtual sptr CreateBackupConnection(BundleName &) = 0; - virtual void Start() = 0; - virtual void Finish() = 0; + virtual ErrCode Start() = 0; + virtual ErrCode Finish() = 0; virtual bool IsOnAllBundlesFinished() = 0; virtual bool IsOnOnStartSched() = 0; virtual bool NeedToUnloadService() = 0; @@ -98,10 +98,10 @@ public: class SvcSessionManagerMock : public BackupSvcSessionManager { public: - MOCK_METHOD(void, VerifyCallerAndScenario, (uint32_t, IServiceReverse::Scenario)); + MOCK_METHOD(ErrCode, VerifyCallerAndScenario, (uint32_t, IServiceReverse::Scenario)); MOCK_METHOD(ErrCode, Active, (SvcSessionManager::Impl)); - MOCK_METHOD(void, Deactive, (const wptr &, bool)); - MOCK_METHOD(void, VerifyBundleName, (std::string &)); + MOCK_METHOD(ErrCode, Deactive, (const wptr &, bool)); + MOCK_METHOD(ErrCode, VerifyBundleName, (std::string &)); MOCK_METHOD(sptr, GetServiceReverseProxy, ()); MOCK_METHOD(IServiceReverse::Scenario, GetScenario, ()); MOCK_METHOD(bool, OnBundleFileReady, (const std::string &, const std::string &)); @@ -110,7 +110,7 @@ public: MOCK_METHOD(wptr, GetExtConnection, (const BundleName &)); MOCK_METHOD(sptr, GetBackupAbilityExt, (const std::string &)); MOCK_METHOD(void, DumpInfo, (const int, const std::vector &)); - MOCK_METHOD(void, InitClient, (SvcSessionManager::Impl &)); + MOCK_METHOD(ErrCode, InitClient, (SvcSessionManager::Impl &)); MOCK_METHOD(void, SetExtFileNameRequest, (const std::string &, const std::string &)); MOCK_METHOD(std::set, GetExtFileNameRequest, (const std::string &)); MOCK_METHOD((std::map::iterator), GetBackupExtNameMap, (const std::string &)); @@ -124,8 +124,8 @@ public: MOCK_METHOD(std::weak_ptr, GetSAExtConnection, (const BundleName &)); MOCK_METHOD(void, AppendBundles, (const std::vector &)); MOCK_METHOD(sptr, CreateBackupConnection, (BundleName &)); - MOCK_METHOD(void, Start, ()); - MOCK_METHOD(void, Finish, ()); + MOCK_METHOD(ErrCode, Start, ()); + MOCK_METHOD(ErrCode, Finish, ()); MOCK_METHOD(bool, IsOnAllBundlesFinished, ()); MOCK_METHOD(bool, IsOnOnStartSched, ()); MOCK_METHOD(bool, NeedToUnloadService, ()); diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 400061e87..d68914175 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -163,10 +163,13 @@ ohos_unittest("backup_service_throw_test") { module_out_path = path_module_out_tests sources = [ - "${path_backup_mock}/accesstoken/accesstoken_kit_mock.cpp", + "${path_backup_mock}/accesstoken/src/accesstoken_kit_mock.cpp", "${path_backup_mock}/module_ipc/app_gallery_dispose_proxy_mock.cpp", + "${path_backup_mock}/module_ipc/src/ipc_skeleton_mock.cpp", "${path_backup_mock}/module_ipc/svc_session_manager_throw_mock.cpp", "${path_backup_mock}/timer/timer_mock.cpp", + "${path_backup_mock}/utils_mock/src/b_jsonutil_mock.cpp", + "${path_backup_mock}/utils_mock/src/backup_para_mock.cpp", "${path_backup}/services/backup_sa/src/module_ipc/sa_backup_connection.cpp", "${path_backup}/services/backup_sa/src/module_ipc/service.cpp", "${path_backup}/services/backup_sa/src/module_ipc/service_incremental.cpp", @@ -183,8 +186,11 @@ ohos_unittest("backup_service_throw_test") { "${path_backup}/services/backup_sa/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", "${path_backup}/tests/unittests/backup_api/backup_impl/include", + "${path_backup_mock}/accesstoken/include", "${path_backup_mock}/b_process", "${path_backup_mock}/module_ipc", + "${path_backup_mock}/module_ipc/include", + "${path_backup_mock}/utils_mock/include", ] deps = [ diff --git a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp index b19ccd042..b8e8e3e0b 100644 --- a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp @@ -42,9 +42,9 @@ UniqueFd Service::GetLocalCapabilities() void Service::StopAll(const wptr &obj, bool force) {} -string Service::VerifyCallerAndGetCallerName() +ErrCode Service::VerifyCallerAndGetCallerName(std::string &bundleName) { - return ""; + return BError(BError::Codes::OK); } ErrCode Service::InitRestoreSession(sptr remote) @@ -148,9 +148,15 @@ void Service::ExtConnectDone(string bundleName) {} void Service::ClearSessionAndSchedInfo(const string &bundleName) {} -void Service::VerifyCaller() {} +ErrCode Service::VerifyCaller() +{ + return BError(BError::Codes::OK); +} -void Service::VerifyCaller(IServiceReverse::Scenario scenario) {} +ErrCode Service::VerifyCaller(IServiceReverse::Scenario scenario) +{ + return BError(BError::Codes::OK); +} void Service::OnAllBundlesFinished(ErrCode errCode) {} @@ -896,12 +902,14 @@ HWTEST_F(ServiceIncrementalTest, SUB_ServiceIncremental_IncrementalBackup_0000, string bundleName; EXPECT_CALL(*session, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(nullptr)); - EXPECT_THROW(service->IncrementalBackup(bundleName), BError); + bool res = service->IncrementalBackup(bundleName); + EXPECT_TRUE(res); EXPECT_CALL(*session, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(connect)); EXPECT_CALL(*connect, GetBackupExtProxy()).WillOnce(Return(nullptr)); - EXPECT_THROW(service->IncrementalBackup(bundleName), BError); + res = service->IncrementalBackup(bundleName); + EXPECT_TRUE(res); EXPECT_CALL(*session, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(connect)); diff --git a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp index 7d4dbb776..a2f71964b 100644 --- a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp @@ -483,25 +483,28 @@ HWTEST_F(ServiceTest, SUB_Service_VerifyCallerAndGetCallerName_0100, TestSize.Le GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_VerifyCallerAndGetCallerName_0100"; try { ASSERT_TRUE(service != nullptr); + std::string bundleName = ""; EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(-1)); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - EXPECT_THROW(service->VerifyCallerAndGetCallerName(), BError); + auto ret = service->VerifyCallerAndGetCallerName(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("")); - auto ret = service->VerifyCallerAndGetCallerName(); - EXPECT_TRUE(ret.empty()); + ret = service->VerifyCallerAndGetCallerName(bundleName); + EXPECT_TRUE(bundleName.empty()); EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - EXPECT_THROW(service->VerifyCallerAndGetCallerName(), BError); + ret = service->VerifyCallerAndGetCallerName(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by VerifyCallerAndGetCallerName."; @@ -521,51 +524,52 @@ HWTEST_F(ServiceTest, SUB_Service_VerifyCallerAndGetCallerName_0100, TestSize.Le HWTEST_F(ServiceTest, SUB_Service_VerifyCaller_0100, TestSize.Level1) { GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_VerifyCaller_0100"; - try { - ASSERT_TRUE(service != nullptr); - EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); - EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE)); - EXPECT_CALL(*token, VerifyAccessToken(_, _)) - .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_DENIED)); - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) - .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - EXPECT_THROW(service->VerifyCaller(), BError); - - EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); - EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE)); - EXPECT_CALL(*token, VerifyAccessToken(_, _)) - .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); - service->VerifyCaller(); - EXPECT_TRUE(true); - - EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); - EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); - EXPECT_CALL(*token, VerifyAccessToken(_, _)) - .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_DENIED)); - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) - .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - EXPECT_THROW(service->VerifyCaller(), BError); - - EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); - EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); - EXPECT_CALL(*token, VerifyAccessToken(_, _)) - .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); - EXPECT_CALL(*token, IsSystemAppByFullTokenID(_)).WillOnce(Return(false)); - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) - .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - EXPECT_THROW(service->VerifyCaller(), BError); - - EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); - EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); - EXPECT_CALL(*token, VerifyAccessToken(_, _)) - .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); - EXPECT_CALL(*token, IsSystemAppByFullTokenID(_)).WillOnce(Return(true)); - service->VerifyCaller(); - EXPECT_TRUE(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by VerifyCaller."; - } + ASSERT_TRUE(service != nullptr); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*token, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_DENIED)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + ErrCode ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*token, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); + ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_DENIED)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); + EXPECT_CALL(*token, IsSystemAppByFullTokenID(_)).WillOnce(Return(false)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_GRANTED)); + EXPECT_CALL(*token, IsSystemAppByFullTokenID(_)).WillOnce(Return(true)); + ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_VerifyCaller_0100"; } @@ -588,19 +592,21 @@ HWTEST_F(ServiceTest, SUB_Service_VerifyCaller_0200, TestSize.Level1) EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::XTS_UID)); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - EXPECT_THROW(service->VerifyCaller(), BError); + ErrCode ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); - service->VerifyCaller(); - EXPECT_TRUE(true); + ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_INVALID)); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - EXPECT_THROW(service->VerifyCaller(), BError); + ret = service->VerifyCaller(); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by VerifyCaller."; @@ -867,8 +873,8 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0200, TestSize.Level1 map isClearDataFlags; RestoreTypeEnum restoreType = RestoreTypeEnum::RESTORE_DATA_WAIT_SEND; std::string backupVersion; - EXPECT_THROW(service->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, - isClearDataFlags, restoreType, backupVersion), BError); + service->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, + isClearDataFlags, restoreType, backupVersion); restoreBundleNames.emplace_back("bundleName"); EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("bundleName")) @@ -1398,22 +1404,14 @@ HWTEST_F(ServiceTest, SUB_Service_ClearResidualBundleData_0100, TestSize.Level1) service->ClearResidualBundleData(bundleName); service->session_ = sptr(new SvcSessionManager(wptr(service))); - try { - EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(nullptr)); - service->ClearResidualBundleData(bundleName); - EXPECT_TRUE(false); - } catch (...) { - EXPECT_TRUE(true); - } - - try { - EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(connect)); - EXPECT_CALL(*connect, GetBackupExtProxy()).WillOnce(Return(nullptr)); - service->ClearResidualBundleData(bundleName); - EXPECT_TRUE(false); - } catch (...) { - EXPECT_TRUE(true); - } + EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(nullptr)); + ErrCode ret = service->ClearResidualBundleData(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); + + EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(connect)); + EXPECT_CALL(*connect, GetBackupExtProxy()).WillOnce(Return(nullptr)); + ret = service->ClearResidualBundleData(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by ClearResidualBundleData."; @@ -1541,7 +1539,7 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateSendRate_0000, TestSize.Level1) EXPECT_CALL(*session, GetExtConnection(_)).WillOnce(Return(connect)); EXPECT_CALL(*connect, GetBackupExtProxy()).WillOnce(Return(nullptr)); ret = service->UpdateSendRate(bundleName, 0, result); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UpdateSendRate."; diff --git a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp index cb112e077..27c48d5e9 100644 --- a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp @@ -16,6 +16,10 @@ #include #include +#include "accesstoken_kit_mock.h" +#include "b_jsonutil_mock.h" +#include "backup_para_mock.h" +#include "ipc_skeleton_mock.h" #include "module_ipc/service.h" #include "svc_session_manager_throw_mock.h" #include "test_manager.h" @@ -25,6 +29,7 @@ using namespace std; using namespace testing; constexpr int32_t SERVICE_ID = 5203; +constexpr int32_t DEBUG_ID = 100; class ServiceThrowTest : public testing::Test { public: @@ -34,7 +39,11 @@ public: void TearDown() {}; static inline sptr service = nullptr; + static inline shared_ptr param = nullptr; static inline shared_ptr sessionMock = nullptr; + static inline shared_ptr jsonUtil = nullptr; + static inline shared_ptr skeleton = nullptr; + static inline shared_ptr token = nullptr; }; void ServiceThrowTest::SetUpTestCase(void) @@ -42,15 +51,31 @@ void ServiceThrowTest::SetUpTestCase(void) GTEST_LOG_(INFO) << "SetUpTestCase enter"; service = sptr(new Service(SERVICE_ID)); sessionMock = make_shared(); + param = make_shared(); + BackupParaMock::backupPara = param; SvcSessionManagerMock::session = sessionMock; + jsonUtil = make_shared(); + BJsonUtilMock::jsonUtil = jsonUtil; + skeleton = make_shared(); + IPCSkeletonMock::skeleton = skeleton; + token = make_shared(); + AccessTokenKitMock::token = token; } void ServiceThrowTest::TearDownTestCase() { GTEST_LOG_(INFO) << "TearDownTestCase enter"; service = nullptr; + BackupParaMock::backupPara = nullptr; + param = nullptr; SvcSessionManagerMock::session = nullptr; sessionMock = nullptr; + BJsonUtilMock::jsonUtil = nullptr; + jsonUtil = nullptr; + IPCSkeletonMock::skeleton = nullptr; + skeleton = nullptr; + AccessTokenKitMock::token = nullptr; + token = nullptr; } /** @@ -106,33 +131,32 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetLocalCapabilities_0100, testing: HWTEST_F(ServiceThrowTest, SUB_Service_throw_InitRestoreSession_0100, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_InitRestoreSession_0100"; - try { - EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return 0; - })); - EXPECT_CALL(*sessionMock, Deactive(_, _)).WillOnce(Return()); - auto ret = service->InitRestoreSession(nullptr); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - return 0; - })); - ret = service->InitRestoreSession(nullptr); - EXPECT_EQ(ret, EPERM); - - EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Invoke([]() { - throw "未知错误"; - return 0; - })); - ret = service->InitRestoreSession(nullptr); - EXPECT_EQ(ret, EPERM); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by InitRestoreSession."; - } + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::DEFAULT_USER_ID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + auto ret = service->InitRestoreSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Return(BError(BError::Codes::SA_REFUSED_ACT))); + EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); + ret = service->InitRestoreSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Return(BError(BError::Codes::OK))); + ret = service->InitRestoreSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_InitRestoreSession_0100"; } @@ -148,18 +172,32 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_InitRestoreSession_0100, testing::e HWTEST_F(ServiceThrowTest, SUB_Service_throw_InitBackupSession_0100, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_InitBackupSession_0100"; - try { - EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, SetMemParaCurSize(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, Deactive(_, _)).WillOnce(Return()); - auto ret = service->InitBackupSession(nullptr); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by InitBackupSession."; - } + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::DEFAULT_USER_ID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + auto ret = service->InitBackupSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Return(BError(BError::Codes::SA_REFUSED_ACT))); + EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); + ret = service->InitBackupSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Return(BError(BError::Codes::OK))); + ret = service->InitBackupSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_InitBackupSession_0100"; } @@ -325,30 +363,33 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesDetailsBackupSession_0 HWTEST_F(ServiceThrowTest, SUB_Service_throw_PublishFile_0100, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_PublishFile_0100"; - try { - EXPECT_NE(service, nullptr); - BFileInfo fileInfo; - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - auto ret = service->PublishFile(fileInfo); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - })); - ret = service->PublishFile(fileInfo); - EXPECT_EQ(ret, EPERM); - - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw "未知错误"; - })); - ret = service->PublishFile(fileInfo); - EXPECT_EQ(ret, EPERM); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by PublishFile."; - } + EXPECT_NE(service, nullptr); + BFileInfo fileInfo; + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)) + .WillOnce(Return(BError(BError::Codes::SDK_MIXED_SCENARIO))); + auto ret = service->PublishFile(fileInfo); + EXPECT_EQ(ret, BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)) + .WillOnce(Return(BError(BError(BError::Codes::SA_REFUSED_ACT)))); + ret = service->PublishFile(fileInfo); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)) + .WillOnce(Return(BError(BError(BError::Codes::OK)))); + EXPECT_CALL(*skeleton, GetCallingTokenID()) + .WillOnce(Return(0)) + .WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE)); + EXPECT_CALL(*token, VerifyAccessToken(_, _)) + .WillOnce(Return(Security::AccessToken::PermissionState::PERMISSION_DENIED)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + ret = service->PublishFile(fileInfo); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_PublishFile_0100"; } @@ -367,23 +408,26 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppFileReady_0100, testing::ext::Te try { EXPECT_NE(service, nullptr); string fileName; - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))); auto ret = service->AppFileReady(fileName, UniqueFd(-1), 0); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - })); - ret = service->AppFileReady(fileName, UniqueFd(-1), 0); - EXPECT_EQ(ret, EPERM); - - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw "未知错误"; - })); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Return(BError(BError::Codes::SA_REFUSED_ACT))); ret = service->AppFileReady(fileName, UniqueFd(-1), 0); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by AppFileReady."; @@ -405,25 +449,14 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppDone_0100, testing::ext::TestSiz GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppDone_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))); EXPECT_CALL(*sessionMock, IsOnAllBundlesFinished()).WillOnce(Return(false)); auto ret = service->AppDone(0); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - })); - EXPECT_CALL(*sessionMock, IsOnAllBundlesFinished()).WillOnce(Return(false)); - ret = service->AppDone(0); - EXPECT_EQ(ret, EPERM); - - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw "未知错误"; - })); - ret = service->AppDone(0); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by AppDone."; @@ -446,26 +479,9 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_LaunchBackupExtension_0100, testing try { EXPECT_NE(service, nullptr); BundleName bundleName; - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return IServiceReverse::Scenario::UNDEFINED; - })); + EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); auto ret = service->LaunchBackupExtension(bundleName); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - return IServiceReverse::Scenario::UNDEFINED; - })); - ret = service->LaunchBackupExtension(bundleName); - EXPECT_EQ(ret, EPERM); - - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw "未知错误"; - return IServiceReverse::Scenario::UNDEFINED; - })); - ret = service->LaunchBackupExtension(bundleName); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by LaunchBackupExtension."; @@ -489,23 +505,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetFileHandle_0100, testing::ext::T EXPECT_NE(service, nullptr); string bundleName; string fileName; - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce( + Return(BError(BError::Codes::SDK_MIXED_SCENARIO))); auto ret = service->GetFileHandle(bundleName, fileName); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - })); - ret = service->GetFileHandle(bundleName, fileName); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw "未知错误"; - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce( + Return(BError(BError::Codes::SA_REFUSED_ACT))); ret = service->GetFileHandle(bundleName, fileName); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by GetFileHandle."; @@ -528,15 +538,12 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_OnBackupExtensionDied_0100, testing try { EXPECT_NE(service, nullptr); string bundleName; - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)) - .WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)) - .WillOnce(Invoke([]() { - throw "未知错误"; - return IServiceReverse::Scenario::UNDEFINED; - })); - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); + EXPECT_CALL(*sessionMock, GetScenario()) + .WillOnce(Return(IServiceReverse::Scenario::CLEAN)) + .WillOnce(Return(IServiceReverse::Scenario::CLEAN)); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)) + .WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))) + .WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))); EXPECT_CALL(*sessionMock, StopFwkTimer(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); return true; @@ -647,10 +654,9 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_NoticeClientFinish_0100, testing::e EXPECT_NE(service, nullptr); string bundleName; ErrCode errCode = 0; - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return IServiceReverse::Scenario::UNDEFINED; - })); + EXPECT_CALL(*sessionMock, GetScenario()) + .WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)) + .WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); EXPECT_CALL(*sessionMock, IsOnAllBundlesFinished()).WillOnce(Return(false)); service->NoticeClientFinish(bundleName, errCode); EXPECT_TRUE(true); @@ -900,20 +906,35 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetAppLocalListAndDoIncrementalBack HWTEST_F(ServiceThrowTest, SUB_Service_throw_InitIncrementalBackupSession_0100, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_InitIncrementalBackupSession_0100"; - try { - EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return 0; - })); - EXPECT_CALL(*sessionMock, Deactive(_, _)).WillOnce(Return()); - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); - auto ret = service->InitIncrementalBackupSession(nullptr); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by InitIncrementalBackupSession."; - } + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::DEFAULT_USER_ID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + auto ret = service->InitIncrementalBackupSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Return(BError(BError::Codes::SA_REFUSED_ACT))); + EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)); + ret = service->InitIncrementalBackupSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + EXPECT_CALL(*sessionMock, Active(_)).WillOnce(Return(BError(BError::Codes::OK))); + ret = service->InitIncrementalBackupSession(nullptr); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_InitIncrementalBackupSession_0100"; } @@ -1003,23 +1024,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_PublishIncrementalFile_0100, testin try { EXPECT_NE(service, nullptr); BFileInfo fileInfo; - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce( + Return(BError(BError::Codes::SDK_MIXED_SCENARIO))); auto ret = service->PublishIncrementalFile(fileInfo); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - })); - ret = service->PublishIncrementalFile(fileInfo); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw "未知错误"; - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce( + Return(BError(BError::Codes::SA_REFUSED_ACT))); ret = service->PublishIncrementalFile(fileInfo); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by PublishIncrementalFile."; @@ -1042,23 +1057,26 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppIncrementalFileReady_0100, testi try { EXPECT_NE(service, nullptr); string fileName; - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))); auto ret = service->AppIncrementalFileReady(fileName, UniqueFd(-1), UniqueFd(-1), 0); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - })); - ret = service->AppIncrementalFileReady(fileName, UniqueFd(-1), UniqueFd(-1), 0); - EXPECT_EQ(ret, EPERM); - - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw "未知错误"; - })); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Return(BError(BError::Codes::SA_REFUSED_ACT))); ret = service->AppIncrementalFileReady(fileName, UniqueFd(-1), UniqueFd(-1), 0); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by AppIncrementalFileReady."; @@ -1080,19 +1098,33 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppIncrementalDone_0100, testing::e GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppIncrementalDone_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Return(BError(BError::Codes::SA_INVAL_ARG))); EXPECT_CALL(*sessionMock, IsOnAllBundlesFinished()).WillOnce(Return(false)); auto ret = service->AppIncrementalDone(0); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - - EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { - throw "未知错误"; - })); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)) + .WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")) + .WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Return(BError(BError::Codes::SA_REFUSED_ACT))); EXPECT_CALL(*sessionMock, IsOnAllBundlesFinished()).WillOnce(Return(false)); ret = service->AppIncrementalDone(0); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by AppIncrementalDone."; @@ -1116,23 +1148,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetIncrementalFileHandle_0100, test EXPECT_NE(service, nullptr); string bundleName; string fileName; - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - auto ret = service->GetIncrementalFileHandle(bundleName, fileName); - EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw runtime_error("运行时错误"); - })); - ret = service->GetIncrementalFileHandle(bundleName, fileName); - EXPECT_EQ(ret, EPERM); - - EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce(Invoke([]() { - throw "未知错误"; - })); + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce( + Return(BError(BError::Codes::SDK_MIXED_SCENARIO))); + auto ret = service->GetIncrementalFileHandle(bundleName, fileName); + EXPECT_EQ(ret, BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode()); + + EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)); + EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP)); + EXPECT_CALL(*token, GetHapTokenInfo(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("bundleName")); + EXPECT_CALL(*sessionMock, VerifyCallerAndScenario(_, _)).WillOnce( + Return(BError(BError::Codes::SA_REFUSED_ACT))); ret = service->GetIncrementalFileHandle(bundleName, fileName); - EXPECT_EQ(ret, EPERM); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by GetIncrementalFileHandle."; diff --git a/tests/unittests/backup_sa/module_ipc/sub_service_test.cpp b/tests/unittests/backup_sa/module_ipc/sub_service_test.cpp index ce2c88e40..c995e219c 100644 --- a/tests/unittests/backup_sa/module_ipc/sub_service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/sub_service_test.cpp @@ -31,6 +31,10 @@ HWTEST_F(ServiceTest, SUB_Service_HandleCurGroupBackupInfos_0000, TestSize.Level map> bundleNameDetailMap; map isClearDataFlags; EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("")); + EXPECT_CALL(*session, GetServiceReverseProxy()).WillOnce(Return(srProxy)); + EXPECT_CALL(*srProxy, BackupOnBundleStarted(_, _)).WillOnce(Return()); + EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) + .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); EXPECT_CALL(*jsonUtil, FindBundleInfoByName(_, _, _, _)).WillOnce(Return(false)); service->HandleCurGroupBackupInfos(backupInfos, bundleNameDetailMap, isClearDataFlags); EXPECT_TRUE(true); diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp index 9370532d0..ad790f884 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp @@ -94,28 +94,21 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_VerifyCallerAndScenario_01 { GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_VerifyCallerAndScenario_0100"; try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::BACKUP; - sessionManagerPtr_->VerifyCallerAndScenario(CLIENT_TOKEN_ID, IServiceReverse::Scenario::RESTORE); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SDK_MIXED_SCENARIO); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::BACKUP; + ErrCode ret = sessionManagerPtr_->VerifyCallerAndScenario(CLIENT_TOKEN_ID, + IServiceReverse::Scenario::RESTORE); + EXPECT_TRUE(ret == BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode()); - try { - sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::BACKUP; - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->VerifyCallerAndScenario(CLIENT_TOKEN_ID, IServiceReverse::Scenario::BACKUP); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_REFUSED_ACT); - } + sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::BACKUP; + sessionManagerPtr_->impl_.clientToken = 0; + ret = sessionManagerPtr_->VerifyCallerAndScenario(CLIENT_TOKEN_ID, IServiceReverse::Scenario::BACKUP); + EXPECT_TRUE(ret == BError(BError::Codes::SA_REFUSED_ACT).GetCode()); sessionManagerPtr_->impl_.scenario = IServiceReverse::Scenario::BACKUP; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->VerifyCallerAndScenario(CLIENT_TOKEN_ID, IServiceReverse::Scenario::BACKUP); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->VerifyCallerAndScenario(CLIENT_TOKEN_ID, IServiceReverse::Scenario::BACKUP); + EXPECT_TRUE(ret == ERR_OK); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by VerifyCallerAndScenario."; @@ -137,43 +130,27 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_Active_0100, testing::ext: GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_Active_0100"; try { SvcSessionManager::Impl newImpl; - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - auto res = sessionManagerPtr_->Active(newImpl); - EXPECT_EQ(res, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); - } catch (BError &err) { - EXPECT_TRUE(false); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + auto res = sessionManagerPtr_->Active(newImpl); + EXPECT_EQ(res, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); - try { - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->Active(newImpl); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + sessionManagerPtr_->impl_.clientToken = 0; + res = sessionManagerPtr_->Active(newImpl); + EXPECT_EQ(res, BError(BError::Codes::SA_INVAL_ARG).GetCode()); - try { - newImpl.clientToken = CLIENT_TOKEN_ID; - newImpl.scenario = IServiceReverse::Scenario::UNDEFINED; - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->Active(newImpl); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + newImpl.clientToken = CLIENT_TOKEN_ID; + newImpl.scenario = IServiceReverse::Scenario::UNDEFINED; + sessionManagerPtr_->impl_.clientToken = 0; + res = sessionManagerPtr_->Active(newImpl); + EXPECT_EQ(res, BError(BError::Codes::SA_INVAL_ARG).GetCode()); - try { - newImpl.clientToken = CLIENT_TOKEN_ID; - newImpl.scenario = IServiceReverse::Scenario::BACKUP; - newImpl.clientProxy = nullptr; - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->Active(newImpl); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + newImpl.clientToken = CLIENT_TOKEN_ID; + newImpl.scenario = IServiceReverse::Scenario::BACKUP; + newImpl.clientProxy = nullptr; + sessionManagerPtr_->impl_.clientToken = 0; + res = sessionManagerPtr_->Active(newImpl); + EXPECT_EQ(res, BError(BError::Codes::SA_INVAL_ARG).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by Active."; @@ -197,27 +174,23 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_Deactive_0100, testing::ex wptr remoteInAction = nullptr; EXPECT_TRUE(sessionManagerPtr_ != nullptr); sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->Deactive(remoteInAction, false); - EXPECT_TRUE(true); + ErrCode ret = sessionManagerPtr_->Deactive(remoteInAction, false); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.clientProxy = nullptr; - sessionManagerPtr_->Deactive(remoteInAction, false); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->Deactive(remoteInAction, false); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); - try { - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->impl_.clientProxy = remote_; - sessionManagerPtr_->Deactive(remoteInAction, false); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.clientProxy = remote_; + ret = sessionManagerPtr_->Deactive(remoteInAction, false); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.clientProxy = remote_; - sessionManagerPtr_->Deactive(remoteInAction, true); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->Deactive(remoteInAction, true); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by Deactive."; @@ -239,28 +212,20 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_VerifyBundleName_0100, tes GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_VerifyBundleName_0100"; try { string bundleName = BUNDLE_NAME; - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->VerifyBundleName(bundleName); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + ErrCode ret = sessionManagerPtr_->VerifyBundleName(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); - try { - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->impl_.backupExtNameMap.clear(); - sessionManagerPtr_->VerifyBundleName(bundleName); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_REFUSED_ACT); - } + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap.clear(); + ret = sessionManagerPtr_->VerifyBundleName(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::SA_REFUSED_ACT).GetCode()); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = {}; - sessionManagerPtr_->VerifyBundleName(bundleName); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->VerifyBundleName(bundleName); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by VerifyBundleName."; @@ -314,18 +279,14 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_getscenario_0100, testing: { GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_getscenario_0100"; try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->GetScenario(); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + IServiceReverse::Scenario scenario = sessionManagerPtr_->GetScenario(); + EXPECT_TRUE(scenario == IServiceReverse::Scenario::UNDEFINED); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->GetScenario(); - EXPECT_TRUE(true); + scenario = sessionManagerPtr_->GetScenario(); + EXPECT_TRUE(scenario == IServiceReverse::Scenario::UNDEFINED); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by getscenario."; @@ -573,18 +534,14 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_InitClient_0100, testing:: GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_InitClient_0100"; try { SvcSessionManager::Impl newImpl; - try { - newImpl.clientProxy = nullptr; - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->InitClient(newImpl); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + newImpl.clientProxy = nullptr; + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + ErrCode ret = sessionManagerPtr_->InitClient(newImpl); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); newImpl.clientProxy = remote_; - sessionManagerPtr_->InitClient(newImpl); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->InitClient(newImpl); + EXPECT_EQ(ret, BError(BError::Codes::OK).GetCode()); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by InitClient."; @@ -725,45 +682,28 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtFileNameRequest_0103 HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtConnection_0100, testing::ext::TestSize.Level1) { GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_GetExtConnection_0100"; - try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } - - try { - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->impl_.backupExtNameMap.clear(); - sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_REFUSED_ACT); - } - - try { - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = {}; - sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } - - BackupExtInfo info; - info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); - sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - auto ret = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); - EXPECT_EQ(reinterpret_cast(ret.GetRefPtr()), - reinterpret_cast(info.backUpConnection.GetRefPtr())); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by GetExtConnection."; - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + auto connection = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); + EXPECT_TRUE(connection == nullptr); + + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap.clear(); + connection = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); + EXPECT_TRUE(connection == nullptr); + + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = {}; + connection = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); + EXPECT_TRUE(connection == nullptr); + + BackupExtInfo info; + info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; + connection = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); + EXPECT_EQ(reinterpret_cast(connection.GetRefPtr()), + reinterpret_cast(info.backUpConnection.GetRefPtr())); GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_GetExtConnection_0100"; } @@ -1590,17 +1530,13 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_Start_0100, testing::ext:: { GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_Start_0100"; try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->Start(); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + ErrCode ret = sessionManagerPtr_->Start(); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->Start(); + ret = sessionManagerPtr_->Start(); EXPECT_TRUE(sessionManagerPtr_->impl_.isBackupStart); } catch (...) { EXPECT_TRUE(false); @@ -1622,17 +1558,13 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_Finish_0100, testing::ext: { GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_Finish_0100"; try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->Finish(); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + ErrCode ret = sessionManagerPtr_->Finish(); + EXPECT_EQ(ret, BError(BError::Codes::SA_INVAL_ARG).GetCode()); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; - sessionManagerPtr_->Finish(); + ret = sessionManagerPtr_->Finish(); EXPECT_TRUE(sessionManagerPtr_->impl_.isAppendFinish); } catch (...) { EXPECT_TRUE(false); -- Gitee