1 /////////////////////////////////////////////////////////////////////////////
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"
21 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
23 #include "wx/zipstrm.h"
26 #include "wx/datstrm.h"
27 #include "wx/zstream.h"
28 #include "wx/mstream.h"
30 #include "wx/buffer.h"
31 #include "wx/ptr_scpd.h"
32 #include "wx/wfstream.h"
36 // value for the 'version needed to extract' field (20 means 2.0)
38 VERSION_NEEDED_TO_EXTRACT
= 20
41 // signatures for the various records (PKxx)
43 CENTRAL_MAGIC
= 0x02014b50, // central directory record
44 LOCAL_MAGIC
= 0x04034b50, // local header
45 END_MAGIC
= 0x06054b50, // end of central directory record
46 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
49 // unix file attributes. zip stores them in the high 16 bits of the
50 // 'external attributes' field, hence the extra zeros.
52 wxZIP_S_IFMT
= 0xF0000000,
53 wxZIP_S_IFDIR
= 0x40000000,
54 wxZIP_S_IFREG
= 0x80000000
57 // minimum sizes for the various records
65 // The number of bytes that must be written to an wxZipOutputStream before
66 // a zip entry is created. The purpose of this latency is so that
67 // OpenCompressor() can see a little data before deciding which compressor
73 // Some offsets into the local header
78 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
79 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
81 wxFORCE_LINK_THIS_MODULE(zipstrm
)
84 /////////////////////////////////////////////////////////////////////////////
87 // read a string of a given length
89 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
92 wxCharBuffer
buf(len
);
93 stream
.Read(buf
.data(), len
);
94 wxString
str(buf
, conv
);
99 wxStringBuffer
buf(str
, len
);
100 stream
.Read(buf
, len
);
107 // Decode a little endian wxUint32 number from a character array
109 static inline wxUint32
CrackUint32(const char *m
)
111 const unsigned char *n
= (const unsigned char*)m
;
112 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
115 // Temporarily lower the logging level in debug mode to avoid a warning
116 // from SeekI about seeking on a stream with data written back to it.
118 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
121 wxLogLevel level
= wxLog::GetLogLevel();
122 wxLog::SetLogLevel(wxLOG_Debug
- 1);
123 wxFileOffset result
= stream
.SeekI(pos
);
124 wxLog::SetLogLevel(level
);
127 return stream
.SeekI(pos
);
132 /////////////////////////////////////////////////////////////////////////////
133 // Stored input stream
134 // Trival decompressor for files which are 'stored' in the zip file.
136 class wxStoredInputStream
: public wxFilterInputStream
139 wxStoredInputStream(wxInputStream
& stream
);
141 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
142 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
144 virtual char Peek() { return wxInputStream::Peek(); }
145 virtual wxFileOffset
GetLength() const { return m_len
; }
148 virtual size_t OnSysRead(void *buffer
, size_t size
);
149 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
155 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
158 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
159 : wxFilterInputStream(stream
),
165 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
167 size_t count
= wx_truncate_cast(size_t,
168 wxMin(size
+ wxFileOffset(0), m_len
- m_pos
+ size_t(0)));
169 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
172 if (m_pos
== m_len
&& count
< size
)
173 m_lasterror
= wxSTREAM_EOF
;
174 else if (!*m_parent_i_stream
)
175 m_lasterror
= wxSTREAM_READ_ERROR
;
181 /////////////////////////////////////////////////////////////////////////////
182 // Stored output stream
183 // Trival compressor for files which are 'stored' in the zip file.
185 class wxStoredOutputStream
: public wxFilterOutputStream
188 wxStoredOutputStream(wxOutputStream
& stream
) :
189 wxFilterOutputStream(stream
), m_pos(0) { }
193 m_lasterror
= wxSTREAM_NO_ERROR
;
198 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
199 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
203 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
206 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
208 if (!IsOk() || !size
)
210 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
212 m_lasterror
= wxSTREAM_WRITE_ERROR
;
218 /////////////////////////////////////////////////////////////////////////////
221 // Used to handle the unusal case of raw copying an entry of unknown
222 // length. This can only happen when the zip being copied from is being
223 // read from a non-seekable stream, and also was original written to a
224 // non-seekable stream.
226 // In this case there's no option but to decompress the stream to find
227 // it's length, but we can still write the raw compressed data to avoid the
228 // compression overhead (which is the greater one).
230 // Usage is like this:
231 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
232 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
234 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
235 // is something like the unix 'tee' command; it is a transparent filter, but
236 // allows the data read to be read a second time via an extra method 'GetData'.
238 // The wxRawInputStream then draws data through the tee using a decompressor
239 // then instead of returning the decompressed data, retuns the raw data
240 // from wxTeeInputStream::GetData().
242 class wxTeeInputStream
: public wxFilterInputStream
245 wxTeeInputStream(wxInputStream
& stream
);
247 size_t GetCount() const { return m_end
- m_start
; }
248 size_t GetData(char *buffer
, size_t size
);
253 wxInputStream
& Read(void *buffer
, size_t size
);
256 virtual size_t OnSysRead(void *buffer
, size_t size
);
257 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
261 wxMemoryBuffer m_buf
;
265 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
268 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
269 : wxFilterInputStream(stream
),
270 m_pos(0), m_buf(8192), m_start(0), m_end(0)
274 void wxTeeInputStream::Open()
276 m_pos
= m_start
= m_end
= 0;
277 m_lasterror
= wxSTREAM_NO_ERROR
;
280 bool wxTeeInputStream::Final()
282 bool final
= m_end
== m_buf
.GetDataLen();
283 m_end
= m_buf
.GetDataLen();
287 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
289 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
290 m_end
= m_buf
.GetDataLen();
291 m_buf
.AppendData(buffer
, count
);
295 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
297 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
298 m_lasterror
= m_parent_i_stream
->GetLastError();
302 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
305 size_t len
= m_buf
.GetDataLen();
306 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
307 m_buf
.SetDataLen(len
);
309 wxFAIL
; // we've already returned data that's now being ungot
312 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
319 if (size
> GetCount())
322 memcpy(buffer
, m_buf
+ m_start
, size
);
324 wxASSERT(m_start
<= m_end
);
327 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
328 size_t len
= m_buf
.GetDataLen();
329 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
331 memmove(buf
, buf
+ m_end
, len
);
332 m_buf
.UngetWriteBuf(len
);
339 class wxRawInputStream
: public wxFilterInputStream
342 wxRawInputStream(wxInputStream
& stream
);
343 virtual ~wxRawInputStream() { delete m_tee
; }
345 wxInputStream
* Open(wxInputStream
*decomp
);
346 wxInputStream
& GetTee() const { return *m_tee
; }
349 virtual size_t OnSysRead(void *buffer
, size_t size
);
350 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
354 wxTeeInputStream
*m_tee
;
356 enum { BUFSIZE
= 8192 };
357 wxCharBuffer m_dummy
;
359 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
362 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
363 : wxFilterInputStream(stream
),
365 m_tee(new wxTeeInputStream(stream
)),
370 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
373 m_parent_i_stream
= decomp
;
375 m_lasterror
= wxSTREAM_NO_ERROR
;
383 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
385 char *buf
= (char*)buffer
;
388 while (count
< size
&& IsOk())
390 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
391 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
393 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
396 if (n
== 0 && m_tee
->Final())
397 m_lasterror
= m_parent_i_stream
->GetLastError();
405 /////////////////////////////////////////////////////////////////////////////
406 // Zlib streams than can be reused without recreating.
408 class wxZlibOutputStream2
: public wxZlibOutputStream
411 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
412 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
414 bool Open(wxOutputStream
& stream
);
415 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
418 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
420 wxCHECK(m_pos
== wxInvalidOffset
, false);
422 m_deflate
->next_out
= m_z_buffer
;
423 m_deflate
->avail_out
= m_z_size
;
425 m_lasterror
= wxSTREAM_NO_ERROR
;
426 m_parent_o_stream
= &stream
;
428 if (deflateReset(m_deflate
) != Z_OK
) {
429 wxLogError(_("can't re-initialize zlib deflate stream"));
430 m_lasterror
= wxSTREAM_WRITE_ERROR
;
437 class wxZlibInputStream2
: public wxZlibInputStream
440 wxZlibInputStream2(wxInputStream
& stream
) :
441 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
443 bool Open(wxInputStream
& stream
);
446 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
448 m_inflate
->avail_in
= 0;
450 m_lasterror
= wxSTREAM_NO_ERROR
;
451 m_parent_i_stream
= &stream
;
453 if (inflateReset(m_inflate
) != Z_OK
) {
454 wxLogError(_("can't re-initialize zlib inflate stream"));
455 m_lasterror
= wxSTREAM_READ_ERROR
;
463 /////////////////////////////////////////////////////////////////////////////
464 // Class to hold wxZipEntry's Extra and LocalExtra fields
469 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
471 wxZipMemory
*AddRef() { m_ref
++; return this; }
472 void Release() { if (--m_ref
== 0) delete this; }
474 char *GetData() const { return m_data
; }
475 size_t GetSize() const { return m_size
; }
476 size_t GetCapacity() const { return m_capacity
; }
478 wxZipMemory
*Unique(size_t size
);
481 ~wxZipMemory() { delete [] m_data
; }
488 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipMemory
)
491 wxZipMemory
*wxZipMemory::Unique(size_t size
)
497 zm
= new wxZipMemory
;
502 if (zm
->m_capacity
< size
) {
503 delete [] zm
->m_data
;
504 zm
->m_data
= new char[size
];
505 zm
->m_capacity
= size
;
512 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
519 static inline void Release(wxZipMemory
*zm
)
525 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
531 static void Unique(wxZipMemory
*& zm
, size_t size
)
534 zm
= new wxZipMemory
;
536 zm
= zm
->Unique(size
);
540 /////////////////////////////////////////////////////////////////////////////
541 // Collection of weak references to entries
543 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
544 wxIntegerEqual
, wx__OffsetZipEntryMap
);
549 wxZipWeakLinks() : m_ref(1) { }
551 void Release(const wxZipInputStream
* WXUNUSED(x
))
552 { if (--m_ref
== 0) delete this; }
553 void Release(wxFileOffset key
)
554 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
556 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
557 void RemoveEntry(wxFileOffset key
)
558 { m_entries
.erase(wx_truncate_cast(key_type
, key
)); }
559 wxZipEntry
*GetEntry(wxFileOffset key
) const;
560 bool IsEmpty() const { return m_entries
.empty(); }
563 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
565 typedef wx__OffsetZipEntryMap::key_type key_type
;
568 wx__OffsetZipEntryMap m_entries
;
570 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipWeakLinks
)
573 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
575 m_entries
[wx_truncate_cast(key_type
, key
)] = entry
;
580 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
582 wx__OffsetZipEntryMap::const_iterator it
=
583 m_entries
.find(wx_truncate_cast(key_type
, key
));
584 return it
!= m_entries
.end() ? it
->second
: NULL
;
588 /////////////////////////////////////////////////////////////////////////////
591 wxZipEntry::wxZipEntry(
592 const wxString
& name
/*=wxEmptyString*/,
593 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
594 wxFileOffset size
/*=wxInvalidOffset*/)
596 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
597 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
598 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
600 m_Method(wxZIP_METHOD_DEFAULT
),
603 m_CompressedSize(wxInvalidOffset
),
605 m_Key(wxInvalidOffset
),
606 m_Offset(wxInvalidOffset
),
608 m_InternalAttributes(0),
609 m_ExternalAttributes(0),
619 wxZipEntry::~wxZipEntry()
622 m_backlink
->Release(m_Key
);
624 Release(m_LocalExtra
);
627 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
629 m_SystemMadeBy(e
.m_SystemMadeBy
),
630 m_VersionMadeBy(e
.m_VersionMadeBy
),
631 m_VersionNeeded(e
.m_VersionNeeded
),
633 m_Method(e
.m_Method
),
634 m_DateTime(e
.m_DateTime
),
636 m_CompressedSize(e
.m_CompressedSize
),
640 m_Offset(e
.m_Offset
),
641 m_Comment(e
.m_Comment
),
642 m_DiskStart(e
.m_DiskStart
),
643 m_InternalAttributes(e
.m_InternalAttributes
),
644 m_ExternalAttributes(e
.m_ExternalAttributes
),
645 m_Extra(AddRef(e
.m_Extra
)),
646 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
652 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
655 m_SystemMadeBy
= e
.m_SystemMadeBy
;
656 m_VersionMadeBy
= e
.m_VersionMadeBy
;
657 m_VersionNeeded
= e
.m_VersionNeeded
;
659 m_Method
= e
.m_Method
;
660 m_DateTime
= e
.m_DateTime
;
662 m_CompressedSize
= e
.m_CompressedSize
;
666 m_Offset
= e
.m_Offset
;
667 m_Comment
= e
.m_Comment
;
668 m_DiskStart
= e
.m_DiskStart
;
669 m_InternalAttributes
= e
.m_InternalAttributes
;
670 m_ExternalAttributes
= e
.m_ExternalAttributes
;
671 Copy(m_Extra
, e
.m_Extra
);
672 Copy(m_LocalExtra
, e
.m_LocalExtra
);
673 m_zipnotifier
= NULL
;
675 m_backlink
->Release(m_Key
);
682 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
684 bool isDir
= IsDir() && !m_Name
.empty();
686 // optimisations for common (and easy) cases
687 switch (wxFileName::GetFormat(format
)) {
690 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
691 for (size_t i
= name
.length() - 1; i
> 0; --i
)
692 if (name
[i
] == _T('/'))
698 return isDir
? m_Name
+ _T("/") : m_Name
;
707 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
709 fn
.Assign(m_Name
, wxPATH_UNIX
);
711 return fn
.GetFullPath(format
);
714 // Static - Internally tars and zips use forward slashes for the path
715 // separator, absolute paths aren't allowed, and directory names have a
716 // trailing slash. This function converts a path into this internal format,
717 // but without a trailing slash for a directory.
719 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
720 wxPathFormat format
/*=wxPATH_NATIVE*/,
721 bool *pIsDir
/*=NULL*/)
725 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
726 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
730 bool isDir
= !internal
.empty() && internal
.Last() == '/';
734 internal
.erase(internal
.length() - 1);
736 while (!internal
.empty() && *internal
.begin() == '/')
737 internal
.erase(0, 1);
738 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
739 internal
.erase(0, 2);
740 if (internal
== _T(".") || internal
== _T(".."))
741 internal
= wxEmptyString
;
746 void wxZipEntry::SetSystemMadeBy(int system
)
748 int mode
= GetMode();
749 bool wasUnix
= IsMadeByUnix();
751 m_SystemMadeBy
= (wxUint8
)system
;
753 if (!wasUnix
&& IsMadeByUnix()) {
756 } else if (wasUnix
&& !IsMadeByUnix()) {
757 m_ExternalAttributes
&= 0xffff;
761 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
764 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
766 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
768 if (IsMadeByUnix()) {
769 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
771 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
773 m_ExternalAttributes
|= wxZIP_S_IFREG
;
777 // Return unix style permission bits
779 int wxZipEntry::GetMode() const
781 // return unix permissions if present
783 return (m_ExternalAttributes
>> 16) & 0777;
785 // otherwise synthesize from the dos attribs
787 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
789 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
795 // Set unix permissions
797 void wxZipEntry::SetMode(int mode
)
799 // Set dos attrib bits to be compatible
801 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
803 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
805 // set the actual unix permission bits if the system type allows
806 if (IsMadeByUnix()) {
807 m_ExternalAttributes
&= ~(0777L << 16);
808 m_ExternalAttributes
|= (mode
& 0777L) << 16;
812 const char *wxZipEntry::GetExtra() const
814 return m_Extra
? m_Extra
->GetData() : NULL
;
817 size_t wxZipEntry::GetExtraLen() const
819 return m_Extra
? m_Extra
->GetSize() : 0;
822 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
824 Unique(m_Extra
, len
);
826 memcpy(m_Extra
->GetData(), extra
, len
);
829 const char *wxZipEntry::GetLocalExtra() const
831 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
834 size_t wxZipEntry::GetLocalExtraLen() const
836 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
839 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
841 Unique(m_LocalExtra
, len
);
843 memcpy(m_LocalExtra
->GetData(), extra
, len
);
846 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
848 wxArchiveEntry::UnsetNotifier();
849 m_zipnotifier
= ¬ifier
;
850 m_zipnotifier
->OnEntryUpdated(*this);
853 void wxZipEntry::Notify()
856 m_zipnotifier
->OnEntryUpdated(*this);
857 else if (GetNotifier())
858 GetNotifier()->OnEntryUpdated(*this);
861 void wxZipEntry::UnsetNotifier()
863 wxArchiveEntry::UnsetNotifier();
864 m_zipnotifier
= NULL
;
867 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
869 wxUint16 nameLen
, extraLen
;
870 wxUint32 compressedSize
, size
, crc
;
872 wxDataInputStream
ds(stream
);
874 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
875 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
876 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
878 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
880 if (sumsValid
|| crc
)
882 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
883 m_CompressedSize
= compressedSize
;
884 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
887 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
889 if (extraLen
|| GetLocalExtraLen()) {
890 Unique(m_LocalExtra
, extraLen
);
892 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
895 return LOCAL_SIZE
+ nameLen
+ extraLen
;
898 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
900 wxString unixName
= GetName(wxPATH_UNIX
);
901 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
902 const char *name
= name_buf
;
903 if (!name
) name
= "";
904 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
906 wxDataOutputStream
ds(stream
);
908 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
909 ds
.Write32(GetDateTime().GetAsDOS());
912 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
?
913 wx_truncate_cast(wxUint32
, m_CompressedSize
) : 0);
914 ds
.Write32(m_Size
!= wxInvalidOffset
?
915 wx_truncate_cast(wxUint32
, m_Size
) : 0);
918 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetLocalExtraLen());
919 ds
.Write16(extraLen
);
921 stream
.Write(name
, nameLen
);
923 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
925 return LOCAL_SIZE
+ nameLen
+ extraLen
;
928 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
930 wxUint16 nameLen
, extraLen
, commentLen
;
932 wxDataInputStream
ds(stream
);
934 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
936 SetVersionNeeded(ds
.Read16());
937 SetFlags(ds
.Read16());
938 SetMethod(ds
.Read16());
939 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
941 SetCompressedSize(ds
.Read32());
942 SetSize(ds
.Read32());
944 ds
>> nameLen
>> extraLen
>> commentLen
945 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
946 SetOffset(ds
.Read32());
948 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
950 if (extraLen
|| GetExtraLen()) {
951 Unique(m_Extra
, extraLen
);
953 stream
.Read(m_Extra
->GetData(), extraLen
);
957 m_Comment
= ReadString(stream
, commentLen
, conv
);
961 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
964 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
966 wxString unixName
= GetName(wxPATH_UNIX
);
967 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
968 const char *name
= name_buf
;
969 if (!name
) name
= "";
970 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
972 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
973 const char *comment
= comment_buf
;
974 if (!comment
) comment
= "";
975 wxUint16 commentLen
= wx_truncate_cast(wxUint16
, strlen(comment
));
977 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetExtraLen());
979 wxDataOutputStream
ds(stream
);
981 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
983 ds
.Write16(wx_truncate_cast(wxUint16
, GetVersionNeeded()));
984 ds
.Write16(wx_truncate_cast(wxUint16
, GetFlags()));
985 ds
.Write16(wx_truncate_cast(wxUint16
, GetMethod()));
986 ds
.Write32(GetDateTime().GetAsDOS());
987 ds
.Write32(GetCrc());
988 ds
.Write32(wx_truncate_cast(wxUint32
, GetCompressedSize()));
989 ds
.Write32(wx_truncate_cast(wxUint32
, GetSize()));
991 ds
.Write16(extraLen
);
993 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
994 << m_ExternalAttributes
<< wx_truncate_cast(wxUint32
, GetOffset());
996 stream
.Write(name
, nameLen
);
998 stream
.Write(GetExtra(), extraLen
);
999 stream
.Write(comment
, commentLen
);
1001 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1004 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1005 // the 1st value is the signature then it is probably an info-zip record,
1006 // though there is a small chance that it is in fact a pkzip record which
1007 // happens to have the signature as it's CRC.
1009 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1011 wxDataInputStream
ds(stream
);
1013 m_Crc
= ds
.Read32();
1014 m_CompressedSize
= ds
.Read32();
1015 m_Size
= ds
.Read32();
1017 // if 1st value is the signature then this is probably an info-zip record
1018 if (m_Crc
== SUMS_MAGIC
)
1021 stream
.Read(buf
, sizeof(buf
));
1022 wxUint32 u1
= CrackUint32(buf
);
1023 wxUint32 u2
= CrackUint32(buf
+ 4);
1025 // look for the signature of the following record to decide which
1026 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1027 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1029 // it's a pkzip style record after all!
1030 stream
.Ungetch(buf
, sizeof(buf
));
1034 // it's an info-zip record as expected
1035 stream
.Ungetch(buf
+ 4, sizeof(buf
) - 4);
1036 m_Crc
= wx_truncate_cast(wxUint32
, m_CompressedSize
);
1037 m_CompressedSize
= m_Size
;
1039 return SUMS_SIZE
+ 4;
1046 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1047 wxFileOffset compressedSize
, wxFileOffset size
)
1050 m_CompressedSize
= compressedSize
;
1053 wxDataOutputStream
ds(stream
);
1056 ds
.Write32(wx_truncate_cast(wxUint32
, compressedSize
));
1057 ds
.Write32(wx_truncate_cast(wxUint32
, size
));
1063 /////////////////////////////////////////////////////////////////////////////
1064 // wxZipEndRec - holds the end of central directory record
1071 int GetDiskNumber() const { return m_DiskNumber
; }
1072 int GetStartDisk() const { return m_StartDisk
; }
1073 int GetEntriesHere() const { return m_EntriesHere
; }
1074 int GetTotalEntries() const { return m_TotalEntries
; }
1075 wxFileOffset
GetSize() const { return m_Size
; }
1076 wxFileOffset
GetOffset() const { return m_Offset
; }
1077 wxString
GetComment() const { return m_Comment
; }
1079 void SetDiskNumber(int num
)
1080 { m_DiskNumber
= wx_truncate_cast(wxUint16
, num
); }
1081 void SetStartDisk(int num
)
1082 { m_StartDisk
= wx_truncate_cast(wxUint16
, num
); }
1083 void SetEntriesHere(int num
)
1084 { m_EntriesHere
= wx_truncate_cast(wxUint16
, num
); }
1085 void SetTotalEntries(int num
)
1086 { m_TotalEntries
= wx_truncate_cast(wxUint16
, num
); }
1087 void SetSize(wxFileOffset size
)
1088 { m_Size
= wx_truncate_cast(wxUint32
, size
); }
1089 void SetOffset(wxFileOffset offset
)
1090 { m_Offset
= wx_truncate_cast(wxUint32
, offset
); }
1091 void SetComment(const wxString
& comment
)
1092 { m_Comment
= comment
; }
1094 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1095 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1098 wxUint16 m_DiskNumber
;
1099 wxUint16 m_StartDisk
;
1100 wxUint16 m_EntriesHere
;
1101 wxUint16 m_TotalEntries
;
1107 wxZipEndRec::wxZipEndRec()
1117 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1119 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1120 const char *comment
= comment_buf
;
1121 if (!comment
) comment
= "";
1122 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1124 wxDataOutputStream
ds(stream
);
1126 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1127 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1129 stream
.Write(comment
, commentLen
);
1131 return stream
.IsOk();
1134 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1136 wxDataInputStream
ds(stream
);
1137 wxUint16 commentLen
;
1139 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1140 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1143 m_Comment
= ReadString(stream
, commentLen
, conv
);
1146 if (m_DiskNumber
== 0 && m_StartDisk
== 0 &&
1147 m_EntriesHere
== m_TotalEntries
)
1150 wxLogError(_("unsupported zip archive"));
1156 /////////////////////////////////////////////////////////////////////////////
1157 // A weak link from an input stream to an output stream
1159 class wxZipStreamLink
1162 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1164 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1165 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1167 void Release(class wxZipInputStream
*WXUNUSED(s
))
1168 { if (--m_ref
== 0) delete this; }
1169 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1170 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1173 ~wxZipStreamLink() { }
1176 wxZipOutputStream
*m_stream
;
1178 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipStreamLink
)
1182 /////////////////////////////////////////////////////////////////////////////
1185 // leave the default wxZipEntryPtr free for users
1186 wxDECLARE_SCOPED_PTR(wxZipEntry
, wx__ZipEntryPtr
)
1187 wxDEFINE_SCOPED_PTR (wxZipEntry
, wx__ZipEntryPtr
)
1191 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1192 wxMBConv
& conv
/*=wxConvLocal*/)
1193 : wxArchiveInputStream(stream
, conv
)
1198 #if 1 //WXWIN_COMPATIBILITY_2_6
1200 // Part of the compatibility constructor, which has been made inline to
1201 // avoid a problem with it not being exported by mingw 3.2.3
1203 void wxZipInputStream::Init(const wxString
& file
)
1205 // no error messages
1208 m_allowSeeking
= true;
1209 m_ffile
= wx_static_cast(wxFFileInputStream
*, m_parent_i_stream
);
1210 wx__ZipEntryPtr entry
;
1212 if (m_ffile
->Ok()) {
1214 entry
.reset(GetNextEntry());
1216 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1219 if (entry
.get() == NULL
)
1220 m_lasterror
= wxSTREAM_READ_ERROR
;
1223 wxInputStream
& wxZipInputStream::OpenFile(const wxString
& archive
)
1226 return *new wxFFileInputStream(archive
);
1229 #endif // WXWIN_COMPATIBILITY_2_6
1231 void wxZipInputStream::Init()
1233 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1239 m_parentSeekable
= false;
1240 m_weaklinks
= new wxZipWeakLinks
;
1241 m_streamlink
= NULL
;
1242 m_offsetAdjustment
= 0;
1243 m_position
= wxInvalidOffset
;
1246 m_lasterror
= m_parent_i_stream
->GetLastError();
1248 #if 1 //WXWIN_COMPATIBILITY_2_6
1249 m_allowSeeking
= false;
1253 wxZipInputStream::~wxZipInputStream()
1255 CloseDecompressor(m_decomp
);
1262 m_weaklinks
->Release(this);
1265 m_streamlink
->Release(this);
1268 wxString
wxZipInputStream::GetComment()
1270 if (m_position
== wxInvalidOffset
)
1271 if (!LoadEndRecord())
1272 return wxEmptyString
;
1274 if (!m_parentSeekable
&& Eof() && m_signature
) {
1275 m_lasterror
= wxSTREAM_NO_ERROR
;
1276 m_lasterror
= ReadLocal(true);
1282 int wxZipInputStream::GetTotalEntries()
1284 if (m_position
== wxInvalidOffset
)
1286 return m_TotalEntries
;
1289 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1291 wxZipStreamLink
*link
= NULL
;
1293 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1294 link
= new wxZipStreamLink(out
);
1296 m_streamlink
->Release(this);
1297 m_streamlink
= link
->AddRef();
1303 bool wxZipInputStream::LoadEndRecord()
1305 wxCHECK(m_position
== wxInvalidOffset
, false);
1311 // First find the end-of-central-directory record.
1312 if (!FindEndRecord()) {
1313 // failed, so either this is a non-seekable stream (ok), or not a zip
1314 if (m_parentSeekable
) {
1315 m_lasterror
= wxSTREAM_READ_ERROR
;
1316 wxLogError(_("invalid zip file"));
1321 wxFileOffset pos
= m_parent_i_stream
->TellI();
1323 //if (pos != wxInvalidOffset)
1324 if (pos
>= 0 && pos
<= LONG_MAX
)
1325 m_offsetAdjustment
= m_position
= pos
;
1332 // Read in the end record
1333 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1334 if (!endrec
.Read(*m_parent_i_stream
, GetConv())) {
1335 if (!*m_parent_i_stream
) {
1336 m_lasterror
= wxSTREAM_READ_ERROR
;
1339 // TODO: try this out
1340 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1343 m_TotalEntries
= endrec
.GetTotalEntries();
1344 m_Comment
= endrec
.GetComment();
1346 // Now find the central-directory. we have the file offset of
1347 // the CD, so look there first.
1348 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1349 ReadSignature() == CENTRAL_MAGIC
) {
1350 m_signature
= CENTRAL_MAGIC
;
1351 m_position
= endrec
.GetOffset();
1352 m_offsetAdjustment
= 0;
1356 // If it's not there, then it could be that the zip has been appended
1357 // to a self extractor, so take the CD size (also in endrec), subtract
1358 // it from the file offset of the end-central-directory and look there.
1359 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1360 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1361 m_signature
= CENTRAL_MAGIC
;
1362 m_position
= endPos
- endrec
.GetSize();
1363 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1367 wxLogError(_("can't find central directory in zip"));
1368 m_lasterror
= wxSTREAM_READ_ERROR
;
1372 // Find the end-of-central-directory record.
1373 // If found the stream will be positioned just past the 4 signature bytes.
1375 bool wxZipInputStream::FindEndRecord()
1377 if (!m_parent_i_stream
->IsSeekable())
1380 // usually it's 22 bytes in size and the last thing in the file
1383 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1387 m_parentSeekable
= true;
1390 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1392 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1395 // unfortunately, the record has a comment field that can be up to 65535
1396 // bytes in length, so if the signature not found then search backwards.
1397 wxFileOffset pos
= m_parent_i_stream
->TellI();
1398 const int BUFSIZE
= 1024;
1399 wxCharBuffer
buf(BUFSIZE
);
1401 memcpy(buf
.data(), magic
, 3);
1402 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1404 while (pos
> minpos
) {
1405 size_t len
= wx_truncate_cast(size_t,
1406 pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1407 memcpy(buf
.data() + len
, buf
, 3);
1410 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1411 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1414 char *p
= buf
.data() + len
;
1416 while (p
-- > buf
.data()) {
1417 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1418 size_t remainder
= buf
.data() + len
- p
;
1420 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1429 wxZipEntry
*wxZipInputStream::GetNextEntry()
1431 if (m_position
== wxInvalidOffset
)
1432 if (!LoadEndRecord())
1435 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1439 wx__ZipEntryPtr
entry(new wxZipEntry(m_entry
));
1440 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1441 return entry
.release();
1444 wxStreamError
wxZipInputStream::ReadCentral()
1449 if (m_signature
== END_MAGIC
)
1450 return wxSTREAM_EOF
;
1452 if (m_signature
!= CENTRAL_MAGIC
) {
1453 wxLogError(_("error reading zip central directory"));
1454 return wxSTREAM_READ_ERROR
;
1457 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1458 return wxSTREAM_READ_ERROR
;
1460 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1461 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1463 return wxSTREAM_READ_ERROR
;
1466 m_signature
= ReadSignature();
1468 if (m_offsetAdjustment
)
1469 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1470 m_entry
.SetKey(m_entry
.GetOffset());
1472 return wxSTREAM_NO_ERROR
;
1475 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1481 m_signature
= ReadSignature();
1483 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1484 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1485 m_streamlink
->Release(this);
1486 m_streamlink
= NULL
;
1490 while (m_signature
== CENTRAL_MAGIC
) {
1491 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1492 return wxSTREAM_EOF
;
1494 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1496 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
)
1497 return wxSTREAM_READ_ERROR
;
1499 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1501 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1502 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1503 entry
->SetComment(m_entry
.GetComment());
1504 entry
->SetDiskStart(m_entry
.GetDiskStart());
1505 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1506 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1507 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1509 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1512 m_signature
= ReadSignature();
1515 if (m_signature
== END_MAGIC
) {
1516 if (readEndRec
|| m_streamlink
) {
1518 endrec
.Read(*m_parent_i_stream
, GetConv());
1519 m_Comment
= endrec
.GetComment();
1522 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1523 m_streamlink
->Release(this);
1524 m_streamlink
= NULL
;
1527 return wxSTREAM_EOF
;
1530 if (m_signature
!= LOCAL_MAGIC
) {
1531 wxLogError(_("error reading zip local header"));
1532 return wxSTREAM_READ_ERROR
;
1535 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1537 m_entry
.SetOffset(m_position
);
1538 m_entry
.SetKey(m_position
);
1540 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1541 return wxSTREAM_READ_ERROR
;
1544 return wxSTREAM_NO_ERROR
;
1548 wxUint32
wxZipInputStream::ReadSignature()
1551 m_parent_i_stream
->Read(magic
, 4);
1552 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1555 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1557 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1558 return zipEntry
? OpenEntry(*zipEntry
) : false;
1563 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1565 if (m_position
== wxInvalidOffset
)
1566 if (!LoadEndRecord())
1568 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1576 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1578 // can only open the current entry on a non-seekable stream
1579 wxCHECK(m_parentSeekable
, false);
1582 m_lasterror
= wxSTREAM_READ_ERROR
;
1587 if (m_parentSeekable
) {
1588 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1591 if (ReadSignature() != LOCAL_MAGIC
) {
1592 wxLogError(_("bad zipfile offset to entry"));
1597 if (m_parentSeekable
|| AtHeader()) {
1598 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1599 if (m_parentSeekable
) {
1600 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1602 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1604 m_weaklinks
->RemoveEntry(ref
->GetKey());
1606 if (entry
&& entry
!= ref
) {
1607 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1613 m_lasterror
= m_parent_i_stream
->GetLastError();
1617 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1619 wxASSERT(AfterHeader());
1621 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1627 if (compressedSize
!= wxInvalidOffset
) {
1628 m_store
->Open(compressedSize
);
1632 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1633 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1636 if (compressedSize
!= wxInvalidOffset
&&
1637 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1638 wxZlibInputStream::CanHandleGZip())) {
1639 m_store
->Open(compressedSize
);
1640 m_decomp
= OpenDecompressor(*m_store
);
1642 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1646 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1647 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1651 // Can be overriden to add support for additional decompression methods
1653 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1655 switch (m_entry
.GetMethod()) {
1656 case wxZIP_METHOD_STORE
:
1657 if (m_entry
.GetSize() == wxInvalidOffset
) {
1658 wxLogError(_("stored file length not in Zip header"));
1661 m_store
->Open(m_entry
.GetSize());
1664 case wxZIP_METHOD_DEFLATE
:
1666 m_inflate
= new wxZlibInputStream2(stream
);
1668 m_inflate
->Open(stream
);
1672 wxLogError(_("unsupported Zip compression method"));
1678 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1680 if (decomp
&& decomp
== m_rawin
)
1681 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1682 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1687 // Closes the current entry and positions the underlying stream at the start
1688 // of the next entry
1690 bool wxZipInputStream::CloseEntry()
1694 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1697 if (!m_parentSeekable
) {
1698 if (!IsOpened() && !OpenDecompressor(true))
1701 const int BUFSIZE
= 8192;
1702 wxCharBuffer
buf(BUFSIZE
);
1704 Read(buf
.data(), BUFSIZE
);
1706 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1709 if (m_lasterror
== wxSTREAM_EOF
)
1710 m_lasterror
= wxSTREAM_NO_ERROR
;
1712 CloseDecompressor(m_decomp
);
1714 m_entry
= wxZipEntry();
1721 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1724 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1725 m_lasterror
= wxSTREAM_READ_ERROR
;
1726 if (!IsOk() || !size
)
1729 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1731 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1732 m_lasterror
= m_decomp
->GetLastError();
1735 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1736 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1737 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1740 entry
->SetCrc(m_entry
.GetCrc());
1741 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1742 entry
->SetSize(m_entry
.GetSize());
1748 m_lasterror
= wxSTREAM_READ_ERROR
;
1750 if (m_parent_i_stream
->IsOk()) {
1751 if (m_entry
.GetSize() != TellI())
1752 wxLogError(_("reading zip stream (entry %s): bad length"),
1753 m_entry
.GetName().c_str());
1754 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1755 wxLogError(_("reading zip stream (entry %s): bad crc"),
1756 m_entry
.GetName().c_str());
1758 m_lasterror
= wxSTREAM_EOF
;
1766 #if 1 //WXWIN_COMPATIBILITY_2_6
1768 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1770 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1772 // seeking works when the stream is created with the compatibility
1774 if (!m_allowSeeking
)
1775 return wxInvalidOffset
;
1777 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1778 m_lasterror
= wxSTREAM_READ_ERROR
;
1780 return wxInvalidOffset
;
1782 // NB: since ZIP files don't natively support seeking, we have to
1783 // implement a brute force workaround -- reading all the data
1784 // between current and the new position (or between beginning of
1785 // the file and new position...)
1787 wxFileOffset nextpos
;
1788 wxFileOffset pos
= TellI();
1792 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1793 case wxFromStart
: nextpos
= seek
; break;
1794 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1795 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1798 wxFileOffset toskip
wxDUMMY_INITIALIZE(0);
1799 if ( nextpos
>= pos
)
1801 toskip
= nextpos
- pos
;
1805 wxZipEntry
current(m_entry
);
1806 if (!OpenEntry(current
))
1808 m_lasterror
= wxSTREAM_READ_ERROR
;
1816 const int BUFSIZE
= 4096;
1818 char buffer
[BUFSIZE
];
1819 while ( toskip
> 0 )
1821 sz
= wx_truncate_cast(size_t, wxMin(toskip
, BUFSIZE
));
1831 #endif // WXWIN_COMPATIBILITY_2_6
1834 /////////////////////////////////////////////////////////////////////////////
1837 #include "wx/listimpl.cpp"
1838 WX_DEFINE_LIST(wx__ZipEntryList
)
1840 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1842 wxMBConv
& conv
/*=wxConvLocal*/)
1843 : wxArchiveOutputStream(stream
, conv
),
1844 m_store(new wxStoredOutputStream(stream
)),
1847 m_initialData(new char[OUTPUT_LATENCY
]),
1856 m_offsetAdjustment(wxInvalidOffset
)
1860 wxZipOutputStream::~wxZipOutputStream()
1863 WX_CLEAR_LIST(wx__ZipEntryList
, m_entries
);
1867 delete [] m_initialData
;
1869 m_backlink
->Release(this);
1872 bool wxZipOutputStream::PutNextEntry(
1873 const wxString
& name
,
1874 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1875 wxFileOffset size
/*=wxInvalidOffset*/)
1877 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1880 bool wxZipOutputStream::PutNextDirEntry(
1881 const wxString
& name
,
1882 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1884 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1886 return PutNextEntry(entry
);
1889 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1890 wxZipInputStream
& inputStream
)
1892 wx__ZipEntryPtr
e(entry
);
1895 inputStream
.DoOpen(e
.get(), true) &&
1896 DoCreate(e
.release(), true) &&
1897 Write(inputStream
).IsOk() && inputStream
.Eof();
1900 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1902 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1905 return PutNextEntry(zipEntry
);
1908 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1909 wxArchiveInputStream
& stream
)
1911 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1913 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
1918 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
1921 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
1923 m_Comment
= inputStream
.GetComment();
1925 m_backlink
->Release(this);
1926 m_backlink
= inputStream
.MakeLink(this);
1930 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
1932 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
1935 void wxZipOutputStream::SetLevel(int level
)
1937 if (level
!= m_level
) {
1938 if (m_comp
!= m_deflate
)
1945 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
1953 // write the signature bytes right away
1954 wxDataOutputStream
ds(*m_parent_o_stream
);
1957 // and if this is the first entry test for seekability
1958 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
1960 bool logging
= wxLog::IsEnabled();
1963 wxFileOffset here
= m_parent_o_stream
->TellO();
1965 if (here
!= wxInvalidOffset
&& here
>= 4) {
1966 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
1967 m_offsetAdjustment
= here
- 4;
1969 wxLog::EnableLogging(logging
);
1971 m_parent_o_stream
->SeekO(here
);
1976 m_pending
->SetOffset(m_headerOffset
);
1978 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1983 m_lasterror
= wxSTREAM_NO_ERROR
;
1987 // Can be overriden to add support for additional compression methods
1989 wxOutputStream
*wxZipOutputStream::OpenCompressor(
1990 wxOutputStream
& stream
,
1992 const Buffer bufs
[])
1994 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
1996 && (IsParentSeekable()
1997 || entry
.GetCompressedSize() != wxInvalidOffset
1998 || entry
.GetSize() != wxInvalidOffset
)) {
1999 entry
.SetMethod(wxZIP_METHOD_STORE
);
2002 for (int i
= 0; bufs
[i
].m_data
; ++i
)
2003 size
+= bufs
[i
].m_size
;
2004 entry
.SetMethod(size
<= 6 ?
2005 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
2009 switch (entry
.GetMethod()) {
2010 case wxZIP_METHOD_STORE
:
2011 if (entry
.GetCompressedSize() == wxInvalidOffset
)
2012 entry
.SetCompressedSize(entry
.GetSize());
2015 case wxZIP_METHOD_DEFLATE
:
2017 int defbits
= wxZIP_DEFLATE_NORMAL
;
2018 switch (GetLevel()) {
2020 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2022 case 2: case 3: case 4:
2023 defbits
= wxZIP_DEFLATE_FAST
;
2026 defbits
= wxZIP_DEFLATE_EXTRA
;
2029 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2030 defbits
| wxZIP_SUMS_FOLLOW
);
2033 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2035 m_deflate
->Open(stream
);
2041 wxLogError(_("unsupported Zip compression method"));
2047 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2049 if (comp
== m_deflate
)
2051 else if (comp
!= m_store
)
2056 // This is called when OUPUT_LATENCY bytes has been written to the
2057 // wxZipOutputStream to actually create the zip entry.
2059 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2061 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2062 wx__ZipEntryPtr
spPending(m_pending
);
2066 { m_initialData
, m_initialSize
},
2067 { (const char*)buffer
, size
},
2074 m_comp
= OpenCompressor(*m_store
, *spPending
,
2075 m_initialSize
? bufs
: bufs
+ 1);
2077 if (IsParentSeekable()
2078 || (spPending
->m_Crc
2079 && spPending
->m_CompressedSize
!= wxInvalidOffset
2080 && spPending
->m_Size
!= wxInvalidOffset
))
2081 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2083 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2084 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2086 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2087 m_lasterror
= m_parent_o_stream
->GetLastError();
2090 m_entries
.push_back(spPending
.release());
2091 OnSysWrite(m_initialData
, m_initialSize
);
2097 // This is called to write out the zip entry when Close has been called
2098 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2100 void wxZipOutputStream::CreatePendingEntry()
2102 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2103 wx__ZipEntryPtr
spPending(m_pending
);
2105 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2108 // Initially compresses the data to memory, then fall back to 'store'
2109 // if the compressor makes the data larger rather than smaller.
2110 wxMemoryOutputStream mem
;
2111 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2112 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2116 if (comp
!= m_store
) {
2117 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2118 CloseCompressor(comp
);
2123 m_entrySize
= m_initialSize
;
2124 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2126 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2127 m_initialSize
= mem
.GetSize();
2128 mem
.CopyTo(m_initialData
, m_initialSize
);
2130 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2133 spPending
->SetSize(m_entrySize
);
2134 spPending
->SetCrc(m_crcAccumulator
);
2135 spPending
->SetCompressedSize(m_initialSize
);
2138 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2139 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2141 if (m_parent_o_stream
->IsOk()) {
2142 m_entries
.push_back(spPending
.release());
2144 m_store
->Write(m_initialData
, m_initialSize
);
2148 m_lasterror
= m_parent_o_stream
->GetLastError();
2151 // Write the 'central directory' and the 'end-central-directory' records.
2153 bool wxZipOutputStream::Close()
2157 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2162 endrec
.SetEntriesHere(m_entries
.size());
2163 endrec
.SetTotalEntries(m_entries
.size());
2164 endrec
.SetOffset(m_headerOffset
);
2165 endrec
.SetComment(m_Comment
);
2167 wx__ZipEntryList::iterator it
;
2168 wxFileOffset size
= 0;
2170 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2171 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2176 endrec
.SetSize(size
);
2177 endrec
.Write(*m_parent_o_stream
, GetConv());
2179 m_lasterror
= m_parent_o_stream
->GetLastError();
2182 m_lasterror
= wxSTREAM_EOF
;
2186 // Finish writing the current entry
2188 bool wxZipOutputStream::CloseEntry()
2190 if (IsOk() && m_pending
)
2191 CreatePendingEntry();
2197 CloseCompressor(m_comp
);
2200 wxFileOffset compressedSize
= m_store
->TellO();
2202 wxZipEntry
& entry
= *m_entries
.back();
2204 // When writing raw the crc and size can't be checked
2206 m_crcAccumulator
= entry
.GetCrc();
2207 m_entrySize
= entry
.GetSize();
2210 // Write the sums in the trailing 'data descriptor' if necessary
2211 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2212 wxASSERT(!IsParentSeekable());
2214 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2215 compressedSize
, m_entrySize
);
2216 m_lasterror
= m_parent_o_stream
->GetLastError();
2219 // If the local header didn't have the correct crc and size written to
2220 // it then seek back and fix it
2221 else if (m_crcAccumulator
!= entry
.GetCrc()
2222 || m_entrySize
!= entry
.GetSize()
2223 || compressedSize
!= entry
.GetCompressedSize())
2225 if (IsParentSeekable()) {
2226 wxFileOffset here
= m_parent_o_stream
->TellO();
2227 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2228 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2229 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2230 compressedSize
, m_entrySize
);
2231 m_parent_o_stream
->SeekO(here
);
2232 m_lasterror
= m_parent_o_stream
->GetLastError();
2234 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2238 m_headerOffset
+= m_headerSize
+ compressedSize
;
2245 m_lasterror
= m_parent_o_stream
->GetLastError();
2247 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2248 entry
.GetName().c_str());
2252 void wxZipOutputStream::Sync()
2254 if (IsOk() && m_pending
)
2255 CreatePendingEntry(NULL
, 0);
2257 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2260 m_lasterror
= m_comp
->GetLastError();
2264 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2266 if (IsOk() && m_pending
) {
2267 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2268 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2269 m_initialSize
+= size
;
2272 CreatePendingEntry(buffer
, size
);
2277 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2278 if (!IsOk() || !size
)
2281 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2282 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2283 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2284 m_entrySize
+= m_comp
->LastWrite();
2286 return m_comp
->LastWrite();
2289 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM