diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp index 42f9bea125e5fdbef2e5ccb35e32f8e806cbf1db..3e6a6f5fdd1f0d92b1de7142ac479d2d4bc50ebc 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp @@ -69,6 +69,38 @@ unique_ptr BIncrementalRestoreSession::Init(Callback return nullptr; } +unique_ptr BIncrementalRestoreSession::Init(Callbacks callbacks, + std::string &errMsg, ErrCode &errCode) +{ + try { + HILOGI("Init IncrementalRestoreSession Begin"); + auto restore = make_unique(); + ServiceProxy::InvaildInstance(); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + errMsg = "Failed to get backup service"; + errCode = BError(BError::Codes::SDK_BROKEN_IPC); + HILOGE("Init IncrementalRestoreSession failed, %{public}s", errMsg.c_str()); + return nullptr; + } + errCode = proxy->InitRestoreSession(sptr(new ServiceReverse(callbacks)), errMsg); + if (errCode != ERR_OK) { + HILOGE("Failed to Restore because of %{public}d", errCode); + AppRadar::Info info ("", "", "create restore session failed"); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BIncrementalRestoreSession::Init", + AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_CREATE_RESTORE_SESSION_FAIL, errCode); + return nullptr; + } + + restore->RegisterBackupServiceDied(callbacks.onBackupServiceDied); + return restore; + } catch (const exception &e) { + HILOGE("Failed to Restore because of %{public}s", e.what()); + errCode = BError(BError::Codes::SDK_INVAL_ARG); + } + return nullptr; +} + ErrCode BIncrementalRestoreSession::PublishFile(BFileInfo fileInfo) { auto proxy = ServiceProxy::GetInstance(); diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 7845556880aca234475fd594fbd4603f61b2bda8..e367757bc9582cf4a80a869fd418456241ce1e71 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -56,6 +56,36 @@ ErrCode ServiceProxy::InitRestoreSession(sptr remote) return reply.ReadInt32(); } +ErrCode ServiceProxy::InitRestoreSession(sptr remote, std::string &errMsg) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + MessageParcel reply; + MessageOption option; + + if (!remote) { + return BError(BError::Codes::SDK_INVAL_ARG, "Empty reverse stub").GetCode(); + } + if (!data.WriteRemoteObject(remote->AsObject().GetRefPtr())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the reverse stub").GetCode(); + } + + int32_t ret = Remote()->SendRequest( + static_cast(IServiceInterfaceCode::SERVICE_CMD_INIT_RESTORE_SESSION_MSG), data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + if (!reply.ReadString(errMsg)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to receive the errMsg").GetCode(); + } + return reply.ReadInt32(); +} + ErrCode ServiceProxy::InitBackupSession(sptr remote) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h index 502fd1a9c39a382a51c9b6965c97a12216ab2ccb..9f1b0b9fddfc8d8124a9cd58c16108b16b8fef24 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h @@ -49,6 +49,17 @@ public: */ static std::unique_ptr Init(Callbacks callbacks); + /** + * @brief 获取一个用于控制恢复流程的会话 + * + * @param callbacks 注册的回调函数 + * @param errMsg 失败信息 + * @param errCode 错误码 + * @return std::unique_ptr 指向BRestoreSession的智能指针。失败时为空指针 + */ + static std::unique_ptr Init(Callbacks callbacks, + std::string &errMsg, ErrCode &errCode); + /** * @brief 通知备份服务文件内容已就绪 * diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h index 630867b95115dd1de4e9342bbcfb610a9860990f..ec94562938692da901f120a2861ae209107c9c56 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h @@ -46,6 +46,7 @@ class IService : public IRemoteBroker { public: virtual ~IService() = default; virtual ErrCode InitRestoreSession(sptr remote) = 0; + virtual ErrCode InitRestoreSession(sptr remote, std::string &errMsg) = 0; virtual ErrCode InitBackupSession(sptr remote) = 0; virtual ErrCode Start() = 0; virtual UniqueFd GetLocalCapabilities() = 0; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h index f6027fab4528e8568b4ccbb2eeb259b229ba3b5c..2431573bcd93f94533b5a4c8d2e88ba0b35e6070 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h @@ -20,6 +20,7 @@ namespace OHOS::FileManagement::Backup { enum class IServiceInterfaceCode { SERVICE_CMD_INIT_RESTORE_SESSION, + SERVICE_CMD_INIT_RESTORE_SESSION_MSG, SERVICE_CMD_INIT_BACKUP_SESSION, SERVICE_CMD_GET_LOCAL_CAPABILITIES, SERVICE_CMD_PUBLISH_FILE, diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h index 07071b41b773b71af3c7eac1f283f182bd343a5c..e2b849c625df350a8f6127eaa10f8cd19bfdeedd 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h @@ -29,6 +29,7 @@ namespace OHOS::FileManagement::Backup { class ServiceProxy : public IRemoteProxy { public: ErrCode InitRestoreSession(sptr remote) override; + ErrCode InitRestoreSession(sptr remote, std::string &errMsg) override; ErrCode InitBackupSession(sptr remote) override; ErrCode Start() override; UniqueFd GetLocalCapabilities() override; diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index ddc36c4c0abbbb33b6754a5105ca9277b9603f56..26afea923e65f273ca4c394b91839d546bd60e45 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -454,6 +454,8 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info auto restoreEntity = std::make_unique(); restoreEntity->callbacks = make_shared(env, ptr, callbacks); restoreEntity->sessionWhole = nullptr; + ErrCode errCode; + std::string errMsg; restoreEntity->sessionSheet = BIncrementalRestoreSession::Init(BIncrementalRestoreSession::Callbacks { .onFileReady = bind(OnFileReadySheet, restoreEntity->callbacks, placeholders::_1, placeholders::_2, placeholders::_3, placeholders::_4), @@ -462,9 +464,12 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info .onAllBundlesFinished = bind(onAllBundlesEnd, restoreEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, restoreEntity->callbacks, placeholders::_1, placeholders::_2), .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks), - .onProcess = bind(OnProcess, restoreEntity->callbacks, placeholders::_1, placeholders::_2)}); + .onProcess = bind(OnProcess, restoreEntity->callbacks, placeholders::_1, placeholders::_2)}, errMsg, errCode); if (!restoreEntity->sessionSheet) { - NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init restore").GetCode()).ThrowErr(env); + std::tuple errInfo = + std::make_tuple(errCode, BError::GetBackupMsgByErrno(errCode) + ", " + errMsg); + ErrParam errorParam = [ errInfo ]() { return errInfo;}; + NError(errorParam).ThrowErr(env); return nullptr; } if (!SetSessionRestoreEntity(env, funcArg, std::move(restoreEntity))) { diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index d877ad4a6550f60ccf892f1b47194fef650035f1..5ca08739d17da6b1c8ea5ba5bdac7b40d13fae7a 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -49,6 +49,7 @@ class Service : public SystemAbility, public ServiceStub, protected NoCopyable { // 以下都是IPC接口 public: ErrCode InitRestoreSession(sptr remote) override; + ErrCode InitRestoreSession(sptr remote, std::string &errMsg) override; ErrCode InitBackupSession(sptr remote) override; ErrCode Start() override; UniqueFd GetLocalCapabilities() override; @@ -325,21 +326,35 @@ private: * @brief 验证调用者 * */ - void VerifyCaller(); + ErrCode VerifyCaller(); + + /** + * @brief 获取调用者名称 + * + * @return std::string + */ + std::string GetCallerName(); + + /** + * @brief 获取用户id + * + * @return int32_t + */ + int32_t GetUserIdDefault(); /** * @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相关资源 @@ -550,6 +565,10 @@ private: void ExtensionConnectFailRadarReport(const std::string &bundleName, const ErrCode errCode, const IServiceReverse::Scenario scenario); + void OnStartResRadarReport(const std::vector &bundleNameList, int32_t stage); + + void PermissionCheckFailRadar(const std::string &info, const std::string &func); + void UpdateFailedBundles(const std::string &bundleName, BundleTaskInfo taskInfo); void ClearFailedBundles(); @@ -568,8 +587,10 @@ private: void SetBundleIncDataInfo(const std::vector &bundlesToBackup, std::vector &supportBundleNames); - + void CancelTask(std::string bundleName, wptr ptr); + + void SetUserIdAndRestoreType(RestoreTypeEnum restoreType, int32_t userId); private: static sptr instance_; static std::mutex instanceLock_; diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h index 8ccaddf564edf79eb8112a9b9e540feefa3ac97b..45acead705fc166c7ec52f35acb9c67ab807e7f9 100644 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ b/services/backup_sa/include/module_ipc/service_stub.h @@ -35,6 +35,7 @@ private: std::map opToInterfaceMap_; int32_t CmdInitRestoreSession(MessageParcel &data, MessageParcel &reply); + int32_t CmdInitRestoreSessionMsg(MessageParcel &data, MessageParcel &reply); int32_t CmdInitBackupSession(MessageParcel &data, MessageParcel &reply); int32_t CmdStart(MessageParcel &data, MessageParcel &reply); int32_t CmdGetLocalCapabilities(MessageParcel &data, MessageParcel &reply); 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 1d63fdf2bdecd8e7b63a89adf5015e705c1acbcc..52c95c152fb31f36822ab8c1af068470e2ceeee5 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -92,6 +92,8 @@ public: RestoreTypeEnum restoreDataType {RESTORE_DATA_WAIT_SEND}; bool isIncrementalBackup {false}; std::string oldBackupVersion {""}; + std::string callerName {}; + std::string activeTime {}; }; public: @@ -103,7 +105,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 +121,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 +129,7 @@ public: * @param bundleName 调用者名称 * @throw BError::Codes::SA_REFUSED_ACT 调用者不是会话所有者 */ - void VerifyBundleName(std::string &bundleName); + ErrCode VerifyBundleName(std::string &bundleName); /** * @brief 获取IServiceReverse @@ -159,6 +161,20 @@ public: */ void SetSessionUserId(int32_t userId); + /** + * @brief 获取当前处理事务会话对应的callerName + * + * @return string + */ + std::string GetSessionCallerName(); + + /** + * @brief 获取当前处理事务会话对应的激活时间 + * + * @return string + */ + std::string GetSessionActiveTime(); + /** * @brief 更新backupExtNameMap并判断是否完成分发 * @@ -301,14 +317,14 @@ public: * * @return ErrCode */ - void Start(); + ErrCode Start(); /** * @brief 结束追加应用 * * @return ErrCode */ - void Finish(); + ErrCode Finish(); /** * @brief 整个备份恢复流程是否结束 @@ -552,7 +568,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 5cc8e65cd91a0b70a2f2687628ec76e864e15e8f..53d994f05f3da64d6a1c7e587e42f7381608c508 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -90,7 +90,7 @@ const int32_t MAX_TRY_CLEAR_DISPOSE_NUM = 3; } // namespace /* Shell/Xts user id equal to 0/1, we need set default 100 */ -static inline int32_t GetUserIdDefault() +int32_t Service::GetUserIdDefault() { auto [isDebug, debugId] = BackupPara().GetBackupDebugOverrideAccount(); if (isDebug && debugId > DEBUG_ID) { @@ -104,7 +104,7 @@ static inline int32_t GetUserIdDefault() return multiuser.userId; } -void OnStartResRadarReport(const std::vector &bundleNameList, int32_t stage) +void Service::OnStartResRadarReport(const std::vector &bundleNameList, int32_t stage) { std::stringstream ss; ss << "failedBundles:{"; @@ -220,6 +220,8 @@ void Service::OnStart() .scenario = IServiceReverse::Scenario::CLEAN, .clientProxy = nullptr, .userId = GetUserIdDefault(), + .callerName = "BackupSA", + .activeTime = TimeUtils::GetCurrentTime(), }, isOccupyingSession_.load()); HILOGE("SA OnStart, cleaning up backup data"); @@ -268,7 +270,12 @@ 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); @@ -336,7 +343,7 @@ void Service::StopAll(const wptr &obj, bool force) session_->Deactive(obj, force); } -static inline void PermissionCheckFailRadar(const std::string &info, const std::string &func) +void Service::PermissionCheckFailRadar(const std::string &info, const std::string &func) { std::string funcPos = "Service::"; AppRadar::Info resInfo("", "", info); @@ -345,7 +352,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 +361,161 @@ 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(), + .callerName = GetCallerName(), + .activeTime = TimeUtils::GetCurrentTime(), + }); + 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); + HILOGE("InitBackupSession oldSize %{public}d", oldSize); + session_->SetMemParaCurSize(oldSize); + ret = session_->Active({ + .clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::BACKUP, + .clientProxy = remote, + .userId = GetUserIdDefault(), + .callerName = GetCallerName(), + .activeTime = TimeUtils::GetCurrentTime(), + }); + 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 +625,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 +678,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 +716,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 +766,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 +815,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 +835,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 +853,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 = @@ -880,7 +912,12 @@ ErrCode Service::ServiceResultReport(const std::string restoreRetInfo, 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 +934,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 +979,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 +1029,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 +1042,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 +1065,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 +1187,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 +1295,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 +1509,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 +1610,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 +1641,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 +1705,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 +1722,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,52 +1743,55 @@ 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."); - } - 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 = 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); - } - auto proxy = backupConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); - if (ret != NO_ERROR) { - result = false; - session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - return BError(BError::Codes::EXT_BROKEN_IPC); - } - result = true; + 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__); - } catch (...) { + return BError(BError::Codes::SA_INVAL_ARG, "Extension mutex ptr is null."); + } + std::lock_guard lock(mutexPtr->callbackMutex); + ErrCode errCode = VerifyCaller(); + if (errCode != ERR_OK) { + HILOGE("Update send rate fail, verify caller failed, errCode:%{public}d", errCode); result = false; session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); - HILOGE("Unexpected exception"); - return EPERM; + return errCode; + } + IServiceReverse::Scenario scenario = session_ -> GetScenario(); + if (scenario != IServiceReverse::Scenario::BACKUP) { + HILOGE("This method is applicable to the backup scenario"); + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::SA_INVAL_ARG); + } + 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 proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + HILOGE("Update send rate fail, extension proxy is empty"); + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::SA_INVAL_ARG); } + auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); + if (ret != NO_ERROR) { + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::EXT_BROKEN_IPC); + } + result = true; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); RemoveExtensionMutex(bundleName); return BError(BError::Codes::OK); } @@ -1945,13 +1888,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(...) { + HILOGE("Unexpected exception"); ReleaseOnException(); - HILOGE("Unexpected exception"); return EPERM; } } @@ -1989,7 +1928,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) { @@ -2056,28 +2000,32 @@ void Service::DoTimeout(wptr ptr, std::string bundleName) IServiceReverse::Scenario scenario = sessionPtr->GetScenario(); TimeoutRadarReport(scenario, bundleName); try { - std::shared_ptr mutexPtr = GetExtensionMutex(bundleName); - if (mutexPtr == nullptr) { - HILOGE("extension mutex ptr is nullptr"); + std::shared_ptr mutexPtr = GetExtensionMutex(bundleName); + if (mutexPtr == nullptr) { + HILOGE("extension mutex ptr is nullptr, bundleName:%{public}s", bundleName.c_str()); + return; + } + std::lock_guard lock(mutexPtr->callbackMutex); + if (SAUtils::IsSABundleName(bundleName)) { + auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName); + shared_ptr saConnection = sessionConnection.lock(); + if (saConnection == nullptr) { + HILOGE("Error, saConnection is empty, bundleName:%{public}s", bundleName.c_str()); return; } - std::lock_guard lock(mutexPtr->callbackMutex); - if (SAUtils::IsSABundleName(bundleName)) { - auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName); - shared_ptr saConnection = sessionConnection.lock(); - if (saConnection == nullptr) { - HILOGE("lock sa connection ptr is nullptr"); - return; - } - saConnection->DisconnectBackupSAExt(); - } else { - auto sessionConnection = sessionPtr->GetExtConnection(bundleName); - sessionConnection->DisconnectBackupExtAbility(); + saConnection->DisconnectBackupSAExt(); + } else { + auto sessionConnection = sessionPtr->GetExtConnection(bundleName); + if (sessionConnection == nullptr) { + HILOGE("Error, sessionConnection is empty, bundleName:%{public}s", bundleName.c_str()); + return; } - sessionPtr->StopFwkTimer(bundleName); - sessionPtr->StopExtTimer(bundleName); - thisPtr->ClearSessionAndSchedInfo(bundleName); - thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + sessionConnection->DisconnectBackupExtAbility(); + } + sessionPtr->StopFwkTimer(bundleName); + sessionPtr->StopExtTimer(bundleName); + thisPtr->ClearSessionAndSchedInfo(bundleName); + thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); } catch (...) { HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); thisPtr->ClearSessionAndSchedInfo(bundleName); @@ -2121,4 +2069,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 d3a9a67aeef8aaf63a49083542d913756c673654..a8687fb866902384839a8b9a464fde28c21a8f11 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -43,6 +43,7 @@ #include "b_radar/b_radar.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" +#include "b_utils/b_time.h" #include "filemgmt_libhilog.h" #include "hisysevent.h" #include "ipc_skeleton.h" @@ -58,26 +59,11 @@ using namespace std; const std::string FILE_BACKUP_EVENTS = "FILE_BACKUP_EVENTS"; namespace { -constexpr int32_t DEBUG_ID = 100; constexpr int32_t INDEX = 3; constexpr int32_t MS_1000 = 1000; const static string UNICAST_TYPE = "unicast"; } // namespace -static inline int32_t GetUserIdDefault() -{ - HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - auto [isDebug, debugId] = BackupPara().GetBackupDebugOverrideAccount(); - if (isDebug && debugId > DEBUG_ID) { - return debugId; - } - auto multiuser = BMultiuser::ParseUid(IPCSkeleton::GetCallingUid()); - if ((multiuser.userId == BConstants::SYSTEM_UID) || (multiuser.userId == BConstants::XTS_UID)) { - return BConstants::DEFAULT_USER_ID; - } - return multiuser.userId; -} - ErrCode Service::Release() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -150,7 +136,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 +168,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 +260,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)); }; @@ -308,26 +301,30 @@ 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, + .callerName = GetCallerName(), + .activeTime = TimeUtils::GetCurrentTime()}); + 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 +339,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 +364,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 +380,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 +410,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 +446,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) @@ -502,9 +514,6 @@ ErrCode Service::AppIncrementalFileReady(const std::string &bundleName, const st 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); auto proxy = backUpConnection->GetBackupExtProxy(); @@ -542,7 +551,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,13 +566,9 @@ 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); auto proxy = backUpConnection->GetBackupExtProxy(); @@ -583,9 +593,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,7 +607,12 @@ ErrCode Service::AppIncrementalDone(ErrCode errCode) HILOGE("AppIncrementalDone error, session is null"); return BError(BError::Codes::SA_INVAL_ARG); } - string callerName = VerifyCallerAndGetCallerName(); + string callerName = ""; + ErrCode ret = VerifyCallerAndGetCallerName(callerName); + if (ret != ERR_OK) { + HILOGE("App incremental done fail, ret:%{public}d", ret); + return ret; + } HILOGI("Service AppIncrementalDone start, callerName is %{public}s, errCode is: %{public}d", callerName.c_str(), errCode); if (session_->OnBundleFileReady(callerName) || errCode != BError(BError::Codes::OK)) { @@ -648,17 +660,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("Verify caller failed, 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); @@ -691,11 +708,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)); @@ -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/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index 89eda115dca683703e171c0cd09cf68b83c55959..ff3d5b2190be36c4c3c364b9b99eec3aafb481cf 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -52,6 +52,8 @@ void ServiceStub::ServiceStubSupplement() &ServiceStub::CmdStartFwkTimer; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_CANCEL_BUNDLE)] = &ServiceStub::CmdCancel; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_INIT_RESTORE_SESSION_MSG)] = + &ServiceStub::CmdInitRestoreSessionMsg; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_STOP_EXT_TIMER)] = &ServiceStub::CmdStopExtTimer; } @@ -156,6 +158,29 @@ int32_t ServiceStub::CmdInitRestoreSession(MessageParcel &data, MessageParcel &r return BError(BError::Codes::OK); } +int32_t ServiceStub::CmdInitRestoreSessionMsg(MessageParcel &data, MessageParcel &reply) +{ + auto remote = data.ReadRemoteObject(); + std::string errMsg; + if (!remote) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the stub"); + } + auto iremote = iface_cast(remote); + if (!iremote) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); + } + int32_t res = InitRestoreSession(iremote, errMsg); + if (!reply.WriteString(errMsg)) { + return BError(BError::Codes::SA_BROKEN_IPC, "Failed to send the errMsg"); + } + if (!reply.WriteInt32(res)) { + stringstream ss; + ss << "Failed to send the result " << res; + return BError(BError::Codes::SA_BROKEN_IPC, ss.str()); + } + return BError(BError::Codes::OK); +} + int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &reply) { auto remote = data.ReadRemoteObject(); diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index c6dc5dd4ee11a13f1c84b245e8947adbab3e3db4..6162f0dfcd9449c8caa188f6295e09f860be6569 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -45,6 +45,7 @@ #include "b_radar/b_radar.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" +#include "b_utils/b_time.h" #include "bundle_mgr_client.h" #include "filemgmt_libhilog.h" #include "hisysevent.h" @@ -78,8 +79,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 +103,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 +142,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 +184,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 +198,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); @@ -208,7 +219,8 @@ ErrCode Service::AppDone(ErrCode errCode) } auto proxy = backUpConnection->GetBackupExtProxy(); if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + HILOGE("Extension backup Proxy is empty"); + return BError(BError::Codes::SA_INVAL_ARG); } proxy->HandleClear(); session_->StopFwkTimer(callerName); @@ -224,12 +236,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 +246,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 +361,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 +406,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 +445,198 @@ 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."); +} + +std::string Service::GetCallerName() +{ + std::string callerName; + uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); + int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); + switch (tokenType) { + case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: { /* Update Service */ + Security::AccessToken::NativeTokenInfo nativeTokenInfo; + if (Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenCaller, nativeTokenInfo) != 0) { + HILOGE("Failed to get native token info"); + break; + } + callerName = nativeTokenInfo.processName; + return callerName; + } + case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: { + Security::AccessToken::HapTokenInfo hapTokenInfo; + if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) { + HILOGE("Failed to get hap token info"); + break; + } + callerName = hapTokenInfo.bundleName; + return callerName; + } + } + HILOGE("Invalid token type, %{public}s", to_string(tokenType).c_str()); + return callerName; +} + +ErrCode Service::InitRestoreSession(sptr remote, std::string &errMsg) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + try { + VerifyCaller(); + if (session_ == nullptr) { + errMsg = "session is empty"; + HILOGE("Init RestoreSession session error, %{public}s", errMsg.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + ErrCode errCode = session_->Active({ + .clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::RESTORE, + .clientProxy = remote, + .userId = GetUserIdDefault(), + .callerName = GetCallerName(), + .activeTime = TimeUtils::GetCurrentTime(), + }); + if (errCode == 0) { + ClearFailedBundles(); + successBundlesNum_ = 0; + ClearBundleRadarReport(); + ClearFileReadyRadarReport(); + } + if (errCode == BError(BError::Codes::SA_SESSION_CONFLICT)) { + errMsg = BJsonUtil::BuildInitSessionErrInfo(session_->GetSessionUserId(), + session_->GetSessionCallerName(), + session_->GetSessionActiveTime()); + } + return errCode; + } catch (const BError &e) { + StopAll(nullptr, true); + errMsg = e.what(); + return e.GetCode(); + } catch (const exception &e) { + errMsg = e.what(); + HILOGE("Catched an unexpected low-level exception %{public}s", errMsg.c_str()); + return EPERM; + } catch (...) { + errMsg = "Unexpected exception"; + HILOGE("%{public}s", errMsg.c_str()); + return EPERM; + } +} } \ 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 9fec17ab3df04c827c7748c08944d34e90277c0d..b67d0fb00fe29af78cae89cd4472a44d196446ed 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() @@ -76,36 +79,44 @@ ErrCode SvcSessionManager::Active(Impl newImpl, bool isOccupyingSession) const Impl &oldImpl = impl_; if (oldImpl.clientToken) { HILOGE("Already have an active session"); - return BError(BError::Codes::SA_REFUSED_ACT); + return BError(BError::Codes::SA_SESSION_CONFLICT); } 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; } @@ -166,6 +180,24 @@ void SvcSessionManager::SetSessionUserId(int32_t userId) impl_.userId = userId; } +string SvcSessionManager::GetSessionCallerName() +{ + shared_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + return impl_.callerName; +} + +string SvcSessionManager::GetSessionActiveTime() +{ + shared_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + return impl_.activeTime; +} + bool SvcSessionManager::OnBundleFileReady(const string &bundleName, const string &fileName) { unique_lock lock(lock_); @@ -357,14 +389,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 +423,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 +591,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/backup_kit_inner/service_proxy_mock.cpp b/tests/mock/backup_kit_inner/service_proxy_mock.cpp index 4ed01cd8f5dd919b6cf0f14fb7fa44ae95d3258c..15c53566cd9059a292e8543ea1327466139669ba 100644 --- a/tests/mock/backup_kit_inner/service_proxy_mock.cpp +++ b/tests/mock/backup_kit_inner/service_proxy_mock.cpp @@ -39,6 +39,14 @@ int32_t ServiceProxy::InitRestoreSession(sptr remote) return 0; } +int32_t ServiceProxy::InitRestoreSession(sptr remote, std::string &errMsg) +{ + if (!GetMockInitBackupOrRestoreSession()) { + return 1; + } + return 0; +} + int32_t ServiceProxy::InitBackupSession(sptr remote) { if (!GetMockInitBackupOrRestoreSession()) { diff --git a/tests/mock/module_ipc/include/svc_session_manager_mock.h b/tests/mock/module_ipc/include/svc_session_manager_mock.h index e8f74bb042c05c7418605739e68aa244abc043bc..fcfb87865130aefb9f55bc6e703c447c240a3a86 100644 --- a/tests/mock/module_ipc/include/svc_session_manager_mock.h +++ b/tests/mock/module_ipc/include/svc_session_manager_mock.h @@ -27,6 +27,8 @@ public: virtual sptr GetServiceReverseProxy() = 0; virtual IServiceReverse::Scenario GetScenario() = 0; virtual int32_t GetSessionUserId() = 0; + virtual std::string GetSessionCallerName() = 0; + virtual std::string GetSessionActiveTime() = 0; virtual bool OnBundleFileReady(const std::string&, const std::string&) = 0; virtual UniqueFd OnBundleExtManageInfo(const std::string&, UniqueFd) = 0; virtual wptr GetExtConnection(const BundleName&) = 0; @@ -72,6 +74,8 @@ public: MOCK_METHOD((sptr), GetServiceReverseProxy, ()); MOCK_METHOD(IServiceReverse::Scenario, GetScenario, ()); MOCK_METHOD(int32_t, GetSessionUserId, ()); + MOCK_METHOD(std::string, GetSessionCallerName, ()); + MOCK_METHOD(std::string, GetSessionActiveTime, ()); MOCK_METHOD(bool, OnBundleFileReady, (const std::string&, const std::string&)); MOCK_METHOD(UniqueFd, OnBundleExtManageInfo, (const std::string&, UniqueFd)); MOCK_METHOD((wptr), GetExtConnection, (const BundleName&)); diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index 786a66bcce577947ff6adb8bd9a04859b914bde7..1cda2b558ca3b7b99f24f47da2a89380d56c6522 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -26,6 +26,11 @@ namespace OHOS::FileManagement::Backup { using namespace std; +int32_t Service::GetUserIdDefault() +{ + return 0; +} + void Service::OnStart() {} void Service::OnStop() {} @@ -37,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) @@ -47,6 +52,11 @@ ErrCode Service::InitRestoreSession(sptr remote) return BError(BError::Codes::OK); } +ErrCode Service::InitRestoreSession(sptr remote, std::string &errMsg) +{ + return BError(BError::Codes::OK); +} + ErrCode Service::InitBackupSession(sptr remote) { return BError(BError::Codes::OK); @@ -143,9 +153,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) {} @@ -297,6 +313,15 @@ void Service::FileReadyRadarReport(const std::string &bundleName, const std::str void Service::ExtensionConnectFailRadarReport(const std::string &bundleName, const ErrCode errCode, const IServiceReverse::Scenario scenario) {} +void Service::PermissionCheckFailRadar(const std::string &info, const std::string &func) {} + +void Service::OnStartResRadarReport(const std::vector &bundleNameList, int32_t stage) {} + +std::string Service::GetCallerName() +{ + return ""; +} + void Service::UpdateFailedBundles(const std::string &bundleName, BundleTaskInfo taskInfo) {} void Service::ClearFailedBundles() {} diff --git a/tests/mock/module_ipc/service_stub_mock.cpp b/tests/mock/module_ipc/service_stub_mock.cpp index 97452a3ebb3fea07c203afafc04f213fee20cfa8..c429636896b4da04ce848de39524935298f82b68 100644 --- a/tests/mock/module_ipc/service_stub_mock.cpp +++ b/tests/mock/module_ipc/service_stub_mock.cpp @@ -85,6 +85,8 @@ void ServiceStub::ServiceStubSupplement() &ServiceStub::CmdUpdateSendRate; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_REPORT_APP_PROCESS_INFO)] = &ServiceStub::CmdReportAppProcessInfo; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_INIT_RESTORE_SESSION_MSG)] = + &ServiceStub::CmdInitRestoreSessionMsg; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_CANCEL_BUNDLE)] = &ServiceStub::CmdCancel; } @@ -114,6 +116,17 @@ int32_t ServiceStub::CmdInitRestoreSession(MessageParcel &data, MessageParcel &r return BError(BError::Codes::OK); } +int32_t ServiceStub::CmdInitRestoreSessionMsg(MessageParcel &data, MessageParcel &reply) +{ + auto remote = data.ReadRemoteObject(); + auto iremote = iface_cast(remote); + std::string errMsg; + int32_t res = InitRestoreSession(iremote, errMsg); + reply.WriteString(errMsg); + reply.WriteInt32(res); + return BError(BError::Codes::OK); +} + int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &reply) { auto remote = data.ReadRemoteObject(); 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 b4aa9f283e7133900b57bb5881dcd69dc52b4730..f1d11bd69931e022dbbdbb020273cc197288b049 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() { @@ -143,6 +162,17 @@ int32_t SvcSessionManager::GetSessionUserId() void SvcSessionManager::SetSessionUserId(int32_t) {} +std::string SvcSessionManager::GetSessionCallerName() +{ + return BSvcSessionManager::sessionManager->GetSessionCallerName(); +} + +std::string SvcSessionManager::GetSessionActiveTime() +{ + return BSvcSessionManager::sessionManager->GetSessionActiveTime(); +} + + void SvcSessionManager::SetBundleRestoreType(const std::string &, RestoreTypeEnum) {} RestoreTypeEnum SvcSessionManager::GetBundleRestoreType(const std::string &bundleName) diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 1e9e265b8fb0cff65b5470aa8279313d9d5b6570..5f32e8386425155246ba1c96d9874c951affe7e4 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() { @@ -291,6 +301,16 @@ void SvcSessionManager::SetSessionUserId(int32_t userId) impl_.userId = userId; } +string SvcSessionManager::GetSessionCallerName() +{ + return impl_.callerName; +} + +string SvcSessionManager::GetSessionActiveTime() +{ + return impl_.activeTime; +} + void SvcSessionManager::SetBundleRestoreType(const std::string &bundleName, RestoreTypeEnum restoreType) { auto it = impl_.backupExtNameMap.find(bundleName); 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 c76234055b29952aa9042d0682b8dcf6f683ae45..a01fb56f248995cb3fd546c7d25ef067e8eef6c4 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() @@ -184,6 +184,16 @@ void SvcSessionManager::SetSessionUserId(int32_t userId) BackupSvcSessionManager::session->SetSessionUserId(userId); } +string SvcSessionManager::GetSessionCallerName() +{ + return BackupSvcSessionManager::session->GetSessionCallerName(); +} + +string SvcSessionManager::GetSessionActiveTime() +{ + return BackupSvcSessionManager::session->GetSessionActiveTime(); +} + void SvcSessionManager::SetBundleRestoreType(const std::string &bundleName, RestoreTypeEnum restoreType) { BackupSvcSessionManager::session->SetBundleRestoreType(bundleName, restoreType); 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 60113e1d789c02e9ce5b655fea4b9a2c365195e4..6947080c7046ebb52dbe5525ef975b0335d52904 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,13 +53,15 @@ 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; virtual int32_t GetSessionUserId() = 0; virtual void SetSessionUserId(int32_t) = 0; + virtual std::string GetSessionCallerName() = 0; + virtual std::string GetSessionActiveTime() = 0; virtual void SetBundleRestoreType(const std::string &, RestoreTypeEnum) = 0; virtual RestoreTypeEnum GetBundleRestoreType(const std::string &) = 0; virtual void SetBundleVersionCode(const std::string &, int64_t) = 0; @@ -98,10 +100,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 +112,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,13 +126,15 @@ 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, ()); MOCK_METHOD(int32_t, GetSessionUserId, ()); MOCK_METHOD(void, SetSessionUserId, (int32_t)); + MOCK_METHOD(std::string, GetSessionCallerName, ()); + MOCK_METHOD(std::string, GetSessionActiveTime, ()); MOCK_METHOD(void, SetBundleRestoreType, (const std::string &, RestoreTypeEnum)); MOCK_METHOD(RestoreTypeEnum, GetBundleRestoreType, (const std::string &)); MOCK_METHOD(void, SetBundleVersionCode, (const std::string &, int64_t)); diff --git a/tests/mock/utils_mock/include/b_jsonutil_mock.h b/tests/mock/utils_mock/include/b_jsonutil_mock.h index 01cfaff0023c242918b69d5c6d543442caf5daf4..e0e0ad7c231b7a56a57386988ed95e68b6146e4c 100644 --- a/tests/mock/utils_mock/include/b_jsonutil_mock.h +++ b/tests/mock/utils_mock/include/b_jsonutil_mock.h @@ -38,6 +38,7 @@ public: virtual bool BuildOnProcessErrInfo(std::string&, std::string, int) = 0; virtual bool BuildBundleInfoJson(int32_t, std::string&) = 0; virtual bool HasUnicastInfo(std::string&) = 0; + virtual std::string BuildInitSessionErrInfo(int32_t, std::string, std::string) = 0; public: BBJsonUtil() = default; virtual ~BBJsonUtil() = default; @@ -62,6 +63,7 @@ public: MOCK_METHOD(bool, BuildOnProcessErrInfo, (std::string&, std::string, int)); MOCK_METHOD(bool, BuildBundleInfoJson, (int32_t, std::string&)); MOCK_METHOD(bool, HasUnicastInfo, (std::string&)); + MOCK_METHOD(std::string, BuildInitSessionErrInfo, (int32_t, std::string, std::string)); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_B_JSONUTIL_MOCK_MOCK_H diff --git a/tests/mock/utils_mock/src/b_jsonutil_mock.cpp b/tests/mock/utils_mock/src/b_jsonutil_mock.cpp index 8d802d4186c04b7c4b62d8a26745208ce491ebb1..eea1cfee0298163e3fc50b55bb9af39f5423472f 100644 --- a/tests/mock/utils_mock/src/b_jsonutil_mock.cpp +++ b/tests/mock/utils_mock/src/b_jsonutil_mock.cpp @@ -72,4 +72,9 @@ bool BJsonUtil::BuildBundleInfoJson(int32_t userId, string &detailInfo) { return BBJsonUtil::jsonUtil->BuildBundleInfoJson(userId, detailInfo); } + +std::string BJsonUtil::BuildInitSessionErrInfo(int32_t userId, string callerName, string activeTime) +{ + return BBJsonUtil::jsonUtil->BuildInitSessionErrInfo(userId, callerName, activeTime); +} } \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h index d0600cbc6ce010d7712e3fefc463926d96a16d62..f923e04ae3e227fb93894f8a2f4c73f1fd7ad750 100644 --- a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h @@ -43,6 +43,14 @@ public: return BError(BError::Codes::OK); } + int32_t InvokeMsgSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) + { + code_ = code; + reply.WriteString(""); + reply.WriteInt32(BError(BError::Codes::OK)); + return BError(BError::Codes::OK); + } + int32_t InvokeGetLocalSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { code_ = code; @@ -59,6 +67,11 @@ public: return BError(BError::Codes::OK); } + ErrCode InitRestoreSession(sptr remote, std::string &errMsg) override + { + return BError(BError::Codes::OK); + } + ErrCode InitBackupSession(sptr remote) override { return BError(BError::Codes::OK); diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 400061e878d30fcca9d20b220e3284d917623390..bea5dbf9efd379a47130f188acb42b2f3b8d93d2 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -165,8 +165,11 @@ ohos_unittest("backup_service_throw_test") { sources = [ "${path_backup_mock}/accesstoken/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 b19ccd042ea254722e57707ac7ac8ebd17100f1a..8249c696c5957d672d13dd2fed3ec8bb66e9fa75 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) @@ -52,6 +52,11 @@ ErrCode Service::InitRestoreSession(sptr remote) return BError(BError::Codes::OK); } +ErrCode Service::InitRestoreSession(sptr remote, std::string &errMsg) +{ + return BError(BError::Codes::OK); +} + ErrCode Service::InitBackupSession(sptr remote) { return BError(BError::Codes::OK); @@ -148,9 +153,20 @@ 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); +} + +int32_t Service::GetUserIdDefault() +{ + return 0; +} void Service::OnAllBundlesFinished(ErrCode errCode) {} @@ -258,6 +274,15 @@ void Service::FileReadyRadarReport(const std::string &bundleName, const std::str void Service::ExtensionConnectFailRadarReport(const std::string &bundleName, const ErrCode errCode, const IServiceReverse::Scenario scenario) {} +void Service::PermissionCheckFailRadar(const std::string &info, const std::string &func) {} + +void Service::OnStartResRadarReport(const std::vector &bundleNameList, int32_t stage) {} + +std::string Service::GetCallerName() +{ + return ""; +} + void Service::UpdateFailedBundles(const std::string &bundleName, BundleTaskInfo taskInfo) {} void Service::ClearFailedBundles() {} @@ -341,51 +366,6 @@ void ServiceIncrementalTest::TearDownTestCase() srProxy = nullptr; } -/** - * @tc.number: SUB_ServiceIncremental_GetUserIdDefault_0000 - * @tc.name: SUB_ServiceIncremental_GetUserIdDefault_0000 - * @tc.desc: 测试 GetUserIdDefault 的正常/异常分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: issueIAKC3I - */ -HWTEST_F(ServiceIncrementalTest, SUB_ServiceIncremental_GetUserIdDefault_0000, TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceIncrementalTest-begin SUB_ServiceIncremental_GetUserIdDefault_0000"; - try { - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) - .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - auto ret = GetUserIdDefault(); - EXPECT_EQ(ret, DEBUG_ID + 1); - - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(false, 0))); - EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); - ret = GetUserIdDefault(); - EXPECT_EQ(ret, BConstants::DEFAULT_USER_ID); - - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(true, 0))); - EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); - ret = GetUserIdDefault(); - EXPECT_EQ(ret, BConstants::DEFAULT_USER_ID); - - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(false, 0))); - EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::XTS_UID)); - ret = GetUserIdDefault(); - EXPECT_EQ(ret, BConstants::DEFAULT_USER_ID); - - EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(false, 0))); - EXPECT_CALL(*skeleton, GetCallingUid()) - .WillOnce(Return(BConstants::SPAN_USERID_UID + BConstants::SPAN_USERID_UID)); - ret = GetUserIdDefault(); - EXPECT_EQ(ret, 2); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceIncrementalTest-an exception occurred by GetUserIdDefault."; - } - GTEST_LOG_(INFO) << "ServiceIncrementalTest-end SUB_ServiceIncremental_GetUserIdDefault_0000"; -} - /** * @tc.number: SUB_ServiceIncremental_GetLocalCapabilitiesIncremental_0000 * @tc.name: SUB_ServiceIncremental_GetLocalCapabilitiesIncremental_0000 @@ -833,6 +813,7 @@ HWTEST_F(ServiceIncrementalTest, SUB_ServiceIncremental_GetIncrementalFileHandle { GTEST_LOG_(INFO) << "ServiceIncrementalTest-begin SUB_ServiceIncremental_GetIncrementalFileHandle_0000"; try { + int32_t DEBUG_ID = 100; string bundleName; string fileName; auto session_ = service->session_; 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 7d4dbb776279b0362580a2fbbb11918f6a42a5ed..45f2f76deb9195d084f045d810d8224bc60bda37 100644 --- a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp @@ -258,28 +258,28 @@ HWTEST_F(ServiceTest, SUB_Service_GetUserIdDefault_0000, TestSize.Level1) try { EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); - auto ret = GetUserIdDefault(); + auto ret = service->GetUserIdDefault(); EXPECT_EQ(ret, DEBUG_ID + 1); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(false, 0))); EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); - ret = GetUserIdDefault(); + ret = service->GetUserIdDefault(); EXPECT_EQ(ret, BConstants::DEFAULT_USER_ID); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(true, 0))); EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); - ret = GetUserIdDefault(); + ret = service->GetUserIdDefault(); EXPECT_EQ(ret, BConstants::DEFAULT_USER_ID); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(false, 0))); EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::XTS_UID)); - ret = GetUserIdDefault(); + ret = service->GetUserIdDefault(); EXPECT_EQ(ret, BConstants::DEFAULT_USER_ID); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()).WillOnce(Return(make_pair(false, 0))); EXPECT_CALL(*skeleton, GetCallingUid()) .WillOnce(Return(BConstants::SPAN_USERID_UID + BConstants::SPAN_USERID_UID)); - ret = GetUserIdDefault(); + ret = service->GetUserIdDefault(); EXPECT_EQ(ret, 2); } catch (...) { EXPECT_TRUE(false); @@ -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")) @@ -1541,7 +1547,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_stub_test.cpp b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp index 3d2029c7a150018ffe3105978a8a1fc7242e6d58..353ed10841ef71a3cccb8d0e21f1da7bf2543da5 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -44,6 +44,7 @@ const string FILE_NAME = "1.tar"; class ServiceMock final : public ServiceStub { public: MOCK_METHOD1(InitRestoreSession, ErrCode(sptr remote)); + MOCK_METHOD2(InitRestoreSession, ErrCode(sptr remote, std::string &errMsg)); MOCK_METHOD1(InitBackupSession, ErrCode(sptr remote)); MOCK_METHOD0(Start, ErrCode()); MOCK_METHOD0(GetLocalCapabilities, UniqueFd()); diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index ff2176f75f40ab5065ad42a9ce2cb07d711a236e..1ca6f3daad5da097cd2c2cb8ef50d0134e5bdf07 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -80,6 +80,7 @@ ErrCode ServiceTest::Init(IServiceReverse::Scenario scenario) "}]"; bundleNames.emplace_back(BUNDLE_NAME); detailInfos.emplace_back(json); + string errMsg; ErrCode ret = 0; if (scenario == IServiceReverse::Scenario::RESTORE) { EXPECT_TRUE(servicePtr_ != nullptr); @@ -88,6 +89,8 @@ ErrCode ServiceTest::Init(IServiceReverse::Scenario scenario) EXPECT_GE(fd, BError(BError::Codes::OK)); ret = servicePtr_->InitRestoreSession(remote_); EXPECT_EQ(ret, BError(BError::Codes::OK)); + ret = servicePtr_->InitRestoreSession(remote_, errMsg); + EXPECT_EQ(ret, BError(BError::Codes::OK)); ret = servicePtr_->AppendBundlesRestoreSession(move(fd), bundleNames, detailInfos); EXPECT_EQ(ret, BError(BError::Codes::OK)); ret = servicePtr_->Finish(); 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 cb112e0770b2edc3bef7e75634241648bb9ccf69..5b4bccda3d9196ae9c0c8e4e554a2dac043295ee 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,27 @@ 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(*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(*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)); + 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 +402,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 +443,10 @@ 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(*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 +469,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 +495,15 @@ 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(*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(*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 +526,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 +642,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 +894,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 +1012,15 @@ 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(*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(*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 +1043,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 +1084,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 +1134,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 ce2c88e40223ff5484f89a794b28518a095c33a7..c995e219cc830ca2803b8892e4c82f177899b7f0 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 9370532d014da1db08e695406c8c62693008cbab..48a930e5415c529ccb1091813efa009fa606b85e 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_SESSION_CONFLICT).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."; @@ -1590,17 +1547,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 +1575,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); diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.cpp b/tests/unittests/backup_sa/session/service_proxy_mock.cpp index d41b0a5b8496a10d2e93ddc5d09551fd839b72f0..d75c3196a8cf6ab5c58835646f0b8f8669515a36 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.cpp +++ b/tests/unittests/backup_sa/session/service_proxy_mock.cpp @@ -25,6 +25,11 @@ int32_t ServiceProxy::InitRestoreSession(sptr remote) return 0; } +int32_t ServiceProxy::InitRestoreSession(sptr remote, std::string &errMsg) +{ + return 0; +} + int32_t ServiceProxy::InitBackupSession(sptr remote) { return 0; diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.h b/tests/unittests/backup_sa/session/service_proxy_mock.h index 18df7af1a3d956b08ce7d511d1e37cedcd2afab4..bf0537b8f09d9e2029ccb19abd4d99b247a25f99 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.h +++ b/tests/unittests/backup_sa/session/service_proxy_mock.h @@ -27,6 +27,7 @@ public: ~ServiceProxyMock() override {} public: MOCK_METHOD1(InitRestoreSession, ErrCode(sptr remote)); + MOCK_METHOD2(InitRestoreSession, ErrCode(sptr remote, std::string &errMsg)); MOCK_METHOD1(InitBackupSession, ErrCode(sptr remote)); MOCK_METHOD0(Start, ErrCode()); MOCK_METHOD0(AsObject, sptr()); diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h index 9e685afd823177c468c9096393aa6847aac1e64d..9073fcc0d24aa2687bc5cd4ae2fe6f5208357ef4 100644 --- a/utils/include/b_error/b_error.h +++ b/utils/include/b_error/b_error.h @@ -73,6 +73,7 @@ public: SA_BOOT_EXT_TIMEOUT = 0x3005, SA_BUNDLE_INFO_EMPTY = 0x3006, SA_BOOT_EXT_FAIL = 0x3007, + SA_SESSION_CONFLICT = 0x3008, // 0x4000~0x4999 backup_SDK错误 SDK_INVAL_ARG = 0x4000, @@ -120,6 +121,7 @@ public: E_TASKFAIL = 13500010, E_CANCEL_UNSTARTED_TASK = 13500011, E_CANCEL_NO_TASK = 13500012, + E_CONFLICT = 13500013, }; public: @@ -268,6 +270,7 @@ private: {Codes::SA_EXT_ERR_CALL, "SA Extension received invalid arguments"}, {Codes::SA_EXT_ERR_SAMGR, "SA Extension get samgr failed"}, {Codes::SA_EXT_RELOAD_FAIL, "SA Extension reload failed"}, + {Codes::SA_SESSION_CONFLICT, "Session Conflict"}, }; static inline const std::map errCodeTable_ { @@ -303,6 +306,7 @@ private: {static_cast(Codes::SA_EXT_ERR_CALL), BackupErrorCode::E_INVAL}, {static_cast(Codes::SA_EXT_ERR_SAMGR), BackupErrorCode::E_IPCSS}, {static_cast(Codes::SA_EXT_RELOAD_FAIL), BackupErrorCode::E_BEF}, + {static_cast(Codes::SA_SESSION_CONFLICT), BackupErrorCode::E_CONFLICT}, {BackupErrorCode::E_IPCSS, BackupErrorCode::E_IPCSS}, {BackupErrorCode::E_INVAL, BackupErrorCode::E_INVAL}, {BackupErrorCode::E_NOTEXIST, BackupErrorCode::E_NOTEXIST}, @@ -322,6 +326,7 @@ private: {BackupErrorCode::E_BEF, BackupErrorCode::E_BEF}, {BackupErrorCode::E_CANCEL_UNSTARTED_TASK, BackupErrorCode::E_CANCEL_UNSTARTED_TASK}, {BackupErrorCode::E_CANCEL_NO_TASK, BackupErrorCode::E_CANCEL_NO_TASK}, + {BackupErrorCode::E_CONFLICT, BackupErrorCode::E_CONFLICT}, }; static inline const std::map sysErrnoCodeTable_ { @@ -359,6 +364,7 @@ private: {BackupErrorCode::E_BEF, "SA failed to boot application extension"}, {BackupErrorCode::E_CANCEL_UNSTARTED_TASK, "Cancel unstarted backup or restore task "}, {BackupErrorCode::E_CANCEL_NO_TASK, "Cancel a backup or restore task that does not exist"}, + {BackupErrorCode::E_CONFLICT, "Session Conflict"}, }; private: diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index ebaadfbeec6011bd03ebfbbaea3176df3a30e1a1..22bf8050605d1764497db7490eca15ce5b4b3081 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -168,6 +168,17 @@ public: * */ static std::string ParseBackupVersion(); + + /** + * @brief 拼接session冲突时报错信息 + * + * @param userId 用户id + * @param callerName session创建方 + * @param activeTime session创建时间 + * + * @return 拼接结果 + */ + static std::string BuildInitSessionErrInfo(int32_t userId, std::string callerName, std::string activeTime); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index 5892f745729ced2d07cae76c21f767f19cb51e07..960f88764582ce83a6427c78ede77be6318ee96c 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -460,4 +460,40 @@ std::string BJsonUtil::ParseBackupVersion() cJSON_Delete(root); return backupVersion; } + +std::string BJsonUtil::BuildInitSessionErrInfo(int32_t userId, std::string callerName, std::string activeTime) +{ + cJSON *info = cJSON_CreateObject(); + if (info == nullptr) { + HILOGE("Failed to create cJSON object info, update errMsg failed"); + return ""; + } + cJSON *sessionInfoArray = cJSON_CreateArray(); + if (sessionInfoArray == nullptr) { + HILOGE("Failed to create cJSON array sessionInfoArray, update errMsg failed"); + cJSON_Delete(info); + return ""; + } + cJSON_AddItemToObject(info, "sessionInfo", sessionInfoArray); + cJSON *sessionInfoObject = cJSON_CreateObject(); + if (sessionInfoObject == nullptr) { + HILOGE("Failed to create cJSON object sessionInfoObject, update errMsg failed"); + cJSON_Delete(info); + return ""; + } + cJSON_AddItemToArray(sessionInfoArray, sessionInfoObject); + cJSON_AddStringToObject(sessionInfoObject, "userId", to_string(userId).c_str()); + cJSON_AddStringToObject(sessionInfoObject, "name", callerName.c_str()); + cJSON_AddStringToObject(sessionInfoObject, "activeTime", activeTime.c_str()); + char *jsonStr = cJSON_Print(info); + if (jsonStr == nullptr) { + HILOGE("update errMsg failed"); + cJSON_Delete(info); + return ""; + } + std::string errMsg = jsonStr; + cJSON_Delete(info); + cJSON_free(jsonStr); + return errMsg; +} } \ No newline at end of file