diff --git a/frameworks/native/backup_ext/src/untar_file.cpp b/frameworks/native/backup_ext/src/untar_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6567ca6634ff7c0540f8deec04a12b741191d64 --- /dev/null +++ b/frameworks/native/backup_ext/src/untar_file.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "untar_file.h" +namespace OHOS::FileManagement::Backup { + +string UntarFile::GenRealPath(const string &rootPath, const string &realName) +{ + if (rootPath.empty() || realName.empty()) { + return ""; + } + string realPath(rootPath); + size_t len = realPath.length(); + if (realPath[len - 1] == '/') { + realPath = realPath.substr(0, len - 1); + } + realPath.append((realName[0] == '/') ? realName : ("/" + realName)); + return realPath; +} + +int UntarFile::CreateDir(string &path, mode_t mode) +{ + size_t len = path.length(); + if (path[len - 1] == '/') { + path[len - 1] = '\0'; + } + int ret = access(path.c_str(), F_OK); + if (ret != 0) { + HILOGE("%{public}s does not exist, err = %{public}d", path.c_str(), errno); + ret = mkdir(path.c_str(), mode); + if (ret != 0) { + HILOGE("Failed to mkdir %{public}s, err = %{public}d", path.c_str(), errno); + } + } + return ret; +} + +FILE *UntarFile::CreateFile(string &filePath, mode_t mode, char fileType) +{ + string fileMode = "wb+"; + if (fileType == SPLIT_END_TYPE || fileType == SPLIT_CONTINUE_TYPE) { + fileMode = "ab+"; + } + FILE *f = fopen(filePath.c_str(), fileMode.c_str()); + if (f != nullptr) { + return f; + } + + HILOGE("Failed to open file %{public}s, err = %{public}d", filePath.c_str(), errno); + size_t pos = filePath.rfind('/'); + if (pos == string::npos) { + return nullptr; + } + + string path = filePath.substr(0, pos); + if (ForceCreateDirectory(path)) { + f = fopen(filePath.c_str(), "wb+"); + if (f == nullptr) { + HILOGE("Failed to open file %{public}s, err = %{public}d", filePath.c_str(), errno); + } + } + + return f; +} + +int UntarFile::CreateSoftlink(const string &oldPath, const string &newPath) +{ + int ret = unlink(newPath.c_str()); + if (ret != 0) { + HILOGE("Failed to unlink, err = %{public}d", errno); + } + ret = symlink(oldPath.c_str(), newPath.c_str()); + if (ret != 0) { + HILOGE("Failed to symlink, err = %{public}d", errno); + } + return ret; +} + +} // namespace OHOS::FileManagement::Backup \ No newline at end of file