1 /* 2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef HI_AUDIT_H 17 #define HI_AUDIT_H 18 19 #include <cstdint> 20 #include <mutex> 21 #include <queue> 22 #include <string> 23 #include <sys/stat.h> 24 25 #include "nocopyable.h" 26 27 namespace OHOS::FileManagement::Backup { 28 struct HiAuditConfig { 29 std::string logPath; 30 std::string logName; 31 uint32_t logSize; // kb 32 uint32_t fileSize; 33 uint32_t fileCount; 34 }; 35 36 struct AuditLog { 37 bool isUserBehavior; 38 std::string cause; 39 std::string operationType; 40 std::string operationScenario; 41 uint32_t operationCount; 42 std::string operationStatus; 43 std::string extend; 44 std::string type; 45 std::string path; 46 TitleStringAuditLog47 const std::string TitleString() const 48 { 49 return "happenTime, packageName, isForeground, cause, isUserBehavior, operationType, operationScenario, " 50 "operationStatus, operationCount, extend, type, path\n"; 51 } 52 ToStringAuditLog53 const std::string ToString() const 54 { 55 return cause + ", " + std::to_string(isUserBehavior) + ", " + operationType + ", " + operationScenario + ", " + 56 operationStatus + ", " + std::to_string(operationCount) + ", " + extend + "," + type + "," + path + "\n"; 57 } 58 }; 59 60 class HiAudit : public NoCopyable { 61 public: 62 static HiAudit &GetInstance(bool isSaJob); 63 void Write(const AuditLog &auditLog); 64 65 private: 66 HiAudit(bool isSaJob); 67 ~HiAudit(); 68 69 void Init(); 70 void GetWriteFilePath(); 71 void WriteToFile(const std::string &log); 72 uint64_t GetMilliseconds(); 73 std::string GetFormattedTimestamp(time_t timeStamp, const std::string &format); 74 std::string GetFormattedTimestampEndWithMilli(); 75 void CleanOldAuditFile(); 76 void ZipAuditLog(); 77 bool MkLogDirSuccess(); 78 79 private: 80 std::mutex mutex_; 81 int writeFd_; 82 std::atomic<uint32_t> writeLogSize_ = 0; 83 bool isSaJob_ = false; 84 HiAuditConfig hiAuditConfig_; 85 }; 86 } // namespace OHOS::FileManagement::Backup 87 #endif // HI_AUDIT_H 88