diff --git a/BUILD.gn b/BUILD.gn index 1b647149015cca09898eec6803d9ed3b494d6fa3..9ece6d75b2f773be3bec582524385d7bc1e40c11 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -13,10 +13,6 @@ import("//build/ohos.gni") -group("libremotefileshare") { - deps = [ "interfaces/kits/js:remotefileshare" ] -} - group("tgt_backup_extension") { deps = [ "frameworks/native/backup_ext:backup_extension_ability_native", diff --git a/README_ZH.md b/README_ZH.md index 5d99da33243b3d9d43e370b6e92a257531a32eb2..4c1135eae71b12ff543ecb5d3ab0ac3a2bdc787c 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -12,28 +12,6 @@ │ └── kits // 对外接口声明 ``` -## **说明** -### 接口说明 -**表1** 应用文件服务接口说明 -| **接口名** | **说明** | -| ------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | -| createSharePath(fd: number, cid: string, callback: AsyncCallback\): void
createSharePath(fd: number, cid: string): Promise\ | 将文件fd与设备cid传递给分布式文件系统,创建跨设备分享路径 | -### 使用说明 -createSharePath接口为分享文件fd创建能够跨设备访问的分布式路径,异步返回创建结果,设备号cid用于指定分享设备。 - -示例: -``` -import remotefileshare from '@ohos.remotefileshare' - -remotefileshare.createSharePath(fd, cid, function(err, path) { - // callback -}); - -remotefileshare.createSharePath(fd, cid).then(function(path) { - // promise -}); -``` - # 备份恢复 ## **简介** diff --git a/bundle.json b/bundle.json index 688519e6d1108853846929ca9748a676a2d9e043..c2bf2f5a5072853969e6deecee974634d7cad34d 100644 --- a/bundle.json +++ b/bundle.json @@ -43,7 +43,9 @@ ], "third_party": [ "bounds_checking_function", - "jsoncpp" + "googletest", + "jsoncpp", + "openssl" ] }, "adapted_system_type": [ "small", "standard" ], @@ -53,7 +55,6 @@ "group_type": { "base_group": [], "fwk_group": [ - "//foundation/filemanagement/app_file_service:libremotefileshare", "//foundation/filemanagement/app_file_service/interfaces/innerkits/native:etc_files", "//foundation/filemanagement/app_file_service/interfaces/innerkits/native:app_file_service_native", "//foundation/filemanagement/app_file_service/interfaces/kits/js:fileshare", @@ -110,6 +111,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/BUILD.gn b/frameworks/native/backup_ext/BUILD.gn index 379f3c72b0d248cd51269d8ceba195bc1f740d83..eb044ee941024402744b702b845a89ec4965dbec 100644 --- a/frameworks/native/backup_ext/BUILD.gn +++ b/frameworks/native/backup_ext/BUILD.gn @@ -65,6 +65,7 @@ ohos_shared_library("backup_extension_ability_native") { "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "napi:ace_napi", ] diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index b822b23f4baad01c1d4e372b757c0f41afa29562..2119f6d8337fb01d63dd4829534f552c12e1a6e1 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -21,7 +21,10 @@ #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" @@ -102,6 +105,22 @@ private: 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/tar_file.h b/frameworks/native/backup_ext/include/tar_file.h index 4e1a8a28e10653eb300c3027d7c6d4bdae1f0328..1310a35fa2c63803b9408685b7026d350ed13270 100644 --- a/frameworks/native/backup_ext/include/tar_file.h +++ b/frameworks/native/backup_ext/include/tar_file.h @@ -87,6 +87,13 @@ public: const std::string &tarFileName, const std::string &pkPath, TarMap &tarMap); + + /** + * @brief set packet mode + * + * @param isReset 是否每次重置 tarMap_ + */ + void SetPacketMode(bool isReset); private: TarFile() {} @@ -226,6 +233,8 @@ private: uint32_t tarFileCount_ {0}; std::string currentFileName_ {}; + + bool isReset_ = false; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/untar_file.h b/frameworks/native/backup_ext/include/untar_file.h index 1f92f88a2094670638d140ef5f511b49788ff36e..c2a28dc2dd4a54de78eec17fd2b6d641a52d4245 100644 --- a/frameworks/native/backup_ext/include/untar_file.h +++ b/frameworks/native/backup_ext/include/untar_file.h @@ -17,6 +17,7 @@ #define OHOS_FILEMGMT_BACKUP_BACKUP_UNTAR_FILE_H #include "tar_file.h" +#include "b_json/b_report_entity.h" namespace OHOS::FileManagement::Backup { struct FileStatInfo { @@ -32,6 +33,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 +49,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 +122,15 @@ private: */ void ParseFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &info); + /** + * @brief parse incremental file by typeFlag + * + * @param typeFlag 文件类型标志 + * @param isSkip 是否跳过当前文件 + * @param info 文件属性结构体 + */ + int ParseIncrementalFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &info); + /** * @brief Handle file ownership groups * @@ -128,6 +147,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 0c0c719619388623e3de925338e07b9e868a340a..5278e3d88285f3fc6deea194424180d7083b84a1 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,12 +40,15 @@ #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" #include "service_proxy.h" +#include "hitrace_meter.h" #include "tar_file.h" #include "untar_file.h" @@ -53,8 +60,15 @@ 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"); @@ -88,6 +102,7 @@ static bool CheckAndCreateDirectory(const string& filePath) static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGE("GetFileHandleForSpecialCloneCloud: fileName is %{public}s", fileName.data()); string filePath = fileName; if (fileName.front() != BConstants::FILE_SEPARATOR_CHAR) { @@ -111,6 +126,7 @@ static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName) UniqueFd BackupExtExtension::GetFileHandle(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { HILOGI("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); @@ -143,11 +159,13 @@ UniqueFd BackupExtExtension::GetFileHandle(const string &fileName) ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); return ERR_OK; } ErrCode BackupExtExtension::HandleClear() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("begin clear"); if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); @@ -159,6 +177,7 @@ ErrCode BackupExtExtension::HandleClear() static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); BJsonCachedEntity cachedEntity( UniqueFd(open(INDEX_FILE_BACKUP.data(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR))); auto cache = cachedEntity.Structuralize(); @@ -181,6 +200,7 @@ static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) static ErrCode BigFileReady(sptr proxy) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); BJsonCachedEntity cachedEntity(UniqueFd(open(INDEX_FILE_BACKUP.data(), O_RDONLY))); auto cache = cachedEntity.Structuralize(); auto pkgInfo = cache.GetExtManageInfo(); @@ -212,6 +232,7 @@ static ErrCode BigFileReady(sptr proxy) static bool IsAllFileReceived(vector tars, bool isSpeicalVersion) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 是否已收到索引文件 if (isSpeicalVersion) { HILOGI("Check if manage.json is received for SpeicalVersion."); @@ -246,6 +267,7 @@ static bool IsAllFileReceived(vector tars, bool isSpeicalVersion) ErrCode BackupExtExtension::PublishFile(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGE("begin publish file. fileName is %{public}s", fileName.data()); try { if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { @@ -290,11 +312,13 @@ ErrCode BackupExtExtension::PublishFile(const string &fileName) ErrCode BackupExtExtension::PublishIncrementalFile(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); return ERR_OK; } ErrCode BackupExtExtension::HandleBackup() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); string usrConfig = extension_->GetUsrConfig(); BJsonCachedEntity cachedEntity(usrConfig); auto cache = cachedEntity.Structuralize(); @@ -309,6 +333,7 @@ ErrCode BackupExtExtension::HandleBackup() static bool IsUserTar(const string &tarFile, const string &indexFile) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); if (tarFile.empty()) { return false; } @@ -328,6 +353,7 @@ static bool IsUserTar(const string &tarFile, const string &indexFile) static pair> GetFileInfos(const vector &includes, const vector &excludes) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto [errCode, files, smallFiles] = BDir::GetBigFiles(includes, excludes); if (errCode != 0) { return {}; @@ -363,6 +389,7 @@ static pair> GetFileInfos(const vector &includes, int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Do backup"); if (extension_->GetExtensionAction() != BConstants::ExtensionAction::BACKUP) { return EPERM; @@ -405,6 +432,7 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) int BackupExtExtension::DoRestore(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Do restore"); if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { return EPERM; @@ -427,6 +455,7 @@ int BackupExtExtension::DoRestore(const string &fileName) void BackupExtExtension::AsyncTaskBackup(const string config) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto task = [obj {wptr(this)}, config]() { auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, @@ -465,6 +494,7 @@ void BackupExtExtension::AsyncTaskBackup(const string config) static void RestoreBigFilesForSpecialCloneCloud(ExtManageInfo item) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); struct stat& sta = item.sta; string fileName = item.hashName; if (chmod(fileName.c_str(), sta.st_mode) != 0) { @@ -480,6 +510,7 @@ static void RestoreBigFilesForSpecialCloneCloud(ExtManageInfo item) static ErrCode RestoreTarForSpeicalCloneCloud(ExtManageInfo item) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); string tarName = item.hashName; if (item.fileName.empty()) { HILOGE("Invalid untar path info for tar %{public}s", tarName.c_str()); @@ -499,6 +530,7 @@ static ErrCode RestoreTarForSpeicalCloneCloud(ExtManageInfo item) static ErrCode RestoreFilesForSpecialCloneCloud() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 获取索引文件内容 string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); BJsonCachedEntity cachedEntity(UniqueFd(open(INDEX_FILE_RESTORE.data(), O_RDONLY))); @@ -590,6 +622,7 @@ static void RestoreBigFileAfter(const string& fileName, const string& filePath, static void RestoreBigFiles(bool appendTargetPath) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 获取索引文件内容 string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); BJsonCachedEntity cachedEntity(UniqueFd(open(INDEX_FILE_RESTORE.data(), O_RDONLY))); @@ -612,13 +645,14 @@ static void RestoreBigFiles(bool appendTargetPath) HILOGE("failed to copy the file. err = %{public}d", errno); continue; } - + RestoreBigFileAfter(fileName, filePath, item.sta, cache.GetHardLinkInfo(item.hashName)); } } static void DeleteBackupTars() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 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(); @@ -702,6 +736,7 @@ void BackupExtExtension::AsyncTaskRestore() void BackupExtExtension::AsyncTaskRestoreForUpgrade() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto task = [obj {wptr(this)}]() { auto ptr = obj.promote(); try { @@ -751,6 +786,7 @@ void BackupExtExtension::ExtClear() void BackupExtExtension::DoClear() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { string backupCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); string restoreCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); @@ -776,6 +812,7 @@ void BackupExtExtension::DoClear() void BackupExtExtension::AppDone(ErrCode errCode) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto proxy = ServiceProxy::GetInstance(); BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); auto ret = proxy->AppDone(errCode); @@ -786,6 +823,7 @@ void BackupExtExtension::AppDone(ErrCode errCode) void BackupExtExtension::AsyncTaskOnBackup() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto task = [obj {wptr(this)}]() { auto ptr = obj.promote(); try { @@ -827,6 +865,7 @@ void BackupExtExtension::AsyncTaskOnBackup() ErrCode BackupExtExtension::HandleRestore() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); VerifyCaller(); if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { HILOGI("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); @@ -848,13 +887,365 @@ ErrCode BackupExtExtension::HandleRestore() return 0; } +static string GetReportFileName(const string &fileName) +{ + string reportName = fileName + "." + string(BConstants::REPORT_FILE_EXT); + return reportName; +} + +using CompareFilesResult = tuple, + map, + map, + map>; + +static CompareFilesResult 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 : ""; + } + + allFiles.try_emplace(path, item.second); + if (cloudFiles.find(path) == cloudFiles.end() || + (item.second.isDir == false && item.second.isIncremental == true && + cloudFiles.find(path)->second.hash != item.second.hash)) { + // 在云空间简报里不存在或者hash不一致 + if (item.second.size < BConstants::BIG_FILE_BOUNDARY) { + smallFiles.try_emplace(path, item.second); + continue; + } + struct stat sta = {}; + if (stat(path.c_str(), &sta) == -1) { + continue; + } + bigFiles.try_emplace(path, sta); + bigInfos.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}; +} + ErrCode BackupExtExtension::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + 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() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); return {UniqueFd(-1), UniqueFd(-1)}; } + +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; + string manageFile = GetReportFileName(tarFile); + 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)); + 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; +} + +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; + // 设置下打包模式 + TarFile::GetInstance().SetPacketMode(true); + 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/tar_file.cpp b/frameworks/native/backup_ext/src/tar_file.cpp index f75011a00d17800fa9583a01ace0d6c1ecd34e75..e08b4c4a0b07467af35150fc5ca1850f32b2d2d2 100644 --- a/frameworks/native/backup_ext/src/tar_file.cpp +++ b/frameworks/native/backup_ext/src/tar_file.cpp @@ -23,6 +23,7 @@ #include #include +#include "b_error/b_error.h" #include "b_resources/b_constants.h" #include "directory_ex.h" #include "filemgmt_libhilog.h" @@ -62,10 +63,7 @@ bool TarFile::Packet(const vector &srcFiles, const string &tarFileName, packagePath_ = packagePath_.substr(0, packagePath_.length() - 1); } - if (!CreateSplitTarFile()) { - HILOGE("Failed to create split tar file"); - return false; - } + CreateSplitTarFile(); size_t index = 0; for (const auto &filePath : srcFiles) { @@ -81,9 +79,8 @@ bool TarFile::Packet(const vector &srcFiles, const string &tarFileName, } } - if (!FillSplitTailBlocks()) { - HILOGE("Failed to fill split tail blocks"); - } + FillSplitTailBlocks(); + tarMap = tarMap_; if (currentTarFile_ != nullptr) { @@ -109,13 +106,14 @@ bool TarFile::TraversalFile(string &filePath) } if (!AddFile(filePath, curFileStat, false)) { HILOGE("Failed to add file to tar package"); - return false; + throw BError(BError::Codes::EXT_BACKUP_PACKET_ERROR, "TraversalFile Failed to add file to tar package"); } if (currentTarFileSize_ >= DEFAULT_SLICE_SIZE) { fileCount_ = 0; FillSplitTailBlocks(); CreateSplitTarFile(); + return true; } // tar包内文件数量大于6000,分片打包 @@ -282,7 +280,7 @@ bool TarFile::CreateSplitTarFile() currentTarFile_ = fopen(currentTarName_.c_str(), "wb+"); if (currentTarFile_ == nullptr) { HILOGE("Failed to open file %{public}s, err = %{public}d", currentTarName_.c_str(), errno); - return false; + throw BError(BError::Codes::EXT_BACKUP_PACKET_ERROR, "CreateSplitTarFile Failed to open file"); } currentTarFileSize_ = 0; @@ -302,26 +300,37 @@ bool TarFile::CompleteBlock(off_t size) bool TarFile::FillSplitTailBlocks() { + if (currentTarFile_ == nullptr) { + throw BError(BError::Codes::EXT_BACKUP_PACKET_ERROR, "FillSplitTailBlocks currentTarFile_ is null"); + } + + // write tar file tail + const int END_BLOCK_SIZE = 1024; + vector buff {}; + buff.resize(BLOCK_SIZE); + WriteAll(buff, END_BLOCK_SIZE); + fflush(currentTarFile_); + struct stat staTar {}; int ret = stat(currentTarName_.c_str(), &staTar); if (ret != 0) { HILOGE("Failed to stat file %{public}s, err = %{public}d", currentTarName_.c_str(), errno); - return false; + throw BError(BError::Codes::EXT_BACKUP_PACKET_ERROR, "FillSplitTailBlocks Failed to stat file"); } - if (staTar.st_size == 0 && tarFileCount_ > 0 && currentTarFile_ != nullptr) { + + if (staTar.st_size == 0 && tarFileCount_ > 0 && fileCount_ == 0) { fclose(currentTarFile_); currentTarFile_ = nullptr; remove(currentTarName_.c_str()); return true; } - // write tar file tail - const int END_BLOCK_SIZE = 1024; - vector buff {}; - buff.resize(BLOCK_SIZE); - WriteAll(buff, END_BLOCK_SIZE); + + if (isReset_) { + tarMap_.clear(); + } + tarMap_.emplace(tarFileName_, make_tuple(currentTarName_, staTar, false)); - fflush(currentTarFile_); fclose(currentTarFile_); currentTarFile_ = nullptr; tarFileCount_++; @@ -477,4 +486,8 @@ bool TarFile::WriteLongName(string &name, char type) return CompleteBlock(sz); } +void TarFile::SetPacketMode(bool isReset) +{ + isReset_ = isReset; +} } // 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 31b9f7713b7f8311c1ec48b2e1dd4c92b0788249..d003b2d82d90023195354083fed80c6f34db2020 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,67 @@ 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); + if (ret != 0) { + HILOGE("Failed to fseeko tarFile SEEK_END, err = %{public}d", errno); + return ret; + } + tarFileSize_ = ftello(tarFilePtr_); + // reback file to begin + if ((ret = fseeko(tarFilePtr_, 0L, SEEK_SET)) != 0) { + HILOGE("Failed to fseeko tarFile SEEK_SET, err = %{public}d", errno); + return ret; + } + + bool finished = false; + while (!finished) { + 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); + if ((ret = ParseIncrementalFileByTypeFlag(header->typeFlag, isSkip, info)) != 0) { + HILOGE("Failed to parse incremental file by type flag"); + return ret; + } + 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 +280,59 @@ void UntarFile::ParseFileByTypeFlag(char typeFlag, bool &isSkip, FileStatInfo &i } } +int 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; + if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) { + HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); + return -1; + } + 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) { + size_t read = fread(&(info.longName[0]), sizeof(char), nameLen, tarFilePtr_); + if (read < nameLen) { + HILOGE("Failed to fread longName of %{private}s, nameLen = %{public}ud, read = %{public}ud", + info.fullPath.c_str(), nameLen, read); + return -1; + } + } + isSkip = true; + if (fseeko(tarFilePtr_, pos_ + tarFileBlockCnt_ * BLOCK_SIZE, SEEK_SET) != 0) { + HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); + return -1; + } + break; + } + default: { + // Ignoring, skip + isSkip = true; + if (fseeko(tarFilePtr_, tarFileBlockCnt_ * BLOCK_SIZE, SEEK_CUR) != 0) { + HILOGE("Failed to fseeko of %{private}s, err = %{public}d", info.fullPath.c_str(), errno); + return -1; + } + break; + } + } + + return 0; +} + 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/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index e89285aba1cdea2b62a31c3813279bf8500a3709..e176da568edd5e26b5f779c50de792e9c9d0a40e 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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..37139fae6965744c9c19c081ae80725fad0aa7de 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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..9336f3d95f948b52ca5a3b7efa57a9582e85ec58 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -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 index 1ce46c0ba46a7e624178e596fea34074dd43d20e..46c0e30718dd6fc48528277f34a39d9bea3d0dfb 100644 --- a/frameworks/native/backup_kit_inner/src/service_incremental_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_incremental_proxy.cpp @@ -24,12 +24,14 @@ #include "filemgmt_libhilog.h" #include "svc_death_recipient.h" #include "unique_fd.h" +#include "hitrace_meter.h" namespace OHOS::FileManagement::Backup { using namespace std; ErrCode ServiceProxy::Release() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -50,6 +52,7 @@ ErrCode ServiceProxy::Release() UniqueFd ServiceProxy::GetLocalCapabilitiesIncremental(const vector &bundleNames) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -79,6 +82,7 @@ UniqueFd ServiceProxy::GetLocalCapabilitiesIncremental(const vector remote) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "remote is nullptr"); MessageParcel data; @@ -110,6 +114,7 @@ ErrCode ServiceProxy::InitIncrementalBackupSession(sptr remote) ErrCode ServiceProxy::AppendBundlesIncrementalBackupSession(const vector &bundlesToBackup) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "remote is nullptr"); MessageParcel data; @@ -138,6 +143,7 @@ ErrCode ServiceProxy::AppendBundlesIncrementalBackupSession(const vector bool ServiceProxy::WriteParcelableVector(const std::vector &parcelableVector, Parcel &data) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); if (!data.WriteUint32(parcelableVector.size())) { HILOGE("failed to WriteInt32 for parcelableVector.size()"); return false; diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 43e01a9942b6e5af5805dc557c778526d84d667f..f771764d627f3ac0a9ca51648444bc368fdf89d8 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -23,12 +23,14 @@ #include "b_resources/b_constants.h" #include "filemgmt_libhilog.h" #include "svc_death_recipient.h" +#include "hitrace_meter.h" namespace OHOS::FileManagement::Backup { using namespace std; ErrCode ServiceProxy::InitRestoreSession(sptr remote) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -56,6 +58,7 @@ ErrCode ServiceProxy::InitRestoreSession(sptr remote) ErrCode ServiceProxy::InitBackupSession(sptr remote) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -83,6 +86,7 @@ ErrCode ServiceProxy::InitBackupSession(sptr remote) ErrCode ServiceProxy::Start() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -103,6 +107,7 @@ ErrCode ServiceProxy::Start() UniqueFd ServiceProxy::GetLocalCapabilities() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -126,6 +131,7 @@ UniqueFd ServiceProxy::GetLocalCapabilities() ErrCode ServiceProxy::PublishFile(const BFileInfo &fileInfo) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -151,6 +157,7 @@ ErrCode ServiceProxy::PublishFile(const BFileInfo &fileInfo) ErrCode ServiceProxy::AppFileReady(const string &fileName, UniqueFd fd) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -178,6 +185,7 @@ ErrCode ServiceProxy::AppFileReady(const string &fileName, UniqueFd fd) ErrCode ServiceProxy::AppDone(ErrCode errCode) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -202,6 +210,7 @@ ErrCode ServiceProxy::AppDone(ErrCode errCode) ErrCode ServiceProxy::GetFileHandle(const string &bundleName, const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -233,6 +242,7 @@ ErrCode ServiceProxy::AppendBundlesRestoreSession(UniqueFd fd, RestoreTypeEnum restoreType, int32_t userId) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -267,6 +277,7 @@ ErrCode ServiceProxy::AppendBundlesRestoreSession(UniqueFd fd, ErrCode ServiceProxy::AppendBundlesBackupSession(const vector &bundleNames) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -292,6 +303,7 @@ ErrCode ServiceProxy::AppendBundlesBackupSession(const vector &bundl ErrCode ServiceProxy::Finish() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -312,6 +324,7 @@ ErrCode ServiceProxy::Finish() sptr ServiceProxy::GetInstance() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); unique_lock lock(proxyMutex_); if (serviceProxy_ != nullptr) { return serviceProxy_; @@ -346,6 +359,7 @@ sptr ServiceProxy::GetInstance() void ServiceProxy::InvaildInstance() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("invalid instance"); unique_lock lock(proxyMutex_); serviceProxy_ = nullptr; @@ -354,6 +368,7 @@ void ServiceProxy::InvaildInstance() void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilitySuccess(int32_t systemAbilityId, const OHOS::sptr &remoteObject) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Load backup sa success, systemAbilityId: %{private}d, remoteObject result:%{private}s", systemAbilityId, (remoteObject != nullptr) ? "true" : "false"); if (systemAbilityId != FILEMANAGEMENT_BACKUP_SERVICE_SA_ID || remoteObject == nullptr) { @@ -384,6 +399,7 @@ void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilitySuccess(int32_t void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGE("Load backup sa failed, systemAbilityId:%{private}d", systemAbilityId); unique_lock lock(proxyMutex_); serviceProxy_ = nullptr; 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..c0fa998645d74655d45b4bf536b5b631e802e5ef 100644 --- a/interfaces/common/include/sandbox_helper.h +++ b/interfaces/common/include/sandbox_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -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..e15b6c1d7f9fe8c5f283112760aa1504aa7296e0 100644 --- a/interfaces/common/src/sandbox_helper.cpp +++ b/interfaces/common/src/sandbox_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -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('.'); @@ -275,6 +310,24 @@ static void GetNetworkIdFromUri(const std::string &fileUri, string &networkId) networkId = networkIdInfo.substr(posIndex + 1); } +static void DoGetPhysicalPath(string &lowerPathTail, string &lowerPathHead, const string &sandboxPath, + std::unordered_map &sandboxPathMap) +{ + string::size_type curPrefixMatchLen = 0; + for (auto it = sandboxPathMap.begin(); it != sandboxPathMap.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); + } + } + } +} + int32_t SandboxHelper::GetPhysicalPath(const std::string &fileUri, const std::string &userId, std::string &physicalPath) { @@ -297,20 +350,44 @@ int32_t SandboxHelper::GetPhysicalPath(const std::string &fileUri, const std::st string lowerPathTail = ""; string lowerPathHead = ""; - string::size_type curPrefixMatchLen = 0; - for (auto it = sandboxPathMap_.begin(); it != sandboxPathMap_.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); - } - } + DoGetPhysicalPath(lowerPathTail, lowerPathHead, sandboxPath, sandboxPathMap_); + + if (lowerPathHead == "") { + LOGE("lowerPathHead is invalid"); + return -EINVAL; + } + + string networkId = LOCAL; + GetNetworkIdFromUri(fileUri, networkId); + + physicalPath = GetLowerPath(lowerPathHead, lowerPathTail, userId, bundleName, networkId); + 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 = ""; + DoGetPhysicalPath(lowerPathTail, lowerPathHead, sandboxPath, backupSandboxPathMap_); + if (lowerPathHead == "") { LOGE("lowerPathHead is invalid"); return -EINVAL; diff --git a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn b/interfaces/inner_api/native/backup_kit_inner/BUILD.gn index 15a5bf02a2b004acdf97ca07d6b3d0f7cdeb3b84..f84fc96cc9e7190e0df11d6f833ae830598f8c91 100644 --- a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn +++ b/interfaces/inner_api/native/backup_kit_inner/BUILD.gn @@ -67,6 +67,7 @@ ohos_shared_library("backup_kit_inner") { external_deps = [ "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "safwk:system_ability_fwk", "samgr:samgr_proxy", 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..b9cc25e1b1b3b319656792d1714f708db709b5aa 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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_session_backup.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h index 059e3b798a1f51788594ab6950b15beb40dc3fba..c662a5844912465670375f87b689276be3a19e2a 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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..59fe34360f272729a45417bdbda13cab9002910b 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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..9b7853706ed8f7ba069a60719ab714a993904bdc 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -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/innerkits/native/BUILD.gn b/interfaces/innerkits/native/BUILD.gn index 60d1aae20b5b2692ea9d12d7d7d4f3225e204437..20a5c1df789a83a920867476a05bf52b9d7e4c82 100644 --- a/interfaces/innerkits/native/BUILD.gn +++ b/interfaces/innerkits/native/BUILD.gn @@ -104,6 +104,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 = [ @@ -184,5 +191,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/innerkits/native/remote_file_share/src/remote_file_share.cpp b/interfaces/innerkits/native/remote_file_share/src/remote_file_share.cpp index 362800abea0b4f28abdf5f7b96d9b7c7c3cd748a..bf42cd686e6061312736918e658ca19f243d8d30 100644 --- a/interfaces/innerkits/native/remote_file_share/src/remote_file_share.cpp +++ b/interfaces/innerkits/native/remote_file_share/src/remote_file_share.cpp @@ -189,8 +189,6 @@ static int CreateShareFile(struct HmdfsShareControl &shareControl, const char* f if (ioctl(dirFd, HMDFS_IOC_SET_SHARE_PATH, &shareControl) < 0) { LOGE("RemoteFileShare::CreateShareFile, ioctl failed with %{public}d", errno); - close(dirFd); - return errno; } close(dirFd); return 0; diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 0d350384f4283ecc89ab26def1288576cd5194ac..e1762314c5a5d45a336b34126ddd65774697ea1a 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -15,42 +15,6 @@ import("//build/ohos.gni") import("//foundation/filemanagement/app_file_service/app_file_service.gni") import("//foundation/filemanagement/app_file_service/backup.gni") -ohos_shared_library("remotefileshare") { - stack_protector_ret = true - sanitize = { - integer_overflow = true - ubsan = true - boundary_sanitize = true - cfi = true - cfi_cross_dso = true - debug = false - } - - include_dirs = [ - "${path_napi}/interfaces/kits", - "//third_party/bounds_checking_function/include", - ] - - sources = [ - "remote_file_share/remotefileshare_n_exporter.cpp", - "remote_file_share/remotefileshare_napi.cpp", - ] - - deps = [ "${third_party_path}/bounds_checking_function:libsec_shared" ] - - external_deps = [ - "file_api:filemgmt_libhilog", - "file_api:filemgmt_libn", - "hilog:libhilog", - "napi:ace_napi", - ] - - relative_install_dir = "module" - - part_name = "app_file_service" - subsystem_name = "filemanagement" -} - ohos_shared_library("fileshare") { include_dirs = [ ".", 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..f607d3b6ce66b0469f0a5cd10476d944194f069e --- /dev/null +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -0,0 +1,299 @@ +/* + * 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 "session_incremental_backup_n_exporter.h" + +#include +#include + +#include "b_error/b_error.h" +#include "b_filesystem/b_file.h" +#include "b_incremental_backup_session.h" +#include "b_incremental_data.h" +#include "b_resources/b_constants.h" +#include "backup_kit_inner.h" +#include "directory_ex.h" +#include "filemgmt_libhilog.h" +#include "general_callbacks.h" +#include "incremental_backup_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; + } + + 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 {}; + } + + return {}; +} + +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; + } + + 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; + } + + 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/remote_file_share/remotefileshare_n_exporter.cpp b/interfaces/kits/js/remote_file_share/remotefileshare_n_exporter.cpp deleted file mode 100644 index 9569c7a30edc64e16bd28288399dde958b39b60c..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/remote_file_share/remotefileshare_n_exporter.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) 2021 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 "remotefileshare_n_exporter.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "securec.h" - -namespace OHOS { -namespace AppFileService { -namespace ModuleRemoteFileShare { -using namespace FileManagement::LibN; -using namespace std; -namespace { - constexpr int HMDFS_CID_SIZE = 64; - constexpr unsigned HMDFS_IOC = 0xf2; - const std::string SHARE_PATH = "/data/storage/el2/distributedfiles/.share"; -} - -#define HMDFS_IOC_SET_SHARE_PATH _IOW(HMDFS_IOC, 1, struct hmdfs_share_control) - -struct hmdfs_share_control { - int src_fd; - char cid[HMDFS_CID_SIZE]; -}; - -static NError CreateSharePath(const int src_fd, const std::string &cid) -{ - struct hmdfs_share_control sc; - int32_t ret = 0; - int32_t dirFd; - - if (access(SHARE_PATH.c_str(), F_OK) != 0) { - ret = mkdir(SHARE_PATH.c_str(), S_IRWXU | S_IRWXG | S_IXOTH); - if (ret < 0) { - return NError(errno); - } - } - - char realPath[PATH_MAX] = {0}; - if (!realpath(SHARE_PATH.c_str(), realPath)) { - return NError(errno); - } - dirFd = open(realPath, O_RDONLY); - if (dirFd < 0) { - return NError(errno); - } - - sc.src_fd = src_fd; - if (memcpy_s(sc.cid, HMDFS_CID_SIZE, cid.c_str(), cid.size()) != 0) { - close(dirFd); - return NError(ENOMEM); - } - - ret = ioctl(dirFd, HMDFS_IOC_SET_SHARE_PATH, &sc); - if (ret < 0) { - close(dirFd); - return NError(errno); - } - - close(dirFd); - return NError(ERRNO_NOERR); -} - -napi_value CreateSharePath(napi_env env, napi_callback_info info) -{ - NFuncArg funcArg(env, info); - if (!funcArg.InitArgs(static_cast(NARG_CNT::TWO), static_cast(NARG_CNT::THREE))) { - NError(EINVAL).ThrowErr(env, "Number of arguments unmatched"); - return nullptr; - } - - bool succ = false; - int src_fd; - std::unique_ptr cid; - size_t cidLen; - tie(succ, src_fd) = NVal(env, funcArg[static_cast(NARG_POS::FIRST)]).ToInt32(); - if (!succ) { - NError(EINVAL).ThrowErr(env, "Invalid fd"); - return nullptr; - } - tie(succ, cid, cidLen) = NVal(env, funcArg[static_cast(NARG_POS::SECOND)]).ToUTF8String(); - if (!succ || cidLen != HMDFS_CID_SIZE) { - NError(EINVAL).ThrowErr(env, "Invalid cid"); - return nullptr; - } - - std::string cidString(cid.get()); - auto cbExec = [src_fd, cidString]() -> NError { - return CreateSharePath(src_fd, cidString); - }; - auto cbComplete = [](napi_env env, NError err) -> NVal { - if (err) { - return { env, err.GetNapiErr(env) }; - } else { - return NVal::CreateUTF8String(env, SHARE_PATH); - } - }; - std::string procedureName = "CreateSharePath"; - NVal thisVar(env, funcArg.GetThisVar()); - if (funcArg.GetArgc() == static_cast(NARG_CNT::TWO)) { - return NAsyncWorkPromise(env, thisVar).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NVal cb(env, funcArg[static_cast(NARG_POS::THIRD)]); - if (cb.TypeIs(napi_function)) { - return NAsyncWorkCallback(env, thisVar, cb).Schedule(procedureName, cbExec, cbComplete).val_; - } else { - NError(EINVAL).ThrowErr(env, "Callback function error"); - return nullptr; - } - } - return NVal::CreateUndefined(env).val_; -} -} // namespace ModuleRemoteFileShare -} // namespace AppFileService -} // namespace OHOS diff --git a/interfaces/kits/js/remote_file_share/remotefileshare_napi.cpp b/interfaces/kits/js/remote_file_share/remotefileshare_napi.cpp deleted file mode 100644 index 69c672088224a6cb15a7e54a346cda83ffaaba04..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/remote_file_share/remotefileshare_napi.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2021 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 "remotefileshare_napi.h" -#include "remotefileshare_n_exporter.h" - -namespace OHOS { -namespace AppFileService { -namespace ModuleRemoteFileShare { -/*********************************************** - * Module export and register - ***********************************************/ -napi_value RemoteFileShareExport(napi_env env, napi_value exports) -{ - static napi_property_descriptor desc[] = { - DECLARE_NAPI_FUNCTION("createSharePath", CreateSharePath), - }; - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; -} - -NAPI_MODULE(remotefileshare, RemoteFileShareExport) -} // namespace ModuleRemoteFileShare -} // namespace AppFileService -} // namespace OHOS diff --git a/services/backup_sa/BUILD.gn b/services/backup_sa/BUILD.gn index fbe375226771cf2380bbc96a46a613eed611a1b9..53ff7a4f5f6bc32b14b6312147c5b76ea5ff5197 100644 --- a/services/backup_sa/BUILD.gn +++ b/services/backup_sa/BUILD.gn @@ -63,6 +63,7 @@ ohos_shared_library("backup_sa") { "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/services/backup_sa/include/module_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h index 7af9bedff1cc049afc013260865c8badff76be75..af1c849e412b84516b18ad76006b633cf9548466 100644 --- a/services/backup_sa/include/module_external/bms_adapter.h +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -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..30b44abd1c85c0bd8f14724bf172b03505219e84 100644 --- a/services/backup_sa/include/module_external/sms_adapter.h +++ b/services/backup_sa/include/module_external/sms_adapter.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (c) 2023-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 @@ -17,6 +17,8 @@ #define OHOS_FILEMGMT_BACKUP_STORAGE_MGR_ADAPTER_H #include +#include +#include #include "istorage_manager.h" @@ -44,6 +46,17 @@ public: * @param size para data */ static int32_t UpdateMemPara(int32_t size); + + /** + * @brief Get the user storage stats object + * + * @param userId user id + * @param bundleNames + * @param incrementalBackTimes + * @param pkgFileSizes bundle backup file size + */ + static int32_t GetBundleStatsForIncrease(uint32_t userId, const std::vector &bundleNames, + const std::vector &incrementalBackTimes, std::vector &pkgFileSizes); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_STORAGE_MGR_ADAPTER_H \ No newline at end of file diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index a8038634bc31e168ca7fee84c21de866e2fc28df..d0753183da328ebe2e2b24ef3f723ea54eafc5e8 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" @@ -169,4 +172,146 @@ string BundleMgrAdapter::GetAppGalleryBundleName() } return bundleName; } + +static bool GetBackupExtConfig(const vector &extensionInfos, + BJsonEntityCaps::BundleBackupConfigPara &backupPara) +{ + 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(); + backupPara.allToBackup = cache.GetAllowToBackupRestore(); + backupPara.extensionName = ext.name; + backupPara.restoreDeps = cache.GetRestoreDeps(); + backupPara.supportScene = cache.GetSupportScene(); + backupPara.includes = cache.GetIncludes(); + backupPara.excludes = cache.GetExcludes(); + return true; + } + 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) { + int32_t err = mkdir(backupSaBundleDir.data(), S_IRWXU | S_IRWXG); + if (err != 0) { + HILOGE("Failed to create folder in backup_sa, err = %{public}d", err); + return false; + } + } + // backup_sa include/exclude + string incExFilePath = backupSaBundleDir + BConstants::BACKUP_INCEXC_SYMBOL + to_string(lastIncrementalTime); + ofstream incExcFile; + incExcFile.open(incExFilePath.data(), ios::out | ios::trunc); + if (!incExcFile.is_open()) { + HILOGE("Cannot create incexc file, err = %{public}d", errno); + return false; + } + incExcFile << BConstants::BACKUP_INCLUDE << endl; + for (auto &include : includes) { + incExcFile << include << endl; + } + incExcFile << BConstants::BACKUP_EXCLUDE << endl; + for (auto &exclude : excludes) { + incExcFile << exclude << endl; + } + incExcFile.close(); + + // backup_sa stat + string statFilePath = backupSaBundleDir + BConstants::BACKUP_STAT_SYMBOL + to_string(lastIncrementalTime); + ofstream statFile; + statFile.open(statFilePath.data(), ios::out | ios::trunc); + if (!statFile.is_open()) { + HILOGE("Cannot create stat file"); + return false; + } + statFile.close(); + + return true; +} + +static bool GenerateBundleStatsIncrease(int32_t userId, const vector &bundleNames, + const vector &lastBackTimes, vector &bundleInfos, + vector &newBundleInfos) +{ + vector pkgFileSizes {}; + int32_t err = StorageMgrAdapter::GetBundleStatsForIncrease(userId, bundleNames, lastBackTimes, pkgFileSizes); + if (err != 0) { + HILOGE("Failed to get bundleStats result from storage, err = %{public}d", err); + return false; + } + + for (size_t i = 0; i < bundleInfos.size(); i++) { + HILOGI("BundleMgrAdapter name for %{private}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); + } + return true; +} + +vector BundleMgrAdapter::GetBundleInfosForIncremental( + const vector &incrementalDataList, int32_t userId) +{ + vector bundleNames; + vector incrementalBackTimes; + vector bundleInfos; + auto bms = GetBundleManager(); + for (auto const &bundleNameTime : incrementalDataList) { + auto bundleName = bundleNameTime.bundleName; + HILOGI("Begin Get bundleName:%{private}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 : %{private}s", installedBundle.name.data()); + continue; + } + struct BJsonEntityCaps::BundleBackupConfigPara backupPara; + if (!GetBackupExtConfig(installedBundle.extensionInfos, backupPara)) { + HILOGE("No backup extension ability found"); + continue; + } + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + installedBundle.versionName, 0, backupPara.allToBackup, + backupPara.extensionName, backupPara.restoreDeps, + backupPara.supportScene}); + if (!CreateIPCInteractionFiles(userId, bundleName, bundleNameTime.lastIncrementalTime, backupPara.includes, + backupPara.excludes)) { + HILOGE("Failed to write include/exclude files, name : %{private}s", installedBundle.name.data()); + continue; + } + bundleNames.emplace_back(bundleName); + incrementalBackTimes.emplace_back(bundleNameTime.lastIncrementalTime); + } + + vector newBundleInfos {}; + if (!GenerateBundleStatsIncrease(userId, bundleNames, incrementalBackTimes, bundleInfos, newBundleInfos)) { + HILOGE("Failed to get bundleStats result"); + return {}; + } + + 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..83a23f557e0b04c53f2367ac13ee0fad86d1af3b 100644 --- a/services/backup_sa/src/module_external/sms_adapter.cpp +++ b/services/backup_sa/src/module_external/sms_adapter.cpp @@ -86,4 +86,14 @@ int32_t StorageMgrAdapter::UpdateMemPara(int32_t size) } return oldSize; } + +int32_t StorageMgrAdapter::GetBundleStatsForIncrease(uint32_t userId, const std::vector &bundleNames, + const std::vector &incrementalBackTimes, std::vector &pkgFileSizes) +{ + auto storageMgr = GetStorageManager(); + if (storageMgr->GetBundleStatsForIncrease(userId, bundleNames, incrementalBackTimes, pkgFileSizes)) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get user storage stats"); + } + return 0; +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 5fad160f52f39868cd53d20f5aed4d1fd2634963..18a2f76d33bd0c3355189ee234d7df72a60dc740 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -55,6 +55,7 @@ #include "module_ipc/svc_restore_deps_manager.h" #include "parameter.h" #include "system_ability_definition.h" +#include "hitrace_meter.h" namespace OHOS::FileManagement::Backup { using namespace std; @@ -81,6 +82,7 @@ static inline int32_t GetUserIdDefault() void Service::OnStart() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); bool res = SystemAbility::Publish(sptr(this)); sched_ = sptr(new SchedScheduler(wptr(this), wptr(session_))); sched_->StartTimer(); @@ -89,6 +91,7 @@ void Service::OnStart() void Service::OnStop() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Called"); int32_t oldMemoryParaSize = BConstants::DEFAULT_VFS_CACHE_PRESSURE; if (session_ != nullptr) { @@ -99,6 +102,7 @@ void Service::OnStop() UniqueFd Service::GetLocalCapabilities() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); /* @@ -139,11 +143,13 @@ UniqueFd Service::GetLocalCapabilities() void Service::StopAll(const wptr &obj, bool force) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); session_->Deactive(obj, force); } string Service::VerifyCallerAndGetCallerName() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { @@ -161,6 +167,7 @@ string Service::VerifyCallerAndGetCallerName() void Service::VerifyCaller() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); switch (tokenType) { @@ -187,12 +194,14 @@ void Service::VerifyCaller() void Service::VerifyCaller(IServiceReverse::Scenario scenario) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); session_->VerifyCallerAndScenario(IPCSkeleton::GetCallingTokenID(), scenario); VerifyCaller(); } ErrCode Service::InitRestoreSession(sptr remote) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { VerifyCaller(); session_->Active({ @@ -216,6 +225,7 @@ ErrCode Service::InitRestoreSession(sptr remote) ErrCode Service::InitBackupSession(sptr remote) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { VerifyCaller(); int32_t oldSize = StorageMgrAdapter::UpdateMemPara(BConstants::BACKUP_VFS_CACHE_PRESSURE); @@ -236,6 +246,7 @@ ErrCode Service::InitBackupSession(sptr remote) ErrCode Service::Start() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); VerifyCaller(session_->GetScenario()); session_->Start(); @@ -257,6 +268,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, sptr session, const vector &bundleNames) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 auto restoreInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session->GetSessionUserId()); BJsonCachedEntity cachedEntity(move(fd)); @@ -291,6 +303,7 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, RestoreTypeEnum restoreType, int32_t userId) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); session_->IncreaseSessionCnt(); @@ -342,6 +355,7 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, ErrCode Service::AppendBundlesBackupSession(const vector &bundleNames) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 @@ -377,6 +391,7 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName ErrCode Service::Finish() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); VerifyCaller(session_->GetScenario()); session_->Finish(); @@ -386,6 +401,7 @@ ErrCode Service::Finish() ErrCode Service::PublishFile(const BFileInfo &fileInfo) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); VerifyCaller(IServiceReverse::Scenario::RESTORE); @@ -415,6 +431,7 @@ ErrCode Service::PublishFile(const BFileInfo &fileInfo) ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); string callerName = VerifyCallerAndGetCallerName(); @@ -458,6 +475,7 @@ ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd) ErrCode Service::AppDone(ErrCode errCode) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); string callerName = VerifyCallerAndGetCallerName(); @@ -493,6 +511,7 @@ ErrCode Service::AppDone(ErrCode errCode) ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGE("begin %{public}s", bundleName.data()); IServiceReverse::Scenario scenario = session_->GetScenario(); @@ -535,6 +554,7 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); VerifyCaller(IServiceReverse::Scenario::RESTORE); @@ -572,6 +592,7 @@ ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) void Service::OnBackupExtensionDied(const string &&bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { string callName = move(bundleName); session_->VerifyBundleName(callName); @@ -613,6 +634,7 @@ void Service::OnBackupExtensionDied(const string &&bundleName) void Service::ExtConnectDied(const string &callName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); /* Clear Timer */ @@ -633,6 +655,7 @@ void Service::ExtConnectDied(const string &callName) void Service::ExtStart(const string &bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGE("begin %{public}s", bundleName.data()); if (IncrementalBackup(bundleName)) { @@ -690,6 +713,7 @@ int Service::Dump(int fd, const vector &args) void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGE("begin %{public}s", bundleName.data()); IServiceReverse::Scenario scenario = session_->GetScenario(); @@ -726,6 +750,7 @@ void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto scenario = session_->GetScenario(); if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(errCode, bundleName); @@ -742,6 +767,7 @@ void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) void Service::ExtConnectDone(string bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); /* Callback for App Ext Timeout Process. */ auto timeoutCallback = [ptr {wptr(this)}, bundleName]() { auto thisPtr = ptr.promote(); @@ -778,6 +804,7 @@ void Service::ExtConnectDone(string bundleName) void Service::ClearSessionAndSchedInfo(const string &bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { session_->RemoveExtInfo(bundleName); sched_->RemoveExtConn(bundleName); @@ -796,6 +823,7 @@ void Service::ClearSessionAndSchedInfo(const string &bundleName) void Service::HandleRestoreDepsBundle(const string &bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); if (session_->GetScenario() != IServiceReverse::Scenario::RESTORE) { return; } @@ -835,6 +863,7 @@ void Service::HandleRestoreDepsBundle(const string &bundleName) void Service::OnAllBundlesFinished(ErrCode errCode) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); if (session_->IsOnAllBundlesFinished()) { IServiceReverse::Scenario scenario = session_->GetScenario(); if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { @@ -855,6 +884,7 @@ void Service::OnAllBundlesFinished(ErrCode errCode) void Service::OnStartSched() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); if (session_->IsOnOnStartSched()) { for (int num = 0; num < BConstants::EXT_CONNECT_MAX_COUNT; num++) { sched_->Sched(); @@ -864,6 +894,7 @@ void Service::OnStartSched() void Service::SendAppGalleryNotify(const BundleName &bundleName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); IServiceReverse::Scenario scenario = session_->GetScenario(); if (scenario == IServiceReverse::Scenario::RESTORE) { DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->StartRestore(bundleName); @@ -874,6 +905,7 @@ void Service::SendAppGalleryNotify(const BundleName &bundleName) void Service::SessionDeactive() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); // 结束定时器 diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index 1d76a877f26e11688f622aa88a9bbda5ed60bfb0..7c737f4de3b657f5b81900f569097a10abab0fe9 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -43,6 +43,7 @@ #include "module_ipc/svc_restore_deps_manager.h" #include "parameter.h" #include "system_ability_definition.h" +#include "hitrace_meter.h" namespace OHOS::FileManagement::Backup { using namespace std; @@ -53,6 +54,7 @@ constexpr int32_t DEBUG_ID = 100; static inline int32_t GetUserIdDefault() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto [isDebug, debugId] = BackupPara().GetBackupDebugOverrideAccount(); if (isDebug && debugId > DEBUG_ID) { return debugId; @@ -66,6 +68,7 @@ static inline int32_t GetUserIdDefault() ErrCode Service::Release() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("KILL"); VerifyCaller(session_->GetScenario()); SessionDeactive(); @@ -74,11 +77,53 @@ ErrCode Service::Release() UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vector &bundleNames) { - return UniqueFd(-EPERM); + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + 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); + UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR)); + if (fd < 0) { + HILOGE("GetLocalCapabilitiesIncremental: open file failed, err = %{public}d", errno); + session_->DecreaseSessionCnt(); + return UniqueFd(-ENOENT); + } + BJsonCachedEntity cachedEntity(move(fd)); + 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) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Begin"); try { VerifyCaller(); @@ -96,6 +141,7 @@ ErrCode Service::InitIncrementalBackupSession(sptr remote) ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector &bundlesToBackup) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 @@ -134,6 +180,7 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorGetScenario(); auto backUpConnection = session_->GetExtConnection(bundleName); auto proxy = backUpConnection->GetBackupExtProxy(); @@ -284,11 +335,11 @@ bool Service::IncrementalBackup(const string &bundleName) } if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { // 本地全量数据 - string path = BConstants::GetSaBundleBackupRootDir(session_->GetSessionUserId()) - .append(bundleName) - .append("/") - .append(BConstants::BACKUP_STAT_SYMBOL) - .append(to_string(session_->GetLastIncrementalTime(bundleName))); + 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); diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index fdbb76c56e7d2c23f38fbae163904d708bcfda01..a458e1ed380cd4d7acced2579b3f8a8ab98a215d 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -278,42 +278,136 @@ int32_t ServiceStub::CmdFinish(MessageParcel &data, MessageParcel &reply) 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 manifestFd"); + } + + 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) { - return BError(BError::Codes::OK); + 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 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 index 8833cda5b2a23805a48b242f9f3222afbb92b105..f674f510c2d2d7fd899fc58e5d672a3b7befa4c1 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp @@ -20,12 +20,14 @@ #include "filemgmt_libhilog.h" #include "iservice_registry.h" #include "system_ability_definition.h" +#include "hitrace_meter.h" namespace OHOS::FileManagement::Backup { using namespace std; ErrCode SvcExtensionProxy::GetIncrementalFileHandle(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -51,6 +53,7 @@ ErrCode SvcExtensionProxy::GetIncrementalFileHandle(const string &fileName) ErrCode SvcExtensionProxy::PublishIncrementalFile(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -76,6 +79,7 @@ ErrCode SvcExtensionProxy::PublishIncrementalFile(const string &fileName) ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -99,6 +103,7 @@ ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, Uniqu tuple SvcExtensionProxy::GetIncrementalBackupFileHandle() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; diff --git a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp index 8d1c9276c23dbb5afcb0df488a4ec022b15f3e39..690a5241bfbb19a4aff54518ff9557cc490dabaa 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp @@ -20,12 +20,14 @@ #include "filemgmt_libhilog.h" #include "iservice_registry.h" #include "system_ability_definition.h" +#include "hitrace_meter.h" namespace OHOS::FileManagement::Backup { using namespace std; UniqueFd SvcExtensionProxy::GetFileHandle(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -52,6 +54,7 @@ UniqueFd SvcExtensionProxy::GetFileHandle(const string &fileName) ErrCode SvcExtensionProxy::HandleClear() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -72,6 +75,7 @@ ErrCode SvcExtensionProxy::HandleClear() ErrCode SvcExtensionProxy::HandleBackup() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -92,6 +96,7 @@ ErrCode SvcExtensionProxy::HandleBackup() ErrCode SvcExtensionProxy::PublishFile(const string &fileName) { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; @@ -117,6 +122,7 @@ ErrCode SvcExtensionProxy::PublishFile(const string &fileName) ErrCode SvcExtensionProxy::HandleRestore() { + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; 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..122a6636ec336a467d27a824300cb681e39fbcf9 100644 --- a/tests/mock/backup_kit_inner/b_session_backup_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_backup_mock.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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..a80632f9b8b3b3c6523b9ae731410f5ee9ab25f4 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * 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 @@ -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..bb68b01a2fb8cb1fbfc8208eec86e33937d8a37b 100644 --- a/tests/mock/backup_kit_inner/b_session_restore_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_restore_mock.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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/module_external/bms_adapter_mock.cpp b/tests/mock/module_external/bms_adapter_mock.cpp index 5b9b776faaf01e24c8a232daa30f3c4d25b8e223..01fa1b8982f8a7ca088a93ce791ba4160c314b38 100644 --- a/tests/mock/module_external/bms_adapter_mock.cpp +++ b/tests/mock/module_external/bms_adapter_mock.cpp @@ -48,4 +48,13 @@ string BundleMgrAdapter::GetAppGalleryBundleName() { return ""; } + +vector BundleMgrAdapter::GetBundleInfosForIncremental( + const vector &incrementalDataList, int32_t userId) +{ + vector bundleInfos; + bundleInfos.emplace_back( + BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, true, "com.example.app2backup"}); + return bundleInfos; +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_external/sms_adapter_mock.cpp b/tests/mock/module_external/sms_adapter_mock.cpp index cafd6c62164e2c2edd3541e35b5b0b610a416864..a9f503746e2d5dedd92aa33a89b94c05c3f8c1e4 100644 --- a/tests/mock/module_external/sms_adapter_mock.cpp +++ b/tests/mock/module_external/sms_adapter_mock.cpp @@ -29,4 +29,10 @@ int32_t StorageMgrAdapter::UpdateMemPara(int32_t size) { return 0; } + +int32_t StorageMgrAdapter::GetBundleStatsForIncrease(uint32_t userId, const std::vector &bundleNames, + const std::vector &incrementalBackTimes, std::vector &pkgFileSizes) +{ + return 0; +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/moduletests/backup_kit_inner/BUILD.gn b/tests/moduletests/backup_kit_inner/BUILD.gn index 84db4ecaf0eb3742472668d5343c4862fff3228f..802b75080f8c887ad6f3e7605f5060d7b53f71cc 100644 --- a/tests/moduletests/backup_kit_inner/BUILD.gn +++ b/tests/moduletests/backup_kit_inner/BUILD.gn @@ -51,6 +51,7 @@ ohos_unittest("b_session_test") { external_deps = [ "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "ipc:ipc_core", "samgr:samgr_proxy", ] diff --git a/tests/moduletests/backup_tool/BUILD.gn b/tests/moduletests/backup_tool/BUILD.gn index 177c8e10be98c52f48ab8b8b710de6a92d6e5b34..6606cc1645eb55d62011d92b366d2a4103b0f8c3 100644 --- a/tests/moduletests/backup_tool/BUILD.gn +++ b/tests/moduletests/backup_tool/BUILD.gn @@ -24,7 +24,10 @@ ohos_unittest("tools_op_test") { "${path_backup}/utils/:backup_utils", ] - external_deps = [ "hilog:libhilog" ] + external_deps = [ + "hilog:libhilog", + "hitrace:hitrace_meter", + ] use_exceptions = true } diff --git a/tests/unittests/backup_api/backup_impl/BUILD.gn b/tests/unittests/backup_api/backup_impl/BUILD.gn index 5f28f599ae17e10316bf72ad5ecb9b85cfcdff18..182e63235ea92d9141ad85e1a16cf11ff9890147 100644 --- a/tests/unittests/backup_api/backup_impl/BUILD.gn +++ b/tests/unittests/backup_api/backup_impl/BUILD.gn @@ -67,6 +67,7 @@ ohos_unittest("backup_sa_impl_test") { external_deps = [ "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "samgr:samgr_proxy", diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index d41d18ddbf74a4bc70566ac65d9a7ec2caa002a5..7c7eb93983f7ce6120d3e6d6756639a19051f43c 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -64,6 +64,7 @@ ohos_unittest("tar_file_test") { "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_core", "c_utils:utils", + "hitrace:hitrace_meter", "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", @@ -124,6 +125,7 @@ ohos_unittest("untar_file_test") { "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_core", "c_utils:utils", + "hitrace:hitrace_meter", "ipc:ipc_core", "napi:ace_napi", "samgr:samgr_proxy", diff --git a/tests/unittests/backup_ext/tar_file_test.cpp b/tests/unittests/backup_ext/tar_file_test.cpp index 058d0ff5a1e88a26a862f4c54ef74adc712c552d..29aa5fd3d8d3e8653052ffb9d53ed97612a8e8ff 100644 --- a/tests/unittests/backup_ext/tar_file_test.cpp +++ b/tests/unittests/backup_ext/tar_file_test.cpp @@ -204,7 +204,7 @@ HWTEST_F(TarFileTest, SUB_Tar_File_Packet_0400, testing::ext::TestSize.Level1) EXPECT_FALSE(ret); EXPECT_TRUE(tarMap.empty()); } catch (...) { - EXPECT_TRUE(false); + EXPECT_TRUE(true); GTEST_LOG_(INFO) << "TarFileTest-an exception occurred by TarFile."; } GTEST_LOG_(INFO) << "TarFileTest-end SUB_Tar_File_Packet_0400"; diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 5f22a9ed130c979e8cdb9eef770707ec1a4c28f0..e320f95e7aef27a9c89662dda858173b56396f75 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -100,6 +100,7 @@ ohos_unittest("backup_service_test") { "ability_runtime:ability_manager", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "safwk:system_ability_fwk", @@ -155,6 +156,7 @@ ohos_unittest("backup_service_session_test") { "bundle_framework:appexecfwk_core", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "safwk:system_ability_fwk", @@ -250,6 +252,7 @@ ohos_unittest("backup_restore_deps_manager_test") { "ability_runtime:ability_manager", "c_utils:utils", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", "safwk:system_ability_fwk", 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 18412af65771ee2f04381b1d42b12ec049dbb678..00723373e1d2af74985991d78237e7ace1c5399a 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -475,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/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index d37ee20fede01baa6197ab61e33b9e3597e625c8..7189421ef030a7f09252cd9b2893cd3851680701 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -68,7 +68,7 @@ ErrCode ServiceTest::Init(IServiceReverse::Scenario scenario) ErrCode ret = 0; if (scenario == IServiceReverse::Scenario::RESTORE) { UniqueFd fd = servicePtr_->GetLocalCapabilities(); - EXPECT_GT(fd, BError(BError::Codes::OK)); + EXPECT_GE(fd, BError(BError::Codes::OK)); ret = servicePtr_->InitRestoreSession(remote_); EXPECT_EQ(ret, BError(BError::Codes::OK)); ret = servicePtr_->AppendBundlesRestoreSession(move(fd), bundleNames); @@ -809,4 +809,47 @@ HWTEST_F(ServiceTest, SUB_Service_OnStop_0100, testing::ext::TestSize.Level1) } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnStop_0100"; } + +/** + * @tc.number: SUB_Service_SendAppGalleryNotify_0100 + * @tc.name: SUB_Service_SendAppGalleryNotify_0100 + * @tc.desc: 测试 SendAppGalleryNotify 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SendAppGalleryNotify_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SendAppGalleryNotify_0100"; + try { + BundleName bundleName = ""; + servicePtr_->SendAppGalleryNotify(bundleName); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SendAppGalleryNotify."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SendAppGalleryNotify_0100"; +} + +/** + * @tc.number: SUB_Service_SessionDeactive_0100 + * @tc.name: SUB_Service_SessionDeactive_0100 + * @tc.desc: 测试 SessionDeactive 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(ServiceTest, SUB_Service_SessionDeactive_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_SessionDeactive_0100"; + try { + servicePtr_->SessionDeactive(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SessionDeactive."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_SessionDeactive_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp index e7e4f0cd93b1fa9ae54d08fbb17eaa23cc7f74e0..8577f9eb3b157541c5e901965fd156c29db7357c 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp @@ -1561,4 +1561,47 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_SetBundleDataSize_0101, te } GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_SetBundleDataSize_0101"; } + +/** + * @tc.number: SUB_backup_sa_session_SetSessionUserId_0100 + * @tc.name: SUB_backup_sa_session_SetSessionUserId_0100 + * @tc.desc: 测试 SetSessionUserId + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_SetSessionUserId_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_backup_sa_session_SetSessionUserId_0100"; + try { + int32_t userId = 1; + sessionManagerPtr_->SetSessionUserId(userId); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by SetSessionUserId."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_backup_sa_session_SetSessionUserId_0100"; +} + +/** + * @tc.number: SUB_backup_sa_session_GetSessionUserId_0100 + * @tc.name: SUB_backup_sa_session_GetSessionUserId_0100 + * @tc.desc: 测试 GetSessionUserId + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I8ZIMJ + */ +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetSessionUserId_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_backup_sa_session_GetSessionUserId_0100"; + try { + sessionManagerPtr_->GetSessionUserId(); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetSessionUserId."; + } + GTEST_LOG_(INFO) << "ServiceTest-end SUB_backup_sa_session_GetSessionUserId_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..34f6cbbe21c722797db22faacf92f309ab91a828 100644 --- a/tools/backup_tool/BUILD.gn +++ b/tools/backup_tool/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-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 @@ -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/src/main.cpp b/tools/backup_tool/src/main.cpp index 4de614c586acb4529aa4755db96fbc513dda3a68..704900544e26aa1696276b0a422734b8aaf1ba6b 100644 --- a/tools/backup_tool/src/main.cpp +++ b/tools/backup_tool/src/main.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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..6339ae583afc2c40fb9f4a8d0eac0ab2aba225a5 100644 --- a/tools/backup_tool/src/tools_op_backup.cpp +++ b/tools/backup_tool/src/tools_op_backup.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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 index f16db990696a416be46b9c96dff8aa57bea41bf9..e21976896d6d258d72d47db5c3ee6ad177d6d90e 100644 --- a/tools/backup_tool/src/tools_op_incremental_backup.cpp +++ b/tools/backup_tool/src/tools_op_incremental_backup.cpp @@ -169,8 +169,7 @@ static void OnFileReady(shared_ptr ctx, const BFileInfo &fileInfo, 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(), + 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)); diff --git a/tools/backup_tool/src/tools_op_restore.cpp b/tools/backup_tool/src/tools_op_restore.cpp index 333099dbd1f4fd160f72439bcdb4d82ae168c8ec..31b52d323b72645eab4736f5ef8266089fc4f77c 100644 --- a/tools/backup_tool/src/tools_op_restore.cpp +++ b/tools/backup_tool/src/tools_op_restore.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-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 @@ -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..b095efa50d4807a4b18de372193d08a25c951605 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -1,4 +1,4 @@ -# Copyright (c) 2022-2023 Huawei Device Co., Ltd. +# Copyright (c) 2022-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 @@ -83,8 +83,10 @@ 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_json/b_report_entity.cpp", "src/b_ohos/startup/backup_para.cpp", "src/b_process/b_guard_cwd.cpp", "src/b_process/b_guard_signal.cpp", @@ -101,6 +103,7 @@ ohos_shared_library("backup_utils") { "c_utils:utils", "faultloggerd:libdfx_dumpcatcher", "hilog:libhilog", + "hitrace:hitrace_meter", "init:libbegetutil", ] @@ -116,6 +119,7 @@ ohos_shared_library("backup_utils") { ":backup_cxx_gen", ":backup_cxx_rust", "${path_jsoncpp}:jsoncpp", + "//third_party/openssl:libcrypto_shared", ] use_exceptions = true diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h index cc0ff5805261948b1b9217926b6f5a1a3721b2cc..d5abb3f847c5bdc5f43af94862983bc6ce8a6323 100644 --- a/utils/include/b_error/b_error.h +++ b/utils/include/b_error/b_error.h @@ -85,6 +85,7 @@ public: EXT_ABILITY_DIED = 0x5004, EXT_ABILITY_TIMEOUT = 0x5005, EXT_FORBID_BACKUP_RESTORE = 0x5006, + EXT_BACKUP_PACKET_ERROR = 0x5007, }; enum BackupErrorCode { @@ -100,6 +101,7 @@ public: E_ETO = 13500003, E_DIED = 13500004, E_EMPTY = 13500005, + E_PACKET = 13500006, }; public: @@ -220,6 +222,7 @@ private: {Codes::EXT_ABILITY_TIMEOUT, "Extension process timeout"}, {Codes::EXT_ABILITY_DIED, "Extension process died"}, {Codes::EXT_FORBID_BACKUP_RESTORE, "forbid backup or restore"}, + {Codes::EXT_BACKUP_PACKET_ERROR, "Backup packet error"}, }; static inline const std::map errCodeTable_ { @@ -247,6 +250,7 @@ private: {static_cast(Codes::EXT_ABILITY_DIED), BackupErrorCode::E_DIED}, {static_cast(Codes::EXT_ABILITY_TIMEOUT), BackupErrorCode::E_ETO}, {static_cast(Codes::EXT_FORBID_BACKUP_RESTORE), BackupErrorCode::E_FORBID}, + {static_cast(Codes::EXT_BACKUP_PACKET_ERROR), BackupErrorCode::E_PACKET}, {BackupErrorCode::E_IPCSS, BackupErrorCode::E_IPCSS}, {BackupErrorCode::E_INVAL, BackupErrorCode::E_INVAL}, {BackupErrorCode::E_UKERR, BackupErrorCode::E_UKERR}, @@ -259,6 +263,7 @@ private: {BackupErrorCode::E_ETO, BackupErrorCode::E_ETO}, {BackupErrorCode::E_DIED, BackupErrorCode::E_DIED}, {BackupErrorCode::E_EMPTY, BackupErrorCode::E_EMPTY}, + {BackupErrorCode::E_PACKET, BackupErrorCode::E_PACKET}, }; private: diff --git a/interfaces/kits/js/remote_file_share/remotefileshare_napi.h b/utils/include/b_filesystem/b_file_hash.h similarity index 52% rename from interfaces/kits/js/remote_file_share/remotefileshare_napi.h rename to utils/include/b_filesystem/b_file_hash.h index 462f6c497523c233ac85740bfe0c19322c7d3cd8..61c763ec2dede6fe37ba1aff1eac06e3d0ec1c46 100644 --- a/interfaces/kits/js/remote_file_share/remotefileshare_napi.h +++ b/utils/include/b_filesystem/b_file_hash.h @@ -1,10 +1,10 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 + * 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, @@ -13,15 +13,17 @@ * limitations under the License. */ -#ifndef REMOTEFILESHARE_NAPI_H -#define REMOTEFILESHARE_NAPI_H +#ifndef OHOS_FILEMGMT_BACKUP_B_FILE_HASH_H +#define OHOS_FILEMGMT_BACKUP_B_FILE_HASH_H -#include "filemgmt_libn.h" +#include +#include -namespace OHOS { -namespace AppFileService { -namespace ModuleRemoteFileShare { -} // namespace ModuleRemoteFileShare -} // namespace AppFileService -} // namespace OHOS -#endif // REMOTEFILESHARE_NAPI_H \ No newline at end of file +namespace OHOS::FileManagement::Backup { +class BFileHash { +public: + 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_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h index f8e86a7d035368e319ed0b2901e5d9e493816937..ef7ce2309a20a57838be6f5b5d86022e549d3109 100644 --- a/utils/include/b_json/b_json_entity_caps.h +++ b/utils/include/b_json/b_json_entity_caps.h @@ -32,7 +32,14 @@ public: std::string restoreDeps; std::string supportScene; }; - + struct BundleBackupConfigPara { + bool allToBackup; + std::string extensionName; + std::string restoreDeps; + std::string supportScene; + std::vector includes; + std::vector excludes; + }; public: void SetSystemFullName(std::string systemFullName) { diff --git a/interfaces/kits/js/remote_file_share/remotefileshare_n_exporter.h b/utils/include/b_json/b_report_entity.h similarity index 30% rename from interfaces/kits/js/remote_file_share/remotefileshare_n_exporter.h rename to utils/include/b_json/b_report_entity.h index 34938bf8238573ae2ec8994c8b566c64713617d6..9bdc59df9901c8d7db5824da7faf07151a229f6c 100644 --- a/interfaces/kits/js/remote_file_share/remotefileshare_n_exporter.h +++ b/utils/include/b_json/b_report_entity.h @@ -1,10 +1,10 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 + * 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, @@ -13,16 +13,54 @@ * limitations under the License. */ -#ifndef REMOTEFILESHARE_N_EXPORTER_H -#define REMOTEFILESHARE_N_EXPORTER_H +#ifndef OHOS_FILEMGMT_BACKUP_B_REPORT_ENTITY_H +#define OHOS_FILEMGMT_BACKUP_B_REPORT_ENTITY_H +#define FILE_DEFAULT_MODE "0660" -#include "filemgmt_libn.h" +#include +#include +#include -namespace OHOS { -namespace AppFileService { -namespace ModuleRemoteFileShare { -napi_value CreateSharePath(napi_env env, napi_callback_info info); -} // namespace ModuleRemoteFileShare -} // namespace AppFileService -} // namespace OHOS -#endif // REMOTEFILESHARE_N_EXPORTER_H \ No newline at end of file +#include "unique_fd.h" + +namespace OHOS::FileManagement::Backup { +struct ReportFileInfo { + std::string filePath; + std::string mode {FILE_DEFAULT_MODE}; + bool isDir {false}; + off_t size {0}; + off_t mtime {0}; + std::string hash; + bool isIncremental {false}; +}; + +class BReportEntity { +public: + /** + * @brief 获取Report信息 + * + * @return std::map + */ + std::map GetReportInfos(); + +public: + /** + * @brief 构造方法 + * + * @param fd + */ + explicit BReportEntity(UniqueFd fd) : srcFile_(std::move(fd)) {} + + BReportEntity() = delete; + virtual ~BReportEntity() = default; + +public: + std::string version; + unsigned int attrNum = 0; + +protected: + UniqueFd srcFile_; +}; +} // namespace OHOS::FileManagement::Backup + +#endif // OHOS_FILEMGMT_BACKUP_B_REPORT_ENTITY_H \ No newline at end of file diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index 6d4df20ac633651ae1277fb13105b86b799866d1..3f02020cd43bd93a6b9bd850f3d243cc5a287fa5 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -118,11 +118,10 @@ static tuple, vector> GetDirFilesDetai continue; } if (sta.st_size <= size) { - HILOGI("Find small file %{public}s", fileName.data()); smallFiles.emplace_back(fileName); continue; } - HILOGI("Find big file"); + files.try_emplace(fileName, sta); } } @@ -225,7 +224,6 @@ tuple, vector> BDir::GetBigFiles(const vector resSmallFiles; for (const auto &item : incSmallFiles) { if (!isMatch(excludes, item)) { - HILOGI("smallfile %{public}s matchs include condition and unmatchs exclude condition", item.c_str()); resSmallFiles.emplace_back(item); } } @@ -233,7 +231,6 @@ tuple, vector> BDir::GetBigFiles(const map bigFiles; for (const auto &item : incFiles) { if (!isMatch(excludes, item.first)) { - HILOGI("file %{public}s matchs include condition and unmatchs exclude condition", item.first.c_str()); bigFiles[item.first] = item.second; } } 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..649be8e33df25bf1b8e01ccc0022d4c2f873ed83 --- /dev/null +++ b/utils/src/b_filesystem/b_file_hash.cpp @@ -0,0 +1,77 @@ +/* + * 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 "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::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_json/b_report_entity.cpp b/utils/src/b_json/b_report_entity.cpp new file mode 100644 index 0000000000000000000000000000000000000000..816441b6eb5ecd13e7b1462be58127f382a401d8 --- /dev/null +++ b/utils/src/b_json/b_report_entity.cpp @@ -0,0 +1,168 @@ +/* + * 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 "b_json/b_report_entity.h" + +#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; +namespace { +const char ATTR_SEP = ';'; +const char LINE_SEP = '\n'; +const char LINE_WRAP = '\r'; +const int64_t HASH_BUFFER_SIZE = 4096; // 每次读取的siz +const int INFO_ALIGN_NUM = 2; +const string INFO_DIR = "dir"; +const string INFO_HASH = "hash"; +const string INFO_IS_INCREMENTAL = "isIncremental"; +const string INFO_MODE = "mode"; +const string INFO_MTIME = "mtime"; +const string INFO_PATH = "path"; +const string INFO_SIZE = "size"; +} // namespace + +static vector SplitStringByChar(const string &str, const char &sep) +{ + vector splits; + stringstream ss(str); + string res; + while (getline(ss, res, sep)) { + splits.push_back(res); + } + + return splits; +} + +static ErrCode ParseReportInfo(struct ReportFileInfo &fileStat, + const vector &splits, + const unordered_map &keys) +{ + // 根据数据拼接结构体 + int len = keys.size(); + int splitsLen = (int)splits.size(); + // 处理path路径 + string path; + vector residue; + try { + for (int i = 0; i < splitsLen; i++) { + if (i <= splitsLen - len) { + path += splits[i] + ";"; + } else { + residue.emplace_back(splits[i]); + } + } + if (residue.size() != keys.size() - 1) { + HILOGE("Error residue size"); + return EPERM; + } + fileStat.filePath = path.substr(0, path.length() - 1); + if (keys.find(INFO_MODE) != keys.end()) { + fileStat.mode = residue[keys.find(INFO_MODE)->second]; + } + if (keys.find(INFO_DIR) != keys.end()) { + fileStat.isDir = residue[keys.find(INFO_DIR)->second] == "1" ? true : false; + } + if (keys.find(INFO_SIZE) != keys.end()) { + stringstream sizeStr(residue[keys.find(INFO_SIZE)->second]); + off_t size = 0; + sizeStr >> size; + fileStat.size = size; + } + if (keys.find(INFO_MTIME) != keys.end()) { + stringstream mtimeStr(residue[keys.find(INFO_MTIME)->second]); + off_t mtime = 0; + mtimeStr >> mtime; + fileStat.mtime = mtime; + } + if (keys.find(INFO_HASH) != keys.end()) { + fileStat.hash = residue[keys.find(INFO_HASH)->second]; + } + if (keys.find(INFO_IS_INCREMENTAL) != keys.end()) { + fileStat.isIncremental = residue[keys.find(INFO_IS_INCREMENTAL)->second] == "1" ? true : false; + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to ParseReportInfo"); + return EPERM; + } +} + +static void DealLine(unordered_map &keys, + int &num, + const string &line, + map &infos) +{ + string currentLine = line; + if (currentLine[currentLine.length() - 1] == LINE_WRAP) { + currentLine = currentLine.substr(0, currentLine.length() - 1); + } + + vector splits = SplitStringByChar(currentLine, ATTR_SEP); + 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); + } + } +} + +map BReportEntity::GetReportInfos() +{ + map infos {}; + + char buffer[HASH_BUFFER_SIZE]; + ssize_t bytesRead; + string currentLine; + unordered_map keys; + + int num = 0; + while ((bytesRead = read(srcFile_, buffer, sizeof(buffer))) > 0) { + for (ssize_t i = 0; i < bytesRead; i++) { + if (buffer[i] == LINE_SEP) { + DealLine(keys, num, currentLine, infos); + currentLine.clear(); + } else { + currentLine += buffer[i]; + } + } + } + + // 处理文件中的最后一行 + if (!currentLine.empty()) { + DealLine(keys, num, currentLine, infos); + } + + return infos; +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file