适配日志落盘

Signed-off-by: yaoruozi1@huawei.com <yaoruozi1@huawei.com>
This commit is contained in:
yaoruozi1@huawei.com 2024-08-30 10:35:26 +08:00
parent 285f94e76c
commit be2062d8fa
11 changed files with 518 additions and 4 deletions

View File

@ -40,7 +40,8 @@
"safwk",
"samgr",
"storage_service",
"sandbox_manager"
"sandbox_manager",
"zlib"
],
"third_party": [
"bounds_checking_function",
@ -170,4 +171,4 @@
]
}
}
}
}

View File

@ -49,6 +49,7 @@
#include "b_ohos/startup/backup_para.h"
#include "b_radar/b_radar.h"
#include "b_tarball/b_tarball_factory.h"
#include "b_hiaudit/hi_audit.h"
#include "filemgmt_libhilog.h"
#include "hitrace_meter.h"
#include "i_service.h"
@ -173,6 +174,9 @@ static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName)
size_t filePathPrefix = filePath.find_last_of(BConstants::FILE_SEPARATOR_CHAR);
if (filePathPrefix == string::npos) {
HILOGE("GetFileHandleForSpecialCloneCloud: Invalid fileName");
AuditLog auditLog = {false, "Open fd failed", "ADD", "DataClone in special scenario", 1, "FAILED",
"GetFileHandleForSpecialCloneCloud", "CommonFile", GetAnonyPath(fllePath)};
HiAudit::GetInstance(false).Write(auditLog);
return UniqueFd(-1);
}
string path = filePath.substr(0, filePathPrefix);
@ -180,12 +184,18 @@ static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName)
bool created = ForceCreateDirectory(path.data());
if (!created) {
HILOGE("Failed to create restore folder.");
AuditLog auditLog = {false, "ForceCreateDirectory failed", "ADD", "DataClone in special scenario", 1,
"FAILED", "GetFileHandleForSpecialCloneCloud", "CommonFile", GetAnonyPath(path)};
HiAudit::GetInstance(false).Write(auditLog);
return UniqueFd(-1);
}
}
UniqueFd fd(open(fileName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
if (fd < 0) {
HILOGE("Open file failed, file name is %{private}s, err = %{public}d", fileName.data(), errno);
AuditLog auditLog = {false, "open fd failed", "ADD", "DataClone in special scenario", 1, "FAILED",
"GetFileHandleForSpecialCloneCloud", "CommonFile", GetAnonyPath(fileName)};
HiAudit::GetInstance(false).Write(auditLog);
return UniqueFd(-1);
}
return fd;
@ -251,6 +261,9 @@ static ErrCode GetIncreFileHandleForSpecialVersion(const string &fileName)
UniqueFd fd = GetFileHandleForSpecialCloneCloud(fileName);
if (fd < 0) {
HILOGE("Failed to open file = %{private}s, err = %{public}d", fileName.c_str(), errno);
AuditLog auditLog = {false, "Open fd failed", "ADD", "DataClone in special scenario", 1, "FAILED",
"GetIncreFileHandleForSpecialVersion", "CommonFile", GetAnonyPath(fileName)};
HiAudit::GetInstance(false).Write(auditLog);
errCode = errno;
}
@ -258,6 +271,9 @@ static ErrCode GetIncreFileHandleForSpecialVersion(const string &fileName)
if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) {
HILOGE("Failed to create restore folder : %{private}s, err = %{public}d", path.c_str(), errno);
errCode = errno;
AuditLog auditLog = {false, "mkdir failed", "ADD", "DataClone in special scenario", 1, "FAILED",
"GetIncreFileHandleForSpecialVersion", "CommonFile", GetAnonyPath(path)};
HiAudit::GetInstance(false).Write(auditLog);
}
string reportName = path + BConstants::BLANK_REPORT_NAME;
UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR));
@ -417,8 +433,10 @@ ErrCode BackupExtExtension::BigFileReady(const TarMap &bigFileInfo, sptr<IServic
if (fd < 0) {
HILOGE("open file failed, file name is %{public}s, err = %{public}d", fllePath.c_str(), errno);
errCode = errno;
AuditLog auditLog = {false, "Open fd failed", "ADD", "DataClone", 1, "FAILED", "Backup File",
"BigFile", GetAnonyPath(fllePath)};
HiAudit::GetInstance(false).Write(auditLog);
}
ret = proxy->AppFileReady(item.first, std::move(fd), errCode);
if (SUCCEEDED(ret)) {
HILOGI("The application is packaged successfully, package name is %{public}s", item.first.c_str());
@ -428,6 +446,8 @@ ErrCode BackupExtExtension::BigFileReady(const TarMap &bigFileInfo, sptr<IServic
fdNum++;
RefreshTimeInfo(startTime, fdNum);
}
AuditLog auditLog = {false, "Send Big File Fd", "ADD", "DataClone", bigFileInfo.size(), "SUCCESS", "Backup Files",
"BigFile", ""};
HILOGI("BigFileReady End");
return ret;
}

View File

@ -25,6 +25,7 @@
#include "b_anony/b_anony.h"
#include "b_error/b_error.h"
#include "b_hiaudit/hi_audit.h"
#include "b_resources/b_constants.h"
#include "directory_ex.h"
#include "filemgmt_libhilog.h"
@ -98,6 +99,9 @@ bool TarFile::TraversalFile(string &filePath)
{
if (access(filePath.c_str(), F_OK) != 0) {
HILOGE("File path does not exists, err = %{public}d", errno);
AuditLog auditLog = {false, "access file failed", "ADD", "DataClone", 1, "FAILED", "TraversalFile",
"Packet File", GetAnonyPath(fllePath)};
HiAudit::GetInstance(false).Write(auditLog);
return false;
}
@ -109,10 +113,16 @@ bool TarFile::TraversalFile(string &filePath)
}
if (lstat(filePath.c_str(), &curFileStat) != 0) {
HILOGE("Failed to lstat, err = %{public}d", errno);
AuditLog auditLog = {false, "lstat file failed", "ADD", "DataClone", 1, "FAILED", "TraversalFile",
"Packet File", GetAnonyPath(fllePath)};
HiAudit::GetInstance(false).Write(auditLog);
return false;
}
if (!AddFile(filePath, curFileStat)) {
HILOGE("Failed to add file to tar package, file path is:%{public}s", GetAnonyPath(filePath).c_str());
AuditLog auditLog = {false, "AddFile failed", "ADD", "DataClone", 1, "FAILED", "TraversalFile",
"Packet File", GetAnonyPath(fllePath)};
HiAudit::GetInstance(false).Write(auditLog);
return false;
}
@ -299,6 +309,9 @@ bool TarFile::WriteFileContent(const string &fileName, off_t size)
int fd = open(fileName.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
HILOGE("Failed to open file %{public}s, err = %{public}d", fileName.data(), errno);
AuditLog auditLog = {false, "open fd failed", "ADD", "DataClone", 1, "FAILED", "WriteFileContent",
"Packet File", GetAnonyPath(fileName)};
HiAudit::GetInstance(false).Write(auditLog);
return false;
}

View File

@ -4,7 +4,7 @@
"path" : ["/system/bin/sa_main", "/system/profile/backup_sa.json"],
"ondemand" : true,
"uid" : "backup",
"gid" : ["backup"],
"gid" : ["backup", "log"],
"secon" : "u:r:backup_sa:s0",
"permission" : [
"ohos.permission.STORAGE_MANAGER",

View File

@ -17,6 +17,7 @@
#include "b_radar/b_radar.h"
#include "b_sa/b_sa_utils.h"
#include "b_hiaudit/hi_audit.h"
#include "filemgmt_libhilog.h"
#include "message_parcel.h"

View File

@ -22,6 +22,7 @@
#include "b_error/b_error.h"
#include "b_file_info.h"
#include "b_hiaudit/hi_audit.h"
#include "b_jsonutil/b_jsonutil.h"
#include "b_json/b_json_entity_extension_config.h"
#include "b_resources/b_constants.h"
@ -75,6 +76,7 @@ static tuple<bool, bool, string, string, string, Json::Value> GetAllowAndExtName
}
vector<string> out;
AppExecFwk::BundleMgrClient client;
AuditLog auditLog = {};
if (!client.GetResConfigFile(ext, "ohos.extension.backup", out) || out.size() == 0) {
HILOGE("Failed to get resconfigfile of bundle, bundle name is:%{public}s", ext.bundleName.c_str());
continue;

View File

@ -65,6 +65,8 @@ ohos_shared_library("backup_utils") {
"src/b_filesystem/b_dir.cpp",
"src/b_filesystem/b_file.cpp",
"src/b_filesystem/b_file_hash.cpp",
"src/b_hiaudit/hi_audit.cpp",
"src/b_hiaudit/zip_util.cpp",
"src/b_json/b_json_clear_data_config.cpp",
"src/b_json/b_json_entity_ext_manage.cpp",
"src/b_json/b_json_entity_extension_config.cpp",
@ -96,6 +98,7 @@ ohos_shared_library("backup_utils") {
"hitrace:hitrace_meter",
"init:libbegetutil",
"ipc:ipc_core",
"zlib:shared_libz",
]
include_dirs = [

View File

@ -0,0 +1,87 @@
/*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HI_AUDIT_H
#define HI_AUDIT_H
#include <cstdint>
#include <mutex>
#include <queue>
#include <string>
#include <sys/stat.h>
#include "nocopyable.h"
namespace OHOS::FileManagement::Backup {
struct HiAuditConfig {
std::string logPath;
std::string logName;
uint32_t logSize; // kb
uint32_t fileSize;
uint32_t fileCount;
};
struct AuditLog {
bool isUserBehavior;
std::string cause;
std::string operationType;
std::string operationScenario;
uint32_t operationCount;
std::string operationStatus;
std::string extend;
std::string type;
std::string path;
const std::string TitleString() const
{
return "happenTime, packageName, isForeground, cause, isUserBehavior, operationType, operationScenario, "
"operationStatus, operationCount, extend, type, path\n";
}
const std::string ToString() const
{
return cause + ", " + std::to_string(isUserBehavior) + ", " + operationType + ", " + operationScenario + ", " +
operationStatus + ", " + std::to_string(operationCount) + ", " + extend + "," + type + "," + path + "\n";
}
};
class HiAudit : public NoCopyable {
public:
static HiAudit &GetInstance(bool isSaJob);
void Write(const AuditLog &auditLog);
private:
HiAudit(bool isSaJob);
~HiAudit();
void Init();
void GetWriteFilePath();
void WriteToFile(const std::string &log);
uint64_t GetMilliseconds();
std::string GetFormattedTimestamp(time_t timeStamp, const std::string &format);
std::string GetFormattedTimestampEndWithMilli();
void CleanOldAuditFile();
void ZipAuditLog();
bool MkLogDirSuccess();
private:
std::mutex mutex_;
int writeFd_;
std::atomic<uint32_t> writeLogSize_ = 0;
bool isSaJob_;
HiAuditConfig hiAuditConfig_;
};
} // namespace OHOS::FileManagement::Backup
#endif // HI_AUDIT_H

View File

@ -0,0 +1,41 @@
/*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ZIP_UTIL_H
#define ZIP_UTIL_H
#include <string>
#include <contrib/minizip/zip.h>
namespace OHOS::FileManagement::Backup {
enum {
KEEP_NONE_PARENT_PATH,
KEEP_ONE_PARENT_PATH,
};
class ZipUtil {
public:
static zipFile CreateZipFile(const std::string &zipPath, int32_t zipMode = APPEND_STATUS_CREATE);
static void CloseZipFile(zipFile &zipfile);
static int AddFileInZip(zipFile &zipfile, const std::string &srcFile, int keepParentPathStatus,
const std::string &dstFileName = "");
static std::string GetDestFilePath(const std::string &srcFile, const std::string &destFilePath,
int keepParentPathStatus);
private:
static FILE *GetFileHandle(const std::string &file);
};
}
#endif

View File

@ -0,0 +1,230 @@
/*
* 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
*
* 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_hiaudit/hi_audit.h"
#include <chrono>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <iomanip>
#include <sstream>
#include <sys/time.h>
#include <unistd.h>
#include "filemgmt_libhilog.h"
#include "b_hiaudit/zip_util.h"
#include "hi_audit.h"
namespace OHOS::FileManagement::Backup {
namespace {
const HiAuditConfig HIAUDIT_CONFIG = { "/data/log/hiaudit/app_file_service/", "appfileservice",
2 * 1024, 3 * 1204 * 1024, 10 };
const HiAuditConfig HIAUDIT_CONFIG_EXT = { "/data/storage/el2/log/hiaudit/", "appfileservice",
2 * 1024, 3 * 1204 * 1024, 10 };
constexpr int8_t MILLISECONDS_LENGTH = 3;
constexpr int64_t SEC_TO_MILLISEC = 1000;
constexpr int MAX_TIME_BUFF = 64; // 64 : for example 2021-05-27-01-01-01
const std::string HIAUDIT_LOG_NAME = HIAUDIT_CONFIG.logPath + HIAUDIT_CONFIG.logName + "_audit.csv";
const std::string HIAUDIT_LOG_NAME_EXT = HIAUDIT_CONFIG_EXT.logPath + HIAUDIT_CONFIG_EXT.logName + "_audit.csv";
}
HiAudit::HiAudit(bool isSaJob)
{
isSaJob_ = isSaJob;
Init();
}
HiAudit::~HiAudit()
{
close(writeFd_);
}
HiAudit &HiAudit::GetInstance(bool isSaJob)
{
static HiAudit hiAudit(isSaJob);
return hiAudit;
}
void HiAudit::Init()
{
std::lock_guard<std::mutex> lock(mutex_);
if (isSaJob_) {
hiAuditConfig_ = HIAUDIT_CONFIG;
} else {
hiAuditConfig_ = HIAUDIT_CONFIG_EXT;
}
if (!MkLogDirSuccess()){
HILOGE("Init, Create log dir failed");
return;
}
std::string logFilePath = hiAuditConfig_.logPath + hiAuditConfig_.logName + "_audit.csv";
writeFd_ =
open(logFilePath.c_str(), O_CREAT | O_APPEND | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
if (writeFd_ < 0) {
HILOGE("Init, writeFd_ open error, logFilePath is:%{public}s", logFilePath.c_str());
}
struct stat st;
writeLogSize_ = stat(HIAUDIT_LOG_NAME.c_str(), &st) ? 0 : static_cast<uint64_t>(st.st_size);
HILOGI("Init, writeLogSize: %{public}u", writeLogSize_.load());
}
uint64_t HiAudit::GetMilliseconds()
{
auto now = std::chrono::system_clock::now();
auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
return millisecs.count();
}
std::string HiAudit::GetFormattedTimestamp(time_t timeStamp, const std::string &format)
{
auto seconds = timeStamp / SEC_TO_MILLISEC;
char date[MAX_TIME_BUFF] = {0};
struct tm result {};
if (localtime_r(&seconds, &result) != nullptr) {
strftime(date, MAX_TIME_BUFF, format.c_str(), &result);
}
return std::string(date);
}
std::string HiAudit::GetFormattedTimestampEndWithMilli()
{
uint64_t milliSeconds = GetMilliseconds();
std::string formattedTimeStamp = GetFormattedTimestamp(milliSeconds, "%Y%m%d%H%M%S");
std::stringstream ss;
ss << formattedTimeStamp;
milliSeconds = milliSeconds % SEC_TO_MILLISEC;
ss << std::setfill('0') << std::setw(MILLISECONDS_LENGTH) << milliSeconds;
return ss.str();
}
void HiAudit::Write(const AuditLog &auditLog)
{
HILOGI("write");
std::lock_guard<std::mutex> lock(mutex_);
if (writeLogSize_ == 0) {
WriteToFile(auditLog.TitleString());
}
std::string writeLog =
GetFormattedTimestampEndWithMilli() + ", " + hiAuditConfig_.logName + ", NO, " + auditLog.ToString();
HILOGE("write %{public}s.", writeLog.c_str());
if (writeLog.length() > hiAuditConfig_.logSize) {
writeLog = writeLog.substr(0, hiAuditConfig_.logSize);
}
writeLog = writeLog + "\n";
WriteToFile(writeLog);
}
void HiAudit::GetWriteFilePath()
{
if (writeLogSize_ < hiAuditConfig_.fileSize) {
return;
}
close(writeFd_);
ZipAuditLog();
CleanOldAuditFile();
if (!MkLogDirSuccess()) {
HILOGE("Create log dir failed");
return;
}
std::string logFilePath = hiAuditConfig_.logPath + hiAuditConfig_.logName + "_audit.csv";
writeFd_ =
open(logFilePath.c_str(), O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
writeLogSize_ = 0;
}
void HiAudit::CleanOldAuditFile()
{
uint32_t zipFileSize = 0;
std::string oldestAuditFile;
if (!MkLogDirSuccess()) {
HILOGE("Create log dir failed");
return;
}
DIR *dir = opendir(hiAuditConfig_.logPath.c_str());
while (true) {
struct dirent *ptr = readdir(dir);
if (ptr == nullptr) {
break;
}
if (std::string(ptr->d_name).find(hiAuditConfig_.logName) != std::string::npos &&
std::string(ptr->d_name).find("zip") != std::string::npos) {
zipFileSize = zipFileSize + 1;
if (oldestAuditFile.empty()) {
oldestAuditFile = hiAuditConfig_.logPath + std::string(ptr->d_name);
continue;
}
struct stat st;
stat((hiAuditConfig_.logPath + std::string(ptr->d_name)).c_str(), &st);
struct stat oldestSt;
stat(oldestAuditFile.c_str(), &oldestSt);
if (st.st_mtime < oldestSt.st_mtime) {
oldestAuditFile = HIAUDIT_CONFIG.logPath + std::string(ptr->d_name);
}
}
}
closedir(dir);
if (zipFileSize > hiAuditConfig_.fileCount) {
remove(oldestAuditFile.c_str());
}
}
void HiAudit::WriteToFile(const std::string &content)
{
GetWriteFilePath();
if (writeFd_ > 0) {
write(writeFd_, content.c_str(), content.length());
} else {
HILOGE("write error.");
}
writeLogSize_ = writeLogSize_ + content.length();
}
void HiAudit::ZipAuditLog()
{
if (!MkLogDirSuccess()) {
HILOGE("Create log dir failed");
return;
}
std::string zipFileName = hiAuditConfig_.logPath + hiAuditConfig_.logName + "_audit_" +
GetFormattedTimestamp(GetMilliseconds(), "%Y%m%d%H%M%S");
std::string logFilePath = hiAuditConfig_.logPath + hiAuditConfig_.logName + "_audit.csv";
std::rename(logFilePath.c_str(), (zipFileName + ".csv").c_str());
zipFile compressZip = StorageDaemon::ZipUtil::CreateZipFile(zipFileName + ".zip");
if (compressZip == nullptr) {
HILOGW("open zip file failed.");
return;
}
if (StorageDaemon::ZipUtil::AddFileInZip(compressZip, zipFileName + ".csv", StorageDaemon::KEEP_NONE_PARENT_PATH) ==
0) {
remove((zipFileName + ".csv").c_str());
}
StorageDaemon::ZipUtil::CloseZipFile(compressZip);
}
bool HiAudit::MkLogDirSuccess()
{
if (access(hiAuditConfig_.logPath.data(), F_OK) != 0) {
int ret = mkdir(hiAuditConfig_.logPath.data(), S_IRWXU | S_IRWXG);
if (ret != 0 || errno != 0 || errno != EEXIST) {
if (access(hiAuditConfig_.logPath.data(), F_OK) != 0) {
HILOGE("create log dir failed");
return false;
}
}
}
return true;
}
} // namespace OHOS::FileManagement::Backup

View File

@ -0,0 +1,116 @@
/*
* 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
*
* 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_hiaudit/zip_util.h"
#include <cerrno>
#include <fstream>
#include <securec.h>
#include "file_util.h"
#include "filemgmt_libhilog.h"
namespace OHOS::FileManagement::Backup {
namespace {
constexpr int READ_MORE_LENGTH = 100 * 1024;
constexpr int ERROR_MEMSET_STRUCT = 1001;
constexpr int ERROR_GET_HANDLE = 1002;
};
zipFile ZipUtil::CreateZipFile(const std::string &zipPath, int32_t zipMode)
{
return zipOpen(zipPath.c_str(), zipMode);
}
void ZipUtil::CloseZipFile(zipFile &zipfile)
{
zipClose(zipfile, nullptr);
}
int ZipUtil::AddFileInZip(zipFile &zipfile, const std::string &srcFile, int keepParentPathStatus,
const std::string &destFileName)
{
zip_fileinfo zipInfo;
errno_t result = memset_s(&zipInfo, sizeof(zipInfo), 0, sizeof(zipInfo));
if (result != EOK) {
HILOGE("AddFileInZip memset_s error, file:%{public}s.", srcFile.c_str());
return ERROR_MEMSET_STRUCT;
}
FILE *srcFp = GetFileHandle(srcFile);
if (srcFp == nullptr) {
HILOGE("get file handle failed:%{public}s, errno: %{public}d.", srcFile.c_str(), errno);
return ERROR_GET_HANDLE;
}
std::string srcFileName = GetDestFilePath(srcFile, destFileName, keepParentPathStatus);
zipOpenNewFileInZip(zipfile, srcFileName.c_str(), &zipInfo, nullptr, 0, nullptr, 0, nullptr, Z_DEFLATED,
Z_DEFAULT_COMPRESSION);
int errcode = 0;
char buf[READ_MORE_LENGTH] = {0};
while (!feof(srcFp)) {
size_t numBytes = fread(buf, 1, sizeof(buf), srcFp);
if (numBytes == 0) {
break;
}
zipWriteInFileInZip(zipfile, buf, static_cast<unsigned int>(numBytes));
if (ferror(srcFp)) {
HILOGE("zip file failed:%{public}s, errno: %{public}d.", srcFile.c_str(), errno);
errcode = errno;
break;
}
}
(void)fclose(srcFp);
zipCloseFileInZip(zipfile);
return errcode;
}
FILE *ZipUtil::GetFileHandle(const std::string &file)
{
std::string realPath;
if (!HiviewDFX::FileUtil::PathToRealPath(file, realPath)) {
return nullptr;
}
return fopen(realPath.c_str(), "rb");
}
std::string ZipUtil::GetDestFilePath(const std::string &srcFile, const std::string &destFilePath,
int keepParentPathStatus)
{
if (!destFilePath.empty()) {
return destFilePath;
}
std::string file = srcFile;
std::string result = file;
std::string parentPathName;
HiviewDFX::FileUtil::FormatPath2UnixStyle(file);
auto pos = file.rfind("/");
if (pos != std::string::npos && pos != file.length() - 1) {
result = file.substr(pos + 1);
std::string parent = file.substr(0, pos);
pos = parent.rfind("/");
if (pos != std::string::npos && pos != parent.length() - 1) {
parentPathName = parent.substr(pos + 1);
} else {
parentPathName = parent;
}
}
parentPathName.append("/");
if (keepParentPathStatus == KEEP_ONE_PARENT_PATH) {
// srcFileName with relative directory path
result.insert(0, parentPathName);
}
return result;
}
}