diff --git a/bundle.json b/bundle.json index b65b71f1710094dccf03d04b62e003dc54670fcd..4e70f8c9affd3f8b56efaad1062f70336c43a5d8 100644 --- a/bundle.json +++ b/bundle.json @@ -42,7 +42,8 @@ ], "third_party": [ "bounds_checking_function", - "jsoncpp" + "jsoncpp", + "openssl" ] }, "adapted_system_type": [ "small", "standard" ], @@ -109,6 +110,9 @@ "header_base": "//foundation/filemanagement/app_file_service/interfaces/inner_api/native/backup_kit_inner", "header_files": [ "backup_kit_inner.h", + "impl/b_incremental_backup_session.h", + "impl/b_incremental_data.h", + "impl/b_incremental_restore_session.h", "impl/b_session_restore.h", "impl/b_session_restore_async.h", "impl/b_file_info.h", diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index 5b2434fe8d3672b80f1ca24fdafc8b0227e729d1..eab04ed2a0929d1c9e551634b573111e007e7507 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -19,12 +19,17 @@ #include #include #include +#include + +#include #include "b_json/b_json_entity_extension_config.h" +#include "b_json/b_report_entity.h" #include "b_resources/b_constants.h" #include "ext_backup_js.h" #include "ext_extension_stub.h" #include "thread_pool.h" +#include "unique_fd.h" namespace OHOS::FileManagement::Backup { class BackupExtExtension : public ExtExtensionStub { @@ -34,8 +39,13 @@ public: ErrCode PublishFile(const std::string &fileName) override; ErrCode HandleBackup() override; ErrCode HandleRestore() override; + ErrCode GetIncrementalFileHandle(const std::string &fileName) override; + ErrCode PublishIncrementalFile(const std::string &fileName) override; + ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; + std::tuple GetIncrementalBackupFileHandle() override; void AsyncTaskRestoreForUpgrade(void); + void AsyncTaskIncrementalRestoreForUpgrade(void); void ExtClear(void); public: @@ -69,6 +79,13 @@ private: */ int DoRestore(const string &fileName); + /** + * @brief incremental restore + * + * @param fileName name of the file that to be untar + */ + int DoIncrementalRestore(const string &fileName); + /** @brief clear backup restore data */ void DoClear(); @@ -94,8 +111,30 @@ private: */ void AsyncTaskRestore(); + /** + * @brief Executing Incremental Restoration Tasks Asynchronously + * + */ + void AsyncTaskIncrementalRestore(); + void AsyncTaskOnBackup(); + int DoIncrementalBackup(const std::map &allFiles, + const std::map &smallFiles, + const std::map &bigFiles, + const std::map &bigInfos); + + void AsyncTaskOnIncrementalBackup(const std::map &allFiles, + const std::map &smallFiles, + const std::map &bigFiles, + const std::map &bigInfos); + + /** + * @brief extension incremental backup restore is done + * + * @param errCode + */ + void AppIncrementalDone(ErrCode errCode); private: std::shared_mutex lock_; std::shared_ptr extension_; diff --git a/frameworks/native/backup_ext/include/ext_extension_stub.h b/frameworks/native/backup_ext/include/ext_extension_stub.h index 806bf85953c11777492c26ed5c51163ff30bd70f..97dabc07c6854d3ea5636703753181ba55ee8c86 100644 --- a/frameworks/native/backup_ext/include/ext_extension_stub.h +++ b/frameworks/native/backup_ext/include/ext_extension_stub.h @@ -36,6 +36,10 @@ private: ErrCode CmdHandleBackup(MessageParcel &data, MessageParcel &reply); ErrCode CmdPublishFile(MessageParcel &data, MessageParcel &reply); ErrCode CmdHandleRestore(MessageParcel &data, MessageParcel &reply); + ErrCode CmdGetIncrementalFileHandle(MessageParcel &data, MessageParcel &reply); + ErrCode CmdPublishIncrementalFile(MessageParcel &data, MessageParcel &reply); + ErrCode CmdHandleIncrementalBackup(MessageParcel &data, MessageParcel &reply); + ErrCode CmdGetIncrementalBackupFileHandle(MessageParcel &data, MessageParcel &reply); private: using ExtensionInterface = int32_t (ExtExtensionStub::*)(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/native/backup_ext/include/untar_file.h b/frameworks/native/backup_ext/include/untar_file.h index 1f92f88a2094670638d140ef5f511b49788ff36e..fe0b12714502216df0e16aba5145f873c2b4eb63 100644 --- a/frameworks/native/backup_ext/include/untar_file.h +++ b/frameworks/native/backup_ext/include/untar_file.h @@ -32,6 +32,8 @@ public: typedef enum { ERR_FORMAT = -1 } ErrorCode; static UntarFile &GetInstance(); int UnPacket(const std::string &tarFile, const std::string &rootPath); + int IncrementalUnPacket(const std::string &tarFile, const std::string &rootPath, + const std::unordered_map &includes); private: UntarFile() = default; @@ -46,6 +48,13 @@ private: */ int ParseTarFile(const std::string &rootPath); + /** + * @brief parse incremental tar file + * + * @param rootpath 解包的目标路径 + */ + int ParseIncrementalTarFile(const std::string &rootPath); + /** * @brief verfy check sum * @@ -112,6 +121,15 @@ private: */ void ParseFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &info); + /** + * @brief parse incremental file by typeFlag + * + * @param typeFlag 文件类型标志 + * @param isSkip 是否跳过当前文件 + * @param info 文件属性结构体 + */ + void ParseIncrementalFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &info); + /** * @brief Handle file ownership groups * @@ -128,6 +146,7 @@ private: off_t tarFileBlockCnt_ {0}; off_t pos_ {0}; size_t readCnt_ {0}; + std::unordered_map includes_; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 2697e0413c6f57f5ea85a3a020d2adcf091c1d58..02a19a279925501fac9c4dcb8fca5863752d6c43 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -16,9 +16,13 @@ #include "ext_extension.h" #include +#include +#include #include +#include #include #include +#include #include #include @@ -36,8 +40,10 @@ #include "b_error/b_excep_utils.h" #include "b_filesystem/b_dir.h" #include "b_filesystem/b_file.h" +#include "b_filesystem/b_file_hash.h" #include "b_json/b_json_cached_entity.h" #include "b_json/b_json_entity_ext_manage.h" +#include "b_json/b_report_entity.h" #include "b_resources/b_constants.h" #include "b_tarball/b_tarball_factory.h" #include "filemgmt_libhilog.h" @@ -53,8 +59,16 @@ const string INDEX_FILE_BACKUP = string(BConstants::PATH_BUNDLE_BACKUP_HOME). const string INDEX_FILE_RESTORE = string(BConstants::PATH_BUNDLE_BACKUP_HOME). append(BConstants::SA_BUNDLE_BACKUP_RESTORE). append(BConstants::EXT_BACKUP_MANAGE); + +const string INDEX_FILE_INCREMENTAL_BACKUP = string(BConstants::PATH_BUNDLE_BACKUP_HOME). + append(BConstants::SA_BUNDLE_BACKUP_BACKUP); using namespace std; +namespace { +const int64_t DEFAULT_SLICE_SIZE = 100 * 1024 * 1024; // 分片文件大小为100M +const uint32_t MAX_FILE_COUNT = 6000; // 单个tar包最多包含6000个文件 +} // namespace + void BackupExtExtension::VerifyCaller() { HILOGI("begin"); @@ -126,6 +140,62 @@ UniqueFd BackupExtExtension::GetFileHandle(const string &fileName) } } +static string GetReportFileName(const string &fileName) +{ + string reportName = fileName + "." + string(BConstants::REPORT_FILE_EXT); + return reportName; +} + +ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) +{ + try { + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { + HILOGI("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); + throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); + } + + VerifyCaller(); + + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { + string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); + throw BError(BError::Codes::EXT_INVAL_ARG, str); + } + + string tarName = path + fileName; + if (fileName.find('/') != string::npos) { + HILOGD("GetFileHandle: fileName include path symbol, need to make hash."); + tarName = path + GenerateHashForFileName(fileName); + if (CheckIfTarSuffix(fileName)) { + tarName += ".tar"; + } + } + if (access(tarName.c_str(), F_OK) == 0) { + throw BError(BError::Codes::EXT_INVAL_ARG, string("The file already exists")); + } + UniqueFd fd = UniqueFd(open(tarName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); + + // 对应的简报文件 + string reportName = GetReportFileName(tarName); + if (access(reportName.c_str(), F_OK) == 0) { + throw BError(BError::Codes::EXT_INVAL_ARG, string("The report file already exists")); + } + UniqueFd reportFd = UniqueFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); + + auto proxy = ServiceProxy::GetInstance(); + auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd)); + if (ret != ERR_OK) { + HILOGI("Failed to AppIncrementalFileReady %{public}d", ret); + } + + return ERR_OK; + } catch (...) { + HILOGE("Failed to get incremental file handle"); + DoClear(); + return BError(BError::Codes::EXT_INVAL_ARG).GetCode(); + } +} + ErrCode BackupExtExtension::HandleClear() { HILOGI("begin clear"); @@ -263,6 +333,57 @@ ErrCode BackupExtExtension::PublishFile(const string &fileName) } } +ErrCode BackupExtExtension::PublishIncrementalFile(const string &fileName) +{ + HILOGE("begin publish incremental file. fileName is %{public}s", fileName.data()); + try { + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { + throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); + } + VerifyCaller(); + + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string tarName = path + fileName; + // 带路径的文件名在这里转换为hash值 + if (fileName.find('/') != string::npos) { + HILOGD("PublishFile: fileName include path symbol, need to make hash."); + tarName = path + GenerateHashForFileName(fileName); + if (CheckIfTarSuffix(fileName)) { + tarName += ".tar"; + } + } + { + BExcepUltils::VerifyPath(tarName, true); + unique_lock lock(lock_); + if (find(tars_.begin(), tars_.end(), fileName) != tars_.end() || access(tarName.data(), F_OK) != 0) { + throw BError(BError::Codes::EXT_INVAL_ARG, "The file does not exist"); + } + tars_.push_back(fileName); + if (!IsAllFileReceived(tars_)) { + return ERR_OK; + } + } + + // 异步执行解压操作 + if (extension_->AllowToBackupRestore()) { + AsyncTaskIncrementalRestore(); + } + + return ERR_OK; + } catch (const BError &e) { + DoClear(); + return e.GetCode(); + } catch (const exception &e) { + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + DoClear(); + return BError(BError::Codes::EXT_BROKEN_FRAMEWORK).GetCode(); + } catch (...) { + HILOGE("Unexpected exception"); + DoClear(); + return BError(BError::Codes::EXT_BROKEN_FRAMEWORK).GetCode(); + } +} + ErrCode BackupExtExtension::HandleBackup() { string usrConfig = extension_->GetUsrConfig(); @@ -414,6 +535,65 @@ int BackupExtExtension::DoRestore(const string &fileName) return ERR_OK; } +static unordered_map GetTarIncludes(const string &tarName) +{ + // 根据简报文件获取待解压的文件列表,如果简报文件内容为空,则进行全量解压,返回空 + unordered_map includes; + + // 获取简报文件内容 + string reportName = GetReportFileName(tarName); + + // 获取简报内容 + BReportEntity rp(UniqueFd(open(reportName.data(), O_RDONLY))); + auto infos = rp.GetReportInfos(); + for (auto iter : infos) { + includes.emplace(iter.first, true); + } + + return includes; +} + +int BackupExtExtension::DoIncrementalRestore(const string &fileName) +{ + HILOGI("Do incremental restore"); + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { + return EPERM; + } + // REM: 给定version + // REM: 解压启动Extension时即挂载好的备份目录中的数据 + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string tarName = path + fileName; + + // 带路径的恢复需要找到hash后的待解压文件 + if (fileName.find('/') != string::npos) { + HILOGD("DoIncrementalRestore: fileName include path symbol, need to make hash."); + string filePath = path + GenerateHashForFileName(fileName); + size_t pos = filePath.rfind('/'); + if (pos == string::npos) { + return EPERM; + } + string folderPath = filePath.substr(0, pos); + if (!ForceCreateDirectory(folderPath.data())) { + HILOGE("Failed to create directory"); + return EPERM; + } + tarName = filePath; + if (CheckIfTarSuffix(fileName)) { + tarName += ".tar"; + } + } + + // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore + if (extension_->SpeicalVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { + UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); + } else { + UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); + } + HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); + + return ERR_OK; +} + void BackupExtExtension::AsyncTaskBackup(const string config) { auto task = [obj {wptr(this)}, config]() { @@ -611,6 +791,36 @@ static void DeleteBackupTars() } } +static void DeleteBackupIncrementalTars() +{ + // The directory include tars and manage.json which would be deleted + BJsonCachedEntity cachedEntity(UniqueFd(open(INDEX_FILE_RESTORE.data(), O_RDONLY))); + auto cache = cachedEntity.Structuralize(); + auto info = cache.GetExtManage(); + auto path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + for (auto &item : info) { + if (ExtractFileExt(item) != "tar" || IsUserTar(item, INDEX_FILE_RESTORE)) { + continue; + } + string tarPath = path + item; + if (!RemoveFile(tarPath)) { + HILOGE("Failed to delete the backup tar %{public}s", tarPath.c_str()); + } + // 删除简报文件 + string reportPath = GetReportFileName(tarPath); + if (!RemoveFile(reportPath)) { + HILOGE("Failed to delete the backup report"); + } + } + if (!RemoveFile(INDEX_FILE_RESTORE)) { + HILOGE("Failed to delete the backup index %{public}s", INDEX_FILE_RESTORE.c_str()); + } + string reportManagePath = GetReportFileName(INDEX_FILE_RESTORE); // GetIncrementalFileHandle创建的空fd + if (!RemoveFile(reportManagePath)) { + HILOGE("Failed to delete the backup report index %{public}s", reportManagePath.c_str()); + } +} + void BackupExtExtension::AsyncTaskRestore() { auto task = [obj {wptr(this)}, tars {tars_}]() { @@ -664,6 +874,59 @@ void BackupExtExtension::AsyncTaskRestore() }); } +void BackupExtExtension::AsyncTaskIncrementalRestore() +{ + auto task = [obj {wptr(this)}, tars {tars_}]() { + auto ptr = obj.promote(); + BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, + "Ext extension handle have been already released"); + try { + // 解压 + int ret = ERR_OK; + for (auto item : tars) { // 处理要解压的tar文件 + if (ExtractFileExt(item) == "tar" && !IsUserTar(item, INDEX_FILE_RESTORE)) { + ret = ptr->DoIncrementalRestore(item); + } + } + // 恢复用户tar包以及大文件 + // 目的地址是否需要拼接path(临时目录),FullBackupOnly为true并且非特殊场景 + bool appendTargetPath = ptr->extension_->UseFullBackupOnly() && + !ptr->extension_->SpeicalVersionForCloneAndCloud(); + RestoreBigFiles(appendTargetPath); + + // delete 1.tar/manage.json + DeleteBackupIncrementalTars(); + + if (ret == ERR_OK) { + HILOGI("after extra, do incremental restore."); + ptr->AsyncTaskIncrementalRestoreForUpgrade(); + } else { + ptr->AppIncrementalDone(ret); + ptr->DoClear(); + } + } catch (const BError &e) { + ptr->AppIncrementalDone(e.GetCode()); + } catch (const exception &e) { + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } catch (...) { + HILOGE("Failed to restore the ext bundle"); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } + }; + + // REM: 这里异步化了,需要做并发控制 + // 在往线程池中投入任务之前将需要的数据拷贝副本到参数中,保证不发生读写竞争, + // 由于拷贝参数时尚运行在主线程中,故在参数拷贝过程中是线程安全的。 + threadPool_.AddTask([task]() { + try { + task(); + } catch (...) { + HILOGE("Failed to add task to thread pool"); + } + }); +} + void BackupExtExtension::AsyncTaskRestoreForUpgrade() { auto task = [obj {wptr(this)}]() { @@ -707,6 +970,49 @@ void BackupExtExtension::AsyncTaskRestoreForUpgrade() }); } +void BackupExtExtension::AsyncTaskIncrementalRestoreForUpgrade() +{ + auto task = [obj {wptr(this)}]() { + auto ptr = obj.promote(); + try { + BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, + "Ext extension handle have been already released"); + BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, + "extension handle have been already released"); + + auto callBackup = [obj]() { + HILOGI("begin call restore"); + auto extensionPtr = obj.promote(); + BExcepUltils::BAssert(extensionPtr, BError::Codes::EXT_BROKEN_FRAMEWORK, + "Ext extension handle have been already released"); + extensionPtr->AppIncrementalDone(BError(BError::Codes::OK)); + // 清空恢复目录 + extensionPtr->DoClear(); + }; + ptr->extension_->OnRestore(callBackup); + } catch (const BError &e) { + ptr->AppIncrementalDone(e.GetCode()); + } catch (const exception &e) { + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } catch (...) { + HILOGE("Failed to restore the ext bundle"); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } + }; + + // REM: 这里异步化了,需要做并发控制 + // 在往线程池中投入任务之前将需要的数据拷贝副本到参数中,保证不发生读写竞争, + // 由于拷贝参数时尚运行在主线程中,故在参数拷贝过程中是线程安全的。 + threadPool_.AddTask([task]() { + try { + task(); + } catch (...) { + HILOGE("Failed to add task to thread pool"); + } + }); +} + void BackupExtExtension::ExtClear() { HILOGI("ext begin clear"); @@ -811,4 +1117,355 @@ ErrCode BackupExtExtension::HandleRestore() return 0; } + +static tuple, map, + map, map> + CompareFiles(const UniqueFd &cloudFd, const UniqueFd &storageFd) +{ + BReportEntity cloudRp(UniqueFd(cloudFd.Get())); + map cloudFiles = cloudRp.GetReportInfos(); + BReportEntity storageRp(UniqueFd(storageFd.Get())); + map storageFiles = storageRp.GetReportInfos(); + map allFiles = {}; + map smallFiles = {}; + map bigFiles = {}; + map bigInfos = {}; + for (auto &item : storageFiles) { + // 进行文件对比 + string path = item.first; + if (item.second.isIncremental == true && item.second.isDir == true) { + smallFiles.try_emplace(path, item.second); + } + if (item.second.isIncremental == true && item.second.isDir == false) { + auto [res, fileHash] = BFileHash::HashWithSHA256(path); + if (fileHash.empty()) { + continue; + } + item.second.hash = fileHash; + item.second.isIncremental = true; + } else { + item.second.hash = (cloudFiles.find(path) == cloudFiles.end()) ? cloudFiles[path].hash : ""; + } + if (cloudFiles.find(path) == cloudFiles.end() || (item.second.isDir == false && + item.second.isIncremental == true && cloudFiles.find(path)->second.hash != item.second.hash)) { + // 在云空间简报里不存在或者hash不一致 + struct stat sta = {}; + if (stat(path.c_str(), &sta) == -1) { + continue; + } + if (sta.st_size < BConstants::BIG_FILE_BOUNDARY) { + item.second.size = sta.st_size; + smallFiles.try_emplace(path, item.second); + } else { + bigFiles.try_emplace(path, sta); + bigInfos.try_emplace(path, item.second); + } + } + allFiles.try_emplace(path, item.second); + } + HILOGI("compareFiles Find small files total: %{public}d", smallFiles.size()); + HILOGI("compareFiles Find big files total: %{public}d", bigFiles.size()); + return {allFiles, smallFiles, bigFiles, bigInfos}; +} + +static void WriteFile(const string &filename, const map &srcFiles) +{ + fstream f; + f.open(filename.data(), ios::out); + // 前面2行先填充进去 + f << "version=1.0&attrNum=6" << endl; + f << "path;mode;dir;size;mtime;hash" << endl; + for (auto item : srcFiles) { + struct ReportFileInfo info = item.second; + string str = item.first + ";" + info.mode + ";" + to_string(info.isDir) + ";" + to_string(info.size); + str += ";" + to_string(info.mtime) + ";" + info.hash; + f << str << endl; + } + f.close(); + HILOGI("WriteFile path: %{public}s", filename.c_str()); +} + +/** + * 获取增量的大文件的信息 +*/ +static TarMap GetIncrmentBigInfos(const map &files) +{ + auto getStringHash = [](const TarMap &m, const string &str) -> string { + ostringstream strHex; + strHex << hex; + + hash strHash; + size_t szHash = strHash(str); + strHex << setfill('0') << setw(BConstants::BIG_FILE_NAME_SIZE) << szHash; + string name = strHex.str(); + for (int i = 0; m.find(name) != m.end(); ++i, strHex.str("")) { + szHash = strHash(str + to_string(i)); + strHex << setfill('0') << setw(BConstants::BIG_FILE_NAME_SIZE) << szHash; + name = strHex.str(); + } + + return name; + }; + + TarMap bigFiles; + for (const auto &item : files) { + string md5Name = getStringHash(bigFiles, item.first); + if (!md5Name.empty()) { + bigFiles.emplace(md5Name, make_tuple(item.first, item.second, true)); + } + } + + return bigFiles; +} + +/** + * 增量tar包和简报信息回传 +*/ +static ErrCode IncrementalTarFileReady(const TarMap &bigFileInfo, const map &srcFiles, + sptr proxy) +{ + string tarFile = bigFileInfo.begin()->first; + HILOGI("IncrementalTarFileReady: tar: %{public}s", tarFile.c_str()); + string manageFile = GetReportFileName(tarFile); + HILOGI("IncrementalTarFileReady: manageFile: %{public}s", tarFile.c_str()); + string file = string(INDEX_FILE_INCREMENTAL_BACKUP).append(manageFile); + WriteFile(file, srcFiles); + + string tarName = string(INDEX_FILE_INCREMENTAL_BACKUP).append(tarFile); + ErrCode ret = + proxy->AppIncrementalFileReady(tarFile, UniqueFd(open(tarName.data(), O_RDONLY)), + UniqueFd(open(file.data(), O_RDONLY))); + if (SUCCEEDED(ret)) { + HILOGI("IncrementalTarFileReady: The application is packaged successfully"); + // 删除文件 + RemoveFile(file); + RemoveFile(tarName); + } else { + HILOGE("IncrementalTarFileReady interface fails to be invoked: %{public}d", ret); + } + return ret; +} + +/** + * 增量大文件和简报信息回传 +*/ +static ErrCode IncrementalBigFileReady(const TarMap &pkgInfo, const map &bigInfos, + sptr proxy) +{ + ErrCode ret {ERR_OK}; + for (auto &item : pkgInfo) { + if (item.first.empty()) { + continue; + } + auto [path, sta, isBeforeTar] = item.second; + + UniqueFd fd(open(path.data(), O_RDONLY)); + if (fd < 0) { + HILOGE("IncrementalBigFileReady open file failed, file name is %{public}s, err = %{public}d", + path.c_str(), errno); + continue; + } + + struct ReportFileInfo info = bigInfos.find(path)->second; + string file = GetReportFileName(string(INDEX_FILE_INCREMENTAL_BACKUP).append(item.first)); + HILOGI("IncrementalBigFileReady write name is %{public}s", path.c_str()); + HILOGI("IncrementalBigFileReady: file: %{public}s", file.c_str()); + map bigInfo; + bigInfo.try_emplace(path, info); + WriteFile(file, bigInfo); + + ret = proxy->AppIncrementalFileReady(item.first, std::move(fd), UniqueFd(open(file.data(), O_RDONLY))); + if (SUCCEEDED(ret)) { + HILOGI("IncrementalBigFileReady:The application is packaged successfully, package name is %{public}s", + item.first.c_str()); + RemoveFile(file); + } else { + HILOGE("IncrementalBigFileReady interface fails to be invoked: %{public}d", ret); + } + } + return ret; +} + +ErrCode BackupExtExtension::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) +{ + string usrConfig = extension_->GetUsrConfig(); + BJsonCachedEntity cachedEntity(usrConfig); + auto cache = cachedEntity.Structuralize(); + if (!cache.GetAllowToBackupRestore()) { + HILOGE("Application does not allow backup or restore"); + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); + } + auto [allFiles, smallFiles, bigFiles, bigInfos] = CompareFiles(move(manifestFd), move(incrementalFd)); + AsyncTaskOnIncrementalBackup(allFiles, smallFiles, bigFiles, bigInfos); + return 0; +} + +tuple BackupExtExtension::GetIncrementalBackupFileHandle() +{ + return {UniqueFd(-1), UniqueFd(-1)}; +} + + +void BackupExtExtension::AsyncTaskOnIncrementalBackup(const map &allFiles, + const map &smallFiles, const map &bigFiles, + const map &bigInfos) +{ + auto task = [obj {wptr(this)}, allFiles, smallFiles, bigFiles, bigInfos]() { + auto ptr = obj.promote(); + try { + BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, + "Ext extension handle have been already released"); + BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, + "extension handle have been already released"); + + auto ret = ptr->DoIncrementalBackup(allFiles, smallFiles, bigFiles, bigInfos); + ptr->AppIncrementalDone(ret); + HILOGE("Incremental backup app done %{public}d", ret); + } catch (const BError &e) { + ptr->AppIncrementalDone(e.GetCode()); + } catch (const exception &e) { + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } catch (...) { + HILOGE("Failed to restore the ext bundle"); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } + }; + + threadPool_.AddTask([task]() { + try { + task(); + } catch (...) { + HILOGE("Failed to add task to thread pool"); + } + }); +} + +static string GetIncrmentPartName() +{ + auto now = chrono::system_clock::now(); + auto duration = now.time_since_epoch(); + auto milliseconds = chrono::duration_cast(duration); + + return to_string(milliseconds.count()) + "_part"; +} + +static void IncrementalPacket(const map &infos, TarMap &tar, sptr proxy) +{ + HILOGI("IncrementalPacket begin"); + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + int64_t totalSize = 0; + uint32_t fileCount = 0; + vector packFiles; + map tarInfos; + + string partName = GetIncrmentPartName(); + for (auto small : infos) { + totalSize += small.second.size; + fileCount += 1; + packFiles.emplace_back(small.first); + tarInfos.try_emplace(small.first, small.second); + if (totalSize >= DEFAULT_SLICE_SIZE || fileCount >= MAX_FILE_COUNT) { + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, partName, path, tarMap); + tar.insert(tarMap.begin(), tarMap.end()); + // 执行tar包回传功能 + IncrementalTarFileReady(tarMap, tarInfos, proxy); + totalSize = 0; + fileCount = 0; + packFiles.clear(); + tarInfos.clear(); + } + } + if (fileCount > 0) { + // 打包回传 + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, partName, path, tarMap); + IncrementalTarFileReady(tarMap, tarInfos, proxy); + tar.insert(tarMap.begin(), tarMap.end()); + packFiles.clear(); + tarInfos.clear(); + } +} + +static ErrCode IncrementalAllFileReady(const TarMap &pkgInfo, const map &srcFiles, + sptr proxy) +{ + BJsonCachedEntity cachedEntity( + UniqueFd(open(INDEX_FILE_BACKUP.data(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR))); + auto cache = cachedEntity.Structuralize(); + cache.SetExtManage(pkgInfo); + cachedEntity.Persist(); + close(cachedEntity.GetFd().Release()); + + string file = GetReportFileName(string(INDEX_FILE_INCREMENTAL_BACKUP).append("all")); + WriteFile(file, srcFiles); + UniqueFd fd(open(INDEX_FILE_BACKUP.data(), O_RDONLY)); + UniqueFd manifestFd(open(file.data(), O_RDONLY)); + ErrCode ret = + proxy->AppIncrementalFileReady(string(BConstants::EXT_BACKUP_MANAGE), std::move(fd), std::move(manifestFd)); + if (SUCCEEDED(ret)) { + HILOGI("IncrementalAllFileReady successfully"); + RemoveFile(file); + } else { + HILOGI( + "successfully but the IncrementalAllFileReady interface fails to be invoked: %{public}d", ret); + } + return ret; +} + +int BackupExtExtension::DoIncrementalBackup(const map &allFiles, + const map &smallFiles, const map &bigFiles, + const map &bigInfos) +{ + HILOGI("Do increment backup"); + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::BACKUP) { + return EPERM; + } + + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { + throw BError(errno); + } + + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + } + // 获取增量文件和全量数据 + if (smallFiles.size() == 0 && bigFiles.size() == 0) { + // 没有增量,则不需要上传 + TarMap tMap; + IncrementalAllFileReady(tMap, allFiles, proxy); + HILOGI("Do increment backup, IncrementalAllFileReady end, file empty"); + return ERR_OK; + } + + // tar包数据 + TarMap tarMap; + IncrementalPacket(smallFiles, tarMap, proxy); + HILOGI("Do increment backup, IncrementalPacket end"); + + // 最后回传大文件 + TarMap bigMap = GetIncrmentBigInfos(bigFiles); + IncrementalBigFileReady(bigMap, bigInfos, proxy); + HILOGI("Do increment backup, IncrementalBigFileReady end"); + bigMap.insert(tarMap.begin(), tarMap.end()); + + // 回传manage.json和全量文件 + IncrementalAllFileReady(bigMap, allFiles, proxy); + HILOGI("Do increment backup, IncrementalAllFileReady end"); + return ERR_OK; +} + +void BackupExtExtension::AppIncrementalDone(ErrCode errCode) +{ + auto proxy = ServiceProxy::GetInstance(); + BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + auto ret = proxy->AppIncrementalDone(errCode); + if (ret != ERR_OK) { + HILOGE("Failed to notify the app done. err = %{public}d", ret); + } +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension_stub.cpp b/frameworks/native/backup_ext/src/ext_extension_stub.cpp index c98380a376c7e175ddfe1e36ea968c1b96d7a764..e01c1ef0ed4843fcccf7c0f483eccc6c8aa8b353 100644 --- a/frameworks/native/backup_ext/src/ext_extension_stub.cpp +++ b/frameworks/native/backup_ext/src/ext_extension_stub.cpp @@ -37,6 +37,14 @@ ExtExtensionStub::ExtExtensionStub() &ExtExtensionStub::CmdPublishFile; opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_HANDLE_RESTORE)] = &ExtExtensionStub::CmdHandleRestore; + opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_GET_INCREMENTAL_FILE_HANDLE)] = + &ExtExtensionStub::CmdGetIncrementalFileHandle; + opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_PUBLISH_INCREMENTAL_FILE)] = + &ExtExtensionStub::CmdPublishIncrementalFile; + opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_HANDLE_INCREMENTAL_BACKUP)] = + &ExtExtensionStub::CmdHandleIncrementalBackup; + opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_GET_INCREMENTAL_BACKUP_FILE_HANDLE)] = + &ExtExtensionStub::CmdGetIncrementalBackupFileHandle; } int32_t ExtExtensionStub::OnRemoteRequest(uint32_t code, @@ -128,4 +136,63 @@ ErrCode ExtExtensionStub::CmdHandleRestore(MessageParcel &data, MessageParcel &r } return BError(BError::Codes::OK); } + +ErrCode ExtExtensionStub::CmdGetIncrementalFileHandle(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + string fileName; + if (!data.ReadString(fileName)) { + return BError(BError::Codes::EXT_INVAL_ARG, "Failed to receive fileName").GetCode(); + } + + ErrCode res = GetIncrementalFileHandle(fileName); + if (!reply.WriteInt32(res)) { + return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the file").GetCode(); + } + return BError(BError::Codes::OK); +} + +ErrCode ExtExtensionStub::CmdPublishIncrementalFile(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + string fileName; + if (!data.ReadString(fileName)) { + return BError(BError::Codes::EXT_INVAL_ARG, "Failed to receive fileName"); + } + + ErrCode res = PublishIncrementalFile(fileName); + if (!reply.WriteInt32(res)) { + stringstream ss; + ss << "Failed to send the result " << res; + return BError(BError::Codes::EXT_BROKEN_IPC, ss.str()).GetCode(); + } + return BError(BError::Codes::OK); +} + +ErrCode ExtExtensionStub::CmdHandleIncrementalBackup(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + UniqueFd incrementalFd(data.ReadFileDescriptor()); + UniqueFd manifestFd(data.ReadFileDescriptor()); + ErrCode res = HandleIncrementalBackup(move(incrementalFd), move(manifestFd)); + if (!reply.WriteInt32(res)) { + stringstream ss; + ss << "Failed to send the result " << res; + return BError(BError::Codes::EXT_BROKEN_IPC, ss.str()).GetCode(); + } + return BError(BError::Codes::OK); +} + +ErrCode ExtExtensionStub::CmdGetIncrementalBackupFileHandle(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + auto [incrementalFd, manifestFd] = GetIncrementalBackupFileHandle(); + if (!reply.WriteFileDescriptor(incrementalFd)) { + return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the file").GetCode(); + } + if (!reply.WriteFileDescriptor(manifestFd)) { + return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the file").GetCode(); + } + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/untar_file.cpp b/frameworks/native/backup_ext/src/untar_file.cpp index 0e188ab36ec12c828398980a6364e01673cfaf97..84d72f8ee108af4783a6b27e6bd6b6ac096d73dd 100644 --- a/frameworks/native/backup_ext/src/untar_file.cpp +++ b/frameworks/native/backup_ext/src/untar_file.cpp @@ -94,6 +94,26 @@ int UntarFile::UnPacket(const string &tarFile, const string &rootPath) return 0; } +int UntarFile::IncrementalUnPacket(const string &tarFile, const string &rootPath, + const unordered_map &includes) +{ + includes_ = includes; + tarFilePtr_ = fopen(tarFile.c_str(), "rb"); + if (tarFilePtr_ == nullptr) { + HILOGE("Failed to open tar file %{public}s, err = %{public}d", tarFile.c_str(), errno); + return errno; + } + + if (ParseIncrementalTarFile(rootPath) != 0) { + HILOGE("Failed to parse tar file"); + } + + fclose(tarFilePtr_); + tarFilePtr_ = nullptr; + + return 0; +} + void UntarFile::HandleTarBuffer(const string &buff, const string &name, FileStatInfo &info) { info.mode = static_cast(ParseOctalStr(&buff[0] + TMODE_BASE, TMODE_LEN)); @@ -164,6 +184,56 @@ int UntarFile::ParseTarFile(const string &rootPath) return ret; } +int UntarFile::ParseIncrementalTarFile(const string &rootPath) +{ + // re-parse tar header + rootPath_ = rootPath; + char buff[BLOCK_SIZE] = {0}; + bool isSkip = false; + FileStatInfo info {}; + + // tarFileSize + int ret = fseeko(tarFilePtr_, 0L, SEEK_END); + tarFileSize_ = ftello(tarFilePtr_); + // reback file to begin + ret = fseeko(tarFilePtr_, 0L, SEEK_SET); + + while (1) { + readCnt_ = fread(buff, 1, BLOCK_SIZE, tarFilePtr_); + if (readCnt_ < BLOCK_SIZE) { + HILOGE("Parsing tar file completed, read data count is less then block size."); + return 0; + } + // two empty continuous block indicate end of file + if (IsEmptyBlock(buff)) { + char tailBuff[BLOCK_SIZE] = {0}; + size_t tailRead = fread(tailBuff, 1, BLOCK_SIZE, tarFilePtr_); + if (tailRead == BLOCK_SIZE && IsEmptyBlock(tailBuff)) { + HILOGE("Parsing tar file completed, tailBuff is empty."); + return 0; + } + } + // check header + TarHeader *header = reinterpret_cast(buff); + if (!IsValidTarBlock(*header)) { + // when split unpack, ftell size is over than file really size [0,READ_BUFF_SIZE] + if (ftello(tarFilePtr_) > (tarFileSize_ + READ_BUFF_SIZE) || !IsEmptyBlock(buff)) { + HILOGE("Invalid tar file format"); + ret = ERR_FORMAT; + } + return ret; + } + HandleTarBuffer(string(buff, BLOCK_SIZE), header->name, info); + ParseIncrementalFileByTypeFlag(header->typeFlag, isSkip, info); + ret = HandleFileProperties(isSkip, info); + if (ret != 0) { + HILOGE("Failed to handle file property"); + } + } + + return ret; +} + void UntarFile::ParseFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &info) { switch (typeFlag) { @@ -199,6 +269,43 @@ void UntarFile::ParseFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &i } } +void UntarFile::ParseIncrementalFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &info) +{ + switch (typeFlag) { + case REGTYPE: + case AREGTYPE: + if (!includes_.empty() && includes_.find(info.fullPath) == includes_.end()) { // not in includes + isSkip = true; + fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET); + break; + } + ParseRegularFile(info, typeFlag, isSkip); + break; + case SYMTYPE: + isSkip = false; + break; + case DIRTYPE: + CreateDir(info.fullPath, info.mode); + isSkip = false; + break; + case GNUTYPE_LONGNAME: { + size_t nameLen = static_cast(tarFileSize_); + if (nameLen < PATH_MAX_LEN) { + fread(&(info.longName[0]), sizeof(char), nameLen, tarFilePtr_); + } + isSkip = true; + fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET); + break; + } + default: { + // Ignoring, skip + isSkip = true; + fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR); + break; + } + } +} + void UntarFile::ParseRegularFile(FileStatInfo &info, char typeFlag, bool &isSkip) { FILE *destFile = CreateFile(info.fullPath, info.mode, typeFlag); diff --git a/frameworks/native/backup_kit_inner/include/service_reverse.h b/frameworks/native/backup_kit_inner/include/service_reverse.h index f0810e14a037ff8cc44e641e5f05b7274313398f..92b22c47e104db32dcc0b9028efb48b4746a34aa 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse.h @@ -18,6 +18,8 @@ #include "b_session_backup.h" #include "b_session_restore.h" +#include "b_incremental_backup_session.h" +#include "b_incremental_restore_session.h" #include "service_reverse_stub.h" namespace OHOS::FileManagement::Backup { @@ -33,16 +35,30 @@ public: void RestoreOnAllBundlesFinished(int32_t errCode) override; void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) override; + void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd) override; + void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) override; + void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; + void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; + + void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; + void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; + void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) override; + void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd) override; + public: ServiceReverse() = delete; explicit ServiceReverse(BSessionRestore::Callbacks callbacks); explicit ServiceReverse(BSessionBackup::Callbacks callbacks); + explicit ServiceReverse(BIncrementalBackupSession::Callbacks callbacks); + explicit ServiceReverse(BIncrementalRestoreSession::Callbacks callbacks); ~ServiceReverse() override = default; private: Scenario scenario_ {Scenario::UNDEFINED}; BSessionBackup::Callbacks callbacksBackup_; BSessionRestore::Callbacks callbacksRestore_; + BIncrementalBackupSession::Callbacks callbacksIncrementalBackup_; + BIncrementalRestoreSession::Callbacks callbacksIncrementalRestore_; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h index 5c46907b26353c54ba03bc29d3ffe32c85579ba6..ea1e5f8beef0a9c10bfc238e642584ca60e6d674 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h @@ -43,6 +43,16 @@ private: int32_t CmdRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnFileReady(MessageParcel &data, MessageParcel &reply); + + int32_t CmdIncrementalBackupOnFileReady(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalBackupOnBundleStarted(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); + + int32_t CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalRestoreOnFileReady(MessageParcel &data, MessageParcel &reply); }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d17428c1b4f8ab351e18cdb2a2b5eac9cb3cf67 --- /dev/null +++ b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_incremental_backup_session.h" + +#include "b_error/b_error.h" +#include "filemgmt_libhilog.h" +#include "service_proxy.h" +#include "service_reverse.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +BIncrementalBackupSession::~BIncrementalBackupSession() +{ + if (!deathRecipient_) { + HILOGI("Death Recipient is nullptr"); + return; + } + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return; + } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; +} + +unique_ptr BIncrementalBackupSession::Init(Callbacks callbacks) +{ + try { + auto backup = make_unique(); + ServiceProxy::InvaildInstance(); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGI("Failed to get backup service"); + return nullptr; + } + + int32_t res = proxy->InitIncrementalBackupSession(sptr(new ServiceReverse(callbacks))); + if (res != 0) { + HILOGE("Failed to Backup because of %{public}d", res); + return nullptr; + } + + backup->RegisterBackupServiceDied(callbacks.onBackupServiceDied); + return backup; + } catch (const exception &e) { + HILOGE("Failed to Backup because of %{public}s", e.what()); + } + return nullptr; +} + +void BIncrementalBackupSession::RegisterBackupServiceDied(function functor) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr || !functor) { + return; + } + auto remoteObj = proxy->AsObject(); + if (!remoteObj) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Proxy's remote object can't be nullptr"); + } + + auto callback = [functor](const wptr &obj) { + ServiceProxy::InvaildInstance(); + HILOGI("Backup service died"); + functor(); + }; + deathRecipient_ = sptr(new SvcDeathRecipient(callback)); + remoteObj->AddDeathRecipient(deathRecipient_); +} + +ErrCode BIncrementalBackupSession::AppendBundles(vector bundlesToBackup) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->AppendBundlesIncrementalBackupSession(bundlesToBackup); +} + +ErrCode BIncrementalBackupSession::Release() +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->Release(); +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2b43886854b0218b408624a9521932d40234908c --- /dev/null +++ b/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_incremental_data.h" + +#include "filemgmt_libhilog.h" +#include "message_parcel.h" + +namespace OHOS { +namespace FileManagement { +namespace Backup { +using namespace std; + +bool BIncrementalData::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(bundleName) || !parcel.WriteInt64(lastIncrementalTime) || + !parcel.WriteString(backupParameters) || !parcel.WriteInt32(backupPriority)) { + HILOGE("Failed"); + return false; + } + auto msgParcel = static_cast(&parcel); + msgParcel->WriteFileDescriptor(manifestFd); + return true; +} + +bool BIncrementalData::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadString(bundleName) || !parcel.ReadInt64(lastIncrementalTime) || + !parcel.ReadString(backupParameters) || !parcel.ReadInt32(backupPriority)) { + HILOGE("Failed"); + return false; + } + auto msgParcel = static_cast(&parcel); + manifestFd = msgParcel->ReadFileDescriptor(); + return true; +} + +BIncrementalData *BIncrementalData::Unmarshalling(Parcel &parcel) +{ + try { + auto result = make_unique(); + if (!result->ReadFromParcel(parcel)) { + return nullptr; + } + return result.release(); + } catch (const bad_alloc &e) { + HILOGE("Failed to unmarshall BIncrementalData because of %{public}s", e.what()); + } + return nullptr; +} +} // namespace Backup +} // namespace FileManagement +} // namespace OHOS \ No newline at end of file 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 new file mode 100644 index 0000000000000000000000000000000000000000..9a9fe5abca7edf1ebdf19380248b20eed2a203c4 --- /dev/null +++ b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_incremental_restore_session.h" + +#include "b_error/b_error.h" +#include "filemgmt_libhilog.h" +#include "service_proxy.h" +#include "service_reverse.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +BIncrementalRestoreSession::~BIncrementalRestoreSession() +{ + if (!deathRecipient_) { + HILOGI("Death Recipient is nullptr"); + return; + } + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return; + } + auto remoteObject = proxy->AsObject(); + if (remoteObject != nullptr) { + remoteObject->RemoveDeathRecipient(deathRecipient_); + } + deathRecipient_ = nullptr; +} + +unique_ptr BIncrementalRestoreSession::Init(Callbacks callbacks) +{ + try { + auto restore = make_unique(); + ServiceProxy::InvaildInstance(); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGI("Failed to get backup service"); + return nullptr; + } + int32_t res = proxy->InitRestoreSession(new ServiceReverse(callbacks)); + if (res != 0) { + HILOGE("Failed to Restore because of %{public}d", res); + return nullptr; + } + + restore->RegisterBackupServiceDied(callbacks.onBackupServiceDied); + return restore; + } catch (const exception &e) { + HILOGE("Failed to Restore because of %{public}s", e.what()); + } + return nullptr; +} + +ErrCode BIncrementalRestoreSession::PublishFile(BFileInfo fileInfo) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + return proxy->PublishIncrementalFile(fileInfo); +} + +ErrCode BIncrementalRestoreSession::GetFileHandle(const string &bundleName, const string &fileName) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->GetIncrementalFileHandle(bundleName, fileName); +} + +ErrCode BIncrementalRestoreSession::AppendBundles(UniqueFd remoteCap, vector bundlesToRestore) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->AppendBundlesRestoreSession(move(remoteCap), bundlesToRestore); +} + +ErrCode BIncrementalRestoreSession::Release() +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->Release(); +} + +void BIncrementalRestoreSession::RegisterBackupServiceDied(function functor) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr || !functor) { + return; + } + auto remoteObj = proxy->AsObject(); + if (!remoteObj) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Proxy's remote object can't be nullptr"); + } + + auto callback = [functor](const wptr &obj) { + HILOGI("Backup service died"); + ServiceProxy::InvaildInstance(); + functor(); + }; + deathRecipient_ = sptr(new SvcDeathRecipient(callback)); + remoteObj->AddDeathRecipient(deathRecipient_); +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index e89285aba1cdea2b62a31c3813279bf8500a3709..d96ef7847eb09d00642cd4ed09f14aedfe02e6e1 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -114,4 +114,14 @@ ErrCode BSessionBackup::Finish() return proxy->Finish(); } + +ErrCode BSessionBackup::Release() +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->Release(); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp index 59a6d67e47a1a621c71357fd77045076943d3d74..f41ea469ba9b53b678040fa885b216b4e8edf3d1 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -113,6 +113,16 @@ ErrCode BSessionRestore::Finish() return proxy->Finish(); } +ErrCode BSessionRestore::Release() +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->Release(); +} + void BSessionRestore::RegisterBackupServiceDied(std::function functor) { auto proxy = ServiceProxy::GetInstance(); diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp index a0a38653c8b6f74d276b29455b6b2400c2a26998..4416e873b309a2c80d88e0677e3ec6d39a0d8742 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp @@ -104,6 +104,16 @@ ErrCode BSessionRestoreAsync::AppendBundles(UniqueFd remoteCap, return proxy->AppendBundlesRestoreSession(move(remoteCap), bundlesToRestore, restoreType, userId); } +ErrCode BSessionRestoreAsync::Release() +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); + } + + return proxy->Release(); +} + void BSessionRestoreAsync::RegisterBackupServiceDied(std::function functor) { auto proxy = ServiceProxy::GetInstance(); diff --git a/frameworks/native/backup_kit_inner/src/service_incremental_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_incremental_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea227c5a36ab7f6b5d1189c5eaafc5e1459c652e --- /dev/null +++ b/frameworks/native/backup_kit_inner/src/service_incremental_proxy.cpp @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "service_proxy.h" + +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "b_resources/b_constants.h" +#include "filemgmt_libhilog.h" +#include "svc_death_recipient.h" +#include "unique_fd.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +ErrCode ServiceProxy::Release() +{ + HILOGI("Begin"); + 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; + int32_t ret = Remote()->SendRequest(static_cast(IServiceInterfaceCode::SERVICE_CMD_RELSEASE_SESSION), + 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(); + } + return reply.ReadInt32(); +} + +UniqueFd ServiceProxy::GetLocalCapabilitiesIncremental(const vector &bundleNames) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + HILOGE("Failed to write descriptor"); + return UniqueFd(-EPERM); + } + + if (!WriteParcelableVector(bundleNames, data)) { + HILOGE("Failed to send the bundleNames"); + return UniqueFd(-EPERM); + } + + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()->SendRequest( + static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_LOCAL_CAPABILITIES_INCREMENTAL), data, reply, + option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return UniqueFd(-ret); + } + UniqueFd fd(reply.ReadFileDescriptor()); + return UniqueFd(fd.Release()); +} + +ErrCode ServiceProxy::InitIncrementalBackupSession(sptr remote) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + HILOGE("Failed to write descriptor"); + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + + MessageParcel reply; + MessageOption option; + + if (!remote) { + HILOGE("Empty reverse stub"); + return BError(BError::Codes::SDK_INVAL_ARG, "Empty reverse stub").GetCode(); + } + if (!data.WriteRemoteObject(remote->AsObject().GetRefPtr())) { + HILOGE("Failed to send the reverse stub"); + 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_INCREMENTAL_BACKUP_SESSION), data, reply, option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return BError(BError::Codes::SDK_INVAL_ARG, "Received error when doing IPC").GetCode(); + } + return reply.ReadInt32(); +} + +ErrCode ServiceProxy::AppendBundlesIncrementalBackupSession(const vector &bundlesToBackup) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + HILOGE("Failed to write descriptor"); + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + + if (!WriteParcelableVector(bundlesToBackup, data)) { + HILOGE("Failed to send the bundleNames"); + return UniqueFd(-EPERM); + } + + MessageParcel reply; + MessageOption option; + + int32_t ret = Remote()->SendRequest( + static_cast(IServiceInterfaceCode::SERVICE_CMD_APPEND_BUNDLES_INCREMENTAL_BACKUP_SESSION), data, + reply, option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return BError(BError::Codes::SDK_INVAL_ARG, "Received error when doing IPC").GetCode(); + } + return reply.ReadInt32(); +} + +ErrCode ServiceProxy::PublishIncrementalFile(const BFileInfo &fileInfo) +{ + HILOGI("Begin"); + 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(); + } + + if (!data.WriteParcelable(&fileInfo)) { + HILOGE("Failed to send the fileInfo"); + return -EPIPE; + } + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest( + static_cast(IServiceInterfaceCode::SERVICE_CMD_PUBLISH_INCREMENTAL_FILE), 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(); + } + return reply.ReadInt32(); +} + +ErrCode ServiceProxy::AppIncrementalFileReady(const std::string &fileName, UniqueFd fd, UniqueFd manifestFd) +{ + HILOGI("Begin"); + 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(); + } + + if (!data.WriteString(fileName)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the filename").GetCode(); + } + if (!data.WriteFileDescriptor(fd)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fd").GetCode(); + } + if (!data.WriteFileDescriptor(manifestFd)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fd").GetCode(); + } + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest( + static_cast(IServiceInterfaceCode::SERVICE_CMD_APP_INCREMENTAL_FILE_READY), 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(); + } + return reply.ReadInt32(); +} + +ErrCode ServiceProxy::AppIncrementalDone(ErrCode errCode) +{ + HILOGI("Begin"); + 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(); + } + + if (!data.WriteInt32(errCode)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the errCode").GetCode(); + } + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest(static_cast(IServiceInterfaceCode::SERVICE_CMD_APP_INCREMENTAL_DONE), + 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(); + } + return reply.ReadInt32(); +} + +ErrCode ServiceProxy::GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) +{ + HILOGI("Begin"); + 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(); + } + + if (!data.WriteString(bundleName)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the bundleName").GetCode(); + } + if (!data.WriteString(fileName)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fileName").GetCode(); + } + + MessageParcel reply; + MessageOption option; + option.SetFlags(MessageOption::TF_ASYNC); + int32_t ret = Remote()->SendRequest( + static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_INCREMENTAL_FILE_NAME), 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(); + } + return ret; +} + +template +bool ServiceProxy::WriteParcelableVector(const std::vector &parcelableVector, Parcel &data) +{ + if (!data.WriteUint32(parcelableVector.size())) { + HILOGE("failed to WriteInt32 for parcelableVector.size()"); + return false; + } + + for (const auto &parcelable : parcelableVector) { + if (!data.WriteParcelable(&parcelable)) { + HILOGE("failed to WriteParcelable for parcelable"); + return false; + } + } + + return true; +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5378ac9465a61f7b2018928e945ba534e58e3590 --- /dev/null +++ b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "service_reverse.h" + +#include "b_error/b_error.h" +#include "filemgmt_libhilog.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +void ServiceReverse::IncrementalBackupOnFileReady(string bundleName, string fileName, int fd, int manifestFd) +{ + HILOGI("begin"); + if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onFileReady) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + BFileInfo bFileInfo(bundleName, fileName, 0); + callbacksIncrementalBackup_.onFileReady(bFileInfo, UniqueFd(fd), UniqueFd(manifestFd)); +} + +void ServiceReverse::IncrementalBackupOnBundleStarted(int32_t errCode, string bundleName) +{ + HILOGI("begin"); + if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onBundleStarted) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksIncrementalBackup_.onBundleStarted(errCode, bundleName); +} + +void ServiceReverse::IncrementalBackupOnBundleFinished(int32_t errCode, string bundleName) +{ + HILOGI("begin"); + if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onBundleFinished) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksIncrementalBackup_.onBundleFinished(errCode, bundleName); +} + +void ServiceReverse::IncrementalBackupOnAllBundlesFinished(int32_t errCode) +{ + HILOGI("errCode = %{public}d", errCode); + if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onAllBundlesFinished) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksIncrementalBackup_.onAllBundlesFinished(errCode); +} + +void ServiceReverse::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) +{ + HILOGI("begin"); + if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onBundleStarted) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksIncrementalRestore_.onBundleStarted(errCode, bundleName); +} + +void ServiceReverse::IncrementalRestoreOnBundleFinished(int32_t errCode, string bundleName) +{ + HILOGI("begin"); + if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onBundleFinished) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksIncrementalRestore_.onBundleFinished(errCode, bundleName); +} + +void ServiceReverse::IncrementalRestoreOnAllBundlesFinished(int32_t errCode) +{ + HILOGI("errCode = %{public}d", errCode); + if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onAllBundlesFinished) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksIncrementalRestore_.onAllBundlesFinished(errCode); +} + +void ServiceReverse::IncrementalRestoreOnFileReady(string bundleName, string fileName, int fd, int manifestFd) +{ + HILOGI("begin"); + if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onFileReady) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + BFileInfo bFileInfo(bundleName, fileName, 0); + callbacksIncrementalRestore_.onFileReady(bFileInfo, UniqueFd(fd), UniqueFd(manifestFd)); +} + +ServiceReverse::ServiceReverse(BIncrementalBackupSession::Callbacks callbacks) + : scenario_(Scenario::BACKUP), callbacksIncrementalBackup_(callbacks) +{ +} + +ServiceReverse::ServiceReverse(BIncrementalRestoreSession::Callbacks callbacks) + : scenario_(Scenario::RESTORE), callbacksIncrementalRestore_(callbacks) +{ +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp index 7cfcb79c0917c3da8e4c8b6e13ca28cea80f60cf..cda7f3521f91aef407b8357aa3f6265bf8730c46 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp @@ -63,6 +63,30 @@ ServiceReverseStub::ServiceReverseStub() &ServiceReverseStub::CmdRestoreOnAllBundlesFinished; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_FILE_READY)] = &ServiceReverseStub::CmdRestoreOnFileReady; + + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY)] = + &ServiceReverseStub::CmdIncrementalBackupOnFileReady; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_STARTED)] = + &ServiceReverseStub::CmdIncrementalBackupOnBundleStarted; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalBackupOnBundleFinished; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalBackupOnAllBundlesFinished; + + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnBundleFinished; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnAllBundlesFinished; + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY)] = + &ServiceReverseStub::CmdIncrementalRestoreOnFileReady; } int32_t ServiceReverseStub::CmdBackupOnFileReady(MessageParcel &data, MessageParcel &reply) @@ -128,4 +152,70 @@ int32_t ServiceReverseStub::CmdRestoreOnFileReady(MessageParcel &data, MessagePa RestoreOnFileReady(bundleName, fileName, fd); return BError(BError::Codes::OK); } + +int32_t ServiceReverseStub::CmdIncrementalBackupOnFileReady(MessageParcel &data, MessageParcel &reply) +{ + auto bundleName = data.ReadString(); + auto fileName = data.ReadString(); + int fd = data.ReadFileDescriptor(); + int manifestFd = data.ReadFileDescriptor(); + IncrementalBackupOnFileReady(bundleName, fileName, fd, manifestFd); + return BError(BError::Codes::OK); +} + +int32_t ServiceReverseStub::CmdIncrementalBackupOnBundleStarted(MessageParcel &data, MessageParcel &reply) +{ + int32_t errCode = data.ReadInt32(); + auto bundleName = data.ReadString(); + IncrementalBackupOnBundleStarted(errCode, bundleName); + return BError(BError::Codes::OK); +} + +int32_t ServiceReverseStub::CmdIncrementalBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply) +{ + int32_t errCode = data.ReadInt32(); + auto bundleName = data.ReadString(); + IncrementalBackupOnBundleFinished(errCode, bundleName); + return BError(BError::Codes::OK); +} + +int32_t ServiceReverseStub::CmdIncrementalBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply) +{ + int32_t errCode = data.ReadInt32(); + IncrementalBackupOnAllBundlesFinished(errCode); + return BError(BError::Codes::OK); +} + +int32_t ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) +{ + int32_t errCode = data.ReadInt32(); + auto bundleName = data.ReadString(); + IncrementalRestoreOnBundleStarted(errCode, bundleName); + return BError(BError::Codes::OK); +} + +int32_t ServiceReverseStub::CmdIncrementalRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply) +{ + int32_t errCode = data.ReadInt32(); + auto bundleName = data.ReadString(); + IncrementalRestoreOnBundleFinished(errCode, bundleName); + return BError(BError::Codes::OK); +} + +int32_t ServiceReverseStub::CmdIncrementalRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply) +{ + int32_t errCode = data.ReadInt32(); + IncrementalRestoreOnAllBundlesFinished(errCode); + return BError(BError::Codes::OK); +} + +int32_t ServiceReverseStub::CmdIncrementalRestoreOnFileReady(MessageParcel &data, MessageParcel &reply) +{ + auto bundleName = data.ReadString(); + auto fileName = data.ReadString(); + int fd = data.ReadFileDescriptor(); + int manifestFd = data.ReadFileDescriptor(); + IncrementalRestoreOnFileReady(bundleName, fileName, fd, manifestFd); + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/interfaces/common/backup_sandbox.json b/interfaces/common/backup_sandbox.json new file mode 100644 index 0000000000000000000000000000000000000000..d4429ab4da687b56acefa5ce36915a48c3b4ca80 --- /dev/null +++ b/interfaces/common/backup_sandbox.json @@ -0,0 +1,34 @@ +{ + "mount-path-map" : [{ + "sandbox-path" : "/data/storage/el2/base/", + "src-path" : "/data/app/el2//base//" + }, { + "sandbox-path" : "/data/storage/el1/base/", + "src-path" : "/data/app/el1//base//" + }, { + "sandbox-path" : "/data/storage/el1/database/", + "src-path" : "/data/app/el1//database//" + }, { + "sandbox-path" : "/data/storage/el2/database/", + "src-path" : "/data/app/el2//database//" + }, { + "sandbox-path" : "/data/storage/el2/distributedfiles/", + "src-path" : "/mnt/hmdfs//account/device_view//data//" + }, { + "sandbox-path" : "/mnt/data/fuse/", + "src-path" : "/mnt/data//fuse/" + }, { + "sandbox-path" : "/storage/Users/currentUser/", + "src-path" : "/mnt/hmdfs//account/device_view//files/Docs/" + }, { + "sandbox-path" : "/storage/External/", + "src-path" : "/mnt/data/external/" + }, { + "sandbox-path" : "/storage/Share/", + "src-path" : "/data/service/el1/public/storage_daemon/share/public/" + }, { + "sandbox-path" : "/data/storage/el2/cloud/", + "src-path" : "/mnt/hmdfs//cloud/data//" + } + ] +} diff --git a/interfaces/common/include/sandbox_helper.h b/interfaces/common/include/sandbox_helper.h index d4ed5dbd3b096754e9fe203a0415e6a68319949a..c491182049cbdcbc3b03c0778a8b0c15cf6674e2 100644 --- a/interfaces/common/include/sandbox_helper.h +++ b/interfaces/common/include/sandbox_helper.h @@ -26,13 +26,17 @@ class SandboxHelper { private: static std::mutex mapMutex_; static std::unordered_map sandboxPathMap_; + static std::unordered_map backupSandboxPathMap_; static bool GetSandboxPathMap(); + static bool GetBackupSandboxPathMap(); public: static std::string Encode(const std::string &uri); static std::string Decode(const std::string &uri); static bool CheckValidPath(const std::string &filePath); static int32_t GetPhysicalPath(const std::string &fileUri, const std::string &userId, std::string &physicalPath); + static int32_t GetBackupPhysicalPath(const std::string &fileUri, const std::string &userId, + std::string &physicalPath); static bool IsValidPath(const std::string &path); }; } // namespace AppFileService diff --git a/interfaces/common/src/sandbox_helper.cpp b/interfaces/common/src/sandbox_helper.cpp index 140fb61e92a30718a408d1c3b09846d0417a2742..7d18b6796818c4bbf697ab0b5fa7167a96aced6f 100644 --- a/interfaces/common/src/sandbox_helper.cpp +++ b/interfaces/common/src/sandbox_helper.cpp @@ -35,6 +35,7 @@ namespace { const string SANDBOX_PATH_KEY = "sandbox-path"; const string MOUNT_PATH_MAP_KEY = "mount-path-map"; const string SANDBOX_JSON_FILE_PATH = "/etc/app_file_service/file_share_sandbox.json"; + const string BACKUP_SANDBOX_JSON_FILE_PATH = "/etc/app_file_service/backup_sandbox.json"; const std::string SHAER_PATH_HEAD = "/mnt/hmdfs/"; const std::string SHAER_PATH_MID = "/account/cloud_merge_view/files/"; const string FILE_MANAGER_URI_HEAD = "/storage/"; @@ -57,6 +58,7 @@ struct MediaUriInfo { }; std::unordered_map SandboxHelper::sandboxPathMap_; +std::unordered_map SandboxHelper::backupSandboxPathMap_; std::mutex SandboxHelper::mapMutex_; string SandboxHelper::Encode(const string &uri) @@ -159,6 +161,39 @@ bool SandboxHelper::GetSandboxPathMap() return true; } +bool SandboxHelper::GetBackupSandboxPathMap() +{ + lock_guard lock(mapMutex_); + if (backupSandboxPathMap_.size() > 0) { + return true; + } + + nlohmann::json jsonObj; + int ret = JsonUtils::GetJsonObjFromPath(jsonObj, BACKUP_SANDBOX_JSON_FILE_PATH); + if (ret != 0) { + LOGE("Get json object failed with %{public}d", ret); + return false; + } + + if (jsonObj.find(MOUNT_PATH_MAP_KEY) == jsonObj.end()) { + LOGE("Json object find mount path map failed"); + return false; + } + + nlohmann::json mountPathMap = jsonObj[MOUNT_PATH_MAP_KEY]; + for (size_t i = 0; i < mountPathMap.size(); i++) { + string srcPath = mountPathMap[i][PHYSICAL_PATH_KEY]; + string sandboxPath = mountPathMap[i][SANDBOX_PATH_KEY]; + backupSandboxPathMap_[sandboxPath] = srcPath; + } + + if (backupSandboxPathMap_.size() == 0) { + return false; + } + + return true; +} + static int32_t GetPathSuffix(const std::string &path, string &pathSuffix) { size_t pos = path.rfind('.'); @@ -323,6 +358,54 @@ int32_t SandboxHelper::GetPhysicalPath(const std::string &fileUri, const std::st return 0; } +int32_t SandboxHelper::GetBackupPhysicalPath(const std::string &fileUri, const std::string &userId, + std::string &physicalPath) +{ + Uri uri(fileUri); + string bundleName = uri.GetAuthority(); + if (bundleName == MEDIA) { + return GetMediaPhysicalPath(uri.GetPath(), userId, physicalPath); + } + + string sandboxPath = SandboxHelper::Decode(uri.GetPath()); + if ((sandboxPath.find(FILE_MANAGER_URI_HEAD) == 0 && bundleName != FILE_MANAGER_AUTHORITY) || + (sandboxPath.find(FUSE_URI_HEAD) == 0 && bundleName != DLP_MANAGER_BUNDLE_NAME)) { + return -EINVAL; + } + + if (!GetBackupSandboxPathMap()) { + LOGE("GetBackupSandboxPathMap failed"); + return -EINVAL; + } + + string lowerPathTail = ""; + string lowerPathHead = ""; + string::size_type curPrefixMatchLen = 0; + for (auto it = backupSandboxPathMap_.begin(); it != backupSandboxPathMap_.end(); it++) { + string sandboxPathPrefix = it->first; + string::size_type prefixMatchLen = sandboxPathPrefix.length(); + if (sandboxPath.length() >= prefixMatchLen) { + string sandboxPathTemp = sandboxPath.substr(0, prefixMatchLen); + if (sandboxPathTemp == sandboxPathPrefix && curPrefixMatchLen <= prefixMatchLen) { + curPrefixMatchLen = prefixMatchLen; + lowerPathHead = it->second; + lowerPathTail = sandboxPath.substr(prefixMatchLen); + } + } + } + + if (lowerPathHead == "") { + LOGE("lowerPathHead is invalid"); + return -EINVAL; + } + + string networkId = LOCAL; + GetNetworkIdFromUri(fileUri, networkId); + + physicalPath = GetLowerPath(lowerPathHead, lowerPathTail, userId, bundleName, networkId); + return 0; +} + bool SandboxHelper::IsValidPath(const std::string &path) { if (path.find("/./") != std::string::npos || diff --git a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn b/interfaces/inner_api/native/backup_kit_inner/BUILD.gn index 5d4dcbd28c4ef746e43e5a2c762d272637f4354e..02da6b9fda75e3c33bfe9bb545fc59767e9ff5a8 100644 --- a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn +++ b/interfaces/inner_api/native/backup_kit_inner/BUILD.gn @@ -43,9 +43,14 @@ ohos_shared_library("backup_kit_inner") { sources = [ "${path_backup}/frameworks/native/backup_kit_inner/src/b_file_info.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_data.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_backup.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_restore.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_proxy.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/service_proxy.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", diff --git a/interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h b/interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h index 7277da994b9f9fe3d73e476f00df3c7ba47c1254..dfe4e48a49e20e13097ed261f306304420466dce 100644 --- a/interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h +++ b/interfaces/inner_api/native/backup_kit_inner/backup_kit_inner.h @@ -16,6 +16,8 @@ #ifndef OHOS_FILEMGMT_BACKUP_BACKUP_KIT_INNER_H #define OHOS_FILEMGMT_BACKUP_BACKUP_KIT_INNER_H +#include "impl/b_incremental_backup_session.h" +#include "impl/b_incremental_restore_session.h" #include "impl/b_session_backup.h" #include "impl/b_session_restore.h" #include "impl/b_session_restore_async.h" diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h new file mode 100644 index 0000000000000000000000000000000000000000..c0805aa7915db042e2ff8dfe5edae0a1703fdce6 --- /dev/null +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_BACKUP_BACKUP_H +#define OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_BACKUP_BACKUP_H + +#include +#include +#include + +#include "b_file_info.h" +#include "b_incremental_data.h" +#include "errors.h" +#include "svc_death_recipient.h" +#include "unique_fd.h" + +namespace OHOS::FileManagement::Backup { +class BIncrementalBackupSession { +public: + struct Callbacks { + std::function onFileReady; // 当备份服务有文件待发送时执行的回调 + std::function onBundleStarted; // 当启动某个应用的备份流程结束时执行的回调函数 + std::function onBundleFinished; // 当某个应用的备份流程结束或意外中止时执行的回调函数 + std::function onAllBundlesFinished; // 当整个备份流程结束或意外中止时执行的回调函数 + std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + }; + +public: + /** + * @brief 获取一个用于控制备份流程的会话 + * + * @param callbacks 注册回调 + * @return std::unique_ptr 指向会话的智能指针。失败时为空指针 + */ + static std::unique_ptr Init(Callbacks callbacks); + + /** + * @brief 用于追加应用,现阶段仅支持在Start之前调用 + * + * @param bundlesToBackup 待备份的应用清单 + * @return ErrCode 规范错误码 + */ + ErrCode AppendBundles(std::vector bundlesToBackup); + + /** + * @brief 用于结束服务 + * + * @return ErrCode 规范错误码 + */ + ErrCode Release(); + + /** + * @brief 注册备份服务意外死亡时执行的回调函数 + * + * @param functor 回调函数 + */ + void RegisterBackupServiceDied(std::function functor); + +public: + ~BIncrementalBackupSession(); + +private: + sptr deathRecipient_; +}; +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_BACKUP_BACKUP_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_data.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_data.h new file mode 100644 index 0000000000000000000000000000000000000000..1c7a25c96b05c21d332de36eb2b4b7391e2726eb --- /dev/null +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_data.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_DATA_H +#define OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_DATA_H + +#include +#include + +#include "parcel.h" +#include "unique_fd.h" + +namespace OHOS::FileManagement::Backup { +struct BIncrementalData : public Parcelable { + std::string bundleName; + int64_t lastIncrementalTime; + int32_t manifestFd; + std::string backupParameters; + int32_t backupPriority; + + BIncrementalData() = default; + BIncrementalData(std::string name, int64_t nTime, int fd = -1, std::string parameters = "", int32_t priority = 0) + : bundleName(name), lastIncrementalTime(nTime), manifestFd(fd), backupParameters(parameters), + backupPriority(priority) + { + } + ~BIncrementalData() override = default; + + bool ReadFromParcel(Parcel &parcel); + bool Marshalling(Parcel &parcel) const override; + static BIncrementalData *Unmarshalling(Parcel &parcel); +}; +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_DATA_H 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 new file mode 100644 index 0000000000000000000000000000000000000000..53293d2d91bde12389de93739a6e9f171f1050b5 --- /dev/null +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_RESTORE_RESTORE_H +#define OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_RESTORE_RESTORE_H + +#include +#include +#include + +#include "b_file_info.h" +#include "b_incremental_data.h" +#include "errors.h" +#include "svc_death_recipient.h" +#include "unique_fd.h" + +namespace OHOS::FileManagement::Backup { +class BIncrementalRestoreSession { +public: + struct Callbacks { + std::function onFileReady; // 当备份服务有文件待发送时执行的回调 + std::function onBundleStarted; // 当启动某个应用的恢复流程结束时执行的回调函数 + std::function onBundleFinished; // 当某个应用的恢复流程结束或意外中止时执行的回调函数 + std::function onAllBundlesFinished; // 当整个恢复流程结束或意外中止时执行的回调函数 + std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + }; + +public: + /** + * @brief 获取一个用于控制恢复流程的会话 + * + * @param callbacks 注册的回调函数 + * @return std::unique_ptr 指向BRestoreSession的智能指针。失败时为空指针 + */ + static std::unique_ptr Init(Callbacks callbacks); + + /** + * @brief 通知备份服务文件内容已就绪 + * + * @param fileInfo 文件描述信息 + * @return ErrCode 规范错误码 + * @see GetFileHandle + */ + ErrCode PublishFile(BFileInfo fileInfo); + + /** + * @brief 请求恢复流程所需的真实文件 + * + * @param bundleName 应用名称 + * @param fileName 文件名称 + */ + ErrCode GetFileHandle(const std::string &bundleName, const std::string &fileName); + + /** + * @brief 用于追加应用,现阶段仅支持在Start之前调用 + * + * @param remoteCap 已打开的保存远端设备能力的Json文件。可使用GetLocalCapabilities方法获取 + * @param bundlesToRestore 待恢复的应用清单 + * @return ErrCode 规范错误码 + */ + ErrCode AppendBundles(UniqueFd remoteCap, std::vector bundlesToRestore); + + /** + * @brief 用于结束服务 + * + * @return ErrCode 规范错误码 + */ + ErrCode Release(); + + /** + * @brief 注册备份服务意外死亡时执行的回调函数 + * + * @param functor 回调函数 + */ + void RegisterBackupServiceDied(std::function functor); + +public: + ~BIncrementalRestoreSession(); + +private: + sptr deathRecipient_; +}; +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_B_INCREMENTAL_RESTORE_RESTORE_H \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h index 059e3b798a1f51788594ab6950b15beb40dc3fba..bed22250cff6f4f86eb5f9fa8d620f81c9bed638 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h @@ -67,6 +67,13 @@ public: */ ErrCode Start(); + /** + * @brief 用于结束服务 + * + * @return ErrCode 规范错误码 + */ + ErrCode Release(); + /** * @brief 注册备份服务意外死亡时执行的回调函数 * diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h index 4654a7bc52263d0f952b86f1121db65c5a31a895..14e730a215f8b6863926d4824fb78ef5bd4db299 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h @@ -85,6 +85,13 @@ public: */ ErrCode Start(); + /** + * @brief 用于结束服务 + * + * @return ErrCode 规范错误码 + */ + ErrCode Release(); + /** * @brief 注册备份服务意外死亡时执行的回调函数 * diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h index 8c4e949d2f3d003f0a39728bb538a195699ee0b3..2b6e0ddcce8a2dc9e717c503cfdb522aec405736 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h @@ -86,6 +86,13 @@ public: RestoreTypeEnum restoreType = RestoreTypeEnum::RESTORE_DATA_WAIT_SEND, int32_t userId = DEFAULT_INVAL_VALUE); + /** + * @brief 用于结束服务 + * + * @return ErrCode 规范错误码 + */ + ErrCode Release(); + public: explicit BSessionRestoreAsync(Callbacks callbacks) : callbacks_(callbacks) {}; ~BSessionRestoreAsync(); diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h index ac9e5c09d6f4ed22293d823251031db80ad6ad99..b2604948cf6c95b3f4a50b70807a2b146cd57806 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h @@ -32,6 +32,10 @@ public: virtual ErrCode HandleBackup() = 0; virtual ErrCode PublishFile(const std::string &fileName) = 0; virtual ErrCode HandleRestore() = 0; + virtual ErrCode GetIncrementalFileHandle(const std::string &fileName) = 0; + virtual ErrCode PublishIncrementalFile(const std::string &fileName) = 0; + virtual ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) = 0; + virtual std::tuple GetIncrementalBackupFileHandle() = 0; }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h index 50a8be51a62a99fe311d412127510651e11c1077..e9e63c21e688a892e356cb9826993c9c39e838cb 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h @@ -24,6 +24,10 @@ enum class IExtensionInterfaceCode { CMD_PUBLISH_FILE, CMD_HANDLE_BACKUP, CMD_HANDLE_RESTORE, + CMD_GET_INCREMENTAL_FILE_HANDLE, + CMD_PUBLISH_INCREMENTAL_FILE, + CMD_HANDLE_INCREMENTAL_BACKUP, + CMD_GET_INCREMENTAL_BACKUP_FILE_HANDLE, }; } // namespace OHOS::FileManagement::Backup 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 e8bb2202acbb022b7e11b901755d83a135fb0c32..869a3ca98ab4eb197227bd8c2d7037dd65f5c933 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 @@ -22,6 +22,7 @@ #include #include "b_file_info.h" +#include "b_incremental_data.h" #include "i_service_ipc_interface_code.h" #include "i_service_reverse.h" #include "iremote_broker.h" @@ -50,6 +51,15 @@ public: int32_t userId = DEFAULT_INVAL_VALUE) = 0; virtual ErrCode AppendBundlesBackupSession(const std::vector &bundleNames) = 0; virtual ErrCode Finish() = 0; + virtual ErrCode Release() = 0; + virtual UniqueFd GetLocalCapabilitiesIncremental(const std::vector &bundleNames) = 0; + virtual ErrCode InitIncrementalBackupSession(sptr remote) = 0; + virtual ErrCode AppendBundlesIncrementalBackupSession(const std::vector &bundlesToBackup) = 0; + + virtual ErrCode PublishIncrementalFile(const BFileInfo &fileInfo) = 0; + virtual ErrCode AppIncrementalFileReady(const std::string &fileName, UniqueFd fd, UniqueFd manifestFd) = 0; + virtual ErrCode AppIncrementalDone(ErrCode errCode) = 0; + virtual ErrCode GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Backup.IService") }; 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 7979210434bd18851135f9f6bc7760b3d0d89a4a..0e224a108318800f3bd59b1951c33d0bf0f0b16c 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 @@ -30,6 +30,14 @@ enum class IServiceInterfaceCode { SERVICE_CMD_APPEND_BUNDLES_RESTORE_SESSION, SERVICE_CMD_APPEND_BUNDLES_BACKUP_SESSION, SERVICE_CMD_FINISH, + SERVICE_CMD_RELSEASE_SESSION, + SERVICE_CMD_GET_LOCAL_CAPABILITIES_INCREMENTAL, + SERVICE_CMD_INIT_INCREMENTAL_BACKUP_SESSION, + SERVICE_CMD_APPEND_BUNDLES_INCREMENTAL_BACKUP_SESSION, + SERVICE_CMD_PUBLISH_INCREMENTAL_FILE, + SERVICE_CMD_APP_INCREMENTAL_FILE_READY, + SERVICE_CMD_APP_INCREMENTAL_DONE, + SERVICE_CMD_GET_INCREMENTAL_FILE_NAME, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h index 0d0f9a7fe709cb2bc30f9a2e057b0e444d507784..0f959c9c05b5f05d2858781993ab80bf94e170c6 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h @@ -41,6 +41,19 @@ public: virtual void RestoreOnAllBundlesFinished(int32_t errCode) = 0; virtual void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) = 0; + virtual void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd) = 0; + virtual void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) = 0; + virtual void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; + virtual void IncrementalBackupOnAllBundlesFinished(int32_t errCode) = 0; + + virtual void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; + virtual void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) = 0; + virtual void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) = 0; + virtual void IncrementalRestoreOnFileReady(std::string bundleName, + std::string fileName, + int fd, + int manifestFd) = 0; + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileManagement.Backup.IServiceReverse") }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h index 5fc63b67ecb9c67535e6bcd870de58d82a731016..b99203b225a4218991af6f6dfeb2ddc6ce3073dc 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h @@ -27,6 +27,14 @@ enum class IServiceReverseInterfaceCode { SERVICER_RESTORE_ON_SUB_TASK_FINISHED, SERVICER_RESTORE_ON_TASK_FINISHED, SERVICER_RESTORE_ON_FILE_READY, + SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY, + SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_STARTED, + SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_FINISHED, + SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED, + SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED, + SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED, + SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED, + SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY, }; } // namespace OHOS::FileManagement::Backup 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 5273921a2ecc0c5dcf88df6d38cac1b48100418f..67a93868acdf7c02dcadc1f85eaaebcd0bd9e75c 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 @@ -42,12 +42,23 @@ public: int32_t userId = DEFAULT_INVAL_VALUE) override; ErrCode AppendBundlesBackupSession(const std::vector &bundleNames) override; ErrCode Finish() override; + ErrCode Release() override; + UniqueFd GetLocalCapabilitiesIncremental(const std::vector &bundleNames) override; + ErrCode InitIncrementalBackupSession(sptr remote) override; + ErrCode AppendBundlesIncrementalBackupSession(const std::vector &bundlesToBackup) override; + + ErrCode PublishIncrementalFile(const BFileInfo &fileInfo) override; + ErrCode AppIncrementalFileReady(const std::string &fileName, UniqueFd fd, UniqueFd manifestFd) override; + ErrCode AppIncrementalDone(ErrCode errCode) override; + ErrCode GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) override; public: explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} ~ServiceProxy() override {} public: + template + bool WriteParcelableVector(const std::vector &parcelableVector, Parcel &data); static sptr GetInstance(); static void InvaildInstance(); diff --git a/interfaces/innerkits/native/BUILD.gn b/interfaces/innerkits/native/BUILD.gn index 7fa9ffad34b919c4500cd1607b441f7658526313..069d1cda033188a83ea6d8bb9c16b71ba80b6100 100644 --- a/interfaces/innerkits/native/BUILD.gn +++ b/interfaces/innerkits/native/BUILD.gn @@ -96,6 +96,13 @@ ohos_prebuilt_etc("file_share_sandbox.json") { module_install_dir = "etc/app_file_service" } +ohos_prebuilt_etc("backup_sandbox.json") { + source = "../../common/backup_sandbox.json" + part_name = "app_file_service" + subsystem_name = "filemanagement" + module_install_dir = "etc/app_file_service" +} + config("remote_file_share_config") { visibility = [ ":*" ] include_dirs = [ @@ -176,5 +183,8 @@ group("app_file_service_native") { } group("etc_files") { - deps = [ ":file_share_sandbox.json" ] + deps = [ + ":backup_sandbox.json", + ":file_share_sandbox.json", + ] } diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index ee1a7758bfeacf36173dac4576abcf81e97d47f1..5feaca179eda1f315ab3f6ac9b41d28b05f9ca88 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -149,6 +149,7 @@ ohos_shared_library("backup") { "${path_backup_js}/backup/module.cpp", "${path_backup_js}/backup/prop_n_exporter.cpp", "${path_backup_js}/backup/session_backup_n_exporter.cpp", + "${path_backup_js}/backup/session_incremental_backup_n_exporter.cpp", "${path_backup_js}/backup/session_restore_n_exporter.cpp", ] diff --git a/interfaces/kits/js/backup/incremental_backup_data.h b/interfaces/kits/js/backup/incremental_backup_data.h new file mode 100644 index 0000000000000000000000000000000000000000..5cb08c819be4a685a9ed1500952accc82e756716 --- /dev/null +++ b/interfaces/kits/js/backup/incremental_backup_data.h @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INTERFACES_KITS_JS_SRC_MOD_BACKUP_INCREMENTAL_BACKUP_DATA_H +#define INTERFACES_KITS_JS_SRC_MOD_BACKUP_INCREMENTAL_BACKUP_DATA_H + +#include +#include +#include +#include + +#include "filemgmt_libn.h" + +namespace OHOS::FileManagement::Backup { +struct IncrementalBackupTime +{ + IncrementalBackupTime(const LibN::NVal &data) { + LibN::NVal name = data.GetProp("bundleName"); + if (name.val_ != nullptr) { + auto [succ, str, ignore] = name.ToUTF8String(); + if (succ) { + bundleName = std::string(str.get()); + } + } + + LibN::NVal time = data.GetProp("lastIncrementalTime"); + if (time.val_ != nullptr) { + auto [succ, tm] = time.ToInt32(); + if (succ) { + lastIncrementalTime = tm; + } + } + } + std::string bundleName = ""; + int64_t lastIncrementalTime = 0; +}; + +struct FileManifestData +{ + FileManifestData(const LibN::NVal &data) { + LibN::NVal fd = data.GetProp("manifestFd"); + if (fd.val_ != nullptr) { + auto [succ, tmp] = fd.ToInt32(); + if (succ) { + manifestFd = tmp; + } + } + } + int32_t manifestFd = -1; +}; + +struct BackupParams +{ + BackupParams(const LibN::NVal &data) { + LibN::NVal para = data.GetProp("parameters"); + if (para.val_ != nullptr) { + auto [succ, str, ignore] = para.ToUTF8String(); + if (succ) { + parameters = std::string(str.get()); + } + } + } + std::string parameters = ""; +}; + +struct BackupPriority +{ + BackupPriority(const LibN::NVal &data) { + LibN::NVal pr = data.GetProp("priority"); + if (pr.val_ != nullptr) { + auto [succ, tmp] = pr.ToInt32(); + if (succ) { + priority = tmp; + } + } + } + int32_t priority = -1; +}; + +struct IncrementalBackupData : public IncrementalBackupTime, public FileManifestData, public BackupParams, public BackupPriority +{ + IncrementalBackupData(const LibN::NVal &data) + : IncrementalBackupTime(data), + FileManifestData(data), + BackupParams(data), + BackupPriority(data) {}; +}; +} // namespace OHOS::FileManagement::Backup +#endif // INTERFACES_KITS_JS_SRC_MOD_BACKUP_INCREMENTAL_BACKUP_DATA_H \ No newline at end of file diff --git a/interfaces/kits/js/backup/local_capabilities.cpp b/interfaces/kits/js/backup/local_capabilities.cpp index d3b9e9eb3b5de4c610dcbfc1d6ac5b7e8fa4fdc2..1ab71842c4b557910dafbbb949abe3143dee4928 100644 --- a/interfaces/kits/js/backup/local_capabilities.cpp +++ b/interfaces/kits/js/backup/local_capabilities.cpp @@ -18,27 +18,24 @@ #include "filemgmt_libn.h" #include "service_proxy.h" +#include "b_incremental_data.h" +#include "incremental_backup_data.h" + namespace OHOS::FileManagement::Backup { using namespace std; using namespace LibN; -napi_value LocalCapabilities::Async(napi_env env, napi_callback_info info) +static napi_value AsyncCallback(napi_env env, const NFuncArg& funcArg) { - HILOGI("called LocalCapabilities::Async begin"); - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { - HILOGE("Number of arguments unmatched"); - NError(EINVAL).ThrowErr(env); - return nullptr; - } + HILOGI("called LocalCapabilities::AsyncCallback begin"); auto fd = make_shared(); auto cbExec = [fd]() -> NError { - HILOGI("called LocalCapabilities::Async cbExec"); + HILOGI("called LocalCapabilities::AsyncCallback cbExec"); ServiceProxy::InvaildInstance(); auto proxy = ServiceProxy::GetInstance(); if (!proxy) { - HILOGI("called LocalCapabilities::Async cbExec, failed to get proxy"); + HILOGI("called LocalCapabilities::AsyncCallback cbExec, failed to get proxy"); return NError(errno); } *fd = proxy->GetLocalCapabilities(); @@ -63,4 +60,83 @@ napi_value LocalCapabilities::Async(napi_env env, napi_callback_info info) return NAsyncWorkCallback(env, thisVar, cb).Schedule(PROCEDURE_LOCALCAPABILITIES_NAME, cbExec, cbCompl).val_; } } + +static std::vector ParseDataList(napi_env env, const napi_value& value) +{ + uint32_t size = 0; + napi_status status = napi_get_array_length(env, value, &size); + if (status != napi_ok || size == 0) { + HILOGI("Get array length failed or array length is zero!"); + return {}; + } + + napi_value result; + std::vector backupData; + for (uint32_t i = 0; i < size; i++) { + status = napi_get_element(env, value, i, &result); + if (status != napi_ok) { + HILOGE("Get element failed! index is :%{public}u", i); + } else { + IncrementalBackupData data(NVal(env, result)); + backupData.emplace_back(data.bundleName, + data.lastIncrementalTime, + data.manifestFd, + data.parameters, + data.priority); + } + } + return backupData; +} + +static napi_value AsyncDataList(napi_env env, const NFuncArg& funcArg) +{ + HILOGI("called LocalCapabilities::AsyncDataList begin"); + + std::vector backupData = ParseDataList(env, funcArg[NARG_POS::FIRST]); + auto fd = make_shared(); + auto cbExec = [fd, backupData { move(backupData) }]() -> NError { + HILOGI("called LocalCapabilities::AsyncDataList cbExec"); + ServiceProxy::InvaildInstance(); + auto proxy = ServiceProxy::GetInstance(); + if (!proxy) { + HILOGI("called LocalCapabilities::AsyncDataList cbExec, failed to get proxy"); + return NError(errno); + } + *fd = proxy->GetLocalCapabilitiesIncremental(backupData); + return NError(ERRNO_NOERR); + }; + auto cbCompl = [fd](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + NVal obj = NVal::CreateObject(env); + obj.AddProp({NVal::DeclareNapiProperty("fd", NVal::CreateInt32(env, fd->Release()).val_)}); + return {obj}; + }; + + HILOGI("called LocalCapabilities::Async::promise"); + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(PROCEDURE_LOCALCAPABILITIES_NAME, cbExec, cbCompl).val_; +} + +napi_value LocalCapabilities::Async(napi_env env, napi_callback_info info) +{ + HILOGI("called LocalCapabilities::Async begin"); + NFuncArg funcArg(env, info); + if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + if (funcArg.GetArgc() == 1) { + bool result = 0; + napi_status status = napi_is_array(env, funcArg[NARG_POS::FIRST], &result); + if (status == napi_ok && result) { + return AsyncDataList(env, funcArg); + } + } + + return AsyncCallback(env, funcArg); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/interfaces/kits/js/backup/module.cpp b/interfaces/kits/js/backup/module.cpp index 59f88491b7e918250b1709822f054d4fc5562803..3fa55d58548965fdeb1f33328ee8f36028d9f53c 100644 --- a/interfaces/kits/js/backup/module.cpp +++ b/interfaces/kits/js/backup/module.cpp @@ -21,6 +21,7 @@ #include "prop_n_exporter.h" #include "session_backup_n_exporter.h" #include "session_restore_n_exporter.h" +#include "session_incremental_backup_n_exporter.h" namespace OHOS::FileManagement::Backup { using namespace std; @@ -32,6 +33,7 @@ static napi_value Export(napi_env env, napi_value exports) products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); products.emplace_back(make_unique(env, exports)); + products.emplace_back(make_unique(env, exports)); for (auto &&product : products) { if (!product->Export()) { HILOGE("INNER BUG. Failed to export class %{public}s for module file.backup", diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_backup_n_exporter.cpp index 713527c7fa679df7dc11f9224d37e6bbd5a28ac6..bc624935c7463aec5388b323c2348661b48f3baf 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_backup_n_exporter.cpp @@ -289,10 +289,46 @@ napi_value SessionBackupNExporter::AppendBundles(napi_env env, napi_callback_inf } } +napi_value SessionBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionBackup::Release begin"); + NFuncArg funcArg(env, cbinfo); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + auto backupEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(backupEntity && backupEntity->session)) { + HILOGE("Failed to get backupSession entity."); + NError(EPERM).ThrowErr(env); + return nullptr; + } + + auto cbExec = [session {backupEntity->session.get()}]() -> NError { + if (!session) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "backup session is nullptr").GetCode()); + } + return NError(session->Release()); + }; + auto cbCompl = [](napi_env env, NError err) -> NVal { + return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); + }; + + HILOGE("Called SessionBackup::Release end."); + + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; +} + bool SessionBackupNExporter::Export() { HILOGI("called SessionBackupNExporter::Export begin"); - vector props = {NVal::DeclareNapiFunction("appendBundles", AppendBundles)}; + vector props = { + NVal::DeclareNapiFunction("appendBundles", AppendBundles), + NVal::DeclareNapiFunction("release", Release), + }; auto [succ, classValue] = NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); if (!succ) { diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.h b/interfaces/kits/js/backup/session_backup_n_exporter.h index afa3c96b2fe3306c795f9795f65250e48bca747f..75dd410b77dc540d1084ad24784373586d2c1981 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.h +++ b/interfaces/kits/js/backup/session_backup_n_exporter.h @@ -27,6 +27,7 @@ public: static napi_value Constructor(napi_env env, napi_callback_info cbinfo); static napi_value AppendBundles(napi_env env, napi_callback_info cbinfo); + static napi_value Release(napi_env env, napi_callback_info cbinfo); SessionBackupNExporter(napi_env env, napi_value exports); ~SessionBackupNExporter() override; diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ef3f451a815a63d89f824e96d7bd5695a66c951 --- /dev/null +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "session_incremental_backup_n_exporter.h" + +#include +#include + +#include "b_error/b_error.h" +#include "b_filesystem/b_file.h" +#include "b_resources/b_constants.h" +#include "b_incremental_backup_session.h" +#include "backup_kit_inner.h" +#include "directory_ex.h" +#include "filemgmt_libhilog.h" +#include "general_callbacks.h" +#include "incremental_backup_data.h" +#include "b_incremental_data.h" +#include "service_proxy.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; +using namespace LibN; + +struct BackupEntity { + unique_ptr session; + shared_ptr callbacks; +}; + +static void OnFileReady(weak_ptr pCallbacks, const BFileInfo &fileInfo, UniqueFd fd, UniqueFd manifestFd) +{ + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function onFileReady has already been released"); + return; + } + if (!bool(callbacks->onFileReady)) { + HILOGI("callback function onFileReady is undefined"); + return; + } + + auto cbCompl = [bundleName {fileInfo.owner}, fileName {fileInfo.fileName}, + fd {make_shared(fd.Release())}, + manifestFd {make_shared(manifestFd.Release())}](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + NVal obj = NVal::CreateObject(env); + obj.AddProp({NVal::DeclareNapiProperty("bundleName", NVal::CreateUTF8String(env, bundleName).val_), + NVal::DeclareNapiProperty("uri", NVal::CreateUTF8String(env, fileName).val_), + NVal::DeclareNapiProperty("fd", NVal::CreateInt32(env, fd->Release()).val_), + NVal::DeclareNapiProperty("manifestFd", NVal::CreateInt32(env, manifestFd->Release()).val_)}); + + return {obj}; + }; + + callbacks->onFileReady.ThreadSafeSchedule(cbCompl); +} + +static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, const BundleName name) +{ + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function onBundleBegin has already been released"); + return; + } + if (!bool(callbacks->onBundleBegin)) { + HILOGI("callback function onBundleBegin is undefined"); + return; + } + + auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + NVal bundleName = NVal::CreateUTF8String(env, name); + if (!err && errCode == 0) { + return bundleName; + } + + NVal res; + if (err) { + res = NVal {env, err.GetNapiErr(env)}; + } else { + res = NVal {env, NError(errCode).GetNapiErr(env)}; + } + napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); + if (status != napi_ok) { + HILOGE("Failed to set data property, status %{public}d, bundleName %{public}s", status, name.c_str()); + } + + return res; + }; + + callbacks->onBundleBegin.ThreadSafeSchedule(cbCompl); +} + +static void onBundleEnd(weak_ptr pCallbacks, ErrCode err, const BundleName name) +{ + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function onBundleEnd has already been released"); + return; + } + if (!bool(callbacks->onBundleEnd)) { + HILOGI("callback function onBundleEnd is undefined"); + return; + } + + auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + NVal bundleName = NVal::CreateUTF8String(env, name); + if (!err && errCode == 0) { + return bundleName; + } + + NVal res; + if (err) { + res = NVal {env, err.GetNapiErr(env)}; + } else { + res = NVal {env, NError(errCode).GetNapiErr(env)}; + } + napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); + if (status != napi_ok) { + HILOGE("Failed to set data property, status %{public}d, bundleName %{public}s", status, name.c_str()); + } + + return res; + }; + + callbacks->onBundleEnd.ThreadSafeSchedule(cbCompl); +} + +static void onAllBundlesEnd(weak_ptr pCallbacks, ErrCode err) +{ + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function onAllBundlesEnd has already been released"); + return; + } + if (!bool(callbacks->onAllBundlesEnd)) { + HILOGI("callback function onAllBundlesEnd is undefined"); + return; + } + + auto cbCompl = [errCode {err}](napi_env env, NError err) -> NVal { + if (!err && errCode == 0) { + return NVal::CreateUndefined(env); + } + + NVal res; + if (err) { + res = NVal {env, err.GetNapiErr(env)}; + } else { + res = NVal {env, NError(errCode).GetNapiErr(env)}; + } + + return res; + }; + + callbacks->onAllBundlesEnd.ThreadSafeSchedule(cbCompl); +} + +static void OnBackupServiceDied(weak_ptr pCallbacks) +{ + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("js callback function onBackupServiceDied has already been released"); + return; + } + if (!bool(callbacks->onBackupServiceDied)) { + HILOGI("callback function onBackupServiceDied is undefined"); + return; + } + + auto cbCompl = [](napi_env env, NError err) -> NVal { + return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); + }; + + callbacks->onBackupServiceDied.ThreadSafeSchedule(cbCompl); +} + +napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionIncrementalBackup::Constructor begin"); + NFuncArg funcArg(env, cbinfo); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + NVal callbacks(env, funcArg[NARG_POS::FIRST]); + if (!callbacks.TypeIs(napi_object)) { + HILOGE("First argument is not an object."); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + NVal ptr(env, funcArg.GetThisVar()); + auto backupEntity = std::make_unique(); + backupEntity->callbacks = make_shared(env, ptr, callbacks); + backupEntity->session = BIncrementalBackupSession::Init(BIncrementalBackupSession::Callbacks { + .onFileReady = bind(OnFileReady, backupEntity->callbacks, placeholders::_1, placeholders::_2, placeholders::_3), + .onBundleStarted = bind(onBundleBegin, backupEntity->callbacks, placeholders::_1, placeholders::_2), + .onBundleFinished = bind(onBundleEnd, backupEntity->callbacks, placeholders::_1, placeholders::_2), + .onAllBundlesFinished = bind(onAllBundlesEnd, backupEntity->callbacks, placeholders::_1), + .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks)}); + if (!backupEntity->session) { + NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init backup").GetCode()).ThrowErr(env); + return nullptr; + } + if (!NClass::SetEntityFor(env, funcArg.GetThisVar(), move(backupEntity))) { + HILOGE("Failed to set BackupEntity entity"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + HILOGI("called SessionIncrementalBackup::Constructor end"); + return funcArg.GetThisVar(); +} + +static std::vector ParseDataList(napi_env env, const napi_value& value) +{ + uint32_t size = 0; + napi_status status = napi_get_array_length(env, value, &size); + if (status != napi_ok || size == 0) { + HILOGI("Get array length failed or array length is zero!"); + return {}; + } + + napi_value result; + std::vector backupData; + for (uint32_t i = 0; i < size; i++) { + status = napi_get_element(env, value, i, &result); + if (status != napi_ok) { + HILOGE("Get element failed! index is :%{public}u", i); + } else { + IncrementalBackupData data(NVal(env, result)); + backupData.emplace_back(data.bundleName, + data.lastIncrementalTime, + data.manifestFd, + data.parameters, + data.priority); + } + } + return backupData; +} + +napi_value SessionIncrementalBackupNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionIncrementalBackup::AppendBundles begin"); + NFuncArg funcArg(env, cbinfo); + if (!funcArg.InitArgs(NARG_CNT::ONE)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + auto bundles = ParseDataList(env, funcArg[NARG_POS::FIRST]); + + auto backupEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(backupEntity && backupEntity->session)) { + HILOGE("Failed to get backupSession entity."); + NError(EPERM).ThrowErr(env); + return nullptr; + } + + auto cbExec = [session {backupEntity->session.get()}, bundles { move(bundles) }]() -> NError { + if (!session) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "backup session is nullptr").GetCode()); + } + return NError(session->AppendBundles(bundles)); + }; + auto cbCompl = [](napi_env env, NError err) -> NVal { + return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); + }; + + HILOGE("Called SessionIncrementalBackup::AppendBundles end."); + + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; +} + +napi_value SessionIncrementalBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionIncrementalBackup::Release begin"); + NFuncArg funcArg(env, cbinfo); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + auto backupEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(backupEntity && backupEntity->session)) { + HILOGE("Failed to get backupSession entity."); + NError(EPERM).ThrowErr(env); + return nullptr; + } + + auto cbExec = [session {backupEntity->session.get()}]() -> NError { + if (!session) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "backup session is nullptr").GetCode()); + } + return NError(session->Release()); + }; + auto cbCompl = [](napi_env env, NError err) -> NVal { + return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); + }; + + HILOGE("Called SessionIncrementalBackup::Release end."); + + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; +} + +bool SessionIncrementalBackupNExporter::Export() +{ + HILOGI("called SessionIncrementalBackupNExporter::Export begin"); + vector props = { + NVal::DeclareNapiFunction("appendBundles", AppendBundles), + NVal::DeclareNapiFunction("release", Release), + }; + + auto [succ, classValue] = NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); + if (!succ) { + HILOGE("Failed to define class"); + NError(EIO).ThrowErr(exports_.env_); + return false; + } + succ = NClass::SaveClass(exports_.env_, className, classValue); + if (!succ) { + HILOGE("Failed to save class"); + NError(EIO).ThrowErr(exports_.env_); + return false; + } + + HILOGI("called SessionIncrementalBackupNExporter::Export end"); + return exports_.AddProp(className, classValue); +} + +string SessionIncrementalBackupNExporter::GetClassName() +{ + return SessionIncrementalBackupNExporter::className; +} + +SessionIncrementalBackupNExporter::SessionIncrementalBackupNExporter(napi_env env, napi_value exports) + : NExporter(env, exports) {} + +SessionIncrementalBackupNExporter::~SessionIncrementalBackupNExporter() {} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.h b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.h new file mode 100644 index 0000000000000000000000000000000000000000..47546568964df39b71fc89bc34d32f92788dfee5 --- /dev/null +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef INTERFACES_KITS_JS_SRC_MOD_BACKUP_PROPERTIES_SESSION_INCREMENTAL_BACKUP_N_EXPORTER_H +#define INTERFACES_KITS_JS_SRC_MOD_BACKUP_PROPERTIES_SESSION_INCREMENTAL_BACKUP_N_EXPORTER_H + +#include "n_exporter.h" + +namespace OHOS::FileManagement::Backup { +class SessionIncrementalBackupNExporter final : public LibN::NExporter { +public: + inline static const std::string className = "IncrementalBackupSession"; + + bool Export() override; + std::string GetClassName() override; + + static napi_value Constructor(napi_env env, napi_callback_info cbinfo); + static napi_value AppendBundles(napi_env env, napi_callback_info cbinfo); + static napi_value Release(napi_env env, napi_callback_info cbinfo); + + SessionIncrementalBackupNExporter(napi_env env, napi_value exports); + ~SessionIncrementalBackupNExporter() override; +}; +} // namespace OHOS::FileManagement::Backup +#endif // INTERFACES_KITS_JS_SRC_MOD_BACKUP_PROPERTIES_SESSION_INCREMENTAL_BACKUP_N_EXPORTER_H \ No newline at end of file diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index 53d9c0df0e658b8f49ab09b5680a3bbf161c7762..51e64b89429b3a61ce6830a49b550c3c73d10ceb 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -20,9 +20,11 @@ #include "b_error/b_error.h" #include "b_filesystem/b_dir.h" #include "b_filesystem/b_file.h" +#include "b_incremental_restore_session.h" #include "b_resources/b_constants.h" #include "b_session_restore.h" #include "backup_kit_inner.h" +#include "b_ohos/startup/backup_para.h" #include "filemgmt_libhilog.h" #include "general_callbacks.h" #include "service_proxy.h" @@ -32,11 +34,12 @@ using namespace std; using namespace LibN; struct RestoreEntity { - unique_ptr session; + unique_ptr sessionWhole; + unique_ptr sessionSheet; shared_ptr callbacks; }; -static void OnFileReady(weak_ptr pCallbacks, const BFileInfo &fileInfo, UniqueFd fd) +static void OnFileReadyWhole(weak_ptr pCallbacks, const BFileInfo &fileInfo, UniqueFd fd) { if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); @@ -68,6 +71,44 @@ static void OnFileReady(weak_ptr pCallbacks, const BFileInfo & callbacks->onFileReady.ThreadSafeSchedule(cbCompl); } +static void OnFileReadySheet(weak_ptr pCallbacks, + const BFileInfo &fileInfo, + UniqueFd fd, + UniqueFd manifestFd) +{ + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function onFileReady has already been released"); + return; + } + if (!bool(callbacks->onFileReady)) { + HILOGI("callback function onFileReady is undefined"); + return; + } + + auto cbCompl = [bundleName {fileInfo.owner}, + fileName {fileInfo.fileName}, + fd {make_shared(fd.Release())}, + manifestFd {make_shared(manifestFd.Release())}](napi_env env, NError err) -> NVal { + if (err) { + return {env, err.GetNapiErr(env)}; + } + NVal obj = NVal::CreateObject(env); + obj.AddProp({NVal::DeclareNapiProperty("bundleName", NVal::CreateUTF8String(env, bundleName).val_), + NVal::DeclareNapiProperty("uri", NVal::CreateUTF8String(env, fileName).val_), + NVal::DeclareNapiProperty("fd", NVal::CreateInt32(env, fd->Release()).val_), + NVal::DeclareNapiProperty("manifestFd", NVal::CreateInt32(env, manifestFd->Release()).val_)}); + + return {obj}; + }; + + callbacks->onFileReady.ThreadSafeSchedule(cbCompl); +} + static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, const BundleName name) { if (pCallbacks.expired()) { @@ -221,15 +262,28 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info } NVal ptr(env, funcArg.GetThisVar()); + bool bSheet = BackupPara().GetBackupOverrideIncrementalRestore(); auto restoreEntity = std::make_unique(); restoreEntity->callbacks = make_shared(env, ptr, callbacks); - restoreEntity->session = BSessionRestore::Init(BSessionRestore::Callbacks { - .onFileReady = bind(OnFileReady, restoreEntity->callbacks, placeholders::_1, placeholders::_2), - .onBundleStarted = bind(onBundleBegin, restoreEntity->callbacks, placeholders::_1, placeholders::_2), - .onBundleFinished = bind(onBundleEnd, restoreEntity->callbacks, placeholders::_1, placeholders::_2), - .onAllBundlesFinished = bind(onAllBundlesEnd, restoreEntity->callbacks, placeholders::_1), - .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks)}); - if (!restoreEntity->session) { + if (bSheet) { + restoreEntity->sessionWhole = nullptr; + restoreEntity->sessionSheet = BIncrementalRestoreSession::Init(BIncrementalRestoreSession::Callbacks { + .onFileReady = + bind(OnFileReadySheet, restoreEntity->callbacks, placeholders::_1, placeholders::_2, placeholders::_3), + .onBundleStarted = bind(onBundleBegin, restoreEntity->callbacks, placeholders::_1, placeholders::_2), + .onBundleFinished = bind(onBundleEnd, restoreEntity->callbacks, placeholders::_1, placeholders::_2), + .onAllBundlesFinished = bind(onAllBundlesEnd, restoreEntity->callbacks, placeholders::_1), + .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks)}); + } else { + restoreEntity->sessionSheet = nullptr; + restoreEntity->sessionWhole = BSessionRestore::Init(BSessionRestore::Callbacks { + .onFileReady = bind(OnFileReadyWhole, restoreEntity->callbacks, placeholders::_1, placeholders::_2), + .onBundleStarted = bind(onBundleBegin, restoreEntity->callbacks, placeholders::_1, placeholders::_2), + .onBundleFinished = bind(onBundleEnd, restoreEntity->callbacks, placeholders::_1, placeholders::_2), + .onAllBundlesFinished = bind(onAllBundlesEnd, restoreEntity->callbacks, placeholders::_1), + .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks)}); + } + if (!restoreEntity->sessionWhole && !restoreEntity->sessionSheet) { NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init restore").GetCode()).ThrowErr(env); return nullptr; } @@ -270,17 +324,20 @@ napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_in } auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!(restoreEntity && restoreEntity->session)) { + if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(EPERM).ThrowErr(env); return nullptr; } - auto cbExec = [session {restoreEntity->session.get()}, fd {fd}, bundles {bundles}]() -> NError { - if (!session) { + auto cbExec = [entity {restoreEntity}, fd {fd}, bundles {bundles}]() -> NError { + if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } - return NError(session->AppendBundles(UniqueFd(fd), bundles)); + if (entity->sessionWhole) { + return NError(entity->sessionWhole->AppendBundles(UniqueFd(fd), bundles)); + } + return NError(entity->sessionSheet->AppendBundles(UniqueFd(fd), bundles)); }; auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); @@ -343,19 +400,22 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info } auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!(restoreEntity && restoreEntity->session)) { + if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(EPERM).ThrowErr(env); return nullptr; } - auto cbExec = [session {restoreEntity->session.get()}, bundleName {string(bundleName.get())}, - fileName {string(fileName.get())}]() -> NError { - if (!session) { + auto cbExec = [entity {restoreEntity}, bundleName {string(bundleName.get())}, + fileName {string(fileName.get())}]() -> NError { + if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } BFileInfo fileInfo(bundleName, fileName, 0); - return NError(session->PublishFile(fileInfo)); + if (entity->sessionWhole) { + return NError(entity->sessionWhole->PublishFile(fileInfo)); + } + return NError(entity->sessionSheet->PublishFile(fileInfo)); }; auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); @@ -397,20 +457,23 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in } auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!(restoreEntity && restoreEntity->session)) { + if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(EPERM).ThrowErr(env); return nullptr; } - auto cbExec = [session {restoreEntity->session.get()}, bundleName {string(bundleName.get())}, - fileName {string(fileName.get())}]() -> NError { - if (!session) { + auto cbExec = [entity {restoreEntity}, bundleName {string(bundleName.get())}, + fileName {string(fileName.get())}]() -> NError { + if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } string bundle = bundleName; string file = fileName; - return NError(session->GetFileHandle(bundle, file)); + if (entity->sessionWhole) { + return NError(entity->sessionWhole->GetFileHandle(bundle, file)); + } + return NError(entity->sessionSheet->GetFileHandle(bundle, file)); }; auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); @@ -427,6 +490,42 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in } } +napi_value SessionRestoreNExporter::Release(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionRestore::Release begin"); + NFuncArg funcArg(env, cbinfo); + if (!funcArg.InitArgs(NARG_CNT::ZERO)) { + HILOGE("Number of arguments unmatched"); + NError(EINVAL).ThrowErr(env); + return nullptr; + } + + auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { + HILOGE("Failed to get RestoreSession entity."); + NError(EPERM).ThrowErr(env); + return nullptr; + } + + auto cbExec = [entity {restoreEntity}]() -> NError { + if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); + } + if (entity->sessionWhole) { + return NError(entity->sessionWhole->Release()); + } + return NError(entity->sessionSheet->Release()); + }; + auto cbCompl = [](napi_env env, NError err) -> NVal { + return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); + }; + + HILOGE("Called SessionRestore::Release end."); + + NVal thisVar(env, funcArg.GetThisVar()); + return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; +} + bool SessionRestoreNExporter::Export() { HILOGI("called SessionRestoreNExporter::Export begin"); @@ -434,6 +533,7 @@ bool SessionRestoreNExporter::Export() NVal::DeclareNapiFunction("appendBundles", AppendBundles), NVal::DeclareNapiFunction("publishFile", PublishFile), NVal::DeclareNapiFunction("getFileHandle", GetFileHandle), + NVal::DeclareNapiFunction("release", Release), }; auto [succ, classValue] = NClass::DefineClass(exports_.env_, className, Constructor, std::move(props)); diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.h b/interfaces/kits/js/backup/session_restore_n_exporter.h index b389b55f5685c0563b0054167586a5141185c7c8..21fc812a2e2196b2b397d93c4fa5d5c18de78f9d 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.h +++ b/interfaces/kits/js/backup/session_restore_n_exporter.h @@ -32,6 +32,7 @@ public: static napi_value AppendBundles(napi_env env, napi_callback_info cbinfo); static napi_value PublishFile(napi_env env, napi_callback_info cbinfo); static napi_value GetFileHandle(napi_env env, napi_callback_info cbinfo); + static napi_value Release(napi_env env, napi_callback_info cbinfo); SessionRestoreNExporter(napi_env env, napi_value exports); ~SessionRestoreNExporter() override; diff --git a/services/backup.para b/services/backup.para index 8f4a7ef77e06ae5f2ab68bcd25c110aedf2b8f22..f4817d2988656c47c425df26f369eb103daddd57 100644 --- a/services/backup.para +++ b/services/backup.para @@ -14,4 +14,7 @@ backup.debug.overrideExtensionConfig=false backup.debug.overrideAccountConfig=false -backup.debug.overrideAccountNumber=0 \ No newline at end of file +backup.debug.overrideAccountNumber=0 + +backup.overrideBackupSARelease=false +backup.overrideIncrementalRestore=false \ No newline at end of file diff --git a/services/backup_sa/BUILD.gn b/services/backup_sa/BUILD.gn index e89cb1f28dd16d72ad8f3b6427789ec36326b5eb..119eb3a22e127a1ffb2d3f973a03436d74fb8917 100644 --- a/services/backup_sa/BUILD.gn +++ b/services/backup_sa/BUILD.gn @@ -29,10 +29,13 @@ ohos_shared_library("backup_sa") { "src/module_app_gallery/app_gallery_dispose_proxy.cpp", "src/module_external/bms_adapter.cpp", "src/module_external/sms_adapter.cpp", + "src/module_ipc/service_incremental_reverse_proxy.cpp", + "src/module_ipc/service_incremental.cpp", "src/module_ipc/service.cpp", "src/module_ipc/service_reverse_proxy.cpp", "src/module_ipc/service_stub.cpp", "src/module_ipc/svc_backup_connection.cpp", + "src/module_ipc/svc_extension_incremental_proxy.cpp", "src/module_ipc/svc_extension_proxy.cpp", "src/module_ipc/svc_restore_deps_manager.cpp", "src/module_ipc/svc_session_manager.cpp", diff --git a/services/backup_sa/include/module_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h index 7af9bedff1cc049afc013260865c8badff76be75..6a33d678aeb1da7becbd209beef43d1cc82d15fb 100644 --- a/services/backup_sa/include/module_external/bms_adapter.h +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -21,6 +21,8 @@ #include "b_json/b_json_entity_caps.h" #include "bundlemgr/bundle_mgr_interface.h" +#include "b_incremental_data.h" +#include "istorage_manager.h" namespace OHOS::FileManagement::Backup { class InnerReceiverImpl; @@ -49,6 +51,16 @@ public: * @brief Get app gallery bundle name */ static std::string GetAppGalleryBundleName(); + + /** + * @brief Get the bundle infos object for incremental backup + * + * @param incrementalDataList bundle Name and time list + * @param userId User ID + * @return std::vector + */ + static std::vector GetBundleInfosForIncremental( + const std::vector &incrementalDataList, int32_t userId); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_BUNDLE_MGR_ADAPTER_H diff --git a/services/backup_sa/include/module_external/sms_adapter.h b/services/backup_sa/include/module_external/sms_adapter.h index 0e3b51e78ee2ba325b4ed9491637116ccc78fb21..3c8b10d684cf71e9097f7a6fd9c3e86a63e3c91e 100644 --- a/services/backup_sa/include/module_external/sms_adapter.h +++ b/services/backup_sa/include/module_external/sms_adapter.h @@ -17,7 +17,8 @@ #define OHOS_FILEMGMT_BACKUP_STORAGE_MGR_ADAPTER_H #include - +#include +#include #include "istorage_manager.h" namespace OHOS::FileManagement::Backup { @@ -38,6 +39,19 @@ public: */ static int64_t GetUserStorageStats(const std::string &bundleName, int32_t userId); + /** + * @brief Get the user storage stats object + * + * @param userId user id + * @param bundleNames + * @param incrementalBackTimes + * @param pkgFileSizes bundle backup file size + * @param pkgStatPaths stat file path + */ + static int32_t GetBundleStatsForIncrease(uint32_t userId, const std::vector &bundleNames, + const std::vector &incrementalBackTimes, std::vector &pkgFileSizes, + std::vector &pkgStatPaths); + /** * @brief update memory para * diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index ff78a909633c12d1451f28e6a7e369de99ceb905..66dc61a548a628e2e0056232a1be444aa188d90e 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -46,6 +46,16 @@ public: int32_t userId = DEFAULT_INVAL_VALUE) override; ErrCode AppendBundlesBackupSession(const std::vector &bundleNames) override; ErrCode Finish() override; + ErrCode Release() override; + + UniqueFd GetLocalCapabilitiesIncremental(const std::vector &bundleNames) override; + ErrCode InitIncrementalBackupSession(sptr remote) override; + ErrCode AppendBundlesIncrementalBackupSession(const std::vector &bundlesToBackup) override; + + ErrCode PublishIncrementalFile(const BFileInfo &fileInfo) override; + ErrCode AppIncrementalFileReady(const std::string &fileName, UniqueFd fd, UniqueFd manifestFd) override; + ErrCode AppIncrementalDone(ErrCode errCode) override; + ErrCode GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) override; // 以下都是非IPC接口 public: @@ -168,6 +178,15 @@ private: */ void HandleRestoreDepsBundle(const std::string &bundleName); + /** + * @brief 增量备份恢复逻辑处理 + * + * @param bundleName + * @return true + * @return false + */ + bool IncrementalBackup(const std::string &bundleName); + /** * @brief extension连接断开 * diff --git a/services/backup_sa/include/module_ipc/service_reverse_proxy.h b/services/backup_sa/include/module_ipc/service_reverse_proxy.h index 5fd75cb57fffe80a8d86cefbf5cf54b4569c2a24..a7cc854fc485668f3934235292c90360fb0ab378 100644 --- a/services/backup_sa/include/module_ipc/service_reverse_proxy.h +++ b/services/backup_sa/include/module_ipc/service_reverse_proxy.h @@ -32,6 +32,16 @@ public: void RestoreOnAllBundlesFinished(int32_t errCode) override; void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) override; + void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd) override; + void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) override; + void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; + void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; + + void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; + void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; + void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) override; + void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd) override; + public: explicit ServiceReverseProxy(const sptr &impl) : IRemoteProxy(impl) {} ~ServiceReverseProxy() override = default; diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h index 1049e15741970b07409f2675d425debb8a2f5d13..4fea6bb3cb5945a5943d1166aca016ae44f4be31 100644 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ b/services/backup_sa/include/module_ipc/service_stub.h @@ -45,6 +45,18 @@ private: int32_t CmdAppendBundlesRestoreSession(MessageParcel &data, MessageParcel &reply); int32_t CmdAppendBundlesBackupSession(MessageParcel &data, MessageParcel &reply); int32_t CmdFinish(MessageParcel &data, MessageParcel &reply); + int32_t CmdRelease(MessageParcel &data, MessageParcel &reply); + int32_t CmdGetLocalCapabilitiesIncremental(MessageParcel &data, MessageParcel &reply); + int32_t CmdInitIncrementalBackupSession(MessageParcel &data, MessageParcel &reply); + int32_t CmdAppendBundlesIncrementalBackupSession(MessageParcel &data, MessageParcel &reply); + int32_t CmdPublishIncrementalFile(MessageParcel &data, MessageParcel &reply); + int32_t CmdAppIncrementalFileReady(MessageParcel &data, MessageParcel &reply); + int32_t CmdAppIncrementalDone(MessageParcel &data, MessageParcel &reply); + int32_t CmdGetIncrementalFileHandle(MessageParcel &data, MessageParcel &reply); + +public: + template + bool ReadParcelableVector(std::vector &parcelableInfos, MessageParcel &data); }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/include/module_ipc/svc_extension_proxy.h b/services/backup_sa/include/module_ipc/svc_extension_proxy.h index b47ba5ded3853a8a47f9b5256d6056a4cc0e0d9a..bfbf52c2323ae3bef2d89a1eff1614d11452d5f3 100644 --- a/services/backup_sa/include/module_ipc/svc_extension_proxy.h +++ b/services/backup_sa/include/module_ipc/svc_extension_proxy.h @@ -18,6 +18,7 @@ #include "i_extension.h" #include "iremote_proxy.h" +#include "unique_fd.h" namespace OHOS::FileManagement::Backup { class SvcExtensionProxy : public IRemoteProxy { @@ -27,6 +28,10 @@ public: ErrCode HandleBackup() override; ErrCode PublishFile(const std::string &fileName) override; ErrCode HandleRestore() override; + ErrCode GetIncrementalFileHandle(const std::string &fileName) override; + ErrCode PublishIncrementalFile(const std::string &fileName) override; + ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; + std::tuple GetIncrementalBackupFileHandle() override; public: explicit SvcExtensionProxy(const sptr &remote) : IRemoteProxy(remote) {} 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 85ca525f84ba81ad0b9e82f784d771537a5d4e3f..be08bcb5847d6f4eaf4a87b8ff1b52332af5d800 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -30,6 +30,7 @@ #include #include "b_file_info.h" +#include "b_incremental_data.h" #include "b_resources/b_constants.h" #include "i_service.h" #include "i_service_reverse.h" @@ -57,6 +58,10 @@ struct BackupExtInfo { /* Timer Status: true is start & false is stop */ bool timerStatus {false}; int64_t dataSize; + int64_t lastIncrementalTime; + int32_t manifestFd; + std::string backupParameters; + int32_t backupPriority; }; class Service; @@ -75,6 +80,7 @@ public: */ int32_t userId {100}; RestoreTypeEnum restoreDataType {RESTORE_DATA_WAIT_SEND}; + bool isIncrementalBackup {false}; }; public: @@ -377,6 +383,37 @@ public: */ void ClearSessionData(); + /** + * @brief Get the Is Incremental Backup object + * + * @return true + * @return false + */ + bool GetIsIncrementalBackup(); + + /** + * @brief Set the Incremental Data object + * + * @param incrementalData + */ + void SetIncrementalData(const BIncrementalData &incrementalData); + + /** + * @brief Get the Manifest Fd object + * + * @param bundleName 应用名称 + * @return int32_t + */ + int32_t GetIncrementalManifestFd(const std::string &bundleName); + + /** + * @brief Get the Last Incremental Time object + * + * @param bundleName + * @return int64_t + */ + int64_t GetLastIncrementalTime(const std::string &bundleName); + /** * @brief 获取备份前内存参数 * diff --git a/services/backup_sa/include/module_sched/sched_scheduler.h b/services/backup_sa/include/module_sched/sched_scheduler.h index 419c87782a0e3041d5b2112c4d930d2dc482d332..5757579fe0fe105aedf87b961a80046d580a2e2b 100644 --- a/services/backup_sa/include/module_sched/sched_scheduler.h +++ b/services/backup_sa/include/module_sched/sched_scheduler.h @@ -72,11 +72,7 @@ public: */ void TryUnloadService(); - void StartTimer() - { - extTime_.Setup(); - TryUnloadServiceTimer(); - } + void StartTimer(); public: explicit SchedScheduler(wptr reversePtr, wptr sessionPtr) diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index a8038634bc31e168ca7fee84c21de866e2fc28df..c9b20b7651700777f113ece6cc4f32336a5952d2 100644 --- a/services/backup_sa/src/module_external/bms_adapter.cpp +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -14,7 +14,10 @@ */ #include "module_external/bms_adapter.h" +#include "module_external/sms_adapter.h" +#include +#include #include #include "b_error/b_error.h" @@ -99,8 +102,8 @@ static int64_t GetBundleStats(const string &bundleName, int32_t userId) bundleStats[i] = 0; } } - int64_t dataSize_ = bundleStats[LOCAL] + bundleStats[DISTRIBUTED] + bundleStats[DATABASE]; - return dataSize_; + int64_t dataSize = bundleStats[LOCAL] + bundleStats[DISTRIBUTED] + bundleStats[DATABASE]; + return dataSize; } vector BundleMgrAdapter::GetBundleInfos(int32_t userId) @@ -169,4 +172,127 @@ string BundleMgrAdapter::GetAppGalleryBundleName() } return bundleName; } + +static tuple, vector> GetBackupExtConfig( + const vector &extensionInfos) +{ + for (auto &&ext : extensionInfos) { + if (ext.type != AppExecFwk::ExtensionAbilityType::BACKUP) { + continue; + } + vector out; + AppExecFwk::BundleMgrClient client; + if (!client.GetResConfigFile(ext, "ohos.extension.backup", out) || out.size() == 0) { + throw BError(BError::Codes::SA_INVAL_ARG, "Failed to get resconfigfile of bundle " + ext.bundleName); + } + BJsonCachedEntity cachedEntity(out[0], ext.bundleName); + auto cache = cachedEntity.Structuralize(); + return {cache.GetAllowToBackupRestore(), ext.name, cache.GetRestoreDeps(), cache.GetSupportScene(), + cache.GetIncludes(), cache.GetExcludes()}; + } + HILOGI("No backup extension ability found"); + return {false, "", "", "", {}, {}}; +} + +static bool CreateIPCInteractionFiles(int32_t userId, const string &bundleName, int64_t lastIncrementalTime, + const vector &includes, const vector &excludes) +{ + // backup_sa bundle path + string backupSaBundleDir = BConstants::BACKUP_PATH_PREFIX + to_string(userId) + BConstants::BACKUP_PATH_SURFFIX + + bundleName + BConstants::FILE_SEPARATOR_CHAR; + if (access(backupSaBundleDir.data(), F_OK) != 0) { + int err = mkdir(backupSaBundleDir.data(), S_IRWXU | S_IRWXG); + if (err != 0) { + HILOGE("Failed to create folder in backup_sa"); + return false; + } + } + // backup_sa include/exclude + string incExFilePath = backupSaBundleDir + BConstants::BACKUP_INCEXC_SYMBOL + to_string(lastIncrementalTime); + std::ofstream incExcFile; + incExcFile.open(incExFilePath.data(), std::ios::out | std::ios::trunc); + if (!incExcFile.is_open()) { + HILOGE("Cannot create incexc file"); + return false; + } + incExcFile << BConstants::BACKUP_INCLUDE << std::endl; + for (auto &include : includes) { + incExcFile << include << std::endl; + } + incExcFile << BConstants::BACKUP_EXCLUDE << std::endl; + for (auto &exclude : excludes) { + incExcFile << exclude << std::endl; + } + incExcFile.close(); + + // backup_sa stat + std::string statFilePath = backupSaBundleDir + BConstants::BACKUP_STAT_SYMBOL + to_string(lastIncrementalTime); + std::ofstream statFile; + statFile.open(statFilePath.data(), std::ios::out | std::ios::trunc); + if (!statFile.is_open()) { + HILOGE("Cannot create stat file"); + return false; + } + statFile.close(); + + return true; +} + + +std::vector BundleMgrAdapter::GetBundleInfosForIncremental( + const std::vector &incrementalDataList, int32_t userId) +{ + std::vector bundleNames; + std::vector incrementalBackTimes; + vector bundleInfos; + auto bms = GetBundleManager(); + for (auto const &bundleNameTime : incrementalDataList) { + auto bundleName = bundleNameTime.bundleName; + HILOGI("Begin Get bundleName:%{public}s", bundleName.c_str()); + AppExecFwk::BundleInfo installedBundle; + if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle info"); + } + if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || + installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { + HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); + continue; + } + auto [allToBackup, extName, restoreDeps, supportScene, includes, excludes] = + GetBackupExtConfig(installedBundle.extensionInfos); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + installedBundle.versionName, 0, allToBackup, + extName, restoreDeps, supportScene}); + if (!CreateIPCInteractionFiles(userId, bundleName, bundleNameTime.lastIncrementalTime, includes, excludes)) { + HILOGE("Failed to write include/exclude files, name : %{public}s", installedBundle.name.data()); + continue; + } + bundleNames.emplace_back(bundleName); + incrementalBackTimes.emplace_back(bundleNameTime.lastIncrementalTime); + } + + std::vector pkgFileSizes {}; + std::vector pkgStatPaths {}; + int32_t err = StorageMgrAdapter::GetBundleStatsForIncrease(userId, bundleNames, incrementalBackTimes, pkgFileSizes, pkgStatPaths); + if (err != 0) { + HILOGE("Failed to get bundleStats result"); + return {}; + } + + vector newBundleInfos {}; + for (size_t i = 0; i < bundleInfos.size(); i++) { + HILOGI("BundleMgrAdapter name for %{public}s", bundleInfos[i].name.c_str()); + BJsonEntityCaps::BundleInfo newBundleInfo = {.name = bundleInfos[i].name, + .versionCode = bundleInfos[i].versionCode, + .versionName = bundleInfos[i].versionName, + .spaceOccupied = pkgFileSizes[i], + .allToBackup = bundleInfos[i].allToBackup, + .extensionName = bundleInfos[i].extensionName, + .restoreDeps = bundleInfos[i].restoreDeps, + .supportScene = bundleInfos[i].supportScene}; + newBundleInfos.emplace_back(newBundleInfo); + } + HILOGI("BundleMgrAdapter GetBundleInfosForIncremental end "); + return newBundleInfos; +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_external/sms_adapter.cpp b/services/backup_sa/src/module_external/sms_adapter.cpp index a46e870f89c2c179e962df38a15b0aa7218d9063..a498445b67bc3ffd6c9bbb5acb7010e1984c81ca 100644 --- a/services/backup_sa/src/module_external/sms_adapter.cpp +++ b/services/backup_sa/src/module_external/sms_adapter.cpp @@ -76,6 +76,17 @@ int64_t StorageMgrAdapter::GetUserStorageStats(const std::string &bundleName, in return 0; } +int32_t StorageMgrAdapter::GetBundleStatsForIncrease(uint32_t userId, const std::vector &bundleNames, + const std::vector &incrementalBackTimes, std::vector &pkgFileSizes, + std::vector &pkgStatPaths) +{ + auto storageMgr = GetStorageManager(); + if (storageMgr->GetBundleStatsForIncrease(userId, bundleNames, incrementalBackTimes, pkgFileSizes, pkgStatPaths)) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get user storage stats"); + } + return 0; +} + int32_t StorageMgrAdapter::UpdateMemPara(int32_t size) { auto storageMgr = GetStorageManager(); diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 5151796a3cd51f60db5a0aada505bc2d255437f8..66d200e46371eed8d8f8059278bc96f39687c143 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -633,6 +633,9 @@ void Service::ExtStart(const string &bundleName) { try { HILOGE("begin %{public}s", bundleName.data()); + if (IncrementalBackup(bundleName)) { + return; + } IServiceReverse::Scenario scenario = session_->GetScenario(); auto backUpConnection = session_->GetExtConnection(bundleName); auto proxy = backUpConnection->GetBackupExtProxy(); @@ -688,7 +691,16 @@ void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) try { HILOGE("begin %{public}s", bundleName.data()); IServiceReverse::Scenario scenario = session_->GetScenario(); - if (scenario == IServiceReverse::Scenario::BACKUP) { + if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { + session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(ret, bundleName); + } else if (scenario == IServiceReverse::Scenario::RESTORE && + BackupPara().GetBackupOverrideIncrementalRestore()) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(ret, bundleName); + + DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName); + HILOGI("ExtConnectFailed EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr, + bundleName.c_str()); + } else if (scenario == IServiceReverse::Scenario::BACKUP) { session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); } else if (scenario == IServiceReverse::Scenario::RESTORE) { session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); @@ -713,7 +725,11 @@ void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) { auto scenario = session_->GetScenario(); - if (scenario == IServiceReverse::Scenario::BACKUP) { + if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { + session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName); + } else if (scenario == IServiceReverse::Scenario::RESTORE && BackupPara().GetBackupOverrideIncrementalRestore()) { + 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); @@ -819,12 +835,19 @@ void Service::OnAllBundlesFinished(ErrCode errCode) { if (session_->IsOnAllBundlesFinished()) { IServiceReverse::Scenario scenario = session_->GetScenario(); - if (scenario == IServiceReverse::Scenario::BACKUP) { + if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { + session_->GetServiceReverseProxy()->IncrementalBackupOnAllBundlesFinished(errCode); + } else if (scenario == IServiceReverse::Scenario::RESTORE && + BackupPara().GetBackupOverrideIncrementalRestore()) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnAllBundlesFinished(errCode); + } else if (scenario == IServiceReverse::Scenario::BACKUP) { session_->GetServiceReverseProxy()->BackupOnAllBundlesFinished(errCode); } else if (scenario == IServiceReverse::Scenario::RESTORE) { session_->GetServiceReverseProxy()->RestoreOnAllBundlesFinished(errCode); } - sched_->TryUnloadServiceTimer(true); + if (!BackupPara().GetBackupOverrideBackupSARelease()) { + sched_->TryUnloadServiceTimer(true); + } } } diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp new file mode 100644 index 0000000000000000000000000000000000000000..121533383ad76e05b278e8f0f44854433fe3f4eb --- /dev/null +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -0,0 +1,361 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * 注意: + * - 注意点1:本文件原则上只处理与IPC无关的业务逻辑 + * - 注意点2:This document, in principle, captures all exceptions. + * Prevent exceptions from spreading to insecure modules. + */ +#include "module_ipc/service.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "accesstoken_kit.h" +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "b_json/b_json_cached_entity.h" +#include "b_json/b_json_entity_caps.h" +#include "b_ohos/startup/backup_para.h" +#include "b_process/b_multiuser.h" +#include "b_resources/b_constants.h" +#include "filemgmt_libhilog.h" +#include "ipc_skeleton.h" +#include "module_external/bms_adapter.h" +#include "module_ipc/svc_backup_connection.h" +#include "module_ipc/svc_restore_deps_manager.h" +#include "parameter.h" +#include "system_ability_definition.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +namespace { +constexpr int32_t DEBUG_ID = 100; +} // namespace + +static inline int32_t GetUserIdDefault() +{ + 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() +{ + HILOGI("KILL"); + VerifyCaller(session_->GetScenario()); + SessionDeactive(); + return BError(BError::Codes::OK); +} + +UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vector &bundleNames) +{ + try { + HILOGI("Begin"); + /* + Only called by restore app before InitBackupSession, + so there must be set init userId. + */ + session_->IncreaseSessionCnt(); + session_->SetSessionUserId(GetUserIdDefault()); + VerifyCaller(); + string path = BConstants::GetSaBundleBackupRootDir(session_->GetSessionUserId()); + BExcepUltils::VerifyPath(path, false); + BJsonCachedEntity cachedEntity( + UniqueFd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR))); + + auto cache = cachedEntity.Structuralize(); + + cache.SetSystemFullName(GetOSFullName()); + cache.SetDeviceType(GetDeviceType()); + auto bundleInfos = BundleMgrAdapter::GetBundleInfosForIncremental(bundleNames, session_->GetSessionUserId()); + cache.SetBundleInfos(bundleInfos); + cachedEntity.Persist(); + HILOGI("Service GetLocalCapabilitiesIncremental persist"); + session_->DecreaseSessionCnt(); + return move(cachedEntity.GetFd()); + } catch (const BError &e) { + session_->DecreaseSessionCnt(); + HILOGE("GetLocalCapabilitiesIncremental failed, errCode = %{public}d", e.GetCode()); + return UniqueFd(-e.GetCode()); + } catch (const exception &e) { + session_->DecreaseSessionCnt(); + HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + return UniqueFd(-EPERM); + } catch (...) { + session_->DecreaseSessionCnt(); + HILOGI("Unexpected exception"); + return UniqueFd(-EPERM); + } +} + +ErrCode Service::InitIncrementalBackupSession(sptr remote) +{ + HILOGI("Begin"); + try { + VerifyCaller(); + session_->Active({.clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::BACKUP, + .clientProxy = remote, + .userId = GetUserIdDefault(), + .isIncrementalBackup = true}); + return BError(BError::Codes::OK); + } catch (const BError &e) { + StopAll(nullptr, true); + return e.GetCode(); + } +} + +ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector &bundlesToBackup) +{ + try { + HILOGI("Begin"); + session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + VerifyCaller(IServiceReverse::Scenario::BACKUP); + vector bundleNames {}; + for (auto &bundle : bundlesToBackup) { + bundleNames.emplace_back(bundle.bundleName); + } + auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); + session_->AppendBundles(bundleNames); + for (auto info : backupInfos) { + session_->SetBundleDataSize(info.name, info.spaceOccupied); + session_->SetBackupExtName(info.name, info.extensionName); + if (info.allToBackup == false) { + session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted( + BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); + session_->RemoveExtInfo(info.name); + } + } + for (auto &bundleInfo : bundlesToBackup) { + session_->SetIncrementalData(bundleInfo); + } + OnStartSched(); + session_->DecreaseSessionCnt(); + return BError(BError::Codes::OK); + } catch (const BError &e) { + session_->DecreaseSessionCnt(); + HILOGE("Failed, errCode = %{public}d", e.GetCode()); + return e.GetCode(); + } catch (...) { + session_->DecreaseSessionCnt(); + HILOGI("Unexpected exception"); + return EPERM; + } +} + +ErrCode Service::PublishIncrementalFile(const BFileInfo &fileInfo) +{ + try { + HILOGI("Begin"); + VerifyCaller(IServiceReverse::Scenario::RESTORE); + + auto backUpConnection = session_->GetExtConnection(fileInfo.owner); + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + 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"); + return EPERM; + } +} + +ErrCode Service::AppIncrementalFileReady(const std::string &fileName, UniqueFd fd, UniqueFd manifestFd) +{ + try { + HILOGI("Begin"); + string callerName = VerifyCallerAndGetCallerName(); + if (session_->GetScenario() == IServiceReverse::Scenario::RESTORE) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnFileReady(callerName, fileName, move(fd), + move(manifestFd)); + return BError(BError::Codes::OK); + } + + if (fileName == BConstants::EXT_BACKUP_MANAGE) { + fd = session_->OnBunleExtManageInfo(callerName, move(fd)); + } + + session_->GetServiceReverseProxy()->IncrementalBackupOnFileReady(callerName, fileName, move(fd), + move(manifestFd)); + if (session_->OnBunleFileReady(callerName, fileName)) { + auto backUpConnection = session_->GetExtConnection(callerName); + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + // 通知extension清空缓存 + proxy->HandleClear(); + // 清除Timer + session_->BundleExtTimerStop(callerName); + // 通知TOOL 备份完成 + session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(BError(BError::Codes::OK), + callerName); + // 断开extension + backUpConnection->DisconnectBackupExtAbility(); + ClearSessionAndSchedInfo(callerName); + } + OnAllBundlesFinished(BError(BError::Codes::OK)); + 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; + } +} + +ErrCode Service::AppIncrementalDone(ErrCode errCode) +{ + try { + HILOGI("Begin"); + string callerName = VerifyCallerAndGetCallerName(); + if (session_->OnBunleFileReady(callerName)) { + auto backUpConnection = session_->GetExtConnection(callerName); + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + proxy->HandleClear(); + session_->BundleExtTimerStop(callerName); + IServiceReverse::Scenario scenario = session_->GetScenario(); + if (scenario == IServiceReverse::Scenario::BACKUP) { + session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, callerName); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleFinished(errCode, callerName); + } + backUpConnection->DisconnectBackupExtAbility(); + ClearSessionAndSchedInfo(callerName); + } + OnAllBundlesFinished(BError(BError::Codes::OK)); + 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; + } +} + +ErrCode Service::GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) +{ + try { + HILOGI("Begin"); + VerifyCaller(IServiceReverse::Scenario::RESTORE); + auto action = session_->GetServiceSchedAction(bundleName); + if (action == BConstants::ServiceSchedAction::RUNNING) { + auto backUpConnection = session_->GetExtConnection(bundleName); + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + int res = proxy->GetIncrementalFileHandle(fileName); + if (res) { + HILOGE("Failed to extension file handle"); + } + } else { + SvcRestoreDepsManager::GetInstance().UpdateToRestoreBundleMap(bundleName, fileName); + session_->SetExtFileNameRequest(bundleName, 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; + } +} + +bool Service::IncrementalBackup(const string &bundleName) +{ + IServiceReverse::Scenario scenario = session_->GetScenario(); + auto backUpConnection = session_->GetExtConnection(bundleName); + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { + //auto [incrementalFd, manifestFd] = proxy->GetIncrementalBackupFileHandle(); + // 本地全量数据 + string path = BConstants::GetSaBundleBackupRootDir(session_->GetSessionUserId()) + .append(bundleName) + .append("/") + .append(BConstants::BACKUP_STAT_SYMBOL) + .append(to_string(session_->GetLastIncrementalTime(bundleName))); + HILOGI("path = %{public}s", path.c_str()); + UniqueFd fdLocal(open(path.data(), O_RDWR, S_IRGRP | S_IWGRP | S_IRGRP | S_IWGRP)); + //BFile::SendFile(incrementalFd, fdLocal); + // 云上存在的数据 + UniqueFd lastManifestFd(session_->GetIncrementalManifestFd(bundleName)); + //BFile::SendFile(manifestFd, lastManifestFd); + auto ret = proxy->HandleIncrementalBackup(move(fdLocal), move(lastManifestFd)); + session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(ret, bundleName); + if (ret) { + ClearSessionAndSchedInfo(bundleName); + } + return true; + } else if (scenario == IServiceReverse::Scenario::RESTORE && BackupPara().GetBackupOverrideIncrementalRestore()) { + auto ret = proxy->HandleRestore(); + session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(ret, bundleName); + auto fileNameVec = session_->GetExtFileNameRequest(bundleName); + for (auto &fileName : fileNameVec) { + ret = proxy->GetIncrementalFileHandle(fileName); + if (ret) { + HILOGE("Failed to extension file handle %{public}s", fileName.c_str()); + } + } + return true; + } + return false; +} +} // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp b/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc9b1dfc3f40fb0a01869d6e0c36ddafd2a48286 --- /dev/null +++ b/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "module_ipc/service_reverse_proxy.h" + +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "filemgmt_libhilog.h" +#include "module_app_gallery/app_gallery_dispose_proxy.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +void ServiceReverseProxy::IncrementalBackupOnFileReady(string bundleName, string fileName, int fd, int manifestFd) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(fileName) || + !data.WriteFileDescriptor(fd) || !data.WriteFileDescriptor(manifestFd)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY), data, reply, + option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + +void ServiceReverseProxy::IncrementalBackupOnBundleStarted(int32_t errCode, string bundleName) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + }; + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_STARTED), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + +void ServiceReverseProxy::IncrementalBackupOnBundleFinished(int32_t errCode, string bundleName) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_FINISHED), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + +void ServiceReverseProxy::IncrementalBackupOnAllBundlesFinished(int32_t errCode) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + +void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + +void ServiceReverseProxy::IncrementalRestoreOnBundleFinished(int32_t errCode, string bundleName) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode) || !data.WriteString(bundleName)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED), + data, reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } + + DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName); + HILOGI("RestoreOnBundleFinished EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr, + bundleName.c_str()); +} + +void ServiceReverseProxy::IncrementalRestoreOnAllBundlesFinished(int32_t errCode) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteInt32(errCode)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + +void ServiceReverseProxy::IncrementalRestoreOnFileReady(string bundleName, string fileName, int fd, int manifestFd) +{ + HILOGI("Begin"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(fileName) || + !data.WriteFileDescriptor(fd) || !data.WriteFileDescriptor(manifestFd)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index eb0f9470d3500c9d155766fb092b6f24f0e98779..327574e6df454b7476691bf708d3f362ae37b8ec 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -25,6 +25,7 @@ #include "b_error/b_error.h" #include "b_error/b_excep_utils.h" +#include "b_resources/b_constants.h" #include "filemgmt_libhilog.h" #include "module_ipc/service_reverse_proxy.h" @@ -52,6 +53,23 @@ ServiceStub::ServiceStub() opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_APPEND_BUNDLES_BACKUP_SESSION)] = &ServiceStub::CmdAppendBundlesBackupSession; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_FINISH)] = &ServiceStub::CmdFinish; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_RELSEASE_SESSION)] = + &ServiceStub::CmdRelease; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_LOCAL_CAPABILITIES_INCREMENTAL)] = + &ServiceStub::CmdGetLocalCapabilitiesIncremental; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_INIT_INCREMENTAL_BACKUP_SESSION)] = + &ServiceStub::CmdInitIncrementalBackupSession; + opToInterfaceMap_[static_cast( + IServiceInterfaceCode::SERVICE_CMD_APPEND_BUNDLES_INCREMENTAL_BACKUP_SESSION)] = + &ServiceStub::CmdAppendBundlesIncrementalBackupSession; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_PUBLISH_INCREMENTAL_FILE)] = + &ServiceStub::CmdPublishIncrementalFile; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_APP_INCREMENTAL_FILE_READY)] = + &ServiceStub::CmdAppIncrementalFileReady; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_APP_INCREMENTAL_DONE)] = + &ServiceStub::CmdAppIncrementalDone; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_INCREMENTAL_FILE_NAME)] = + &ServiceStub::CmdGetIncrementalFileHandle; } int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -257,4 +275,161 @@ int32_t ServiceStub::CmdFinish(MessageParcel &data, MessageParcel &reply) } return BError(BError::Codes::OK); } + +int32_t ServiceStub::CmdRelease(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + int res = Release(); + if (!reply.WriteInt32(res)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to send the result ") + to_string(res)); + } + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdGetLocalCapabilitiesIncremental(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + vector bundleNames; + if (!ReadParcelableVector(bundleNames, data)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); + } + + UniqueFd fd(GetLocalCapabilitiesIncremental(bundleNames)); + if (!reply.WriteFileDescriptor(fd)) { + return BError(BError::Codes::SA_BROKEN_IPC, "Failed to send out the file"); + } + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdInitIncrementalBackupSession(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + auto remote = data.ReadRemoteObject(); + if (!remote) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); + } + auto iremote = iface_cast(remote); + if (!iremote) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); + } + + int32_t res = InitIncrementalBackupSession(iremote); + 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::CmdAppendBundlesIncrementalBackupSession(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + vector bundlesToBackup; + if (!ReadParcelableVector(bundlesToBackup, data)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); + } + + int32_t res = AppendBundlesIncrementalBackupSession(bundlesToBackup); + if (!reply.WriteInt32(res)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to send the result ") + to_string(res)); + } + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdPublishIncrementalFile(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + unique_ptr fileInfo(data.ReadParcelable()); + if (!fileInfo) { + return BError(BError::Codes::SA_BROKEN_IPC, "Failed to receive fileInfo"); + } + int res = PublishIncrementalFile(*fileInfo); + 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::CmdAppIncrementalFileReady(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + string fileName; + if (!data.ReadString(fileName)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fileName"); + } + UniqueFd fd(data.ReadFileDescriptor()); + if (fd < 0) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fd"); + } + + UniqueFd manifestFd(data.ReadFileDescriptor()); + if (manifestFd < 0) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fd"); + } + + int res = AppIncrementalFileReady(fileName, move(fd), move(manifestFd)); + 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::CmdAppIncrementalDone(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + int32_t ret; + if (!data.ReadInt32(ret)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bool flag"); + } + int res = AppIncrementalDone(ret); + 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::CmdGetIncrementalFileHandle(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + string bundleName; + if (!data.ReadString(bundleName)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleName").GetCode(); + } + string fileName; + if (!data.ReadString(fileName)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fileName").GetCode(); + } + + return GetIncrementalFileHandle(bundleName, fileName); +} + +template +bool ServiceStub::ReadParcelableVector(std::vector &parcelableInfos, MessageParcel &data) +{ + int32_t infoSize = 0; + if (!data.ReadInt32(infoSize)) { + HILOGE("Failed to read Parcelable size."); + return false; + } + + parcelableInfos.clear(); + infoSize = (infoSize < BConstants::MAX_PARCELABLE_VECTOR_NUM) ? infoSize : BConstants::MAX_PARCELABLE_VECTOR_NUM; + for (int32_t index = 0; index < infoSize; index++) { + sptr info = data.ReadParcelable(); + if (info == nullptr) { + HILOGE("Failed to read Parcelable infos."); + return false; + } + parcelableInfos.emplace_back(move(*info)); + } + + return true; +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8833cda5b2a23805a48b242f9f3222afbb92b105 --- /dev/null +++ b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "module_ipc/svc_extension_proxy.h" + +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "filemgmt_libhilog.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +ErrCode SvcExtensionProxy::GetIncrementalFileHandle(const string &fileName) +{ + HILOGI("Start"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + + if (!data.WriteString(fileName)) { + BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fileName"); + return ErrCode(EPERM); + } + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest(static_cast(IExtensionInterfaceCode::CMD_GET_INCREMENTAL_FILE_HANDLE), + data, reply, option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return ErrCode(ret); + } + + HILOGI("Successful"); + return reply.ReadInt32(); +} + +ErrCode SvcExtensionProxy::PublishIncrementalFile(const string &fileName) +{ + HILOGI("Start"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + + if (!data.WriteString(fileName)) { + BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fileName"); + return ErrCode(EPERM); + } + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest(static_cast(IExtensionInterfaceCode::CMD_PUBLISH_INCREMENTAL_FILE), + data, reply, option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return ErrCode(ret); + } + + HILOGI("Successful"); + return reply.ReadInt32(); +} + +ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) +{ + HILOGI("Start"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + + data.WriteFileDescriptor(incrementalFd); + data.WriteFileDescriptor(manifestFd); + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest(static_cast(IExtensionInterfaceCode::CMD_HANDLE_INCREMENTAL_BACKUP), + data, reply, option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return ErrCode(ret); + } + + HILOGI("Successful"); + return reply.ReadInt32(); +} + +tuple SvcExtensionProxy::GetIncrementalBackupFileHandle() +{ + HILOGI("Start"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest( + static_cast(IExtensionInterfaceCode::CMD_GET_INCREMENTAL_BACKUP_FILE_HANDLE), data, reply, option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return {UniqueFd(-1), UniqueFd(-1)}; + } + + HILOGI("Successful"); + UniqueFd incrementalFd(reply.ReadFileDescriptor()); + UniqueFd manifestFd(reply.ReadFileDescriptor()); + return {move(incrementalFd), move(manifestFd)}; +} +} // namespace OHOS::FileManagement::Backup \ 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 c2898a340a28ba4707543b41611c28c93911f6fe..3c12999bb0cd455b6058ea58393b777958d9cc5d 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -30,6 +30,7 @@ #include "filemgmt_libhilog.h" #include "module_ipc/service.h" #include "module_ipc/svc_restore_deps_manager.h" +#include "unique_fd.h" namespace OHOS::FileManagement::Backup { using namespace std; @@ -621,6 +622,10 @@ void SvcSessionManager::ClearSessionData() } // disconnect extension if (it.second.schedAction == BConstants::ServiceSchedAction::RUNNING) { + auto proxy = it.second.backUpConnection->GetBackupExtProxy(); + if (proxy && impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) { + proxy->HandleClear(); + } it.second.backUpConnection->DisconnectBackupExtAbility(); } // clear data @@ -629,6 +634,48 @@ void SvcSessionManager::ClearSessionData() impl_.backupExtNameMap.clear(); } +bool SvcSessionManager::GetIsIncrementalBackup() +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + return impl_.isIncrementalBackup; +} + +void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(incrementalData.bundleName); + it->second.lastIncrementalTime = incrementalData.lastIncrementalTime; + it->second.manifestFd = incrementalData.manifestFd; + it->second.backupParameters = incrementalData.backupParameters; + it->second.backupPriority = incrementalData.backupPriority; +} + +int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + return it->second.manifestFd; +} + +int64_t SvcSessionManager::GetLastIncrementalTime(const string &bundleName) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + return it->second.lastIncrementalTime; +} + int32_t SvcSessionManager::GetMemParaCurSize() { return memoryParaCurSize_; diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp index 3b25ef40b039dd398003f6b2edfd8ad60d3a58dd..468241b96623c912808165342461eaa03a43cf48 100644 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ b/services/backup_sa/src/module_sched/sched_scheduler.cpp @@ -28,6 +28,7 @@ #include #include "b_error/b_error.h" +#include "b_ohos/startup/backup_para.h" #include "filemgmt_libhilog.h" #include "iservice_registry.h" #include "module_external/bms_adapter.h" @@ -117,6 +118,14 @@ void SchedScheduler::RemoveExtConn(const string &bundleName) } } +void SchedScheduler::StartTimer() +{ + extTime_.Setup(); + if (!BackupPara().GetBackupOverrideBackupSARelease()) { + TryUnloadServiceTimer(); + } +} + void SchedScheduler::TryUnloadServiceTimer(bool force) { auto tryUnload = [sessionPtr {sessionPtr_}]() { diff --git a/tests/mock/backup_kit_inner/b_session_backup_mock.cpp b/tests/mock/backup_kit_inner/b_session_backup_mock.cpp index f3a8f5193f46dc3de5826e83733947a150c143d4..4f34a37d75298de10474538a9f5a357431009743 100644 --- a/tests/mock/backup_kit_inner/b_session_backup_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_backup_mock.cpp @@ -92,4 +92,9 @@ ErrCode BSessionBackup::Finish() { return BError(BError::Codes::OK); } + +ErrCode BSessionBackup::Release() +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp b/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp index 4068bd936ab84ae53c40831bd299431cf1510fdb..def40ed6e1de89e6d005ead3c8e0656376fa8416 100644 --- a/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp @@ -96,5 +96,10 @@ ErrCode BSessionRestoreAsync::AppendBundles(UniqueFd remoteCap, void BSessionRestoreAsync::OnBackupServiceDied() {} +ErrCode BSessionRestoreAsync::Release() +{ + return BError(BError::Codes::OK); +} + void BSessionRestoreAsync::RegisterBackupServiceDied(function functor) {} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/b_session_restore_mock.cpp b/tests/mock/backup_kit_inner/b_session_restore_mock.cpp index 49d4126bc78421e2777214451166d53971ce661d..3af358b953796c476659de13c143aa3101f2197a 100644 --- a/tests/mock/backup_kit_inner/b_session_restore_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_restore_mock.cpp @@ -96,5 +96,10 @@ ErrCode BSessionRestore::Finish() return BError(BError::Codes::OK); } +ErrCode BSessionRestore::Release() +{ + return BError(BError::Codes::OK); +} + void BSessionRestore::RegisterBackupServiceDied(function functor) {} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/service_proxy_mock.cpp b/tests/mock/backup_kit_inner/service_proxy_mock.cpp index cd0808e1a69bc51bcdbe2d59c7169bb212484474..760bd11588f3bb6e56aa4c8d8f2633d670e7b709 100644 --- a/tests/mock/backup_kit_inner/service_proxy_mock.cpp +++ b/tests/mock/backup_kit_inner/service_proxy_mock.cpp @@ -98,6 +98,46 @@ ErrCode ServiceProxy::Finish() return BError(BError::Codes::OK); } +ErrCode ServiceProxy::Release() +{ + return BError(BError::Codes::OK); +} + +UniqueFd ServiceProxy::GetLocalCapabilitiesIncremental(const vector &bundleNames) +{ + return UniqueFd(-1); +} + +ErrCode ServiceProxy::InitIncrementalBackupSession(sptr remote) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::AppendBundlesIncrementalBackupSession(const vector &bundlesToBackup) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::PublishIncrementalFile(const BFileInfo &fileInfo) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::AppIncrementalFileReady(const string &fileName, UniqueFd fd, UniqueFd manifestFd) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::AppIncrementalDone(ErrCode errCode) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) +{ + return BError(BError::Codes::OK); +} + sptr ServiceProxy::GetInstance() { if (!GetMockGetInstance()) { diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index 06391ad286a3bfbbd792563d0a89695d4e1a2c78..cb41e78f0e45c0d13670d9be5568897e23fb9377 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -131,4 +131,44 @@ void Service::OnStartSched() {} void Service::SendAppGalleryNotify(const BundleName &bundleName) {} void Service::SessionDeactive() {} + +ErrCode Service::Release() +{ + return BError(BError::Codes::OK); +} + +UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vector &bundleNames) +{ + return UniqueFd(-1); +} + +ErrCode Service::InitIncrementalBackupSession(sptr remote) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector &bundlesToBackup) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::PublishIncrementalFile(const BFileInfo &fileInfo) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::AppIncrementalFileReady(const string &fileName, UniqueFd fd, UniqueFd manifestFd) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::AppIncrementalDone(ErrCode errCode) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::GetIncrementalFileHandle(const string &bundleName, const string &fileName) +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp b/tests/mock/module_ipc/service_reverse_proxy_mock.cpp index 0f98e5e2e3ee68626493b10faf07cf46fb595abc..456a8146585fef73b4e372be376db006fd207bd8 100644 --- a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp +++ b/tests/mock/module_ipc/service_reverse_proxy_mock.cpp @@ -35,4 +35,20 @@ void ServiceReverseProxy::RestoreOnBundleFinished(int32_t errCode, string bundle void ServiceReverseProxy::RestoreOnAllBundlesFinished(int32_t errCode) {} void ServiceReverseProxy::RestoreOnFileReady(string bundleName, string fileName, int fd) {} + +void ServiceReverseProxy::IncrementalBackupOnFileReady(string bundleName, string fileName, int fd, int manifestFd) {} + +void ServiceReverseProxy::IncrementalBackupOnBundleStarted(int32_t errCode, string bundleName) {} + +void ServiceReverseProxy::IncrementalBackupOnBundleFinished(int32_t errCode, string bundleName) {} + +void ServiceReverseProxy::IncrementalBackupOnAllBundlesFinished(int32_t errCode) {} + +void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) {} + +void ServiceReverseProxy::IncrementalRestoreOnBundleFinished(int32_t errCode, string bundleName) {} + +void ServiceReverseProxy::IncrementalRestoreOnAllBundlesFinished(int32_t errCode) {} + +void ServiceReverseProxy::IncrementalRestoreOnFileReady(string bundleName, string fileName, int fd, int manifestFd) {} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_ipc/service_stub_mock.cpp b/tests/mock/module_ipc/service_stub_mock.cpp index 07e131cac1724ae7e44995d2f638a22f67e1ea19..3e65392b33905392136d647c7060efac00ad0cc0 100644 --- a/tests/mock/module_ipc/service_stub_mock.cpp +++ b/tests/mock/module_ipc/service_stub_mock.cpp @@ -44,6 +44,21 @@ ServiceStub::ServiceStub() opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_APPEND_BUNDLES_BACKUP_SESSION)] = &ServiceStub::CmdAppendBundlesBackupSession; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_FINISH)] = &ServiceStub::CmdFinish; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_RELSEASE_SESSION)] = + &ServiceStub::CmdRelease; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_LOCAL_CAPABILITIES_INCREMENTAL)] = + &ServiceStub::CmdGetLocalCapabilitiesIncremental; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_INIT_INCREMENTAL_BACKUP_SESSION)] = + &ServiceStub::CmdInitIncrementalBackupSession; + opToInterfaceMap_[static_cast( + IServiceInterfaceCode::SERVICE_CMD_APPEND_BUNDLES_INCREMENTAL_BACKUP_SESSION)] = + &ServiceStub::CmdAppendBundlesIncrementalBackupSession; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_PUBLISH_INCREMENTAL_FILE)] = + &ServiceStub::CmdPublishIncrementalFile; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_APP_INCREMENTAL_FILE_READY)] = + &ServiceStub::CmdAppIncrementalFileReady; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_INCREMENTAL_FILE_NAME)] = + &ServiceStub::CmdGetIncrementalFileHandle; } int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -159,4 +174,41 @@ int32_t ServiceStub::CmdFinish(MessageParcel &data, MessageParcel &reply) reply.WriteInt32(res); return BError(BError::Codes::OK); } + +int32_t ServiceStub::CmdRelease(MessageParcel &data, MessageParcel &reply) +{ + int res = Release(); + reply.WriteInt32(res); + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdGetLocalCapabilitiesIncremental(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdInitIncrementalBackupSession(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdAppendBundlesIncrementalBackupSession(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdPublishIncrementalFile(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdAppIncrementalFileReady(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdGetIncrementalFileHandle(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp index 2403f2d2fb8f982329b618a6c61f531e5ab5ee53..cc3f5790296388a13d5fc1656d6d5212ae216475 100644 --- a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp +++ b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp @@ -42,4 +42,24 @@ ErrCode SvcExtensionProxy::HandleRestore() { return 0; } + +ErrCode SvcExtensionProxy::GetIncrementalFileHandle(const string &fileName) +{ + return 0; +} + +ErrCode SvcExtensionProxy::PublishIncrementalFile(const string &fileName) +{ + return 0; +} + +ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) +{ + return 0; +} + +tuple SvcExtensionProxy::GetIncrementalBackupFileHandle() +{ + return {UniqueFd(-1), UniqueFd(-1)}; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 580b034bb779d11764b48ebfc2a1d49a882490f7..bd628cfc3210fc876a256c830bb424dd1d911d3c 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -321,4 +321,21 @@ int32_t SvcSessionManager::GetMemParaCurSize() void SvcSessionManager::SetMemParaCurSize(int32_t size) {} void SvcSessionManager::ClearSessionData() {} + +bool SvcSessionManager::GetIsIncrementalBackup() +{ + return true; +} + +void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) {} + +int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName) +{ + return 0; +} + +int64_t SvcSessionManager::GetLastIncrementalTime(const string &bundleName) +{ + return 0; +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_sched/sched_scheduler_mock.cpp b/tests/mock/module_sched/sched_scheduler_mock.cpp index 82fdc44855cc827205e86ff4dcaf38071cbaf20f..65c744fa70589ffd79719bbd7b31a17e92b97ed5 100644 --- a/tests/mock/module_sched/sched_scheduler_mock.cpp +++ b/tests/mock/module_sched/sched_scheduler_mock.cpp @@ -30,6 +30,8 @@ void SchedScheduler::ExecutingQueueTasks(const string &bundleName) {} void SchedScheduler::RemoveExtConn(const string &bundleName) {} +void SchedScheduler::StartTimer() {} + void SchedScheduler::TryUnloadServiceTimer(bool force) {} void SchedScheduler::TryUnloadService() {} diff --git a/tests/moduletests/backup_kit_inner/BUILD.gn b/tests/moduletests/backup_kit_inner/BUILD.gn index 71baea891c54c820e5671e1de93dbbf391f38360..212467ce1d5fc4788801e0da4278bc85f2e3141c 100644 --- a/tests/moduletests/backup_kit_inner/BUILD.gn +++ b/tests/moduletests/backup_kit_inner/BUILD.gn @@ -21,6 +21,7 @@ ohos_unittest("b_session_test") { "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_backup.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_restore.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp", + "${path_backup}/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse.cpp", "${path_backup}/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp", "b_session_backup_test.cpp", diff --git a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h index bc7ed16ebd3546d087eb513767e36a0a3da40a1c..07cf8be790dadb7fa52d0f8213d878aad69c6139 100644 --- a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h @@ -97,6 +97,26 @@ public: return BError(BError::Codes::OK); }; + ErrCode GetIncrementalFileHandle(const std::string &fileName) override + { + return BError(BError::Codes::OK); + }; + + ErrCode PublishIncrementalFile(const std::string &fileName) override + { + return BError(BError::Codes::OK); + }; + + ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override + { + return BError(BError::Codes::OK); + }; + + std::tuple GetIncrementalBackupFileHandle() override + { + return {UniqueFd(-1), UniqueFd(-1)}; + }; + private: int32_t nHandleBackupNum_ = 0; }; 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 2af0cb1e1db5c84f8157947b87cab3efd571274a..3436577a1a723a703f2790fa8be0f5e88c91a3fc 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 @@ -110,6 +110,46 @@ public: { return BError(BError::Codes::OK); } + + ErrCode Release() override + { + return BError(BError::Codes::OK); + } + + UniqueFd GetLocalCapabilitiesIncremental(const std::vector &bundleNames) override + { + return UniqueFd(-1); + } + + ErrCode InitIncrementalBackupSession(sptr remote) override + { + return BError(BError::Codes::OK); + } + + ErrCode AppendBundlesIncrementalBackupSession(const std::vector &bundlesToBackup) override + { + return BError(BError::Codes::OK); + } + + ErrCode PublishIncrementalFile(const BFileInfo &fileInfo) + { + return BError(BError::Codes::OK); + } + + ErrCode AppIncrementalFileReady(const std::string &fileName, UniqueFd fd, UniqueFd manifestFd) + { + return BError(BError::Codes::OK); + } + + ErrCode AppIncrementalDone(ErrCode errCode) + { + return BError(BError::Codes::OK); + } + + ErrCode GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) + { + return BError(BError::Codes::OK); + } }; } // namespace OHOS::FileManagement::Backup #endif // MOCK_I_SERVICE_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h b/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h index e4f6e2a2ad631f17f261727abc20b0cf6e0db567..9808e5d4198981eea600b4006cf69e6afa40cd02 100644 --- a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h @@ -45,6 +45,16 @@ public: void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {} void RestoreOnAllBundlesFinished(int32_t errCode) override {} void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd) override {} + + void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd) override {} + void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) override {} + void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override {} + void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override {} + + void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {} + void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {} + void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) override {} + void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd) override {} }; } // namespace OHOS::FileManagement::Backup #endif // MOCK_SERVICE_REVERSE_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp b/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp index c3f41057db2354130407f184a9035bcb89f0fa9b..2fd0b60a71b9f4d219ccced3656220dedaa48430 100644 --- a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp @@ -47,6 +47,14 @@ public: MOCK_METHOD2(RestoreOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(RestoreOnAllBundlesFinished, void(int32_t errCode)); MOCK_METHOD3(RestoreOnFileReady, void(string bundleName, string fileName, int fd)); + MOCK_METHOD4(IncrementalBackupOnFileReady, void(string bundleName, string fileName, int fd, int manifestFd)); + MOCK_METHOD2(IncrementalBackupOnBundleStarted, void(int32_t errCode, string bundleName)); + MOCK_METHOD2(IncrementalBackupOnBundleFinished, void(int32_t errCode, string bundleName)); + MOCK_METHOD1(IncrementalBackupOnAllBundlesFinished, void(int32_t errCode)); + MOCK_METHOD2(IncrementalRestoreOnBundleStarted, void(int32_t errCode, std::string bundleName)); + MOCK_METHOD2(IncrementalRestoreOnBundleFinished, void(int32_t errCode, string bundleName)); + MOCK_METHOD1(IncrementalRestoreOnAllBundlesFinished, void(int32_t errCode)); + MOCK_METHOD4(IncrementalRestoreOnFileReady, void(string bundleName, string fileName, int fd, int manifestFd)); }; class ServiceReverseStubTest : public testing::Test { diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index f78d3da0d51ea33c1b90eb98708ab768960ece78..95682ff99f433fa5ba679753eb94252ca791968d 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -69,6 +69,7 @@ ohos_unittest("backup_service_test") { "${path_backup_mock}/accesstoken/accesstoken_kit_mock.cpp", "${path_backup_mock}/module_ipc/app_gallery_dispose_proxy_mock.cpp", "${path_backup_mock}/timer/timer_mock.cpp", + "${path_backup}/services/backup_sa/src/module_ipc/service_incremental.cpp", "${path_backup}/services/backup_sa/src/module_ipc/service.cpp", "${path_backup}/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp", "service_test.cpp", @@ -218,6 +219,7 @@ ohos_unittest("backup_restore_deps_manager_test") { sources = [ "${path_backup_mock}/accesstoken/accesstoken_kit_mock.cpp", "${path_backup}/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp", + "${path_backup}/services/backup_sa/src/module_ipc/service_incremental.cpp", "${path_backup}/services/backup_sa/src/module_ipc/service.cpp", "${path_backup}/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp", "svc_restore_deps_manager_test.cpp", 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 8b06ed40ce4a9731e81b72d2532f2fcacc6e21ee..2e221933d139d427a2fed30d3ce1e43c3622971d 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -53,6 +53,15 @@ public: ErrCode(UniqueFd fd, const std::vector &bundleNames, RestoreTypeEnum restoreType, int32_t userId)); MOCK_METHOD1(AppendBundlesBackupSession, ErrCode(const std::vector &bundleNames)); MOCK_METHOD0(Finish, ErrCode()); + MOCK_METHOD0(Release, ErrCode()); + MOCK_METHOD1(GetLocalCapabilitiesIncremental, UniqueFd(const std::vector &bundleNames)); + MOCK_METHOD1(InitIncrementalBackupSession, ErrCode(sptr remote)); + MOCK_METHOD1(AppendBundlesIncrementalBackupSession, ErrCode(const std::vector &bundlesToBackup)); + + MOCK_METHOD1(PublishIncrementalFile, ErrCode(const BFileInfo &fileInfo)); + MOCK_METHOD3(AppIncrementalFileReady, ErrCode(const std::string &fileName, UniqueFd fd, UniqueFd manifestFd)); + MOCK_METHOD1(AppIncrementalDone, ErrCode(ErrCode errCode)); + MOCK_METHOD2(GetIncrementalFileHandle, ErrCode(const std::string &bundleName, const std::string &fileName)); UniqueFd InvokeGetLocalCapabilities() { if (bCapabilities_) { @@ -466,4 +475,34 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_Finish_0100, testing::ext::T } GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_Finish_0100"; } + +/** + * @tc.number: SUB_backup_sa_ServiceStub_Release_0100 + * @tc.name: SUB_backup_sa_ServiceStub_Release_0100 + * @tc.desc: Test function of Release interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6URNZ + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_Release_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_Release_0100"; + try { + MockService service; + EXPECT_CALL(service, Release()).WillOnce(Return(BError(BError::Codes::OK))); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); + EXPECT_EQ(BError(BError::Codes::OK), + service.OnRemoteRequest(static_cast(IServiceInterfaceCode::SERVICE_CMD_RELSEASE_SESSION), + data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by Release."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_Release_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/BUILD.gn b/tools/backup_tool/BUILD.gn index b164c2006f9131c71d997ab472746d43c661ed9b..edf619c79fd1ad9b2950f6c6295ff982da270ae0 100644 --- a/tools/backup_tool/BUILD.gn +++ b/tools/backup_tool/BUILD.gn @@ -39,6 +39,8 @@ ohos_executable("backup_tool") { "src/tools_op_backup.cpp", "src/tools_op_check_sa.cpp", "src/tools_op_help.cpp", + "src/tools_op_incremental_backup.cpp", + "src/tools_op_incremental_restore.cpp", "src/tools_op_restore.cpp", "src/tools_op_restore_async.cpp", ] diff --git a/tools/backup_tool/include/tools_op_incremental_backup.h b/tools/backup_tool/include/tools_op_incremental_backup.h new file mode 100644 index 0000000000000000000000000000000000000000..e1d581d5544086866e3e203fb157d46510bf68fe --- /dev/null +++ b/tools/backup_tool/include/tools_op_incremental_backup.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_TOOLS_OP_INCREMENTAL_BACKUP_H +#define OHOS_FILEMGMT_BACKUP_TOOLS_OP_INCREMENTAL_BACKUP_H + +namespace OHOS::FileManagement::Backup { + bool IncrementalBackUpRegister(); + +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_TOOLS_OP_INCREMENTAL_BACKUP_H \ No newline at end of file diff --git a/tools/backup_tool/include/tools_op_incremental_restore.h b/tools/backup_tool/include/tools_op_incremental_restore.h new file mode 100644 index 0000000000000000000000000000000000000000..7cc4bcd0a192b61f619e0e54a9893d1fc0e9f842 --- /dev/null +++ b/tools/backup_tool/include/tools_op_incremental_restore.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_TOOLS_OP_INCREMENTAL_RESTORE_H +#define OHOS_FILEMGMT_BACKUP_TOOLS_OP_INCREMENTAL_RESTORE_H + +namespace OHOS::FileManagement::Backup { + bool IncrementalRestoreRegister(); + +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_TOOLS_OP_INCREMENTAL_RESTORE_H \ No newline at end of file diff --git a/tools/backup_tool/src/main.cpp b/tools/backup_tool/src/main.cpp index 4de614c586acb4529aa4755db96fbc513dda3a68..278999739936da0c650cce6e94c61f05e13147a9 100644 --- a/tools/backup_tool/src/main.cpp +++ b/tools/backup_tool/src/main.cpp @@ -27,6 +27,8 @@ int main() #include "tools_op_help.h" #include "tools_op_restore.h" #include "tools_op_restore_async.h" +#include "tools_op_incremental_backup.h" +#include "tools_op_incremental_restore.h" #include #include @@ -83,6 +85,8 @@ void ToolRegister() OHOS::FileManagement::Backup::CheckSaRegister(); OHOS::FileManagement::Backup::RestoreRegister(); OHOS::FileManagement::Backup::RestoreAsyncRegister(); + OHOS::FileManagement::Backup::IncrementalBackUpRegister(); + OHOS::FileManagement::Backup::IncrementalRestoreRegister(); } int ParseOpAndExecute(const int argc, char *const argv[]) diff --git a/tools/backup_tool/src/tools_op_backup.cpp b/tools/backup_tool/src/tools_op_backup.cpp index d79b1ba6212944de93c7b55a1647e4d48e716708..e9c1e97e682589be4fd624241a1825698989aaf7 100644 --- a/tools/backup_tool/src/tools_op_backup.cpp +++ b/tools/backup_tool/src/tools_op_backup.cpp @@ -258,6 +258,7 @@ static int32_t InitPathCapFile(const string &pathCapFile, vector bundleN ctx->SetBundleFinishedCount(bundleNames.size()); ctx->Wait(); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); + ctx->session_->Release(); return 0; } diff --git a/tools/backup_tool/src/tools_op_incremental_backup.cpp b/tools/backup_tool/src/tools_op_incremental_backup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f16db990696a416be46b9c96dff8aa57bea41bf9 --- /dev/null +++ b/tools/backup_tool/src/tools_op_incremental_backup.cpp @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tools_op_incremental_backup.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "b_error/b_error.h" +#include "b_filesystem/b_file.h" +#include "b_json/b_json_entity_ext_manage.h" +#include "b_resources/b_constants.h" +#include "backup_kit_inner.h" +#include "base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h" +#include "service_proxy.h" +#include "tools_op.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +class SessionBckup { +public: + void UpdateBundleReceivedFiles(const BundleName &bundleName, const string &fileName) + { + lock_guard lk(lock_); + bundleStatusMap_[bundleName].receivedFile.insert(fileName); + TryClearBundleOfMap(bundleName); + } + + void SetIndexFiles(const BundleName &bundleName, UniqueFd fd) + { + BJsonCachedEntity cachedEntity(move(fd)); + auto cache = cachedEntity.Structuralize(); + lock_guard lk(lock_); + bundleStatusMap_[bundleName].indexFile = cache.GetExtManage(); + TryClearBundleOfMap(bundleName); + } + + void TryNotify(bool flag = false) + { + if (flag == true) { + ready_ = true; + cv_.notify_all(); + } else if (bundleStatusMap_.size() == 0 && cnt_ == 0 && isAllBundelsFinished.load()) { + ready_ = true; + cv_.notify_all(); + } + } + + void UpdateBundleFinishedCount() + { + lock_guard lk(lock_); + cnt_--; + } + + void SetBundleFinishedCount(uint32_t cnt) + { + cnt_ = cnt; + } + + void Wait() + { + unique_lock lk(lock_); + cv_.wait(lk, [&] { return ready_; }); + } + + unique_ptr session_ = {}; + +private: + struct BundleStatus { + set receivedFile; + set indexFile; + }; + + void TryClearBundleOfMap(const BundleName &bundleName) + { + if (bundleStatusMap_[bundleName].indexFile == bundleStatusMap_[bundleName].receivedFile) { + bundleStatusMap_.erase(bundleName); + } + } + + map bundleStatusMap_; + mutable condition_variable cv_; + mutex lock_; + bool ready_ = false; + uint32_t cnt_ {0}; + +public: + std::atomic isAllBundelsFinished {false}; + vector lastIncrementalData {}; +}; + +static string GenHelpMsg() +{ + return "\t\tThis operation helps to backup application data.\n" + "\t\t--isLocal\t\t This parameter should be true or flase; true: local backup false: others.\n" + "\t\t--pathCapFile\t\t This parameter should be the path of the capability file.\n" + "\t\t--bundle\t\t This parameter is bundleName."; +} + +static void OnFileReady(shared_ptr ctx, const BFileInfo &fileInfo, UniqueFd fd, UniqueFd manifestFd) +{ + printf("FileReady owner = %s, fileName = %s, fd = %d, manifestFd = %d\n", fileInfo.owner.c_str(), + fileInfo.fileName.c_str(), fd.Get(), manifestFd.Get()); + string tmpPath = string(BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR) + fileInfo.owner; + if (access(tmpPath.data(), F_OK) != 0 && mkdir(tmpPath.data(), S_IRWXU) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + auto iter = find_if(ctx->lastIncrementalData.begin(), ctx->lastIncrementalData.end(), + [bundleName {fileInfo.owner}](const auto &data) { return bundleName == data.bundleName; }); + if (iter == ctx->lastIncrementalData.end()) { + throw BError(BError::Codes::TOOL_INVAL_ARG); + } + tmpPath = tmpPath + "/" + to_string(iter->lastIncrementalTime); + if (access(tmpPath.data(), F_OK) != 0 && mkdir(tmpPath.data(), S_IRWXU) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + // 数据文件保存 路径拼接方式: /data/backup/incrementalreceived/bundleName/时间戳/incremental/文件名 + string tmpDataPath = tmpPath + string(BConstants::BACKUP_TOOL_INCREMENTAL); + if (access(tmpDataPath.data(), F_OK) != 0 && mkdir(tmpDataPath.data(), S_IRWXU) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + UniqueFd fdLocal(open((tmpDataPath + "/" + fileInfo.fileName).data(), O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU)); + if (fdLocal < 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + BFile::SendFile(fdLocal, fd); + + // 简报文件保存 路径拼接方式: /data/backup/incrementalreceived/bundleName/时间戳/manifest/文件名.rp + string tmpmanifestPath = tmpPath + string(BConstants::BACKUP_TOOL_MANIFEST); + if (access(tmpmanifestPath.data(), F_OK) != 0 && mkdir(tmpmanifestPath.data(), S_IRWXU) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + UniqueFd fdManifest( + open((tmpmanifestPath + "/" + fileInfo.fileName + ".rp").data(), O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)); + if (fdManifest < 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + BFile::SendFile(fdManifest, manifestFd); + if (fileInfo.fileName == BConstants::EXT_BACKUP_MANAGE) { + UniqueFd fullDatFd(open((string(BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR) + fileInfo.owner + + string(BConstants::BACKUP_TOOL_MANIFEST).append(".rp")) + .data(), + O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)); + BFile::SendFile(fullDatFd, fdManifest); + ctx->SetIndexFiles(fileInfo.owner, move(fd)); + } else { + ctx->UpdateBundleReceivedFiles(fileInfo.owner, fileInfo.fileName); + } + ctx->TryNotify(); +} + +static void OnBundleStarted(shared_ptr ctx, ErrCode err, const BundleName name) +{ + printf("BundleStarted errCode = %d, BundleName = %s\n", err, name.c_str()); + if (err != 0) { + ctx->isAllBundelsFinished.store(true); + ctx->UpdateBundleFinishedCount(); + ctx->TryNotify(); + } +} + +static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleName name) +{ + printf("BundleFinished errCode = %d, BundleName = %s\n", err, name.c_str()); + ctx->UpdateBundleFinishedCount(); + ctx->TryNotify(); +} + +static void OnAllBundlesFinished(shared_ptr ctx, ErrCode err) +{ + ctx->isAllBundelsFinished.store(true); + if (err == 0) { + printf("all bundles backup finished end\n"); + } else { + printf("Failed to Unplanned Abort error: %d\n", err); + ctx->TryNotify(true); + return; + } + ctx->TryNotify(); +} + +static void OnBackupServiceDied(shared_ptr ctx) +{ + printf("backupServiceDied\n"); + ctx->TryNotify(true); +} + +static void BackupToolDirSoftlinkToBackupDir() +{ + // 判断BConstants::BACKUP_TOOL_LINK_DIR 是否是软链接 + if (access(BConstants::BACKUP_TOOL_LINK_DIR.data(), F_OK) == 0) { + struct stat inStat = {}; + if (lstat(BConstants::BACKUP_TOOL_LINK_DIR.data(), &inStat) == -1) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + + if ((inStat.st_mode & S_IFMT) == S_IFLNK) { + return; + } + // 非软连接删除重新创建 + if (!ForceRemoveDirectory(BConstants::BACKUP_TOOL_LINK_DIR.data())) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + } + + if (access(BConstants::GetSaBundleBackupToolDir(BConstants::DEFAULT_USER_ID).data(), F_OK) != 0 && + mkdir(BConstants::GetSaBundleBackupToolDir(BConstants::DEFAULT_USER_ID).data(), S_IRWXU) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + if (symlink(BConstants::GetSaBundleBackupToolDir(BConstants::DEFAULT_USER_ID).data(), + BConstants::BACKUP_TOOL_LINK_DIR.data()) == -1) { + HILOGE("failed to create soft link file %{public}s errno : %{public}d", + BConstants::BACKUP_TOOL_LINK_DIR.data(), errno); + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + + if (access((BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR).data(), F_OK) != 0 && + mkdir((BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR).data(), S_IRWXU) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } +} + +static int GetLocalCapabilitiesIncremental(shared_ptr ctx, + const string &pathCapFile, + const vector &bundleNames, + const vector ×) +{ + if (bundleNames.size() != times.size()) { + fprintf(stderr, "Inconsistent amounts of bundles and incrementalTime!\n"); + return -EPERM; + } + UniqueFd fdLocal(open(pathCapFile.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)); + if (fdLocal < 0) { + fprintf(stderr, "Failed to open file. error: %d %s\n", errno, strerror(errno)); + return -EPERM; + } + auto proxy = ServiceProxy::GetInstance(); + if (!proxy) { + fprintf(stderr, "Get an empty backup sa proxy\n"); + return -EPERM; + } + int num = 0; + for (auto &bundleName : bundleNames) { + BIncrementalData data; + data.bundleName = bundleName; + data.lastIncrementalTime = atoi(times[num].c_str()); + ctx->lastIncrementalData.push_back(data); + num++; + } + UniqueFd fd = proxy->GetLocalCapabilitiesIncremental(ctx->lastIncrementalData); + if (fd < 0) { + fprintf(stderr, "error GetLocalCapabilitiesIncremental"); + } else { + BFile::SendFile(fdLocal, fd); + } + return 0; +} + +static int32_t Init(const string &pathCapFile, vector bundleNames, vector times) +{ + StartTrace(HITRACE_TAG_FILEMANAGEMENT, "Init"); + // SELinux backup_tool工具/data/文件夹下创建文件夹 SA服务因root用户的自定义标签无写入权限 此处调整为软链接形式 + BackupToolDirSoftlinkToBackupDir(); + + auto ctx = make_shared(); + ctx->session_ = BIncrementalBackupSession::Init(BIncrementalBackupSession::Callbacks { + .onFileReady = bind(OnFileReady, ctx, placeholders::_1, placeholders::_2, placeholders::_3), + .onBundleStarted = bind(OnBundleStarted, ctx, placeholders::_1, placeholders::_2), + .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), + .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), + .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + if (ctx->session_ == nullptr) { + printf("Failed to init backup\n"); + FinishTrace(HITRACE_TAG_FILEMANAGEMENT); + return -EPERM; + } + + if (int ret = GetLocalCapabilitiesIncremental(ctx, pathCapFile, bundleNames, times); ret != 0) { + return ret; + } + vector bundlesToBackup; + for (auto &data : ctx->lastIncrementalData) { + string tmpPath = string(BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR) + data.bundleName; + if (access(tmpPath.data(), F_OK) != 0 && mkdir(tmpPath.data(), S_IRWXU) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + tmpPath = tmpPath + string(BConstants::BACKUP_TOOL_MANIFEST).append(".rp"); + data.manifestFd = open(tmpPath.data(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + } + int ret = ctx->session_->AppendBundles(ctx->lastIncrementalData); + if (ret != 0) { + printf("backup append bundles error: %d\n", ret); + throw BError(BError::Codes::TOOL_INVAL_ARG, "backup append bundles error"); + } + + ctx->SetBundleFinishedCount(bundleNames.size()); + ctx->Wait(); + FinishTrace(HITRACE_TAG_FILEMANAGEMENT); + ctx->session_->Release(); + return 0; +} + +static int g_exec(map> &mapArgToVal) +{ + if (mapArgToVal.find("pathCapFile") == mapArgToVal.end() || mapArgToVal.find("bundles") == mapArgToVal.end() || + mapArgToVal.find("incrementalTime") == mapArgToVal.end()) { + return -EPERM; + } + return Init(*(mapArgToVal["pathCapFile"].begin()), mapArgToVal["bundles"], mapArgToVal["incrementalTime"]); +} + +bool IncrementalBackUpRegister() +{ + return ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { + .opName = {"incrementalbackup"}, + .argList = {{ + .paramName = "pathCapFile", + .repeatable = false, + }, + { + .paramName = "bundles", + .repeatable = true, + }, + { + .paramName = "incrementalTime", + .repeatable = true, + }}, + .funcGenHelpMsg = GenHelpMsg, + .funcExec = g_exec, + }}); +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/src/tools_op_incremental_restore.cpp b/tools/backup_tool/src/tools_op_incremental_restore.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ffab7d1e57e5dc631e5251b49c4cccd88a160a0f --- /dev/null +++ b/tools/backup_tool/src/tools_op_incremental_restore.cpp @@ -0,0 +1,362 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "tools_op_incremental_restore.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "b_filesystem/b_dir.h" +#include "b_filesystem/b_file.h" +#include "b_json/b_json_entity_caps.h" +#include "b_json/b_json_entity_ext_manage.h" +#include "b_resources/b_constants.h" +#include "backup_kit_inner.h" +#include "base/hiviewdfx/hitrace/interfaces/native/innerkits/include/hitrace_meter/hitrace_meter.h" +#include "errors.h" +#include "service_proxy.h" +#include "tools_op.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +class SessionRestore { +public: + void UpdateBundleSendFiles(const BundleName &bundleName, const string &fileName) + { + lock_guard lk(lock_); + bundleStatusMap_[bundleName].sendFile.insert(fileName); + } + + void ClearBundleOfMap(const BundleName &bundleName) + { + lock_guard lk(lock_); + bundleStatusMap_.erase(bundleName); + } + + void TryNotify(bool flag = false) + { + if (flag == true) { + ready_ = true; + cv_.notify_all(); + } else if (bundleStatusMap_.size() == 0 && cnt_ == 0 && isAllBundelsFinished.load()) { + ready_ = true; + cv_.notify_all(); + } + } + + void UpdateBundleFinishedCount() + { + lock_guard lk(lock_); + cnt_--; + } + + void SetBundleFinishedCount(uint32_t cnt) + { + cnt_ = cnt; + } + + void Wait() + { + unique_lock lk(lock_); + cv_.wait(lk, [&] { return ready_; }); + } + + unique_ptr session_ = {}; + +private: + struct BundleStatus { + set sendFile; + set sentFile; + }; + + void TryClearBundleOfMap(const BundleName &bundleName) + { + if (bundleStatusMap_[bundleName].sendFile == bundleStatusMap_[bundleName].sentFile) { + bundleStatusMap_.erase(bundleName); + } + } + + map bundleStatusMap_; + mutable condition_variable cv_; + mutex lock_; + bool ready_ = false; + uint32_t cnt_ {0}; + +public: + std::atomic isAllBundelsFinished {false}; + vector lastIncrementalData {}; +}; + +static string GenHelpMsg() +{ + return "\t\tThis operation helps to restore application data.\n" + "\t\t--pathCapFile\t\t This parameter should be the path of the capability file.\n" + "\t\t--bundle\t\t This parameter is bundleName."; +} + +static void OnFileReady(shared_ptr ctx, const BFileInfo &fileInfo, UniqueFd fd, UniqueFd manifestFd) +{ + printf("FileReady owner = %s, fileName = %s, sn = %u, fd = %d\n", fileInfo.owner.c_str(), fileInfo.fileName.c_str(), + fileInfo.sn, fd.Get()); + if (fileInfo.fileName.find('/') != string::npos) { + throw BError(BError::Codes::TOOL_INVAL_ARG, "Filename is not valid"); + } + auto iter = find_if(ctx->lastIncrementalData.begin(), ctx->lastIncrementalData.end(), + [bundleName {fileInfo.owner}](const auto &data) { return bundleName == data.bundleName; }); + if (iter == ctx->lastIncrementalData.end()) { + throw BError(BError::Codes::TOOL_INVAL_ARG); + } + // 待恢复文件 路径拼接方式: /data/backup/incrementalreceived/bundleName/时间戳/incremental/文件名 + string tmpPath = string(BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR) + fileInfo.owner + "/" + + to_string(iter->lastIncrementalTime) + string(BConstants::BACKUP_TOOL_INCREMENTAL) + "/" + + fileInfo.fileName; + if (access(tmpPath.data(), F_OK) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + UniqueFd fdLocal(open(tmpPath.data(), O_RDONLY)); + if (fdLocal < 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + BFile::SendFile(fd, fdLocal); + // manifest文件 路径拼接方式: /data/backup/incrementalreceived/bundleName/时间戳/manifest/文件名.rp + tmpPath = string(BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR) + fileInfo.owner + "/" + + to_string(iter->lastIncrementalTime) + string(BConstants::BACKUP_TOOL_MANIFEST) + "/" + + fileInfo.fileName + ".rp"; + if (access(tmpPath.data(), F_OK) == 0) { + UniqueFd fdManifest(open(tmpPath.data(), O_RDONLY)); + if (fdManifest < 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + BFile::SendFile(manifestFd, fdManifest); + } + // 文件准备完成 + int ret = ctx->session_->PublishFile(fileInfo); + if (ret != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, "PublishFile error"); + } + ctx->TryNotify(); +} + +static void OnBundleStarted(shared_ptr ctx, ErrCode err, const BundleName name) +{ + printf("BundleStarted errCode = %d, BundleName = %s\n", err, name.c_str()); + if (err != 0) { + ctx->UpdateBundleFinishedCount(); + ctx->isAllBundelsFinished.store(true); + ctx->ClearBundleOfMap(name); + ctx->TryNotify(); + } +} + +static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleName name) +{ + printf("BundleFinished errCode = %d, BundleName = %s\n", err, name.c_str()); + ctx->UpdateBundleFinishedCount(); + if (err != 0) { + ctx->isAllBundelsFinished.store(true); + } + ctx->ClearBundleOfMap(name); + ctx->TryNotify(); +} + +static void OnAllBundlesFinished(shared_ptr ctx, ErrCode err) +{ + ctx->isAllBundelsFinished.store(true); + if (err == 0) { + printf("all bundles restore finished end\n"); + } else { + printf("Failed to Unplanned Abort error: %d\n", err); + ctx->TryNotify(true); + return; + } + ctx->TryNotify(); +} + +static void OnBackupServiceDied(shared_ptr ctx) +{ + printf("backupServiceDied\n"); + ctx->TryNotify(true); +} + +static void RestoreApp(shared_ptr restore) +{ + StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); + if (!restore || !restore->session_) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + for (auto &data : restore->lastIncrementalData) { + string path = string(BConstants::BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR) + data.bundleName + "/" + + to_string(data.lastIncrementalTime) + string(BConstants::BACKUP_TOOL_INCREMENTAL); + if (access(path.data(), F_OK) != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); + } + const auto [err, filePaths] = BDir::GetDirFiles(path); + if (err != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, "error path"); + } + for (auto &filePath : filePaths) { + string fileName = filePath.substr(filePath.rfind("/") + 1); + restore->session_->GetFileHandle(data.bundleName, fileName); + restore->UpdateBundleSendFiles(data.bundleName, fileName); + } + } + FinishTrace(HITRACE_TAG_FILEMANAGEMENT); +} + +static bool GetRealPath(string &path) +{ + string absPath = BExcepUltils::Canonicalize(path); + if (access(absPath.data(), F_OK) != 0) { + return false; + } + return true; +} + +static int32_t InitRestoreSession(shared_ptr ctx, + vector &bundleNames, + vector ×) +{ + if (bundleNames.size() != times.size()) { + fprintf(stderr, "Inconsistent amounts of bundles and incrementalTime!\n"); + return -EPERM; + } + if (!ctx) { + return -EPERM; + } + ctx->session_ = BIncrementalRestoreSession::Init(BIncrementalRestoreSession::Callbacks { + .onFileReady = bind(OnFileReady, ctx, placeholders::_1, placeholders::_2, placeholders::_3), + .onBundleStarted = bind(OnBundleStarted, ctx, placeholders::_1, placeholders::_2), + .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), + .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), + .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + if (ctx->session_ == nullptr) { + printf("Failed to init restore\n"); + FinishTrace(HITRACE_TAG_FILEMANAGEMENT); + return -EPERM; + } + + int num = 0; + for (auto &bundleName : bundleNames) { + BIncrementalData data; + data.bundleName = bundleName; + data.lastIncrementalTime = atoi(times[num].c_str()); + ctx->lastIncrementalData.push_back(data); + num++; + } + return 0; +} + +static int32_t Init(const string &pathCapFile, vector bundleNames, bool depMode, vector times) +{ + StartTrace(HITRACE_TAG_FILEMANAGEMENT, "Init"); + string realPath = pathCapFile; + if (!GetRealPath(realPath)) { + fprintf(stderr, "path to realpath error"); + return -errno; + } + + UniqueFd fd(open(realPath.data(), O_RDWR, S_IRWXU)); + auto ctx = make_shared(); + int32_t ret = InitRestoreSession(ctx, bundleNames, times); + if (ret != 0) { + printf("Failed to init restore session error:%d\n", ret); + return ret; + } + + if (depMode) { + for (auto &bundleName : bundleNames) { + UniqueFd fileFd(open(realPath.data(), O_RDWR, S_IRWXU)); + if (fileFd < 0) { + fprintf(stderr, "Failed to open file error: %d %s\n", errno, strerror(errno)); + FinishTrace(HITRACE_TAG_FILEMANAGEMENT); + return -errno; + } + int result = ctx->session_->AppendBundles(move(fileFd), {bundleName}); + if (result != 0) { + printf("restore append bundles error: %d\n", result); + return -result; + } + } + } else { + ret = ctx->session_->AppendBundles(move(fd), bundleNames); + if (ret != 0) { + printf("restore append bundles error: %d\n", ret); + return -ret; + } + } + ctx->SetBundleFinishedCount(bundleNames.size()); + RestoreApp(ctx); + ctx->Wait(); + ctx->session_->Release(); + return 0; +} + +static int g_exec(map> &mapArgToVal) +{ + bool depMode = false; + if (mapArgToVal.find("depMode") != mapArgToVal.end()) { + string strFlag = *(mapArgToVal["depMode"].begin()); + depMode = (strFlag == "true"); + } + + if (mapArgToVal.find("pathCapFile") == mapArgToVal.end() || mapArgToVal.find("bundles") == mapArgToVal.end() || + mapArgToVal.find("incrementalTime") == mapArgToVal.end()) { + return -EPERM; + } + return Init(*(mapArgToVal["pathCapFile"].begin()), mapArgToVal["bundles"], depMode, mapArgToVal["incrementalTime"]); +} + +bool IncrementalRestoreRegister() +{ + return ToolsOp::Register(ToolsOp {ToolsOp::Descriptor { + .opName = {"incrementalrestore"}, + .argList = {{ + .paramName = "pathCapFile", + .repeatable = false, + }, + { + .paramName = "bundles", + .repeatable = true, + }, + { + .paramName = "depMode", + .repeatable = false, + }, + { + .paramName = "incrementalTime", + .repeatable = true, + }}, + .funcGenHelpMsg = GenHelpMsg, + .funcExec = g_exec, + }}); +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/src/tools_op_restore.cpp b/tools/backup_tool/src/tools_op_restore.cpp index 333099dbd1f4fd160f72439bcdb4d82ae168c8ec..9f21842b563cb9bfb03e5883840b2a332de355b6 100644 --- a/tools/backup_tool/src/tools_op_restore.cpp +++ b/tools/backup_tool/src/tools_op_restore.cpp @@ -160,8 +160,8 @@ static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleN ctx->UpdateBundleFinishedCount(); if (err != 0) { ctx->isAllBundelsFinished.store(true); - ctx->ClearBundleOfMap(name); } + ctx->ClearBundleOfMap(name); ctx->TryNotify(); } @@ -286,6 +286,7 @@ static int32_t InitPathCapFile(const string &pathCapFile, vector bundleN ctx->SetBundleFinishedCount(bundleNames.size()); RestoreApp(ctx, bundleNames); ctx->Wait(); + ctx->session_->Release(); return 0; } diff --git a/utils/BUILD.gn b/utils/BUILD.gn index ff90af9810f2c75ce15b6e62199b1227553a9fd4..9bd937cbe9a521b00ff54ec5f7465e5b536bbb8d 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -83,6 +83,7 @@ ohos_shared_library("backup_utils") { "src/b_error/b_excep_utils.cpp", "src/b_filesystem/b_dir.cpp", "src/b_filesystem/b_file.cpp", + "src/b_filesystem/b_file_hash.cpp", "src/b_json/b_json_entity_ext_manage.cpp", "src/b_json/b_json_entity_extension_config.cpp", "src/b_ohos/startup/backup_para.cpp", @@ -109,6 +110,7 @@ ohos_shared_library("backup_utils") { "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", "${path_rust}/crates/cxx/include", "${target_gen_dir}/rust/src", + "//third_party/openssl/include", ] deps = [ @@ -116,8 +118,11 @@ ohos_shared_library("backup_utils") { ":backup_cxx_gen", ":backup_cxx_rust", "${path_jsoncpp}:jsoncpp", + "//third_party/openssl:libcrypto_shared", ] + defines = [ "OPENSSL_SUPPRESS_DEPRECATED" ] + use_exceptions = true innerapi_tags = [ "platformsdk" ] part_name = "app_file_service" diff --git a/utils/include/b_filesystem/b_file_hash.h b/utils/include/b_filesystem/b_file_hash.h new file mode 100644 index 0000000000000000000000000000000000000000..8fff58760d5c1969528d89cde4188d2d71fbb3f5 --- /dev/null +++ b/utils/include/b_filesystem/b_file_hash.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_FILE_HASH_H +#define OHOS_FILEMGMT_BACKUP_B_FILE_HASH_H + +#include +#include + +namespace OHOS::FileManagement::Backup { +using namespace std; +class BFileHash { +public: + static std::tuple HashWithMD5(const std::string &fpath); + static std::tuple HashWithSHA1(const std::string &fpath); + static std::tuple HashWithSHA256(const std::string &fpath); +}; +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_B_FILE_HASH_H \ No newline at end of file diff --git a/utils/include/b_json/b_report_entity.h b/utils/include/b_json/b_report_entity.h new file mode 100644 index 0000000000000000000000000000000000000000..9934c3d48d10625b4fe9da4692fea58f810ef1ee --- /dev/null +++ b/utils/include/b_json/b_report_entity.h @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_REPORT_ENTITY_H +#define OHOS_FILEMGMT_BACKUP_B_REPORT_ENTITY_H + +#include +#include +#include +#include +#include +#include + +#include "b_error/b_error.h" +#include "filemgmt_libhilog.h" +#include "unique_fd.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; +struct ReportFileInfo { + string filePath {""}; + string mode {""}; + bool isDir {false}; + off_t size {0}; + off_t mtime {0}; + string hash {""}; + bool isIncremental {false}; +}; + +class BReportEntity { +public: + std::vector SplitStringByChar(const std::string &str, const char &sep) + { + std::vector eles = {}; + std::stringstream ss = std::stringstream(str); + std::string ele = {}; + while (!ss.eof()) { + getline(ss, ele, sep); + eles.push_back(ele); + } + + return eles; + } + + ErrCode ParseReportInfo(struct ReportFileInfo &fileStat, const std::vector &splits, + const std::unordered_map &keys) + { + // 根据数据拼接结构体 + int len = keys.size(); + int splitsLen = (int)splits.size(); + // 处理path路径 + std::string path; + std::vector residue; + try { + for (int i = 0; i < splitsLen; i++) { + if (i <= splitsLen - len) { + path += splits[i] + ";"; + } else { + residue.emplace_back(splits[i]); + } + } + fileStat.filePath = path.substr(0, path.length() - 1); + if (keys.find("mode") != keys.end()) { + fileStat.mode = residue[keys.find("mode")->second]; + } + if (keys.find("dir") != keys.end()) { + fileStat.isDir = atoi(residue[keys.find("dir")->second].c_str()) == 1 ? true : false; + } + if (keys.find("size") != keys.end()) { + fileStat.size = static_cast(atol(residue[keys.find("size")->second].c_str())); + } + if (keys.find("mtime") != keys.end()) { + fileStat.mtime = static_cast(atol(residue[keys.find("mtime")->second].c_str())); + } + if (keys.find("hash") != keys.end()) { + fileStat.hash = residue[keys.find("hash")->second]; + } + if (keys.find("isIncremental") != keys.end()) { + fileStat.isIncremental = atoi(residue[keys.find("isIncremental")->second].c_str()) == 1 ? true : false; + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to ParseReportInfo"); + return EPERM; + } + } + + void DealLine(std::unordered_map &keys, int &num, const std::string &line, + std::map &infos) + { + std::string currentLine = line; + if (currentLine[currentLine.length()-1] == '\r') { + currentLine = currentLine.substr(0, currentLine.length()-1); + } + + std::vector splits = SplitStringByChar(currentLine, attrSep_); + HILOGE("DealLine end"); + if (num < INFO_ALIGN_NUM_) { + if (num == 1) { + for (int j = 0; j < (int)splits.size(); j++) { + keys.emplace(splits[j], j - 1); + } + } + num++; + } else { + struct ReportFileInfo fileState; + auto code = ParseReportInfo(fileState, splits, keys); + if (code != ERR_OK) { + HILOGE("ParseReportInfo err:%{public}d, %{public}s", code, currentLine.c_str()); + } else { + infos.try_emplace(fileState.filePath, fileState); + } + } + } + + /** + * @brief 获取Report信息 + * + * @return std::map + */ + std::map GetReportInfos() + { + std::map infos {}; + + char buffer[HASH_BUFFER_SIZE_]; + ssize_t bytesRead; + std::string currentLine; + std::unordered_map keys; + + int num = 0; + while ((bytesRead = read(srcFile_, buffer, sizeof(buffer))) > 0) { + HILOGI("GetReportInfos line:%{public}s", buffer); + for (ssize_t i = 0; i < bytesRead; i++) { + if (buffer[i] == lineSep_) { + HILOGI("GetReportInfos line:%{public}s", currentLine.c_str()); + DealLine(keys, num, currentLine, infos); + HILOGI("GetReportInfos end"); + currentLine.clear(); + } else { + currentLine += buffer[i]; + } + } + } + + // 处理文件中的最后一行 + if (!currentLine.empty()) { + HILOGI("GetReportInfos2 line:%{public}s", currentLine.c_str()); + DealLine(keys, num, currentLine, infos); + HILOGI("GetReportInfos2 end"); + } + + return infos; + } + +public: + /** + * @brief 构造方法 + * + * @param fd + */ + explicit BReportEntity(UniqueFd fd) : srcFile_(std::move(fd)) {} + + BReportEntity() = delete; + virtual ~BReportEntity() = default; + +public: + string version = ""; + unsigned int attrNum = 0; + +protected: + UniqueFd srcFile_; + const char lineSep_ = '\n'; + const char attrSep_ = ';'; + const char infoSep_ = '&'; + const char infoAlign_ = '='; + const int INFO_ALIGN_NUM_ = 2; + const string VERSION_TAG_ = "version"; + const string ATTR_NUM_TAG_ = "attrNum"; + const int64_t HASH_BUFFER_SIZE_ = 4096; // 每次读取的siz +}; +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_B_REPORT_ENTITY_H \ No newline at end of file diff --git a/utils/include/b_ohos/startup/backup_para.h b/utils/include/b_ohos/startup/backup_para.h index 1f6cad36477a496240c1fadba25d45e2b4ae3f5e..bac2a43004d82f22306a1170de68fea7951dc9d3 100644 --- a/utils/include/b_ohos/startup/backup_para.h +++ b/utils/include/b_ohos/startup/backup_para.h @@ -35,6 +35,20 @@ public: * @return int32_t值为配置项backup.debug.overrideAccountNumber值 */ std::tuple GetBackupDebugOverrideAccount(); + + /** + * @brief 获取backup.para配置项backup.overrideBackupSARelease的值 + * + * @return 获取的配置项backup.overrideBackupSARelease的值为true时则返回true,否则返回false + */ + bool GetBackupOverrideBackupSARelease(); + + /** + * @brief 获取backup.para配置项backup.overrideIncrementalRestore的值 + * + * @return 获取的配置项backup.overrideIncrementalRestore的值为true时则返回true,否则返回false + */ + bool GetBackupOverrideIncrementalRestore(); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index e832d95bdc3f0c05d123eae02f6fa847a9062d4b..0cd7ec5de46306d3116382ddd79161ea3833caec 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -62,6 +62,7 @@ constexpr int EXT_CONNECT_MAX_COUNT = 3; // extension 最大启动数 constexpr int EXT_CONNECT_MAX_TIME = 15000; // SA 启动 extension 等待连接最大时间 constexpr int IPC_MAX_WAIT_TIME = 3000; // IPC通讯最大等待时间(s) +constexpr int MAX_PARCELABLE_VECTOR_NUM = 10000; constexpr int DEFAULT_VFS_CACHE_PRESSURE = 100; // 默认内存回收参数 constexpr int BACKUP_VFS_CACHE_PRESSURE = 10000; // 备份过程修改参数 @@ -73,6 +74,21 @@ static inline std::string BACKUP_DEBUG_OVERRIDE_EXTENSION_CONFIG_KEY = "backup.d static inline std::string BACKUP_DEBUG_OVERRIDE_ACCOUNT_CONFIG_KEY = "backup.debug.overrideAccountConfig"; static inline std::string BACKUP_DEBUG_OVERRIDE_ACCOUNT_NUMBER_KEY = "backup.debug.overrideAccountNumber"; +// 增量备份相关处理目录 +constexpr char FILE_SEPARATOR_CHAR = '/'; +static const std::string BACKUP_PATH_PREFIX = "/data/service/el2/"; +static const std::string BACKUP_PATH_SURFFIX = "/backup/backup_sa/"; +static const std::string BACKUP_INCEXC_SYMBOL = "incExc_"; +static const std::string BACKUP_STAT_SYMBOL = "stat_"; +static const std::string BACKUP_INCLUDE = "INCLUDES"; +static const std::string BACKUP_EXCLUDE = "EXCLUDES"; + +// backup.para内配置项的名称,该配置项为true时备份恢复支持Release接口调用 +static inline std::string BACKUP_OVERRIDE_BACKUP_SA_RELEASE_KEY = "backup.overrideBackupSARelease"; + +// backup.para内配置项的名称,该配置项为true时备份恢复支持增量恢复 +static inline std::string BACKUP_OVERRIDE_INCREMENTAL_KEY = "backup.overrideIncrementalRestore"; + // 应用备份数据暂存路径 static inline std::string_view SA_BUNDLE_BACKUP_BACKUP = "/backup/"; static inline std::string_view SA_BUNDLE_BACKUP_RESTORE = "/restore/"; @@ -81,6 +97,9 @@ static inline std::string_view BACKUP_TOOL_RECEIVE_DIR = "/data/backup/received/ static inline std::string_view PATH_BUNDLE_BACKUP_HOME_EL1 = "/data/storage/el1/backup"; static inline std::string_view PATH_BUNDLE_BACKUP_HOME = "/data/storage/el2/backup"; static inline std::string_view BACKUP_TOOL_LINK_DIR = "/data/backup"; +static inline std::string_view BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR = "/data/backup/incrementalreceived/"; +static inline std::string_view BACKUP_TOOL_MANIFEST = "/manifest"; +static inline std::string_view BACKUP_TOOL_INCREMENTAL = "/incremental"; // 多用户场景应用备份数据路径 static inline std::string GetSaBundleBackupDir(int32_t userId) @@ -119,6 +138,9 @@ static inline std::string_view EXT_BACKUP_MANAGE = "manage.json"; // 包管理元数据配置文件 static inline std::string_view BACKUP_CONFIG_JSON = "backup_config.json"; +// 简报文件名后缀 +static inline std::string_view REPORT_FILE_EXT = "rp"; + // 特殊版本信息 constexpr int DEFAULT_VERSION_CODE = 0; static inline std::string_view DEFAULT_VERSION_NAME = "0.0.0.0"; diff --git a/utils/src/b_filesystem/b_file_hash.cpp b/utils/src/b_filesystem/b_file_hash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b84790b82dd917390ce95abb77dd5e59aaee651 --- /dev/null +++ b/utils/src/b_filesystem/b_file_hash.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_filesystem/b_file_hash.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace OHOS::FileManagement::Backup { +using namespace std; + +static tuple HashFinal(int err, const unique_ptr &hashBuf, size_t hashLen) +{ + if (err) { + return { err, "" }; + } + + stringstream ss; + for (size_t i = 0; i < hashLen; ++i) { + const int hexPerByte = 2; + ss << std::uppercase << std::setfill('0') << std::setw(hexPerByte) << std::hex << + static_cast(hashBuf[i]); + } + + return { err, ss.str() }; +} + +static int ForEachFileSegment(const string &fpath, function executor) +{ + unique_ptr filp = { fopen(fpath.c_str(), "r"), fclose }; + if (!filp) { + return errno; + } + + const size_t pageSize { getpagesize() }; + auto buf = make_unique(pageSize); + size_t actLen; + do { + actLen = fread(buf.get(), 1, pageSize, filp.get()); + if (actLen > 0) { + executor(buf.get(), actLen); + } + } while (actLen == pageSize); + + return ferror(filp.get()) ? errno : 0; +} + +tuple BFileHash::HashWithSHA1(const string &fpath) +{ + auto res = make_unique(SHA_DIGEST_LENGTH); + SHA_CTX ctx; + SHA1_Init(&ctx); + auto sha1Update = [ctx = &ctx](char *buf, size_t len) { + SHA1_Update(ctx, buf, len); + }; + int err = ForEachFileSegment(fpath, sha1Update); + SHA1_Final(res.get(), &ctx); + return HashFinal(err, res, SHA_DIGEST_LENGTH); +} + +tuple BFileHash::HashWithSHA256(const string &fpath) +{ + auto res = make_unique(SHA256_DIGEST_LENGTH); + SHA256_CTX ctx; + SHA256_Init(&ctx); + auto sha256Update = [ctx = &ctx](char *buf, size_t len) { + SHA256_Update(ctx, buf, len); + }; + int err = ForEachFileSegment(fpath, sha256Update); + SHA256_Final(res.get(), &ctx); + return HashFinal(err, res, SHA256_DIGEST_LENGTH); +} + +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_ohos/startup/backup_para.cpp b/utils/src/b_ohos/startup/backup_para.cpp index 8047ef0e1ae2a2e5d9aea18b52bca320ad80384b..c3028632a8077db4a28644499e2fbf588ecfb40e 100644 --- a/utils/src/b_ohos/startup/backup_para.cpp +++ b/utils/src/b_ohos/startup/backup_para.cpp @@ -66,6 +66,26 @@ bool BackupPara::GetBackupDebugOverrideExtensionConfig() return value == "true"; } +bool BackupPara::GetBackupOverrideBackupSARelease() +{ + auto [getCfgParaValSucc, value] = + GetConfigParameterValue(BConstants::BACKUP_OVERRIDE_BACKUP_SA_RELEASE_KEY, BConstants::BACKUP_PARA_VALUE_MAX); + if (!getCfgParaValSucc) { + throw BError(BError::Codes::SA_INVAL_ARG, "Fail to get configuration parameter value of backup.para"); + } + return value == "true"; +} + +bool BackupPara::GetBackupOverrideIncrementalRestore() +{ + auto [getCfgParaValSucc, value] = + GetConfigParameterValue(BConstants::BACKUP_OVERRIDE_INCREMENTAL_KEY, BConstants::BACKUP_PARA_VALUE_MAX); + if (!getCfgParaValSucc) { + throw BError(BError::Codes::SA_INVAL_ARG, "Fail to get configuration parameter value of backup.para"); + } + return value == "true"; +} + tuple BackupPara::GetBackupDebugOverrideAccount() { auto [getCfgParaValSucc, value] = GetConfigParameterValue(BConstants::BACKUP_DEBUG_OVERRIDE_ACCOUNT_CONFIG_KEY,