#ifndef ELECTRON_SHELL_COMMON_ASAR_ARCHIVE_H_
#define ELECTRON_SHELL_COMMON_ASAR_ARCHIVE_H_
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include "base/containers/span.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/synchronization/lock.h"
#include "base/thread_annotations.h"
#include "base/values.h"
#include "build/build_config.h"
#include "shell/common/uv_includes.h"
#include "third_party/abseil-cpp/absl/container/flat_hash_map.h"
namespace asar {
class ScopedTemporaryFile;
enum class HashAlgorithm {
kSHA256,
kNone,
};
struct IntegrityPayload {
IntegrityPayload();
~IntegrityPayload();
IntegrityPayload(const IntegrityPayload& other);
IntegrityPayload(IntegrityPayload&& other);
IntegrityPayload& operator=(const IntegrityPayload& other);
IntegrityPayload& operator=(IntegrityPayload&& other);
HashAlgorithm algorithm = HashAlgorithm::kNone;
std::string hash;
uint32_t block_size = 0U;
std::vector<std::string> blocks;
};
class Archive {
public:
struct FileInfo {
FileInfo();
~FileInfo();
bool unpacked = false;
bool executable = false;
uint32_t size = 0U;
uint64_t offset = 0U;
std::optional<IntegrityPayload> integrity;
};
enum class FileType {
kFile = UV_DIRENT_FILE,
kDirectory = UV_DIRENT_DIR,
kLink = UV_DIRENT_LINK,
};
struct Stats : public FileInfo {
FileType type = FileType::kFile;
};
explicit Archive(const base::FilePath& path);
virtual ~Archive();
Archive(const Archive&) = delete;
Archive& operator=(const Archive&) = delete;
bool Init();
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
std::optional<IntegrityPayload> HeaderIntegrity() const;
std::optional<base::FilePath> RelativePath() const;
#endif
bool GetFileInfo(const base::FilePath& path, FileInfo* info) const;
bool GetFileInfo(std::string_view path, FileInfo* info) const;
bool Stat(std::string_view path, Stats* stats) const;
bool Readdir(std::string_view path,
std::vector<std::string>* names,
std::vector<FileType>* types) const;
bool Realpath(std::string_view path, std::string* realpath) const;
bool CopyFileOut(const base::FilePath& path, base::FilePath* out);
bool ReadFileAt(uint64_t offset, base::span<uint8_t> buf);
base::File DuplicateFile();
int GetUnsafeFD() const;
private:
bool GetFileInfo(std::string_view path, FileInfo* info, int depth) const;
const base::DictValue* LookupNode(std::string_view path) const;
bool initialized_ = false;
bool header_validated_ = false;
const base::FilePath path_;
base::File file_{base::File::FILE_OK};
int fd_ = -1;
uint32_t header_size_ = 0;
uint64_t file_size_ = 0;
std::optional<base::DictValue> header_;
mutable base::Lock node_cache_lock_;
mutable absl::flat_hash_map<std::string, const base::DictValue*> node_cache_
GUARDED_BY(node_cache_lock_);
base::Lock external_files_lock_;
absl::flat_hash_map<base::FilePath::StringType,
std::unique_ptr<ScopedTemporaryFile>>
external_files_;
};
}
#endif