LCOV - code coverage report
Current view: top level - source/lib/file/archive - archive_zip.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 106 302 35.1 %
Date: 2026-12-03 01:19:39 Functions: 10 29 34.5 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  *
       3             :  * Permission is hereby granted, free of charge, to any person obtaining
       4             :  * a copy of this software and associated documentation files (the
       5             :  * "Software"), to deal in the Software without restriction, including
       6             :  * without limitation the rights to use, copy, modify, merge, publish,
       7             :  * distribute, sublicense, and/or sell copies of the Software, and to
       8             :  * permit persons to whom the Software is furnished to do so, subject to
       9             :  * the following conditions:
      10             :  *
      11             :  * The above copyright notice and this permission notice shall be included
      12             :  * in all copies or substantial portions of the Software.
      13             :  *
      14             :  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
      15             :  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
      16             :  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
      17             :  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
      18             :  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
      19             :  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
      20             :  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      21             :  */
      22             : 
      23             : /*
      24             :  * archive backend for Zip files.
      25             :  */
      26             : 
      27             : #include "precompiled.h"
      28             : 
      29             : #include "archive_zip.h"
      30             : 
      31             : #include "lib/alignment.h"
      32             : #include "lib/allocators/dynarray.h"
      33             : #include "lib/allocators/pool.h"
      34             : #include "lib/bits.h"
      35             : #include "lib/byte_order.h"
      36             : #include "lib/code_annotation.h"
      37             : #include "lib/debug.h"
      38             : #include "lib/file/archive/archive.h"
      39             : #include "lib/file/archive/codec.h"
      40             : #include "lib/file/archive/codec_zlib.h"
      41             : #include "lib/file/archive/stream.h"
      42             : #include "lib/file/file.h"
      43             : #include "lib/file/file_system.h"
      44             : #include "lib/file/io/io.h"
      45             : #include "lib/lib.h"
      46             : #include "lib/path.h"
      47             : #include "lib/posix/posix_types.h"
      48             : #include "lib/status.h"
      49             : #include "lib/utf8.h"
      50             : 
      51             : #include <algorithm>
      52             : #include <cstdint>
      53             : #include <cstring>
      54             : #include <ctime>
      55             : #include <exception>
      56             : #include <fcntl.h>
      57             : #include <memory>
      58             : #include <string>
      59             : 
      60             : //-----------------------------------------------------------------------------
      61             : // timestamp conversion: DOS FAT <-> Unix time_t
      62             : //-----------------------------------------------------------------------------
      63             : 
      64           1 : static time_t time_t_from_FAT(std::uint32_t fat_timedate)
      65             : {
      66           1 :     const std::uint32_t fat_time = bits(fat_timedate, 0, 15);
      67           1 :     const std::uint32_t fat_date = bits(fat_timedate, 16, 31);
      68             : 
      69           1 :     struct tm t;                            // struct tm format:
      70           1 :     t.tm_sec   = bits(fat_time, 0,4) * 2;   // [0,59]
      71           1 :     t.tm_min   = bits(fat_time, 5,10);      // [0,59]
      72           1 :     t.tm_hour  = bits(fat_time, 11,15);     // [0,23]
      73           1 :     t.tm_mday  = bits(fat_date, 0,4);       // [1,31]
      74           1 :     t.tm_mon   = bits(fat_date, 5,8) - 1;   // [0,11]
      75           1 :     t.tm_year  = bits(fat_date, 9,15) + 80; // since 1900
      76           1 :     t.tm_isdst = -1;    // unknown - let libc determine
      77             : 
      78             :     // otherwise: totally bogus, and at the limit of 32-bit time_t
      79           1 :     ENSURE(t.tm_year < 138);
      80             : 
      81           1 :     time_t ret = mktime(&t);
      82           1 :     ENSURE(ret != (time_t)-1);  // mktime shouldn't fail
      83           1 :     return ret;
      84             : }
      85             : 
      86             : 
      87           0 : static std::uint32_t FAT_from_time_t(time_t time)
      88             : {
      89             :     // (values are adjusted for DST)
      90           0 :     struct tm* t = localtime(&time);
      91             : 
      92           0 :     const std::uint16_t fat_time = static_cast<std::uint16_t>(
      93           0 :         (t->tm_sec/2) |          // 5
      94           0 :         (static_cast<std::uint16_t>(t->tm_min) << 5) | // 6
      95           0 :         (static_cast<std::uint16_t>(t->tm_hour) << 11)   // 5
      96             :         );
      97             : 
      98           0 :     const std::uint16_t fat_date = static_cast<std::uint16_t>(
      99           0 :         (t->tm_mday) |            // 5
     100           0 :         (static_cast<std::uint16_t>(t->tm_mon+1) << 5) | // 4
     101           0 :         (static_cast<std::uint16_t>(t->tm_year-80) << 9) // 7
     102             :         );
     103             : 
     104           0 :     std::uint32_t fat_timedate = u32_from_u16(fat_date, fat_time);
     105           0 :     return fat_timedate;
     106             : }
     107             : 
     108             : 
     109             : //-----------------------------------------------------------------------------
     110             : // Zip archive definitions
     111             : //-----------------------------------------------------------------------------
     112             : 
     113             : static const std::uint32_t cdfh_magic = FOURCC_LE('P','K','\1','\2');
     114             : static const std::uint32_t lfh_magic = FOURCC_LE('P','K','\3','\4');
     115             : static const std::uint32_t ecdr_magic = FOURCC_LE('P','K','\5','\6');
     116             : 
     117             : enum ZipMethod
     118             : {
     119             :     ZIP_METHOD_NONE    = 0,
     120             :     ZIP_METHOD_DEFLATE = 8
     121             : };
     122             : 
     123             : #pragma pack(push, 1)
     124             : 
     125             : class LFH
     126             : {
     127             : public:
     128           0 :     void Init(const CFileInfo& fileInfo, off_t csize, ZipMethod method, std::uint32_t checksum,
     129             :         const Path& pathname)
     130             :     {
     131           0 :         const std::string pathnameUTF8 = utf8_from_wstring(pathname.string());
     132           0 :         const size_t pathnameSize = pathnameUTF8.length();
     133             : 
     134           0 :         m_magic     = lfh_magic;
     135           0 :         m_x1        = to_le16(0);
     136           0 :         m_flags     = to_le16(0);
     137           0 :         m_method    = to_le16(u16_from_larger(method));
     138           0 :         m_fat_mtime = to_le32(FAT_from_time_t(fileInfo.MTime()));
     139           0 :         m_crc       = to_le32(checksum);
     140           0 :         m_csize     = to_le32(u32_from_larger(csize));
     141           0 :         m_usize     = to_le32(u32_from_larger(fileInfo.Size()));
     142           0 :         m_fn_len    = to_le16(u16_from_larger(pathnameSize));
     143           0 :         m_e_len     = to_le16(0);
     144             : 
     145           0 :         memcpy((char*)this + sizeof(LFH), pathnameUTF8.c_str(), pathnameSize);
     146           0 :     }
     147             : 
     148           0 :     size_t Size() const
     149             :     {
     150           0 :         ENSURE(m_magic == lfh_magic);
     151           0 :         size_t size = sizeof(LFH);
     152           0 :         size += read_le16(&m_fn_len);
     153           0 :         size += read_le16(&m_e_len);
     154             :         // note: LFH doesn't have a comment field!
     155           0 :         return size;
     156             :     }
     157             : 
     158             : private:
     159             :     std::uint32_t m_magic;
     160             :     std::uint16_t m_x1;         // version needed
     161             :     std::uint16_t m_flags;
     162             :     std::uint16_t m_method;
     163             :     std::uint32_t m_fat_mtime;  // last modified time (DOS FAT format)
     164             :     std::uint32_t m_crc;
     165             :     std::uint32_t m_csize;
     166             :     std::uint32_t m_usize;
     167             :     std::uint16_t m_fn_len;
     168             :     std::uint16_t m_e_len;
     169             : };
     170             : 
     171             : cassert(sizeof(LFH) == 30);
     172             : 
     173             : 
     174             : class CDFH
     175             : {
     176             : public:
     177           0 :     void Init(const CFileInfo& fileInfo, off_t ofs, off_t csize, ZipMethod method,
     178             :         std::uint32_t checksum, const Path& pathname, size_t slack)
     179             :     {
     180           0 :         const std::string pathnameUTF8 = utf8_from_wstring(pathname.string());
     181           0 :         const size_t pathnameLength = pathnameUTF8.length();
     182             : 
     183           0 :         m_magic     = cdfh_magic;
     184           0 :         m_x1        = to_le32(0);
     185           0 :         m_flags     = to_le16(0);
     186           0 :         m_method    = to_le16(u16_from_larger(method));
     187           0 :         m_fat_mtime = to_le32(FAT_from_time_t(fileInfo.MTime()));
     188           0 :         m_crc       = to_le32(checksum);
     189           0 :         m_csize     = to_le32(u32_from_larger(csize));
     190           0 :         m_usize     = to_le32(u32_from_larger(fileInfo.Size()));
     191           0 :         m_fn_len    = to_le16(u16_from_larger(pathnameLength));
     192           0 :         m_e_len     = to_le16(0);
     193           0 :         m_c_len     = to_le16(u16_from_larger((size_t)slack));
     194           0 :         m_x2        = to_le32(0);
     195           0 :         m_x3        = to_le32(0);
     196           0 :         m_lfh_ofs   = to_le32(u32_from_larger(ofs));
     197             : 
     198           0 :         memcpy((char*)this + sizeof(CDFH), pathnameUTF8.c_str(), pathnameLength);
     199           0 :     }
     200             : 
     201           1 :     Path Pathname() const
     202             :     {
     203           1 :         const size_t length = (size_t)read_le16(&m_fn_len);
     204           1 :         const char* pathname = (const char*)this + sizeof(CDFH); // not 0-terminated!
     205           2 :         return Path(std::string(pathname, length));
     206             :     }
     207             : 
     208           1 :     off_t HeaderOffset() const
     209             :     {
     210           2 :         return read_le32(&m_lfh_ofs);
     211             :     }
     212             : 
     213           1 :     off_t USize() const
     214             :     {
     215           2 :         return (off_t)read_le32(&m_usize);
     216             :     }
     217             : 
     218           1 :     off_t CSize() const
     219             :     {
     220           2 :         return (off_t)read_le32(&m_csize);
     221             :     }
     222             : 
     223           1 :     ZipMethod Method() const
     224             :     {
     225           2 :         return (ZipMethod)read_le16(&m_method);
     226             :     }
     227             : 
     228           1 :     std::uint32_t Checksum() const
     229             :     {
     230           1 :         return read_le32(&m_crc);
     231             :     }
     232             : 
     233           1 :     time_t MTime() const
     234             :     {
     235           2 :         const std::uint32_t fat_mtime = read_le32(&m_fat_mtime);
     236           1 :         return time_t_from_FAT(fat_mtime);
     237             :     }
     238             : 
     239           1 :     size_t Size() const
     240             :     {
     241           1 :         size_t size = sizeof(CDFH);
     242           1 :         size += read_le16(&m_fn_len);
     243           1 :         size += read_le16(&m_e_len);
     244           1 :         size += read_le16(&m_c_len);
     245           1 :         return size;
     246             :     }
     247             : 
     248             : private:
     249             :     std::uint32_t m_magic;
     250             :     std::uint32_t m_x1;         // versions
     251             :     std::uint16_t m_flags;
     252             :     std::uint16_t m_method;
     253             :     std::uint32_t m_fat_mtime;  // last modified time (DOS FAT format)
     254             :     std::uint32_t m_crc;
     255             :     std::uint32_t m_csize;
     256             :     std::uint32_t m_usize;
     257             :     std::uint16_t m_fn_len;
     258             :     std::uint16_t m_e_len;
     259             :     std::uint16_t m_c_len;
     260             :     std::uint32_t m_x2;         // spanning
     261             :     std::uint32_t m_x3;         // attributes
     262             :     std::uint32_t m_lfh_ofs;
     263             : };
     264             : 
     265             : cassert(sizeof(CDFH) == 46);
     266             : 
     267             : 
     268             : class ECDR
     269             : {
     270             : public:
     271           0 :     void Init(size_t cd_numEntries, off_t cd_ofs, size_t cd_size)
     272             :     {
     273           0 :         m_magic         = ecdr_magic;
     274           0 :         m_diskNum       = to_le16(0);
     275           0 :         m_cd_diskNum    = to_le16(0);
     276           0 :         m_cd_numEntriesOnDisk = to_le16(u16_from_larger(cd_numEntries));
     277           0 :         m_cd_numEntries = m_cd_numEntriesOnDisk;
     278           0 :         m_cd_size       = to_le32(u32_from_larger(cd_size));
     279           0 :         m_cd_ofs        = to_le32(u32_from_larger(cd_ofs));
     280           0 :         m_comment_len   = to_le16(0);
     281           0 :     }
     282             : 
     283           1 :     void Decompose(size_t& cd_numEntries, off_t& cd_ofs, size_t& cd_size) const
     284             :     {
     285           1 :         cd_numEntries = (size_t)read_le16(&m_cd_numEntries);
     286           1 :         cd_ofs       = (off_t)read_le32(&m_cd_ofs);
     287           1 :         cd_size      = (size_t)read_le32(&m_cd_size);
     288           1 :     }
     289             : 
     290           1 :     off_t GetCommentLength() const
     291             :     {
     292           2 :         return static_cast<off_t>(read_le16(&m_comment_len));
     293             :     }
     294             : 
     295             : private:
     296             :     std::uint32_t m_magic;
     297             :     std::uint16_t m_diskNum;
     298             :     std::uint16_t m_cd_diskNum;
     299             :     std::uint16_t m_cd_numEntriesOnDisk;
     300             :     std::uint16_t m_cd_numEntries;
     301             :     std::uint32_t m_cd_size;
     302             :     std::uint32_t m_cd_ofs;
     303             :     std::uint16_t m_comment_len;
     304             : };
     305             : 
     306             : cassert(sizeof(ECDR) == 22);
     307             : 
     308             : #pragma pack(pop)
     309             : 
     310             : 
     311             : //-----------------------------------------------------------------------------
     312             : // ArchiveFile_Zip
     313             : //-----------------------------------------------------------------------------
     314             : 
     315             : class ArchiveFile_Zip final : public IArchiveFile
     316             : {
     317             : public:
     318           1 :     ArchiveFile_Zip(const PFile& file, off_t ofs, off_t csize, std::uint32_t checksum, ZipMethod method)
     319           2 :         : m_file(file), m_ofs(ofs)
     320           1 :         , m_csize(csize), m_checksum(checksum), m_method(static_cast<std::uint16_t>(method))
     321           1 :         , m_flags(NeedsFixup)
     322             :     {
     323             :     }
     324             : 
     325           0 :     size_t Precedence() const override
     326             :     {
     327           0 :         return 2u;
     328             :     }
     329             : 
     330           0 :     wchar_t LocationCode() const override
     331             :     {
     332           0 :         return 'A';
     333             :     }
     334             : 
     335           0 :     const OsPath& Path() const override
     336             :     {
     337           0 :         return m_file->Pathname();
     338             :     }
     339             : 
     340           0 :     Status Load(const OsPath& /*name*/, const std::span<std::uint8_t> buffer) const override
     341             :     {
     342           0 :         AdjustOffset();
     343             : 
     344           0 :         PICodec codec;
     345           0 :         switch(m_method)
     346             :         {
     347           0 :         case ZIP_METHOD_NONE:
     348           0 :             codec = CreateCodec_ZLibNone();
     349           0 :             break;
     350           0 :         case ZIP_METHOD_DEFLATE:
     351           0 :             codec = CreateDecompressor_ZLibDeflate();
     352           0 :             break;
     353           0 :         default:
     354           0 :             WARN_RETURN(ERR::ARCHIVE_UNKNOWN_METHOD);
     355             :         }
     356             : 
     357           0 :         Stream stream(codec);
     358           0 :         stream.SetOutputBuffer(buffer.data(), buffer.size());
     359           0 :         io::Operation op(*m_file.get(), 0, m_csize, m_ofs);
     360           0 :         StreamFeeder streamFeeder(stream);
     361           0 :         RETURN_STATUS_IF_ERR(io::Run(op, io::Parameters(), streamFeeder));
     362           0 :         RETURN_STATUS_IF_ERR(stream.Finish());
     363             : #if CODEC_COMPUTE_CHECKSUM
     364           0 :         ENSURE(m_checksum == stream.Checksum());
     365             : #endif
     366             : 
     367             :         return INFO::OK;
     368           0 :     }
     369             : 
     370             : private:
     371             :     enum Flags
     372             :     {
     373             :         // indicates m_ofs points to a "local file header" instead of
     374             :         // the file data. a fixup routine is called when reading the file;
     375             :         // it skips past the LFH and clears this flag.
     376             :         // this is somewhat of a hack, but vital to archive open performance.
     377             :         // without it, we'd have to scan through the entire archive file,
     378             :         // which can take *seconds*.
     379             :         // (we cannot use the information in CDFH, because its 'extra' field
     380             :         // has been observed to differ from that of the LFH)
     381             :         // since we read the LFH right before the rest of the file, the block
     382             :         // cache will absorb the IO cost.
     383             :         NeedsFixup = 1
     384             :     };
     385             : 
     386             :     struct LFH_Copier
     387             :     {
     388           0 :         LFH_Copier(std::uint8_t* lfh_dst, size_t lfh_bytes_remaining)
     389           0 :             : lfh_dst(lfh_dst), lfh_bytes_remaining(lfh_bytes_remaining)
     390             :         {
     391             :         }
     392             : 
     393             :         // this code grabs an LFH struct from file block(s) that are
     394             :         // passed to the callback. usually, one call copies the whole thing,
     395             :         // but the LFH may straddle a block boundary.
     396             :         //
     397             :         // rationale: this allows using temp buffers for zip_fixup_lfh,
     398             :         // which avoids involving the file buffer manager and thus
     399             :         // avoids cluttering the trace and cache contents.
     400           0 :         Status operator()(const std::uint8_t* block, size_t size) const
     401             :         {
     402           0 :             ENSURE(size <= lfh_bytes_remaining);
     403           0 :             memcpy(lfh_dst, block, size);
     404           0 :             lfh_dst += size;
     405           0 :             lfh_bytes_remaining -= size;
     406             : 
     407           0 :             return INFO::OK;
     408             :         }
     409             : 
     410             :         mutable std::uint8_t* lfh_dst;
     411             :         mutable size_t lfh_bytes_remaining;
     412             :     };
     413             : 
     414             :     /**
     415             :      * fix up m_ofs (adjust it to point to cdata instead of the LFH).
     416             :      *
     417             :      * note: we cannot use CDFH filename and extra field lengths to skip
     418             :      * past LFH since that may not mirror CDFH (has happened).
     419             :      *
     420             :      * this is called at file-open time instead of while mounting to
     421             :      * reduce seeks: since reading the file will typically follow, the
     422             :      * block cache entirely absorbs the IO cost.
     423             :      **/
     424           0 :     void AdjustOffset() const
     425             :     {
     426           0 :         if(!(m_flags & NeedsFixup))
     427           0 :             return;
     428           0 :         m_flags &= ~NeedsFixup;
     429             : 
     430             :         // performance note: this ends up reading one file block, which is
     431             :         // only in the block cache if the file starts in the same block as a
     432             :         // previously read file (i.e. both are small).
     433           0 :         LFH lfh;
     434           0 :         io::Operation op(*m_file.get(), 0, sizeof(LFH), m_ofs);
     435           0 :         if(io::Run(op, io::Parameters(), LFH_Copier(reinterpret_cast<std::uint8_t*>(&lfh), sizeof(LFH))) == INFO::OK)
     436           0 :             m_ofs += (off_t)lfh.Size();
     437             :     }
     438             : 
     439             :     PFile m_file;
     440             : 
     441             :     // all relevant LFH/CDFH fields not covered by CFileInfo
     442             :     mutable off_t m_ofs;
     443             :     off_t m_csize;
     444             :     std::uint32_t m_checksum;
     445             :     std::uint16_t m_method;
     446             :     mutable std::uint16_t m_flags;
     447             : };
     448             : 
     449             : 
     450             : //-----------------------------------------------------------------------------
     451             : // ArchiveReader_Zip
     452             : //-----------------------------------------------------------------------------
     453             : 
     454             : class ArchiveReader_Zip : public IArchiveReader
     455             : {
     456             : public:
     457           1 :     ArchiveReader_Zip(const OsPath& pathname)
     458           1 :         : m_file(new File(pathname, O_RDONLY))
     459             :     {
     460           1 :         CFileInfo fileInfo;
     461           1 :         GetFileInfo(pathname, &fileInfo);
     462           1 :         m_fileSize = fileInfo.Size();
     463           1 :         const size_t minFileSize = sizeof(LFH)+sizeof(CDFH)+sizeof(ECDR);
     464           1 :         ENSURE(m_fileSize >= off_t(minFileSize));
     465           1 :     }
     466             : 
     467           1 :     virtual Status ReadEntries(ArchiveEntryCallback cb, uintptr_t cbData)
     468             :     {
     469             :         // locate and read Central Directory
     470           1 :         off_t cd_ofs = 0;
     471           1 :         size_t cd_numEntries = 0;
     472           1 :         size_t cd_size = 0;
     473           1 :         RETURN_STATUS_IF_ERR(LocateCentralDirectory(m_file, m_fileSize, cd_ofs, cd_numEntries, cd_size));
     474           1 :         io::BufferPtr buf(io::Allocate(cd_size));
     475             : 
     476           1 :         io::Operation op(*m_file.get(), buf.get(), cd_size, cd_ofs);
     477           1 :         RETURN_STATUS_IF_ERR(io::Run(op));
     478             : 
     479             :         // iterate over Central Directory
     480             :         const std::uint8_t* pos = buf.get();
     481           2 :         for(size_t i = 0; i < cd_numEntries; i++)
     482             :         {
     483             :             // scan for next CDFH
     484           1 :             CDFH* cdfh = (CDFH*)FindRecord(buf.get(), cd_size, pos, cdfh_magic, sizeof(CDFH));
     485           1 :             if(!cdfh)
     486           0 :                 WARN_RETURN(ERR::CORRUPTED);
     487             : 
     488           2 :             const Path relativePathname(cdfh->Pathname());
     489           1 :             if(!relativePathname.IsDirectory())
     490             :             {
     491           1 :                 const OsPath name = relativePathname.Filename();
     492           2 :                 CFileInfo fileInfo(name, cdfh->USize(), cdfh->MTime());
     493           1 :                 std::shared_ptr<ArchiveFile_Zip> archiveFile = std::make_shared<ArchiveFile_Zip>(m_file, cdfh->HeaderOffset(), cdfh->CSize(), cdfh->Checksum(), cdfh->Method());
     494           2 :                 cb(relativePathname, fileInfo, archiveFile, cbData);
     495           3 :             }
     496             : 
     497           1 :             pos += cdfh->Size();
     498             :         }
     499             : 
     500             :         return INFO::OK;
     501           1 :     }
     502             : 
     503             : private:
     504             :     /**
     505             :      * Scan buffer for a Zip file record.
     506             :      *
     507             :      * @param buf
     508             :      * @param size
     509             :      * @param start position within buffer
     510             :      * @param magic signature of record
     511             :      * @param recordSize size of record (including signature)
     512             :      * @return pointer to record within buffer or 0 if not found.
     513             :      **/
     514           1 :     static const std::uint8_t* FindRecord(const std::uint8_t* buf, size_t size,
     515             :         const std::uint8_t* start, std::uint32_t magic, size_t recordSize)
     516             :     {
     517             :         // (don't use <start> as the counter - otherwise we can't tell if
     518             :         // scanning within the buffer was necessary.)
     519           1 :         for(const std::uint8_t* p = start; p <= buf+size-recordSize; p++)
     520             :         {
     521             :             // found it
     522           1 :             if(*reinterpret_cast<const std::uint32_t*>(p) == magic)
     523             :             {
     524           1 :                 ENSURE(p == start); // otherwise, the archive is a bit broken
     525           1 :                 return p;
     526             :             }
     527             :         }
     528             : 
     529             :         // passed EOF, didn't find it.
     530             :         // note: do not warn - this happens in the initial ECDR search at
     531             :         // EOF if the archive contains a comment field.
     532             :         return 0;
     533             :     }
     534             : 
     535             :     // search for ECDR in the last <maxScanSize> bytes of the file.
     536             :     // if found, fill <dst_ecdr> with a copy of the (little-endian) ECDR and
     537             :     // return INFO::OK, otherwise IO error or ERR::CORRUPTED.
     538           1 :     static Status ScanForEcdr(const PFile& file, off_t fileSize, std::uint8_t* buf, size_t maxScanSize,
     539             :         size_t& cd_numEntries, off_t& cd_ofs, size_t& cd_size)
     540             :     {
     541             :         // don't scan more than the entire file
     542           1 :         const size_t scanSize = std::min(maxScanSize, size_t(fileSize));
     543             : 
     544             :         // read desired chunk of file into memory
     545           1 :         const off_t ofs = fileSize - off_t(scanSize);
     546           1 :         io::Operation op(*file.get(), buf, scanSize, ofs);
     547           1 :         RETURN_STATUS_IF_ERR(io::Run(op));
     548             : 
     549             :         // Scanning for ECDR first assumes no comment exists
     550             :         // (standard case), so ECDR structure exists right at
     551             :         // end of file
     552           1 :         off_t offsetInBlock = scanSize - sizeof(ECDR);
     553           1 :         const ECDR* ecdr = nullptr;
     554             : 
     555          63 :         for (off_t commentSize = 0; commentSize <= offsetInBlock && !ecdr; ++commentSize)
     556             :         {
     557          63 :             const std::uint8_t *pECDRTest = buf + offsetInBlock - commentSize;
     558          63 :             if (*reinterpret_cast<const std::uint32_t*>(pECDRTest) == ecdr_magic)
     559             :             {
     560             :                 // Signature matches, test whether comment
     561             :                 // fills up the whole space following the
     562             :                 // ECDR
     563           1 :                 ecdr = reinterpret_cast<const ECDR*>(pECDRTest);
     564           1 :                 if (commentSize != ecdr->GetCommentLength())
     565             :                 {
     566             :                     // Signature matches but there is some other data between
     567             :                     // header, comment and EOF. There are three possibilities
     568             :                     // for this:
     569             :                     // 1) Header file format and size differ from what we expect
     570             :                     // 2) File has been truncated
     571             :                     // 3) The magic id occurs inside a zip comment
     572             :                     ecdr = nullptr;
     573             :                 }
     574             :                 else
     575             :                 {
     576             :                     // Seems like a valid archive header before an archive-level
     577             :                     // comment
     578             :                     break;
     579             :                 }
     580             :             }
     581             :         }
     582             : 
     583           1 :         if(!ecdr)
     584             :             return INFO::CANNOT_HANDLE;
     585             : 
     586           1 :         ecdr->Decompose(cd_numEntries, cd_ofs, cd_size);
     587             :         return INFO::OK;
     588             :     }
     589             : 
     590           1 :     static Status LocateCentralDirectory(const PFile& file, off_t fileSize, off_t& cd_ofs, size_t& cd_numEntries, size_t& cd_size)
     591             :     {
     592           1 :         const size_t maxScanSize = 66000u;  // see below
     593           1 :         io::BufferPtr buf(io::Allocate(maxScanSize));
     594           1 :         Status ret = ScanForEcdr(file, fileSize, static_cast<std::uint8_t*>(buf.get()), maxScanSize,
     595             :             cd_numEntries, cd_ofs, cd_size);
     596           1 :         if(ret == INFO::OK)
     597             :             return INFO::OK;
     598             : 
     599           0 :         io::Operation op(*file.get(), buf.get(), sizeof(LFH));
     600           0 :         RETURN_STATUS_IF_ERR(io::Run(op));
     601             :         // the Zip file has an LFH but lacks an ECDR. this can happen if
     602             :         // the user hard-exits while an archive is being written.
     603             :         // notes:
     604             :         // - return ERR::CORRUPTED so VFS will not include this file.
     605             :         // - we could work around this by scanning all LFHs, but won't bother
     606             :         //   because it'd be slow.
     607             :         // - do not warn - the corrupt archive will be deleted on next
     608             :         //   successful archive builder run anyway.
     609           0 :         if(FindRecord(buf.get(), sizeof(LFH), buf.get(), lfh_magic, sizeof(LFH)))
     610             :             return ERR::CORRUPTED;  // NOWARN
     611             :         // totally bogus
     612             :         else
     613           1 :             WARN_RETURN(ERR::ARCHIVE_UNKNOWN_FORMAT);
     614           1 :     }
     615             : 
     616             :     PFile m_file;
     617             :     off_t m_fileSize;
     618             : };
     619             : 
     620           1 : PIArchiveReader CreateArchiveReader_Zip(const OsPath& archivePathname)
     621             : {
     622           1 :     try
     623             :     {
     624           2 :         return PIArchiveReader(new ArchiveReader_Zip(archivePathname));
     625             :     }
     626           0 :     catch(Status)
     627             :     {
     628           0 :         return PIArchiveReader();
     629           0 :     }
     630             : }
     631             : 
     632             : 
     633             : //-----------------------------------------------------------------------------
     634             : // ArchiveWriter_Zip
     635             : //-----------------------------------------------------------------------------
     636             : 
     637             : class ArchiveWriter_Zip : public IArchiveWriter
     638             : {
     639             : public:
     640           0 :     ArchiveWriter_Zip(const OsPath& archivePathname, bool noDeflate)
     641           0 :         : m_file(new File(archivePathname, O_WRONLY)), m_fileSize(0)
     642           0 :         , m_numEntries(0), m_noDeflate(noDeflate)
     643             :     {
     644           0 :         THROW_STATUS_IF_ERR(pool_create(&m_cdfhPool, 10*MiB, 0));
     645           0 :     }
     646             : 
     647           0 :     ~ArchiveWriter_Zip()
     648           0 :     {
     649             :         // append an ECDR to the CDFH list (this allows us to
     650             :         // write out both to the archive file in one burst)
     651           0 :         const size_t cd_size = m_cdfhPool.da.pos;
     652           0 :         ECDR* ecdr = (ECDR*)pool_alloc(&m_cdfhPool, sizeof(ECDR));
     653           0 :         if(!ecdr)
     654           0 :             std::terminate();
     655           0 :         const off_t cd_ofs = m_fileSize;
     656           0 :         ecdr->Init(m_numEntries, cd_ofs, cd_size);
     657             : 
     658           0 :         if(write(m_file->Descriptor(), m_cdfhPool.da.base, cd_size+sizeof(ECDR)) < 0)
     659           0 :             DEBUG_WARN_ERR(ERR::IO);    // no way to return error code
     660             : 
     661           0 :         (void)pool_destroy(&m_cdfhPool);
     662           0 :     }
     663             : 
     664           0 :     Status AddFile(const OsPath& pathname, const OsPath& pathnameInArchive)
     665             :     {
     666           0 :         CFileInfo fileInfo;
     667           0 :         RETURN_STATUS_IF_ERR(GetFileInfo(pathname, &fileInfo));
     668             : 
     669           0 :         PFile file(new File);
     670           0 :         RETURN_STATUS_IF_ERR(file->Open(pathname, O_RDONLY));
     671             : 
     672           0 :         return AddFileOrMemory(fileInfo, pathnameInArchive, file, NULL);
     673           0 :     }
     674             : 
     675           0 :     Status AddMemory(const std::uint8_t* data, size_t size, time_t mtime,
     676             :         const OsPath& pathnameInArchive)
     677             :     {
     678           0 :         CFileInfo fileInfo(pathnameInArchive, size, mtime);
     679             : 
     680           0 :         return AddFileOrMemory(fileInfo, pathnameInArchive, PFile(), data);
     681           0 :     }
     682             : 
     683           0 :     Status AddFileOrMemory(const CFileInfo& fileInfo, const OsPath& pathnameInArchive, const PFile& file,
     684             :         const std::uint8_t* data)
     685             :     {
     686           0 :         ENSURE((file && !data) || (data && !file));
     687             : 
     688           0 :         const off_t usize = fileInfo.Size();
     689             :         // skip 0-length files.
     690             :         // rationale: zip.cpp needs to determine whether a CDFH entry is
     691             :         // a file or directory (the latter are written by some programs but
     692             :         // not needed - they'd only pollute the file table).
     693             :         // it looks like checking for usize=csize=0 is the safest way -
     694             :         // relying on file attributes (which are system-dependent!) is
     695             :         // even less safe.
     696             :         // we thus skip 0-length files to avoid confusing them with directories.
     697           0 :         if(!usize)
     698             :             return INFO::SKIPPED;
     699             : 
     700           0 :         const size_t pathnameLength = pathnameInArchive.string().length();
     701             : 
     702             :         // choose method and the corresponding codec
     703           0 :         ZipMethod method;
     704           0 :         PICodec codec;
     705           0 :         if(m_noDeflate || IsFileTypeIncompressible(pathnameInArchive))
     706             :         {
     707           0 :             method = ZIP_METHOD_NONE;
     708           0 :             codec = CreateCodec_ZLibNone();
     709             :         }
     710             :         else
     711             :         {
     712           0 :             method = ZIP_METHOD_DEFLATE;
     713           0 :             codec = CreateCompressor_ZLibDeflate();
     714             :         }
     715             : 
     716             :         // allocate memory
     717           0 :         const size_t csizeMax = codec->MaxOutputSize(size_t(usize));
     718           0 :         io::BufferPtr buf(io::Allocate(sizeof(LFH) + pathnameLength + csizeMax));
     719             : 
     720             :         // read and compress file contents
     721           0 :         size_t csize; std::uint32_t checksum;
     722           0 :         {
     723           0 :             std::uint8_t* cdata = buf.get() + sizeof(LFH) + pathnameLength;
     724           0 :             Stream stream(codec);
     725           0 :             stream.SetOutputBuffer(cdata, csizeMax);
     726           0 :             StreamFeeder streamFeeder(stream);
     727           0 :             if(file)
     728             :             {
     729           0 :                 io::Operation op(*file.get(), 0, usize);
     730           0 :                 RETURN_STATUS_IF_ERR(io::Run(op, io::Parameters(), streamFeeder));
     731             :             }
     732             :             else
     733             :             {
     734           0 :                 RETURN_STATUS_IF_ERR(streamFeeder(data, usize));
     735             :             }
     736           0 :             RETURN_STATUS_IF_ERR(stream.Finish());
     737           0 :             csize = stream.OutSize();
     738           0 :             checksum = stream.Checksum();
     739           0 :         }
     740             : 
     741             :         // build LFH
     742           0 :         {
     743           0 :             LFH* lfh = reinterpret_cast<LFH*>(buf.get());
     744           0 :             lfh->Init(fileInfo, (off_t)csize, method, checksum, pathnameInArchive);
     745             :         }
     746             : 
     747             :         // append a CDFH to the central directory (in memory)
     748           0 :         const off_t ofs = m_fileSize;
     749           0 :         const size_t prev_pos = m_cdfhPool.da.pos;  // (required to determine padding size)
     750           0 :         const size_t cdfhSize = sizeof(CDFH) + pathnameLength;
     751           0 :         CDFH* cdfh = (CDFH*)pool_alloc(&m_cdfhPool, cdfhSize);
     752           0 :         if(!cdfh)
     753           0 :             WARN_RETURN(ERR::NO_MEM);
     754           0 :         const size_t slack = m_cdfhPool.da.pos - prev_pos - cdfhSize;
     755           0 :         cdfh->Init(fileInfo, ofs, (off_t)csize, method, checksum, pathnameInArchive, slack);
     756           0 :         m_numEntries++;
     757             : 
     758             :         // write LFH, pathname and cdata to file
     759           0 :         const size_t packageSize = sizeof(LFH) + pathnameLength + csize;
     760           0 :         if(write(m_file->Descriptor(), buf.get(), packageSize) < 0)
     761           0 :             WARN_RETURN(ERR::IO);
     762           0 :         m_fileSize += (off_t)packageSize;
     763             : 
     764           0 :         return INFO::OK;
     765             :     }
     766             : 
     767             : private:
     768           0 :     static bool IsFileTypeIncompressible(const OsPath& pathname)
     769             :     {
     770           0 :         const OsPath extension = pathname.Extension();
     771             : 
     772             :         // file extensions that we don't want to compress
     773           0 :         static const wchar_t* incompressibleExtensions[] =
     774             :         {
     775             :             L".zip", L".rar",
     776             :             L".jpg", L".jpeg", L".png",
     777             :             L".ogg", L".mp3"
     778             :         };
     779             : 
     780           0 :         for(size_t i = 0; i < ARRAY_SIZE(incompressibleExtensions); i++)
     781             :         {
     782           0 :             if(extension == incompressibleExtensions[i])
     783             :                 return true;
     784             :         }
     785             : 
     786             :         return false;
     787           0 :     }
     788             : 
     789             :     PFile m_file;
     790             :     off_t m_fileSize;
     791             : 
     792             :     Pool m_cdfhPool;
     793             :     size_t m_numEntries;
     794             : 
     795             :     bool m_noDeflate;
     796             : };
     797             : 
     798           0 : PIArchiveWriter CreateArchiveWriter_Zip(const OsPath& archivePathname, bool noDeflate)
     799             : {
     800           0 :     try
     801             :     {
     802           0 :         return PIArchiveWriter(new ArchiveWriter_Zip(archivePathname, noDeflate));
     803             :     }
     804           0 :     catch(Status)
     805             :     {
     806           0 :         return PIArchiveWriter();
     807           0 :     }
     808             : }

Generated by: LCOV version 1.16