1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/zipstrm.cpp
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
6 // Copyright: (c) Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
17 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
25 #include "wx/zipstrm.h"
26 #include "wx/datstrm.h"
27 #include "wx/zstream.h"
28 #include "wx/mstream.h"
29 #include "wx/buffer.h"
30 #include "wx/ptr_scpd.h"
31 #include "wx/wfstream.h"
35 // value for the 'version needed to extract' field (20 means 2.0)
37 VERSION_NEEDED_TO_EXTRACT
= 20
40 // signatures for the various records (PKxx)
42 CENTRAL_MAGIC
= 0x02014b50, // central directory record
43 LOCAL_MAGIC
= 0x04034b50, // local header
44 END_MAGIC
= 0x06054b50, // end of central directory record
45 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
48 // unix file attributes. zip stores them in the high 16 bits of the
49 // 'external attributes' field, hence the extra zeros.
51 wxZIP_S_IFMT
= 0xF0000000,
52 wxZIP_S_IFDIR
= 0x40000000,
53 wxZIP_S_IFREG
= 0x80000000
56 // minimum sizes for the various records
64 // The number of bytes that must be written to an wxZipOutputStream before
65 // a zip entry is created. The purpose of this latency is so that
66 // OpenCompressor() can see a little data before deciding which compressor
72 // Some offsets into the local header
77 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
78 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
80 wxFORCE_LINK_THIS_MODULE(zipstrm
)
83 /////////////////////////////////////////////////////////////////////////////
86 // read a string of a given length
88 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
94 wxCharBuffer
buf(len
);
95 stream
.Read(buf
.data(), len
);
96 wxString
str(buf
, conv
);
101 wxStringBuffer
buf(str
, len
);
102 stream
.Read(buf
, len
);
109 // Decode a little endian wxUint32 number from a character array
111 static inline wxUint32
CrackUint32(const char *m
)
113 const unsigned char *n
= (const unsigned char*)m
;
114 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
117 // Decode a little endian wxUint16 number from a character array
119 static inline wxUint16
CrackUint16(const char *m
)
121 const unsigned char *n
= (const unsigned char*)m
;
122 return (n
[1] << 8) | n
[0];
125 // Temporarily lower the logging level in debug mode to avoid a warning
126 // from SeekI about seeking on a stream with data written back to it.
128 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
130 #if defined(__WXDEBUG__) && wxUSE_LOG
131 wxLogLevel level
= wxLog::GetLogLevel();
132 wxLog::SetLogLevel(wxLOG_Debug
- 1);
133 wxFileOffset result
= stream
.SeekI(pos
);
134 wxLog::SetLogLevel(level
);
137 return stream
.SeekI(pos
);
142 /////////////////////////////////////////////////////////////////////////////
148 wxZipHeader(wxInputStream
& stream
, size_t size
);
150 inline wxUint8
Read8();
151 inline wxUint16
Read16();
152 inline wxUint32
Read32();
154 const char *GetData() const { return m_data
; }
155 size_t GetSize() const { return m_size
; }
156 operator bool() const { return m_ok
; }
158 size_t Seek(size_t pos
) { m_pos
= pos
; return m_pos
; }
159 size_t Skip(size_t size
) { m_pos
+= size
; return m_pos
; }
161 wxZipHeader
& operator>>(wxUint8
& n
) { n
= Read8(); return *this; }
162 wxZipHeader
& operator>>(wxUint16
& n
) { n
= Read16(); return *this; }
163 wxZipHeader
& operator>>(wxUint32
& n
) { n
= Read32(); return *this; }
172 wxZipHeader::wxZipHeader(wxInputStream
& stream
, size_t size
)
177 wxCHECK_RET(size
<= sizeof(m_data
), _T("buffer too small"));
178 m_size
= stream
.Read(m_data
, size
).LastRead();
179 m_ok
= m_size
== size
;
182 wxUint8
wxZipHeader::Read8()
184 wxASSERT(m_pos
< m_size
);
185 return m_data
[m_pos
++];
188 wxUint16
wxZipHeader::Read16()
190 wxASSERT(m_pos
+ 2 <= m_size
);
191 wxUint16 n
= CrackUint16(m_data
+ m_pos
);
196 wxUint32
wxZipHeader::Read32()
198 wxASSERT(m_pos
+ 4 <= m_size
);
199 wxUint32 n
= CrackUint32(m_data
+ m_pos
);
205 /////////////////////////////////////////////////////////////////////////////
206 // Stored input stream
207 // Trival decompressor for files which are 'stored' in the zip file.
209 class wxStoredInputStream
: public wxFilterInputStream
212 wxStoredInputStream(wxInputStream
& stream
);
214 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
215 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
217 virtual char Peek() { return wxInputStream::Peek(); }
218 virtual wxFileOffset
GetLength() const { return m_len
; }
221 virtual size_t OnSysRead(void *buffer
, size_t size
);
222 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
228 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
231 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
232 : wxFilterInputStream(stream
),
238 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
240 size_t count
= wx_truncate_cast(size_t,
241 wxMin(size
+ wxFileOffset(0), m_len
- m_pos
+ size_t(0)));
242 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
246 m_lasterror
= m_pos
== m_len
? wxSTREAM_EOF
: wxSTREAM_READ_ERROR
;
252 /////////////////////////////////////////////////////////////////////////////
253 // Stored output stream
254 // Trival compressor for files which are 'stored' in the zip file.
256 class wxStoredOutputStream
: public wxFilterOutputStream
259 wxStoredOutputStream(wxOutputStream
& stream
) :
260 wxFilterOutputStream(stream
), m_pos(0) { }
264 m_lasterror
= wxSTREAM_NO_ERROR
;
269 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
270 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
274 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
277 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
279 if (!IsOk() || !size
)
281 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
283 m_lasterror
= wxSTREAM_WRITE_ERROR
;
289 /////////////////////////////////////////////////////////////////////////////
292 // Used to handle the unusal case of raw copying an entry of unknown
293 // length. This can only happen when the zip being copied from is being
294 // read from a non-seekable stream, and also was original written to a
295 // non-seekable stream.
297 // In this case there's no option but to decompress the stream to find
298 // it's length, but we can still write the raw compressed data to avoid the
299 // compression overhead (which is the greater one).
301 // Usage is like this:
302 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
303 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
305 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
306 // is something like the unix 'tee' command; it is a transparent filter, but
307 // allows the data read to be read a second time via an extra method 'GetData'.
309 // The wxRawInputStream then draws data through the tee using a decompressor
310 // then instead of returning the decompressed data, retuns the raw data
311 // from wxTeeInputStream::GetData().
313 class wxTeeInputStream
: public wxFilterInputStream
316 wxTeeInputStream(wxInputStream
& stream
);
318 size_t GetCount() const { return m_end
- m_start
; }
319 size_t GetData(char *buffer
, size_t size
);
324 wxInputStream
& Read(void *buffer
, size_t size
);
327 virtual size_t OnSysRead(void *buffer
, size_t size
);
328 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
332 wxMemoryBuffer m_buf
;
336 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
339 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
340 : wxFilterInputStream(stream
),
341 m_pos(0), m_buf(8192), m_start(0), m_end(0)
345 void wxTeeInputStream::Open()
347 m_pos
= m_start
= m_end
= 0;
348 m_lasterror
= wxSTREAM_NO_ERROR
;
351 bool wxTeeInputStream::Final()
353 bool final
= m_end
== m_buf
.GetDataLen();
354 m_end
= m_buf
.GetDataLen();
358 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
360 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
361 m_end
= m_buf
.GetDataLen();
362 m_buf
.AppendData(buffer
, count
);
366 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
368 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
370 m_lasterror
= m_parent_i_stream
->GetLastError();
374 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
377 size_t len
= m_buf
.GetDataLen();
378 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
379 m_buf
.SetDataLen(len
);
381 wxFAIL
; // we've already returned data that's now being ungot
384 m_parent_i_stream
->Reset();
385 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
392 if (size
> GetCount())
395 memcpy(buffer
, m_buf
+ m_start
, size
);
397 wxASSERT(m_start
<= m_end
);
400 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
401 size_t len
= m_buf
.GetDataLen();
402 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
404 memmove(buf
, buf
+ m_end
, len
);
405 m_buf
.UngetWriteBuf(len
);
412 class wxRawInputStream
: public wxFilterInputStream
415 wxRawInputStream(wxInputStream
& stream
);
416 virtual ~wxRawInputStream() { delete m_tee
; }
418 wxInputStream
* Open(wxInputStream
*decomp
);
419 wxInputStream
& GetTee() const { return *m_tee
; }
422 virtual size_t OnSysRead(void *buffer
, size_t size
);
423 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
427 wxTeeInputStream
*m_tee
;
429 enum { BUFSIZE
= 8192 };
430 wxCharBuffer m_dummy
;
432 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
435 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
436 : wxFilterInputStream(stream
),
438 m_tee(new wxTeeInputStream(stream
)),
443 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
446 m_parent_i_stream
= decomp
;
448 m_lasterror
= wxSTREAM_NO_ERROR
;
456 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
458 char *buf
= (char*)buffer
;
461 while (count
< size
&& IsOk())
463 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
464 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
466 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
469 if (n
== 0 && m_tee
->Final())
470 m_lasterror
= m_parent_i_stream
->GetLastError();
478 /////////////////////////////////////////////////////////////////////////////
479 // Zlib streams than can be reused without recreating.
481 class wxZlibOutputStream2
: public wxZlibOutputStream
484 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
485 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
487 bool Open(wxOutputStream
& stream
);
488 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
491 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
493 wxCHECK(m_pos
== wxInvalidOffset
, false);
495 m_deflate
->next_out
= m_z_buffer
;
496 m_deflate
->avail_out
= m_z_size
;
498 m_lasterror
= wxSTREAM_NO_ERROR
;
499 m_parent_o_stream
= &stream
;
501 if (deflateReset(m_deflate
) != Z_OK
) {
502 wxLogError(_("can't re-initialize zlib deflate stream"));
503 m_lasterror
= wxSTREAM_WRITE_ERROR
;
510 class wxZlibInputStream2
: public wxZlibInputStream
513 wxZlibInputStream2(wxInputStream
& stream
) :
514 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
516 bool Open(wxInputStream
& stream
);
519 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
521 m_inflate
->avail_in
= 0;
523 m_lasterror
= wxSTREAM_NO_ERROR
;
524 m_parent_i_stream
= &stream
;
526 if (inflateReset(m_inflate
) != Z_OK
) {
527 wxLogError(_("can't re-initialize zlib inflate stream"));
528 m_lasterror
= wxSTREAM_READ_ERROR
;
536 /////////////////////////////////////////////////////////////////////////////
537 // Class to hold wxZipEntry's Extra and LocalExtra fields
542 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
544 wxZipMemory
*AddRef() { m_ref
++; return this; }
545 void Release() { if (--m_ref
== 0) delete this; }
547 char *GetData() const { return m_data
; }
548 size_t GetSize() const { return m_size
; }
549 size_t GetCapacity() const { return m_capacity
; }
551 wxZipMemory
*Unique(size_t size
);
554 ~wxZipMemory() { delete [] m_data
; }
561 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipMemory
)
564 wxZipMemory
*wxZipMemory::Unique(size_t size
)
570 zm
= new wxZipMemory
;
575 if (zm
->m_capacity
< size
) {
576 delete [] zm
->m_data
;
577 zm
->m_data
= new char[size
];
578 zm
->m_capacity
= size
;
585 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
592 static inline void Release(wxZipMemory
*zm
)
598 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
604 static void Unique(wxZipMemory
*& zm
, size_t size
)
607 zm
= new wxZipMemory
;
609 zm
= zm
->Unique(size
);
613 /////////////////////////////////////////////////////////////////////////////
614 // Collection of weak references to entries
616 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
617 wxIntegerEqual
, wx__OffsetZipEntryMap
);
622 wxZipWeakLinks() : m_ref(1) { }
624 void Release(const wxZipInputStream
* WXUNUSED(x
))
625 { if (--m_ref
== 0) delete this; }
626 void Release(wxFileOffset key
)
627 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
629 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
630 void RemoveEntry(wxFileOffset key
)
631 { m_entries
.erase(wx_truncate_cast(key_type
, key
)); }
632 wxZipEntry
*GetEntry(wxFileOffset key
) const;
633 bool IsEmpty() const { return m_entries
.empty(); }
636 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
638 typedef wx__OffsetZipEntryMap::key_type key_type
;
641 wx__OffsetZipEntryMap m_entries
;
643 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipWeakLinks
)
646 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
648 m_entries
[wx_truncate_cast(key_type
, key
)] = entry
;
653 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
655 wx__OffsetZipEntryMap::const_iterator it
=
656 m_entries
.find(wx_truncate_cast(key_type
, key
));
657 return it
!= m_entries
.end() ? it
->second
: NULL
;
661 /////////////////////////////////////////////////////////////////////////////
664 wxZipEntry::wxZipEntry(
665 const wxString
& name
/*=wxEmptyString*/,
666 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
667 wxFileOffset size
/*=wxInvalidOffset*/)
669 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
670 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
671 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
673 m_Method(wxZIP_METHOD_DEFAULT
),
676 m_CompressedSize(wxInvalidOffset
),
678 m_Key(wxInvalidOffset
),
679 m_Offset(wxInvalidOffset
),
681 m_InternalAttributes(0),
682 m_ExternalAttributes(0),
692 wxZipEntry::~wxZipEntry()
695 m_backlink
->Release(m_Key
);
697 Release(m_LocalExtra
);
700 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
702 m_SystemMadeBy(e
.m_SystemMadeBy
),
703 m_VersionMadeBy(e
.m_VersionMadeBy
),
704 m_VersionNeeded(e
.m_VersionNeeded
),
706 m_Method(e
.m_Method
),
707 m_DateTime(e
.m_DateTime
),
709 m_CompressedSize(e
.m_CompressedSize
),
713 m_Offset(e
.m_Offset
),
714 m_Comment(e
.m_Comment
),
715 m_DiskStart(e
.m_DiskStart
),
716 m_InternalAttributes(e
.m_InternalAttributes
),
717 m_ExternalAttributes(e
.m_ExternalAttributes
),
718 m_Extra(AddRef(e
.m_Extra
)),
719 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
725 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
728 m_SystemMadeBy
= e
.m_SystemMadeBy
;
729 m_VersionMadeBy
= e
.m_VersionMadeBy
;
730 m_VersionNeeded
= e
.m_VersionNeeded
;
732 m_Method
= e
.m_Method
;
733 m_DateTime
= e
.m_DateTime
;
735 m_CompressedSize
= e
.m_CompressedSize
;
739 m_Offset
= e
.m_Offset
;
740 m_Comment
= e
.m_Comment
;
741 m_DiskStart
= e
.m_DiskStart
;
742 m_InternalAttributes
= e
.m_InternalAttributes
;
743 m_ExternalAttributes
= e
.m_ExternalAttributes
;
744 Copy(m_Extra
, e
.m_Extra
);
745 Copy(m_LocalExtra
, e
.m_LocalExtra
);
746 m_zipnotifier
= NULL
;
748 m_backlink
->Release(m_Key
);
755 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
757 bool isDir
= IsDir() && !m_Name
.empty();
759 // optimisations for common (and easy) cases
760 switch (wxFileName::GetFormat(format
)) {
763 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
764 for (size_t i
= 0; i
< name
.length(); i
++)
765 if (name
[i
] == _T('/'))
771 return isDir
? m_Name
+ _T("/") : m_Name
;
780 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
782 fn
.Assign(m_Name
, wxPATH_UNIX
);
784 return fn
.GetFullPath(format
);
787 // Static - Internally tars and zips use forward slashes for the path
788 // separator, absolute paths aren't allowed, and directory names have a
789 // trailing slash. This function converts a path into this internal format,
790 // but without a trailing slash for a directory.
792 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
793 wxPathFormat format
/*=wxPATH_NATIVE*/,
794 bool *pIsDir
/*=NULL*/)
798 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
799 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
803 bool isDir
= !internal
.empty() && internal
.Last() == '/';
807 internal
.erase(internal
.length() - 1);
809 while (!internal
.empty() && *internal
.begin() == '/')
810 internal
.erase(0, 1);
811 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
812 internal
.erase(0, 2);
813 if (internal
== _T(".") || internal
== _T(".."))
814 internal
= wxEmptyString
;
819 void wxZipEntry::SetSystemMadeBy(int system
)
821 int mode
= GetMode();
822 bool wasUnix
= IsMadeByUnix();
824 m_SystemMadeBy
= (wxUint8
)system
;
826 if (!wasUnix
&& IsMadeByUnix()) {
829 } else if (wasUnix
&& !IsMadeByUnix()) {
830 m_ExternalAttributes
&= 0xffff;
834 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
837 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
839 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
841 if (IsMadeByUnix()) {
842 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
844 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
846 m_ExternalAttributes
|= wxZIP_S_IFREG
;
850 // Return unix style permission bits
852 int wxZipEntry::GetMode() const
854 // return unix permissions if present
856 return (m_ExternalAttributes
>> 16) & 0777;
858 // otherwise synthesize from the dos attribs
860 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
862 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
868 // Set unix permissions
870 void wxZipEntry::SetMode(int mode
)
872 // Set dos attrib bits to be compatible
874 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
876 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
878 // set the actual unix permission bits if the system type allows
879 if (IsMadeByUnix()) {
880 m_ExternalAttributes
&= ~(0777L << 16);
881 m_ExternalAttributes
|= (mode
& 0777L) << 16;
885 const char *wxZipEntry::GetExtra() const
887 return m_Extra
? m_Extra
->GetData() : NULL
;
890 size_t wxZipEntry::GetExtraLen() const
892 return m_Extra
? m_Extra
->GetSize() : 0;
895 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
897 Unique(m_Extra
, len
);
899 memcpy(m_Extra
->GetData(), extra
, len
);
902 const char *wxZipEntry::GetLocalExtra() const
904 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
907 size_t wxZipEntry::GetLocalExtraLen() const
909 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
912 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
914 Unique(m_LocalExtra
, len
);
916 memcpy(m_LocalExtra
->GetData(), extra
, len
);
919 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
921 wxArchiveEntry::UnsetNotifier();
922 m_zipnotifier
= ¬ifier
;
923 m_zipnotifier
->OnEntryUpdated(*this);
926 void wxZipEntry::Notify()
929 m_zipnotifier
->OnEntryUpdated(*this);
930 else if (GetNotifier())
931 GetNotifier()->OnEntryUpdated(*this);
934 void wxZipEntry::UnsetNotifier()
936 wxArchiveEntry::UnsetNotifier();
937 m_zipnotifier
= NULL
;
940 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
942 wxUint16 nameLen
, extraLen
;
943 wxUint32 compressedSize
, size
, crc
;
945 wxZipHeader
ds(stream
, LOCAL_SIZE
- 4);
949 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
950 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
951 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
953 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
955 if (sumsValid
|| crc
)
957 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
958 m_CompressedSize
= compressedSize
;
959 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
962 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
963 if (stream
.LastRead() != nameLen
+ 0u)
966 if (extraLen
|| GetLocalExtraLen()) {
967 Unique(m_LocalExtra
, extraLen
);
969 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
970 if (stream
.LastRead() != extraLen
+ 0u)
975 return LOCAL_SIZE
+ nameLen
+ extraLen
;
978 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
980 wxString unixName
= GetName(wxPATH_UNIX
);
981 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
982 const char *name
= name_buf
;
983 if (!name
) name
= "";
984 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
986 wxDataOutputStream
ds(stream
);
988 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
989 ds
.Write32(GetDateTime().GetAsDOS());
992 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
?
993 wx_truncate_cast(wxUint32
, m_CompressedSize
) : 0);
994 ds
.Write32(m_Size
!= wxInvalidOffset
?
995 wx_truncate_cast(wxUint32
, m_Size
) : 0);
998 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetLocalExtraLen());
999 ds
.Write16(extraLen
);
1001 stream
.Write(name
, nameLen
);
1003 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
1005 return LOCAL_SIZE
+ nameLen
+ extraLen
;
1008 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
1010 wxUint16 nameLen
, extraLen
, commentLen
;
1012 wxZipHeader
ds(stream
, CENTRAL_SIZE
- 4);
1016 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
1018 SetVersionNeeded(ds
.Read16());
1019 SetFlags(ds
.Read16());
1020 SetMethod(ds
.Read16());
1021 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
1022 SetCrc(ds
.Read32());
1023 SetCompressedSize(ds
.Read32());
1024 SetSize(ds
.Read32());
1026 ds
>> nameLen
>> extraLen
>> commentLen
1027 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
1028 SetOffset(ds
.Read32());
1030 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
1031 if (stream
.LastRead() != nameLen
+ 0u)
1034 if (extraLen
|| GetExtraLen()) {
1035 Unique(m_Extra
, extraLen
);
1037 stream
.Read(m_Extra
->GetData(), extraLen
);
1038 if (stream
.LastRead() != extraLen
+ 0u)
1044 m_Comment
= ReadString(stream
, commentLen
, conv
);
1045 if (stream
.LastRead() != commentLen
+ 0u)
1051 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1054 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
1056 wxString unixName
= GetName(wxPATH_UNIX
);
1057 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
1058 const char *name
= name_buf
;
1059 if (!name
) name
= "";
1060 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
1062 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1063 const char *comment
= comment_buf
;
1064 if (!comment
) comment
= "";
1065 wxUint16 commentLen
= wx_truncate_cast(wxUint16
, strlen(comment
));
1067 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetExtraLen());
1069 wxDataOutputStream
ds(stream
);
1071 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
1073 ds
.Write16(wx_truncate_cast(wxUint16
, GetVersionNeeded()));
1074 ds
.Write16(wx_truncate_cast(wxUint16
, GetFlags()));
1075 ds
.Write16(wx_truncate_cast(wxUint16
, GetMethod()));
1076 ds
.Write32(GetDateTime().GetAsDOS());
1077 ds
.Write32(GetCrc());
1078 ds
.Write32(wx_truncate_cast(wxUint32
, GetCompressedSize()));
1079 ds
.Write32(wx_truncate_cast(wxUint32
, GetSize()));
1080 ds
.Write16(nameLen
);
1081 ds
.Write16(extraLen
);
1083 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
1084 << m_ExternalAttributes
<< wx_truncate_cast(wxUint32
, GetOffset());
1086 stream
.Write(name
, nameLen
);
1088 stream
.Write(GetExtra(), extraLen
);
1089 stream
.Write(comment
, commentLen
);
1091 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1094 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1095 // the 1st value is the signature then it is probably an info-zip record,
1096 // though there is a small chance that it is in fact a pkzip record which
1097 // happens to have the signature as it's CRC.
1099 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1101 wxZipHeader
ds(stream
, SUMS_SIZE
);
1105 m_Crc
= ds
.Read32();
1106 m_CompressedSize
= ds
.Read32();
1107 m_Size
= ds
.Read32();
1109 // if 1st value is the signature then this is probably an info-zip record
1110 if (m_Crc
== SUMS_MAGIC
)
1112 wxZipHeader
buf(stream
, 8);
1113 wxUint32 u1
= buf
.GetSize() >= 4 ? buf
.Read32() : (wxUint32
)LOCAL_MAGIC
;
1114 wxUint32 u2
= buf
.GetSize() == 8 ? buf
.Read32() : 0;
1116 // look for the signature of the following record to decide which
1117 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1118 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1120 // it's a pkzip style record after all!
1121 if (buf
.GetSize() > 0)
1122 stream
.Ungetch(buf
.GetData(), buf
.GetSize());
1126 // it's an info-zip record as expected
1127 if (buf
.GetSize() > 4)
1128 stream
.Ungetch(buf
.GetData() + 4, buf
.GetSize() - 4);
1129 m_Crc
= wx_truncate_cast(wxUint32
, m_CompressedSize
);
1130 m_CompressedSize
= m_Size
;
1132 return SUMS_SIZE
+ 4;
1139 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1140 wxFileOffset compressedSize
, wxFileOffset size
)
1143 m_CompressedSize
= compressedSize
;
1146 wxDataOutputStream
ds(stream
);
1149 ds
.Write32(wx_truncate_cast(wxUint32
, compressedSize
));
1150 ds
.Write32(wx_truncate_cast(wxUint32
, size
));
1156 /////////////////////////////////////////////////////////////////////////////
1157 // wxZipEndRec - holds the end of central directory record
1164 int GetDiskNumber() const { return m_DiskNumber
; }
1165 int GetStartDisk() const { return m_StartDisk
; }
1166 int GetEntriesHere() const { return m_EntriesHere
; }
1167 int GetTotalEntries() const { return m_TotalEntries
; }
1168 wxFileOffset
GetSize() const { return m_Size
; }
1169 wxFileOffset
GetOffset() const { return m_Offset
; }
1170 wxString
GetComment() const { return m_Comment
; }
1172 void SetDiskNumber(int num
)
1173 { m_DiskNumber
= wx_truncate_cast(wxUint16
, num
); }
1174 void SetStartDisk(int num
)
1175 { m_StartDisk
= wx_truncate_cast(wxUint16
, num
); }
1176 void SetEntriesHere(int num
)
1177 { m_EntriesHere
= wx_truncate_cast(wxUint16
, num
); }
1178 void SetTotalEntries(int num
)
1179 { m_TotalEntries
= wx_truncate_cast(wxUint16
, num
); }
1180 void SetSize(wxFileOffset size
)
1181 { m_Size
= wx_truncate_cast(wxUint32
, size
); }
1182 void SetOffset(wxFileOffset offset
)
1183 { m_Offset
= wx_truncate_cast(wxUint32
, offset
); }
1184 void SetComment(const wxString
& comment
)
1185 { m_Comment
= comment
; }
1187 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1188 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1191 wxUint16 m_DiskNumber
;
1192 wxUint16 m_StartDisk
;
1193 wxUint16 m_EntriesHere
;
1194 wxUint16 m_TotalEntries
;
1200 wxZipEndRec::wxZipEndRec()
1210 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1212 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1213 const char *comment
= comment_buf
;
1214 if (!comment
) comment
= "";
1215 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1217 wxDataOutputStream
ds(stream
);
1219 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1220 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1222 stream
.Write(comment
, commentLen
);
1224 return stream
.IsOk();
1227 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1229 wxZipHeader
ds(stream
, END_SIZE
- 4);
1233 wxUint16 commentLen
;
1235 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1236 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1239 m_Comment
= ReadString(stream
, commentLen
, conv
);
1240 if (stream
.LastRead() != commentLen
+ 0u)
1244 if (m_DiskNumber
!= 0 || m_StartDisk
!= 0 ||
1245 m_EntriesHere
!= m_TotalEntries
)
1246 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1252 /////////////////////////////////////////////////////////////////////////////
1253 // A weak link from an input stream to an output stream
1255 class wxZipStreamLink
1258 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1260 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1261 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1263 void Release(class wxZipInputStream
*WXUNUSED(s
))
1264 { if (--m_ref
== 0) delete this; }
1265 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1266 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1269 ~wxZipStreamLink() { }
1272 wxZipOutputStream
*m_stream
;
1274 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipStreamLink
)
1278 /////////////////////////////////////////////////////////////////////////////
1281 // leave the default wxZipEntryPtr free for users
1282 wxDECLARE_SCOPED_PTR(wxZipEntry
, wx__ZipEntryPtr
)
1283 wxDEFINE_SCOPED_PTR (wxZipEntry
, wx__ZipEntryPtr
)
1287 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1288 wxMBConv
& conv
/*=wxConvLocal*/)
1289 : wxArchiveInputStream(stream
, conv
)
1294 #if 1 //WXWIN_COMPATIBILITY_2_6
1296 // Part of the compatibility constructor, which has been made inline to
1297 // avoid a problem with it not being exported by mingw 3.2.3
1299 void wxZipInputStream::Init(const wxString
& file
)
1301 // no error messages
1304 m_allowSeeking
= true;
1305 m_ffile
= wx_static_cast(wxFFileInputStream
*, m_parent_i_stream
);
1306 wx__ZipEntryPtr entry
;
1308 if (m_ffile
->Ok()) {
1310 entry
.reset(GetNextEntry());
1312 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1315 if (entry
.get() == NULL
)
1316 m_lasterror
= wxSTREAM_READ_ERROR
;
1319 wxInputStream
& wxZipInputStream::OpenFile(const wxString
& archive
)
1322 return *new wxFFileInputStream(archive
);
1325 #endif // WXWIN_COMPATIBILITY_2_6
1327 void wxZipInputStream::Init()
1329 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1335 m_parentSeekable
= false;
1336 m_weaklinks
= new wxZipWeakLinks
;
1337 m_streamlink
= NULL
;
1338 m_offsetAdjustment
= 0;
1339 m_position
= wxInvalidOffset
;
1342 m_lasterror
= m_parent_i_stream
->GetLastError();
1344 #if 1 //WXWIN_COMPATIBILITY_2_6
1345 m_allowSeeking
= false;
1349 wxZipInputStream::~wxZipInputStream()
1351 CloseDecompressor(m_decomp
);
1358 m_weaklinks
->Release(this);
1361 m_streamlink
->Release(this);
1364 wxString
wxZipInputStream::GetComment()
1366 if (m_position
== wxInvalidOffset
)
1367 if (!LoadEndRecord())
1368 return wxEmptyString
;
1370 if (!m_parentSeekable
&& Eof() && m_signature
) {
1371 m_lasterror
= wxSTREAM_NO_ERROR
;
1372 m_lasterror
= ReadLocal(true);
1378 int wxZipInputStream::GetTotalEntries()
1380 if (m_position
== wxInvalidOffset
)
1382 return m_TotalEntries
;
1385 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1387 wxZipStreamLink
*link
= NULL
;
1389 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1390 link
= new wxZipStreamLink(out
);
1392 m_streamlink
->Release(this);
1393 m_streamlink
= link
->AddRef();
1399 bool wxZipInputStream::LoadEndRecord()
1401 wxCHECK(m_position
== wxInvalidOffset
, false);
1407 // First find the end-of-central-directory record.
1408 if (!FindEndRecord()) {
1409 // failed, so either this is a non-seekable stream (ok), or not a zip
1410 if (m_parentSeekable
) {
1411 m_lasterror
= wxSTREAM_READ_ERROR
;
1412 wxLogError(_("invalid zip file"));
1417 wxFileOffset pos
= m_parent_i_stream
->TellI();
1418 if (pos
!= wxInvalidOffset
)
1419 m_offsetAdjustment
= m_position
= pos
;
1426 // Read in the end record
1427 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1428 if (!endrec
.Read(*m_parent_i_stream
, GetConv()))
1431 m_TotalEntries
= endrec
.GetTotalEntries();
1432 m_Comment
= endrec
.GetComment();
1434 // Now find the central-directory. we have the file offset of
1435 // the CD, so look there first.
1436 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1437 ReadSignature() == CENTRAL_MAGIC
) {
1438 m_signature
= CENTRAL_MAGIC
;
1439 m_position
= endrec
.GetOffset();
1440 m_offsetAdjustment
= 0;
1444 // If it's not there, then it could be that the zip has been appended
1445 // to a self extractor, so take the CD size (also in endrec), subtract
1446 // it from the file offset of the end-central-directory and look there.
1447 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1448 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1449 m_signature
= CENTRAL_MAGIC
;
1450 m_position
= endPos
- endrec
.GetSize();
1451 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1455 wxLogError(_("can't find central directory in zip"));
1456 m_lasterror
= wxSTREAM_READ_ERROR
;
1460 // Find the end-of-central-directory record.
1461 // If found the stream will be positioned just past the 4 signature bytes.
1463 bool wxZipInputStream::FindEndRecord()
1465 if (!m_parent_i_stream
->IsSeekable())
1468 // usually it's 22 bytes in size and the last thing in the file
1471 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1475 m_parentSeekable
= true;
1478 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1480 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1483 // unfortunately, the record has a comment field that can be up to 65535
1484 // bytes in length, so if the signature not found then search backwards.
1485 wxFileOffset pos
= m_parent_i_stream
->TellI();
1486 const int BUFSIZE
= 1024;
1487 wxCharBuffer
buf(BUFSIZE
);
1489 memcpy(buf
.data(), magic
, 3);
1490 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1492 while (pos
> minpos
) {
1493 size_t len
= wx_truncate_cast(size_t,
1494 pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1495 memcpy(buf
.data() + len
, buf
, 3);
1498 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1499 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1502 char *p
= buf
.data() + len
;
1504 while (p
-- > buf
.data()) {
1505 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1506 size_t remainder
= buf
.data() + len
- p
;
1508 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1517 wxZipEntry
*wxZipInputStream::GetNextEntry()
1519 if (m_position
== wxInvalidOffset
)
1520 if (!LoadEndRecord())
1523 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1527 wx__ZipEntryPtr
entry(new wxZipEntry(m_entry
));
1528 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1529 return entry
.release();
1532 wxStreamError
wxZipInputStream::ReadCentral()
1537 if (m_signature
== END_MAGIC
)
1538 return wxSTREAM_EOF
;
1540 if (m_signature
!= CENTRAL_MAGIC
) {
1541 wxLogError(_("error reading zip central directory"));
1542 return wxSTREAM_READ_ERROR
;
1545 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1546 return wxSTREAM_READ_ERROR
;
1548 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1551 return wxSTREAM_READ_ERROR
;
1555 m_signature
= ReadSignature();
1557 if (m_offsetAdjustment
)
1558 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1559 m_entry
.SetKey(m_entry
.GetOffset());
1561 return wxSTREAM_NO_ERROR
;
1564 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1570 m_signature
= ReadSignature();
1572 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1573 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1574 m_streamlink
->Release(this);
1575 m_streamlink
= NULL
;
1579 while (m_signature
== CENTRAL_MAGIC
) {
1580 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1581 return wxSTREAM_EOF
;
1583 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1587 return wxSTREAM_READ_ERROR
;
1589 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1591 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1592 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1593 entry
->SetComment(m_entry
.GetComment());
1594 entry
->SetDiskStart(m_entry
.GetDiskStart());
1595 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1596 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1597 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1599 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1602 m_signature
= ReadSignature();
1605 if (m_signature
== END_MAGIC
) {
1606 if (readEndRec
|| m_streamlink
) {
1608 endrec
.Read(*m_parent_i_stream
, GetConv());
1609 m_Comment
= endrec
.GetComment();
1612 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1613 m_streamlink
->Release(this);
1614 m_streamlink
= NULL
;
1617 return wxSTREAM_EOF
;
1620 if (m_signature
== LOCAL_MAGIC
) {
1621 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1623 m_entry
.SetOffset(m_position
);
1624 m_entry
.SetKey(m_position
);
1628 return wxSTREAM_NO_ERROR
;
1632 wxLogError(_("error reading zip local header"));
1633 return wxSTREAM_READ_ERROR
;
1636 wxUint32
wxZipInputStream::ReadSignature()
1639 m_parent_i_stream
->Read(magic
, 4);
1640 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1643 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1645 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1646 return zipEntry
? OpenEntry(*zipEntry
) : false;
1651 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1653 if (m_position
== wxInvalidOffset
)
1654 if (!LoadEndRecord())
1656 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1664 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1666 // can only open the current entry on a non-seekable stream
1667 wxCHECK(m_parentSeekable
, false);
1670 m_lasterror
= wxSTREAM_READ_ERROR
;
1675 if (m_parentSeekable
) {
1676 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1679 if (ReadSignature() != LOCAL_MAGIC
) {
1680 wxLogError(_("bad zipfile offset to entry"));
1685 if (m_parentSeekable
|| AtHeader()) {
1686 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1687 if (m_headerSize
&& m_parentSeekable
) {
1688 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1690 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1692 m_weaklinks
->RemoveEntry(ref
->GetKey());
1694 if (entry
&& entry
!= ref
) {
1695 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1702 m_lasterror
= wxSTREAM_NO_ERROR
;
1706 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1708 wxASSERT(AfterHeader());
1710 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1716 if (compressedSize
!= wxInvalidOffset
) {
1717 m_store
->Open(compressedSize
);
1721 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1722 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1725 if (compressedSize
!= wxInvalidOffset
&&
1726 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1727 wxZlibInputStream::CanHandleGZip())) {
1728 m_store
->Open(compressedSize
);
1729 m_decomp
= OpenDecompressor(*m_store
);
1731 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1735 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1736 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1740 // Can be overriden to add support for additional decompression methods
1742 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1744 switch (m_entry
.GetMethod()) {
1745 case wxZIP_METHOD_STORE
:
1746 if (m_entry
.GetSize() == wxInvalidOffset
) {
1747 wxLogError(_("stored file length not in Zip header"));
1750 m_store
->Open(m_entry
.GetSize());
1753 case wxZIP_METHOD_DEFLATE
:
1755 m_inflate
= new wxZlibInputStream2(stream
);
1757 m_inflate
->Open(stream
);
1761 wxLogError(_("unsupported Zip compression method"));
1767 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1769 if (decomp
&& decomp
== m_rawin
)
1770 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1771 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1776 // Closes the current entry and positions the underlying stream at the start
1777 // of the next entry
1779 bool wxZipInputStream::CloseEntry()
1783 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1786 if (!m_parentSeekable
) {
1787 if (!IsOpened() && !OpenDecompressor(true))
1790 const int BUFSIZE
= 8192;
1791 wxCharBuffer
buf(BUFSIZE
);
1793 Read(buf
.data(), BUFSIZE
);
1795 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1798 if (m_lasterror
== wxSTREAM_EOF
)
1799 m_lasterror
= wxSTREAM_NO_ERROR
;
1801 CloseDecompressor(m_decomp
);
1803 m_entry
= wxZipEntry();
1810 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1813 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1814 m_lasterror
= wxSTREAM_READ_ERROR
;
1815 if (!IsOk() || !size
)
1818 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1820 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1822 m_lasterror
= m_decomp
->GetLastError();
1825 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1826 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1827 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1830 entry
->SetCrc(m_entry
.GetCrc());
1831 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1832 entry
->SetSize(m_entry
.GetSize());
1838 m_lasterror
= wxSTREAM_READ_ERROR
;
1840 if (m_entry
.GetSize() != TellI())
1841 wxLogError(_("reading zip stream (entry %s): bad length"),
1842 m_entry
.GetName().c_str());
1843 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1844 wxLogError(_("reading zip stream (entry %s): bad crc"),
1845 m_entry
.GetName().c_str());
1847 m_lasterror
= wxSTREAM_EOF
;
1854 #if 1 //WXWIN_COMPATIBILITY_2_6
1856 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1858 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1860 // seeking works when the stream is created with the compatibility
1862 if (!m_allowSeeking
)
1863 return wxInvalidOffset
;
1865 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1866 m_lasterror
= wxSTREAM_READ_ERROR
;
1868 return wxInvalidOffset
;
1870 // NB: since ZIP files don't natively support seeking, we have to
1871 // implement a brute force workaround -- reading all the data
1872 // between current and the new position (or between beginning of
1873 // the file and new position...)
1875 wxFileOffset nextpos
;
1876 wxFileOffset pos
= TellI();
1880 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1881 case wxFromStart
: nextpos
= seek
; break;
1882 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1883 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1886 wxFileOffset toskip
wxDUMMY_INITIALIZE(0);
1887 if ( nextpos
>= pos
)
1889 toskip
= nextpos
- pos
;
1893 wxZipEntry
current(m_entry
);
1894 if (!OpenEntry(current
))
1896 m_lasterror
= wxSTREAM_READ_ERROR
;
1904 const int BUFSIZE
= 4096;
1906 char buffer
[BUFSIZE
];
1907 while ( toskip
> 0 )
1909 sz
= wx_truncate_cast(size_t, wxMin(toskip
, BUFSIZE
));
1919 #endif // WXWIN_COMPATIBILITY_2_6
1922 /////////////////////////////////////////////////////////////////////////////
1925 #include "wx/listimpl.cpp"
1926 WX_DEFINE_LIST(wx__ZipEntryList
)
1928 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1930 wxMBConv
& conv
/*=wxConvLocal*/)
1931 : wxArchiveOutputStream(stream
, conv
),
1932 m_store(new wxStoredOutputStream(stream
)),
1935 m_initialData(new char[OUTPUT_LATENCY
]),
1944 m_offsetAdjustment(wxInvalidOffset
)
1948 wxZipOutputStream::~wxZipOutputStream()
1951 WX_CLEAR_LIST(wx__ZipEntryList
, m_entries
);
1955 delete [] m_initialData
;
1957 m_backlink
->Release(this);
1960 bool wxZipOutputStream::PutNextEntry(
1961 const wxString
& name
,
1962 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1963 wxFileOffset size
/*=wxInvalidOffset*/)
1965 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1968 bool wxZipOutputStream::PutNextDirEntry(
1969 const wxString
& name
,
1970 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1972 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1974 return PutNextEntry(entry
);
1977 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1978 wxZipInputStream
& inputStream
)
1980 wx__ZipEntryPtr
e(entry
);
1983 inputStream
.DoOpen(e
.get(), true) &&
1984 DoCreate(e
.release(), true) &&
1985 Write(inputStream
).IsOk() && inputStream
.Eof();
1988 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1990 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1993 return PutNextEntry(zipEntry
);
1996 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1997 wxArchiveInputStream
& stream
)
1999 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2001 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
2006 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
2009 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
2011 m_Comment
= inputStream
.GetComment();
2013 m_backlink
->Release(this);
2014 m_backlink
= inputStream
.MakeLink(this);
2018 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
2020 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
2023 void wxZipOutputStream::SetLevel(int level
)
2025 if (level
!= m_level
) {
2026 if (m_comp
!= m_deflate
)
2033 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
2041 // write the signature bytes right away
2042 wxDataOutputStream
ds(*m_parent_o_stream
);
2045 // and if this is the first entry test for seekability
2046 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
2048 bool logging
= wxLog::IsEnabled();
2051 wxFileOffset here
= m_parent_o_stream
->TellO();
2053 if (here
!= wxInvalidOffset
&& here
>= 4) {
2054 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
2055 m_offsetAdjustment
= here
- 4;
2057 wxLog::EnableLogging(logging
);
2059 m_parent_o_stream
->SeekO(here
);
2064 m_pending
->SetOffset(m_headerOffset
);
2066 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
2071 m_lasterror
= wxSTREAM_NO_ERROR
;
2075 // Can be overriden to add support for additional compression methods
2077 wxOutputStream
*wxZipOutputStream::OpenCompressor(
2078 wxOutputStream
& stream
,
2080 const Buffer bufs
[])
2082 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
2084 && (IsParentSeekable()
2085 || entry
.GetCompressedSize() != wxInvalidOffset
2086 || entry
.GetSize() != wxInvalidOffset
)) {
2087 entry
.SetMethod(wxZIP_METHOD_STORE
);
2090 for (int i
= 0; bufs
[i
].m_data
; ++i
)
2091 size
+= bufs
[i
].m_size
;
2092 entry
.SetMethod(size
<= 6 ?
2093 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
2097 switch (entry
.GetMethod()) {
2098 case wxZIP_METHOD_STORE
:
2099 if (entry
.GetCompressedSize() == wxInvalidOffset
)
2100 entry
.SetCompressedSize(entry
.GetSize());
2103 case wxZIP_METHOD_DEFLATE
:
2105 int defbits
= wxZIP_DEFLATE_NORMAL
;
2106 switch (GetLevel()) {
2108 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2110 case 2: case 3: case 4:
2111 defbits
= wxZIP_DEFLATE_FAST
;
2114 defbits
= wxZIP_DEFLATE_EXTRA
;
2117 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2118 defbits
| wxZIP_SUMS_FOLLOW
);
2121 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2123 m_deflate
->Open(stream
);
2129 wxLogError(_("unsupported Zip compression method"));
2135 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2137 if (comp
== m_deflate
)
2139 else if (comp
!= m_store
)
2144 // This is called when OUPUT_LATENCY bytes has been written to the
2145 // wxZipOutputStream to actually create the zip entry.
2147 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2149 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2150 wx__ZipEntryPtr
spPending(m_pending
);
2154 { m_initialData
, m_initialSize
},
2155 { (const char*)buffer
, size
},
2162 m_comp
= OpenCompressor(*m_store
, *spPending
,
2163 m_initialSize
? bufs
: bufs
+ 1);
2165 if (IsParentSeekable()
2166 || (spPending
->m_Crc
2167 && spPending
->m_CompressedSize
!= wxInvalidOffset
2168 && spPending
->m_Size
!= wxInvalidOffset
))
2169 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2171 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2172 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2174 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2175 m_lasterror
= m_parent_o_stream
->GetLastError();
2178 m_entries
.push_back(spPending
.release());
2179 OnSysWrite(m_initialData
, m_initialSize
);
2185 // This is called to write out the zip entry when Close has been called
2186 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2188 void wxZipOutputStream::CreatePendingEntry()
2190 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2191 wx__ZipEntryPtr
spPending(m_pending
);
2193 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2196 // Initially compresses the data to memory, then fall back to 'store'
2197 // if the compressor makes the data larger rather than smaller.
2198 wxMemoryOutputStream mem
;
2199 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2200 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2204 if (comp
!= m_store
) {
2205 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2206 CloseCompressor(comp
);
2211 m_entrySize
= m_initialSize
;
2212 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2214 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2215 m_initialSize
= mem
.GetSize();
2216 mem
.CopyTo(m_initialData
, m_initialSize
);
2218 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2221 spPending
->SetSize(m_entrySize
);
2222 spPending
->SetCrc(m_crcAccumulator
);
2223 spPending
->SetCompressedSize(m_initialSize
);
2226 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2227 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2229 if (m_parent_o_stream
->IsOk()) {
2230 m_entries
.push_back(spPending
.release());
2232 m_store
->Write(m_initialData
, m_initialSize
);
2236 m_lasterror
= m_parent_o_stream
->GetLastError();
2239 // Write the 'central directory' and the 'end-central-directory' records.
2241 bool wxZipOutputStream::Close()
2245 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2250 endrec
.SetEntriesHere(m_entries
.size());
2251 endrec
.SetTotalEntries(m_entries
.size());
2252 endrec
.SetOffset(m_headerOffset
);
2253 endrec
.SetComment(m_Comment
);
2255 wx__ZipEntryList::iterator it
;
2256 wxFileOffset size
= 0;
2258 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2259 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2264 endrec
.SetSize(size
);
2265 endrec
.Write(*m_parent_o_stream
, GetConv());
2267 m_lasterror
= m_parent_o_stream
->GetLastError();
2270 m_lasterror
= wxSTREAM_EOF
;
2274 // Finish writing the current entry
2276 bool wxZipOutputStream::CloseEntry()
2278 if (IsOk() && m_pending
)
2279 CreatePendingEntry();
2285 CloseCompressor(m_comp
);
2288 wxFileOffset compressedSize
= m_store
->TellO();
2290 wxZipEntry
& entry
= *m_entries
.back();
2292 // When writing raw the crc and size can't be checked
2294 m_crcAccumulator
= entry
.GetCrc();
2295 m_entrySize
= entry
.GetSize();
2298 // Write the sums in the trailing 'data descriptor' if necessary
2299 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2300 wxASSERT(!IsParentSeekable());
2302 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2303 compressedSize
, m_entrySize
);
2304 m_lasterror
= m_parent_o_stream
->GetLastError();
2307 // If the local header didn't have the correct crc and size written to
2308 // it then seek back and fix it
2309 else if (m_crcAccumulator
!= entry
.GetCrc()
2310 || m_entrySize
!= entry
.GetSize()
2311 || compressedSize
!= entry
.GetCompressedSize())
2313 if (IsParentSeekable()) {
2314 wxFileOffset here
= m_parent_o_stream
->TellO();
2315 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2316 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2317 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2318 compressedSize
, m_entrySize
);
2319 m_parent_o_stream
->SeekO(here
);
2320 m_lasterror
= m_parent_o_stream
->GetLastError();
2322 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2326 m_headerOffset
+= m_headerSize
+ compressedSize
;
2333 m_lasterror
= m_parent_o_stream
->GetLastError();
2335 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2336 entry
.GetName().c_str());
2340 void wxZipOutputStream::Sync()
2342 if (IsOk() && m_pending
)
2343 CreatePendingEntry(NULL
, 0);
2345 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2348 m_lasterror
= m_comp
->GetLastError();
2352 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2354 if (IsOk() && m_pending
) {
2355 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2356 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2357 m_initialSize
+= size
;
2360 CreatePendingEntry(buffer
, size
);
2365 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2366 if (!IsOk() || !size
)
2369 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2370 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2371 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2372 m_entrySize
+= m_comp
->LastWrite();
2374 return m_comp
->LastWrite();
2377 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM