Files
hrynco-kswitcher/tests/files_archive.cpp
T

233 lines
11 KiB
C++

#include "files_archive.h"
#include <windows.h>
#include <archive.h>
#include <archive_entry.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
namespace
{
namespace fs=std::filesystem;
using namespace ks::files;
void expect(bool success,const char *message)
{
if(!success) throw std::runtime_error(message);
}
struct Temp
{
fs::path path;
Temp()
{
GUID id{};
wchar_t name[40]{};
expect(SUCCEEDED(CoCreateGuid(&id)) && StringFromGUID2(id,name,40),"temporary path");
path=fs::temp_directory_path()/(L"ks-test-archive-"+std::wstring(name));
expect(fs::create_directory(path),"temporary directory");
}
~Temp()
{
std::error_code error;
fs::remove_all(path,error);
}
};
struct Entry
{
const char *name;
std::string_view data{};
unsigned type=AE_IFREG;
};
void makeArchive(const fs::path &file,const std::vector<Entry> &members,bool sevenZip=false,bool encrypted=false)
{
std::unique_ptr<archive,decltype(&archive_write_free)> writer(archive_write_new(),archive_write_free);
expect(writer!=nullptr,"archive writer");
auto *out=writer.get();
expect((sevenZip?archive_write_set_format_7zip(out):archive_write_set_format_zip(out))==ARCHIVE_OK,"archive format");
if(sevenZip) expect(archive_write_set_options(out,"compression=lzma2")==ARCHIVE_OK,"LZMA2 format");
else expect(archive_write_set_options(out,"hdrcharset=UTF-8")==ARCHIVE_OK,"UTF-8 ZIP names");
if(encrypted)
{
expect(archive_write_set_options(out,"encryption=aes256")==ARCHIVE_OK,"encrypted ZIP");
expect(archive_write_set_passphrase(out,"fixture-only")==ARCHIVE_OK,"fixture passphrase");
}
expect(archive_write_open_filename_w(out,file.c_str())==ARCHIVE_OK,"archive output");
for(const auto &item:members)
{
std::unique_ptr<archive_entry,decltype(&archive_entry_free)> entry(archive_entry_new(),archive_entry_free);
const int length=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,item.name,-1,nullptr,0);
expect(length>0,"UTF-8 fixture filename");
std::wstring name(length,L'\0');
MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,item.name,-1,name.data(),length);
archive_entry_copy_pathname_w(entry.get(),name.c_str());
archive_entry_set_filetype(entry.get(),item.type);
archive_entry_set_perm(entry.get(),item.type==AE_IFDIR?0755:0644);
archive_entry_set_size(entry.get(),item.data.size());
archive_entry_set_mtime(entry.get(),1738400000,0);
if(item.type==AE_IFLNK) archive_entry_set_symlink(entry.get(),"../outside.txt");
if(archive_write_header(out,entry.get())!=ARCHIVE_OK)
throw std::runtime_error(std::string(item.name)+": "+archive_error_string(out));
if(!item.data.empty())
expect(archive_write_data(out,item.data.data(),item.data.size())==static_cast<la_ssize_t>(item.data.size()),
"archive member contents");
}
expect(archive_write_close(out)==ARCHIVE_OK,"close archive");
}
std::string contents(const fs::path &file)
{
std::ifstream in(file,std::ios::binary);
return {std::istreambuf_iterator<char>(in),std::istreambuf_iterator<char>()};
}
template<class Operation>
void expectError(const Operation &operation,std::string_view word)
{
try {operation();}
catch(const std::exception &error)
{
expect(std::string_view(error.what()).find(word)!=std::string_view::npos,error.what());
return;
}
throw std::runtime_error("operation unexpectedly succeeded");
}
}
int main()
{
try
{
Temp temp;
for(const bool sevenZip:{false,true})
{
const auto file=temp.path/(sevenZip?L"каталог.7z":L"каталог.zip");
const std::string data(1024*128,'a');
makeArchive(file,{{"folder/sub/дані.txt",data},{"folder/empty/",{},AE_IFDIR},{"other.txt","skip"}},sevenZip);
const auto entries=readArchive(file,{});
expect(entries.size()==5 && entries.at(L"folder").directory && entries.at(L"folder\\sub").directory,
"implicit directories in archive index");
const auto staged=temp.path/(sevenZip?L"7z-out":L"zip-out");
expect(fs::create_directory(staged),"extraction staging");
extractArchiveSelection(file,L"folder",{L"folder\\sub",L"folder\\empty"},staged,{});
expect(contents(staged/L"sub"/L"дані.txt")==data && fs::is_empty(staged/L"empty") &&
!fs::exists(staged/L"other.txt"),"selective extraction");
const auto fromRoot=staged/L"from-root";
expect(fs::create_directory(fromRoot),"root extraction staging");
extractArchiveSelection(file,{},{L"folder"},fromRoot,{});
expect(contents(fromRoot/L"folder"/L"sub"/L"дані.txt")==data,"extract directory from archive root");
const auto viewer=staged/L"content";
const auto member=readArchiveMember(file,L"folder\\sub\\дані.txt",viewer,data.size(),{});
expect(contents(viewer)==data && member.size==data.size() && member.modified!=0,"viewer stream and metadata");
expectError([&]{readArchiveMember(file,L"folder\\sub\\дані.txt",staged/L"oversize",1,{});},"too large");
}
const auto protectedZip=temp.path/L"protected.zip";
makeArchive(protectedZip,{{"protected.txt","secret"}},false,true);
expect(readArchive(protectedZip,{}).at("protected.txt").encrypted,"password flag");
expectError([&]{readArchiveMember(protectedZip,"protected.txt",temp.path/L"protected.txt",512,{});},"password");
const auto unsafe=temp.path/L"unsafe.zip";
for(const auto bad:{"../escape.txt","nested/../../escape.txt","C:/escape.txt","a/escape.txt:stream",
"//server/escape.txt","nested/COM1.txt","nested/a. ","nested//escape.txt"})
{
makeArchive(unsafe,{{"safe.txt","safe"},{bad,"bad"}});
expectError([&]{readArchive(unsafe,{});},"unsafe");
}
makeArchive(unsafe,{{"Same/a.txt","first"},{"same/b.txt","second"}});
expectError([&]{readArchive(unsafe,{});},"conflicting");
makeArchive(unsafe,{{"link",{},AE_IFLNK}});
expectError([&]{readArchive(unsafe,{});},"link");
expect(!fs::exists(temp.path/L"escape.txt") && !fs::exists(temp.path/L"protected.txt"),"no unsafe output");
const auto source=temp.path/L"source", update=temp.path/L"update";
fs::create_directories(source/L"empty");
fs::create_directories(update);
const auto item=source/L"дані.txt", replacement=update/L"дані.txt", added=update/L"new.txt";
std::ofstream(item,std::ios::binary)<<"initial";
std::ofstream(source/L"keep.txt",std::ios::binary)<<std::string(32*1024,'k');
std::ofstream(replacement,std::ios::binary)<<"updated";
std::ofstream(added,std::ios::binary)<<std::string(128*1024,'z');
for(const auto extension:{L".zip",L".7z"})
{
const auto archive=temp.path/(std::wstring(L"write")+extension);
writeArchive(archive,ArchiveWriteMode::create,{}, {source},{});
SYSTEMTIME fixtureDate{2003,3,0,5};
FILETIME creation{};
expect(SystemTimeToFileTime(&fixtureDate,&creation),"fixture creation time");
const HANDLE handle=CreateFileW(archive.c_str(),FILE_WRITE_ATTRIBUTES,FILE_SHARE_READ,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
expect(handle!=INVALID_HANDLE_VALUE,"open fixture archive attributes");
const bool timeSet=SetFileTime(handle,&creation,nullptr,nullptr)!=0;
CloseHandle(handle);
expect(timeSet,"set fixture creation time");
WIN32_FILE_ATTRIBUTE_DATA attributes{};
expect(GetFileAttributesExW(archive.c_str(),GetFileExInfoStandard,&attributes),"read archive attributes");
const auto creationBefore=attributes.ftCreationTime;
const auto index=readArchive(archive,{});
expect(index.at(L"source\\дані.txt").size==7 && index.at(L"source\\empty").directory,"archive creation");
const auto before=contents(archive);
bool canceled=false;
try
{
writeArchive(archive,ArchiveWriteMode::update,L"source",{replacement,added},
[](uint64_t done,uint64_t){return done==0;});
}
catch(const std::system_error &error) {canceled=error.code().value()==ERROR_CANCELLED;}
expect(canceled && contents(archive)==before,"canceled update preserved original");
expectError([&]{
writeArchive(archive,ArchiveWriteMode::update,{}, {archive},{});
},"contain itself");
expect(contents(archive)==before,"invalid update preserved original");
bool altered=false;
expectError([&]{
writeArchive(archive,ArchiveWriteMode::update,L"source",{replacement},[&](uint64_t done,uint64_t)
{
if(done && !altered)
{
altered=true;
std::ofstream(replacement,std::ios::binary)<<"changed during rewrite";
}
return true;
});
},"changed before");
expect(altered && contents(archive)==before,"failed rewrite preserved original");
std::ofstream(replacement,std::ios::binary)<<"updated";
writeArchive(archive,ArchiveWriteMode::update,L"source",{replacement,added},{});
expect(GetFileAttributesExW(archive.c_str(),GetFileExInfoStandard,&attributes) &&
CompareFileTime(&creationBefore,&attributes.ftCreationTime)==0,"update preserved creation time");
const auto changed=readArchive(archive,{});
expect(changed.at(L"source\\new.txt").size==128*1024 && changed.at(L"source\\empty").directory,
"update preserved folder and added entry");
const auto dest=temp.path/(std::wstring(L"updated")+extension);
readArchiveMember(archive,L"source\\дані.txt",dest,100,{});
expect(contents(dest)=="updated","update replaced matching file");
}
const auto encryptedBefore=contents(protectedZip);
expectError([&]{writeArchive(protectedZip,ArchiveWriteMode::update,{}, {added},{});},"Password-protected");
expect(contents(protectedZip)==encryptedBefore,"encrypted update preserved original");
expectError([&]{writeArchive(temp.path/L"wrong.rar",ArchiveWriteMode::create,{}, {item},{});},"ZIP and 7z");
const auto primary=temp.path/L"primary.zip", competing=temp.path/L"competing.zip";
bool attempted=false;
writeArchive(primary,ArchiveWriteMode::create,{}, {added},[&](uint64_t done,uint64_t)
{
if(done && !attempted)
{
attempted=true;
expectError([&]{writeArchive(competing,ArchiveWriteMode::create,{}, {item},{});},"archive operation");
}
return true;
});
expect(attempted && fs::exists(primary) && !fs::exists(competing),"concurrent archive writes are serialized");
const auto unchanged=contents(primary);
expectError([&]{writeArchive(primary,ArchiveWriteMode::create,{}, {item},{});},"already exists");
expect(contents(primary)==unchanged,"creating an existing archive preserved the original");
return 0;
}
catch(const std::exception &error)
{
std::cerr<<error.what()<<'\n';
return 1;
}
}