1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
6 // Copyright: (c) Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
11 #pragma implementation "zipstrm.h"
14 // For compilers that support precompilation, includes "wx.h".
15 #include "wx/wxprec.h"
25 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
27 #include "wx/zipstrm.h"
30 #include "wx/datstrm.h"
31 #include "wx/zstream.h"
32 #include "wx/mstream.h"
34 #include "wx/buffer.h"
35 #include "wx/ptr_scpd.h"
36 #include "wx/wfstream.h"
37 #include "wx/html/forcelnk.h"
40 // value for the 'version needed to extract' field (20 means 2.0)
42 VERSION_NEEDED_TO_EXTRACT
= 20
45 // signatures for the various records (PKxx)
47 CENTRAL_MAGIC
= 0x02014b50, // central directory record
48 LOCAL_MAGIC
= 0x04034b50, // local header
49 END_MAGIC
= 0x06054b50, // end of central directory record
50 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
53 // unix file attributes. zip stores them in the high 16 bits of the
54 // 'external attributes' field, hence the extra zeros.
56 wxZIP_S_IFMT
= 0xF0000000,
57 wxZIP_S_IFDIR
= 0x40000000,
58 wxZIP_S_IFREG
= 0x80000000
61 // minimum sizes for the various records
69 // The number of bytes that must be written to an wxZipOutputStream before
70 // a zip entry is created. The purpose of this latency is so that
71 // OpenCompressor() can see a little data before deciding which compressor
77 // Some offsets into the local header
82 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
83 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
85 FORCE_LINK_ME(zipstrm
)
88 /////////////////////////////////////////////////////////////////////////////
91 // read a string of a given length
93 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
96 wxCharBuffer
buf(len
);
97 stream
.Read(buf
.data(), len
);
98 wxString
str(buf
, conv
);
103 wxStringBuffer
buf(str
, len
);
104 stream
.Read(buf
, len
);
111 // Decode a little endian wxUint32 number from a character array
113 static inline wxUint32
CrackUint32(const char *m
)
115 const unsigned char *n
= (const unsigned char*)m
;
116 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
119 // Temporarily lower the logging level in debug mode to avoid a warning
120 // from SeekI about seeking on a stream with data written back to it.
122 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
125 wxLogLevel level
= wxLog::GetLogLevel();
126 wxLog::SetLogLevel(wxLOG_Debug
- 1);
127 wxFileOffset result
= stream
.SeekI(pos
);
128 wxLog::SetLogLevel(level
);
131 return stream
.SeekI(pos
);
136 /////////////////////////////////////////////////////////////////////////////
137 // Stored input stream
138 // Trival decompressor for files which are 'stored' in the zip file.
140 class wxStoredInputStream
: public wxFilterInputStream
143 wxStoredInputStream(wxInputStream
& stream
);
145 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
146 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
148 virtual char Peek() { return wxInputStream::Peek(); }
149 virtual size_t GetSize() const { return m_len
; }
152 virtual size_t OnSysRead(void *buffer
, size_t size
);
153 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
159 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
162 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
163 : wxFilterInputStream(stream
),
169 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
171 size_t count
= wxMin(size
, m_len
- m_pos
+ (size_t)0);
172 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
176 m_lasterror
= wxSTREAM_EOF
;
177 else if (!*m_parent_i_stream
)
178 m_lasterror
= wxSTREAM_READ_ERROR
;
184 /////////////////////////////////////////////////////////////////////////////
185 // Stored output stream
186 // Trival compressor for files which are 'stored' in the zip file.
188 class wxStoredOutputStream
: public wxFilterOutputStream
191 wxStoredOutputStream(wxOutputStream
& stream
) :
192 wxFilterOutputStream(stream
), m_pos(0) { }
196 m_lasterror
= wxSTREAM_NO_ERROR
;
201 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
202 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
206 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
209 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
211 if (!IsOk() || !size
)
213 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
215 m_lasterror
= wxSTREAM_WRITE_ERROR
;
221 /////////////////////////////////////////////////////////////////////////////
224 // Used to handle the unusal case of raw copying an entry of unknown
225 // length. This can only happen when the zip being copied from is being
226 // read from a non-seekable stream, and also was original written to a
227 // non-seekable stream.
229 // In this case there's no option but to decompress the stream to find
230 // it's length, but we can still write the raw compressed data to avoid the
231 // compression overhead (which is the greater one).
233 // Usage is like this:
234 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
235 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
237 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
238 // is something like the unix 'tee' command; it is a transparent filter, but
239 // allows the data read to be read a second time via an extra method 'GetData'.
241 // The wxRawInputStream then draws data through the tee using a decompressor
242 // then instead of returning the decompressed data, retuns the raw data
243 // from wxTeeInputStream::GetData().
245 class wxTeeInputStream
: public wxFilterInputStream
248 wxTeeInputStream(wxInputStream
& stream
);
250 size_t GetCount() const { return m_end
- m_start
; }
251 size_t GetData(char *buffer
, size_t size
);
256 wxInputStream
& Read(void *buffer
, size_t size
);
259 virtual size_t OnSysRead(void *buffer
, size_t size
);
260 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
264 wxMemoryBuffer m_buf
;
268 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
271 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
272 : wxFilterInputStream(stream
),
273 m_pos(0), m_buf(8192), m_start(0), m_end(0)
277 void wxTeeInputStream::Open()
279 m_pos
= m_start
= m_end
= 0;
280 m_lasterror
= wxSTREAM_NO_ERROR
;
283 bool wxTeeInputStream::Final()
285 bool final
= m_end
== m_buf
.GetDataLen();
286 m_end
= m_buf
.GetDataLen();
290 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
292 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
293 m_end
= m_buf
.GetDataLen();
294 m_buf
.AppendData(buffer
, count
);
298 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
300 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
301 m_lasterror
= m_parent_i_stream
->GetLastError();
305 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
308 size_t len
= m_buf
.GetDataLen();
309 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
310 m_buf
.SetDataLen(len
);
312 wxFAIL
; // we've already returned data that's now being ungot
315 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
322 if (size
> GetCount())
325 memcpy(buffer
, m_buf
+ m_start
, size
);
327 wxASSERT(m_start
<= m_end
);
330 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
331 size_t len
= m_buf
.GetDataLen();
332 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
334 memmove(buf
, buf
+ m_end
, len
);
335 m_buf
.UngetWriteBuf(len
);
342 class wxRawInputStream
: public wxFilterInputStream
345 wxRawInputStream(wxInputStream
& stream
);
346 virtual ~wxRawInputStream() { delete m_tee
; }
348 wxInputStream
* Open(wxInputStream
*decomp
);
349 wxInputStream
& GetTee() const { return *m_tee
; }
352 virtual size_t OnSysRead(void *buffer
, size_t size
);
353 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
357 wxTeeInputStream
*m_tee
;
359 enum { BUFSIZE
= 8192 };
360 wxCharBuffer m_dummy
;
362 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
365 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
366 : wxFilterInputStream(stream
),
368 m_tee(new wxTeeInputStream(stream
)),
373 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
376 m_parent_i_stream
= decomp
;
378 m_lasterror
= wxSTREAM_NO_ERROR
;
386 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
388 char *buf
= (char*)buffer
;
391 while (count
< size
&& IsOk())
393 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
394 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
396 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
399 if (n
== 0 && m_tee
->Final())
400 m_lasterror
= m_parent_i_stream
->GetLastError();
408 /////////////////////////////////////////////////////////////////////////////
409 // Zlib streams than can be reused without recreating.
411 class wxZlibOutputStream2
: public wxZlibOutputStream
414 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
415 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
417 bool Open(wxOutputStream
& stream
);
418 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
421 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
423 wxCHECK(m_pos
== wxInvalidOffset
, false);
425 m_deflate
->next_out
= m_z_buffer
;
426 m_deflate
->avail_out
= m_z_size
;
428 m_lasterror
= wxSTREAM_NO_ERROR
;
429 m_parent_o_stream
= &stream
;
431 if (deflateReset(m_deflate
) != Z_OK
) {
432 wxLogError(_("can't re-initialize zlib deflate stream"));
433 m_lasterror
= wxSTREAM_WRITE_ERROR
;
440 class wxZlibInputStream2
: public wxZlibInputStream
443 wxZlibInputStream2(wxInputStream
& stream
) :
444 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
446 bool Open(wxInputStream
& stream
);
449 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
451 m_inflate
->avail_in
= 0;
453 m_lasterror
= wxSTREAM_NO_ERROR
;
454 m_parent_i_stream
= &stream
;
456 if (inflateReset(m_inflate
) != Z_OK
) {
457 wxLogError(_("can't re-initialize zlib inflate stream"));
458 m_lasterror
= wxSTREAM_READ_ERROR
;
466 /////////////////////////////////////////////////////////////////////////////
467 // Class to hold wxZipEntry's Extra and LocalExtra fields
472 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
474 wxZipMemory
*AddRef() { m_ref
++; return this; }
475 void Release() { if (--m_ref
== 0) delete this; }
477 char *GetData() const { return m_data
; }
478 size_t GetSize() const { return m_size
; }
479 size_t GetCapacity() const { return m_capacity
; }
481 wxZipMemory
*Unique(size_t size
);
484 ~wxZipMemory() { delete m_data
; }
492 wxZipMemory
*wxZipMemory::Unique(size_t size
)
498 zm
= new wxZipMemory
;
503 if (zm
->m_capacity
< size
) {
505 zm
->m_data
= new char[size
];
506 zm
->m_capacity
= size
;
513 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
520 static inline void Release(wxZipMemory
*zm
)
526 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
532 static void Unique(wxZipMemory
*& zm
, size_t size
)
535 zm
= new wxZipMemory
;
537 zm
= zm
->Unique(size
);
541 /////////////////////////////////////////////////////////////////////////////
542 // Collection of weak references to entries
544 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
545 wxIntegerEqual
, _wxOffsetZipEntryMap
);
550 wxZipWeakLinks() : m_ref(1) { }
552 void Release(const wxZipInputStream
* WXUNUSED(x
))
553 { if (--m_ref
== 0) delete this; }
554 void Release(wxFileOffset key
)
555 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
557 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
558 void RemoveEntry(wxFileOffset key
) { m_entries
.erase(key
); }
559 wxZipEntry
*GetEntry(wxFileOffset key
) const;
560 bool IsEmpty() const { return m_entries
.empty(); }
563 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
566 _wxOffsetZipEntryMap m_entries
;
569 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
571 m_entries
[key
] = entry
;
576 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
578 _wxOffsetZipEntryMap::const_iterator it
= m_entries
.find(key
);
579 return it
!= m_entries
.end() ? it
->second
: NULL
;
583 /////////////////////////////////////////////////////////////////////////////
586 wxZipEntry::wxZipEntry(
587 const wxString
& name
/*=wxEmptyString*/,
588 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
589 wxFileOffset size
/*=wxInvalidOffset*/)
591 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
592 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
593 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
595 m_Method(wxZIP_METHOD_DEFAULT
),
598 m_CompressedSize(wxInvalidOffset
),
600 m_Key(wxInvalidOffset
),
601 m_Offset(wxInvalidOffset
),
603 m_InternalAttributes(0),
604 m_ExternalAttributes(0),
614 wxZipEntry::~wxZipEntry()
617 m_backlink
->Release(m_Key
);
619 Release(m_LocalExtra
);
622 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
623 : m_SystemMadeBy(e
.m_SystemMadeBy
),
624 m_VersionMadeBy(e
.m_VersionMadeBy
),
625 m_VersionNeeded(e
.m_VersionNeeded
),
627 m_Method(e
.m_Method
),
628 m_DateTime(e
.m_DateTime
),
630 m_CompressedSize(e
.m_CompressedSize
),
634 m_Offset(e
.m_Offset
),
635 m_Comment(e
.m_Comment
),
636 m_DiskStart(e
.m_DiskStart
),
637 m_InternalAttributes(e
.m_InternalAttributes
),
638 m_ExternalAttributes(e
.m_ExternalAttributes
),
639 m_Extra(AddRef(e
.m_Extra
)),
640 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
641 m_zipnotifier(e
.m_zipnotifier
),
646 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
649 m_SystemMadeBy
= e
.m_SystemMadeBy
;
650 m_VersionMadeBy
= e
.m_VersionMadeBy
;
651 m_VersionNeeded
= e
.m_VersionNeeded
;
653 m_Method
= e
.m_Method
;
654 m_DateTime
= e
.m_DateTime
;
656 m_CompressedSize
= e
.m_CompressedSize
;
660 m_Offset
= e
.m_Offset
;
661 m_Comment
= e
.m_Comment
;
662 m_DiskStart
= e
.m_DiskStart
;
663 m_InternalAttributes
= e
.m_InternalAttributes
;
664 m_ExternalAttributes
= e
.m_ExternalAttributes
;
665 Copy(m_Extra
, e
.m_Extra
);
666 Copy(m_LocalExtra
, e
.m_LocalExtra
);
667 m_zipnotifier
= e
.m_zipnotifier
;
669 m_backlink
->Release(m_Key
);
676 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
678 bool isDir
= IsDir() && !m_Name
.empty();
680 switch (wxFileName::GetFormat(format
)) {
683 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
684 for (size_t i
= name
.length() - 1; i
> 0; --i
)
685 if (name
[i
] == _T('/'))
691 return isDir
? m_Name
+ _T("/") : m_Name
;
700 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
702 fn
.Assign(m_Name
, wxPATH_UNIX
);
704 return fn
.GetFullPath(format
);
707 // Static - Internally tars and zips use forward slashes for the path
708 // separator, absolute paths aren't allowed, and directory names have a
709 // trailing slash. This function converts a path into this internal format,
710 // but without a trailing slash for a directory.
712 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
713 wxPathFormat format
/*=wxPATH_NATIVE*/,
714 bool *pIsDir
/*=NULL*/)
718 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
719 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
723 bool isDir
= !internal
.empty() && internal
.Last() == '/';
727 internal
.erase(internal
.length() - 1);
729 while (!internal
.empty() && *internal
.begin() == '/')
730 internal
.erase(0, 1);
731 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
732 internal
.erase(0, 2);
733 if (internal
== _T(".") || internal
== _T(".."))
734 internal
= wxEmptyString
;
739 void wxZipEntry::SetSystemMadeBy(int system
)
741 int mode
= GetMode();
742 bool wasUnix
= IsMadeByUnix();
744 m_SystemMadeBy
= system
;
746 if (!wasUnix
&& IsMadeByUnix()) {
749 } else if (wasUnix
&& !IsMadeByUnix()) {
750 m_ExternalAttributes
&= 0xffff;
754 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
757 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
759 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
761 if (IsMadeByUnix()) {
762 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
764 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
766 m_ExternalAttributes
|= wxZIP_S_IFREG
;
770 // Return unix style permission bits
772 int wxZipEntry::GetMode() const
774 // return unix permissions if present
776 return (m_ExternalAttributes
>> 16) & 0777;
778 // otherwise synthesize from the dos attribs
780 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
782 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
788 // Set unix permissions
790 void wxZipEntry::SetMode(int mode
)
792 // Set dos attrib bits to be compatible
794 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
796 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
798 // set the actual unix permission bits if the system type allows
799 if (IsMadeByUnix()) {
800 m_ExternalAttributes
&= ~(0777L << 16);
801 m_ExternalAttributes
|= (mode
& 0777L) << 16;
805 const char *wxZipEntry::GetExtra() const
807 return m_Extra
? m_Extra
->GetData() : NULL
;
810 size_t wxZipEntry::GetExtraLen() const
812 return m_Extra
? m_Extra
->GetSize() : 0;
815 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
817 Unique(m_Extra
, len
);
819 memcpy(m_Extra
->GetData(), extra
, len
);
822 const char *wxZipEntry::GetLocalExtra() const
824 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
827 size_t wxZipEntry::GetLocalExtraLen() const
829 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
832 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
834 Unique(m_LocalExtra
, len
);
836 memcpy(m_LocalExtra
->GetData(), extra
, len
);
839 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
841 wxArchiveEntry::UnsetNotifier();
842 m_zipnotifier
= ¬ifier
;
843 m_zipnotifier
->OnEntryUpdated(*this);
846 void wxZipEntry::Notify()
849 m_zipnotifier
->OnEntryUpdated(*this);
850 else if (GetNotifier())
851 GetNotifier()->OnEntryUpdated(*this);
854 void wxZipEntry::UnsetNotifier()
856 wxArchiveEntry::UnsetNotifier();
857 m_zipnotifier
= NULL
;
860 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
862 wxUint16 nameLen
, extraLen
;
863 wxUint32 compressedSize
, size
, crc
;
865 wxDataInputStream
ds(stream
);
867 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
868 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
869 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
871 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
873 if (sumsValid
|| crc
)
875 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
876 m_CompressedSize
= compressedSize
;
877 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
880 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
882 if (extraLen
|| GetLocalExtraLen()) {
883 Unique(m_LocalExtra
, extraLen
);
885 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
888 return LOCAL_SIZE
+ nameLen
+ extraLen
;
891 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
893 wxString unixName
= GetName(wxPATH_UNIX
);
894 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
895 const char *name
= name_buf
;
896 if (!name
) name
= "";
897 wxUint16 nameLen
= strlen(name
);
899 wxDataOutputStream
ds(stream
);
901 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
902 ds
.Write32(GetDateTime().GetAsDOS());
905 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
? m_CompressedSize
: 0);
906 ds
.Write32(m_Size
!= wxInvalidOffset
? m_Size
: 0);
909 wxUint16 extraLen
= GetLocalExtraLen();
910 ds
.Write16(extraLen
);
912 stream
.Write(name
, nameLen
);
914 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
916 return LOCAL_SIZE
+ nameLen
+ extraLen
;
919 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
921 wxUint16 nameLen
, extraLen
, commentLen
;
923 wxDataInputStream
ds(stream
);
925 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
927 SetVersionNeeded(ds
.Read16());
928 SetFlags(ds
.Read16());
929 SetMethod(ds
.Read16());
930 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
932 SetCompressedSize(ds
.Read32());
933 SetSize(ds
.Read32());
935 ds
>> nameLen
>> extraLen
>> commentLen
936 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
937 SetOffset(ds
.Read32());
939 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
941 if (extraLen
|| GetExtraLen()) {
942 Unique(m_Extra
, extraLen
);
944 stream
.Read(m_Extra
->GetData(), extraLen
);
948 m_Comment
= ReadString(stream
, commentLen
, conv
);
952 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
955 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
957 wxString unixName
= GetName(wxPATH_UNIX
);
958 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
959 const char *name
= name_buf
;
960 if (!name
) name
= "";
961 wxUint16 nameLen
= strlen(name
);
963 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
964 const char *comment
= comment_buf
;
965 if (!comment
) comment
= "";
966 wxUint16 commentLen
= strlen(comment
);
968 wxUint16 extraLen
= GetExtraLen();
970 wxDataOutputStream
ds(stream
);
972 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
974 ds
.Write16(GetVersionNeeded());
975 ds
.Write16(GetFlags());
976 ds
.Write16(GetMethod());
977 ds
.Write32(GetDateTime().GetAsDOS());
978 ds
.Write32(GetCrc());
979 ds
.Write32(GetCompressedSize());
980 ds
.Write32(GetSize());
982 ds
.Write16(extraLen
);
984 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
985 << m_ExternalAttributes
<< (wxUint32
)GetOffset();
987 stream
.Write(name
, nameLen
);
989 stream
.Write(GetExtra(), extraLen
);
990 stream
.Write(comment
, commentLen
);
992 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
995 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
996 // the 1st value is the signature then it is probably an info-zip record,
997 // though there is a small chance that it is in fact a pkzip record which
998 // happens to have the signature as it's CRC.
1000 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1002 wxDataInputStream
ds(stream
);
1004 m_Crc
= ds
.Read32();
1005 m_CompressedSize
= ds
.Read32();
1006 m_Size
= ds
.Read32();
1008 // if 1st value is the signature then this is probably an info-zip record
1009 if (m_Crc
== SUMS_MAGIC
)
1012 stream
.Read(buf
, sizeof(buf
));
1013 wxUint32 u1
= CrackUint32(buf
);
1014 wxUint32 u2
= CrackUint32(buf
+ 4);
1016 // look for the signature of the following record to decide which
1017 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1018 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1020 // it's a pkzip style record after all!
1021 stream
.Ungetch(buf
, sizeof(buf
));
1025 // it's an info-zip record as expected
1026 stream
.Ungetch(buf
+ 4, sizeof(buf
) - 4);
1027 m_Crc
= m_CompressedSize
;
1028 m_CompressedSize
= m_Size
;
1030 return SUMS_SIZE
+ 4;
1037 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1038 wxFileOffset compressedSize
, wxFileOffset size
)
1041 m_CompressedSize
= compressedSize
;
1044 wxDataOutputStream
ds(stream
);
1047 ds
.Write32(compressedSize
);
1054 /////////////////////////////////////////////////////////////////////////////
1055 // wxZipEndRec - holds the end of central directory record
1062 int GetDiskNumber() const { return m_DiskNumber
; }
1063 int GetStartDisk() const { return m_StartDisk
; }
1064 int GetEntriesHere() const { return m_EntriesHere
; }
1065 int GetTotalEntries() const { return m_TotalEntries
; }
1066 wxFileOffset
GetSize() const { return m_Size
; }
1067 wxFileOffset
GetOffset() const { return m_Offset
; }
1068 wxString
GetComment() const { return m_Comment
; }
1070 void SetDiskNumber(int num
) { m_DiskNumber
= num
; }
1071 void SetStartDisk(int num
) { m_StartDisk
= num
; }
1072 void SetEntriesHere(int num
) { m_EntriesHere
= num
; }
1073 void SetTotalEntries(int num
) { m_TotalEntries
= num
; }
1074 void SetSize(wxFileOffset size
) { m_Size
= (wxUint32
)size
; }
1075 void SetOffset(wxFileOffset offset
) { m_Offset
= (wxUint32
)offset
; }
1076 void SetComment(const wxString
& comment
) { m_Comment
= comment
; }
1078 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1079 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1082 wxUint16 m_DiskNumber
;
1083 wxUint16 m_StartDisk
;
1084 wxUint16 m_EntriesHere
;
1085 wxUint16 m_TotalEntries
;
1091 wxZipEndRec::wxZipEndRec()
1101 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1103 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1104 const char *comment
= comment_buf
;
1105 if (!comment
) comment
= "";
1106 wxUint16 commentLen
= strlen(comment
);
1108 wxDataOutputStream
ds(stream
);
1110 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1111 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1113 stream
.Write(comment
, commentLen
);
1115 return stream
.IsOk();
1118 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1120 wxDataInputStream
ds(stream
);
1121 wxUint16 commentLen
;
1123 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1124 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1127 m_Comment
= ReadString(stream
, commentLen
, conv
);
1130 if (m_DiskNumber
== 0 && m_StartDisk
== 0 &&
1131 m_EntriesHere
== m_TotalEntries
)
1134 wxLogError(_("unsupported zip archive"));
1140 /////////////////////////////////////////////////////////////////////////////
1141 // A weak link from an input stream to an output stream
1143 class wxZipStreamLink
1146 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1148 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1149 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1151 void Release(class wxZipInputStream
*WXUNUSED(s
))
1152 { if (--m_ref
== 0) delete this; }
1153 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1154 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1157 ~wxZipStreamLink() { }
1160 wxZipOutputStream
*m_stream
;
1164 /////////////////////////////////////////////////////////////////////////////
1167 wxDECLARE_SCOPED_PTR(wxZipEntry
, _wxZipEntryPtr
)
1168 wxDEFINE_SCOPED_PTR (wxZipEntry
, _wxZipEntryPtr
)
1172 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1173 wxMBConv
& conv
/*=wxConvLocal*/)
1174 : wxArchiveInputStream(stream
, conv
)
1180 // Compatibility constructor
1182 wxZipInputStream::wxZipInputStream(const wxString
& archive
,
1183 const wxString
& file
)
1184 : wxArchiveInputStream(OpenFile(archive
), wxConvLocal
)
1186 // no error messages
1189 _wxZipEntryPtr entry
;
1191 if (m_ffile
->Ok()) {
1193 entry
.reset(GetNextEntry());
1195 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1198 if (entry
.get() == NULL
)
1199 m_lasterror
= wxSTREAM_READ_ERROR
;
1202 wxInputStream
& wxZipInputStream::OpenFile(const wxString
& archive
)
1205 m_ffile
= new wxFFileInputStream(archive
);
1209 void wxZipInputStream::Init()
1211 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1217 m_parentSeekable
= false;
1218 m_weaklinks
= new wxZipWeakLinks
;
1219 m_streamlink
= NULL
;
1220 m_offsetAdjustment
= 0;
1221 m_position
= wxInvalidOffset
;
1224 m_lasterror
= m_parent_i_stream
->GetLastError();
1227 wxZipInputStream::~wxZipInputStream()
1229 CloseDecompressor(m_decomp
);
1236 m_weaklinks
->Release(this);
1239 m_streamlink
->Release(this);
1242 wxString
wxZipInputStream::GetComment()
1244 if (m_position
== wxInvalidOffset
)
1245 if (!LoadEndRecord())
1246 return wxEmptyString
;
1248 if (!m_parentSeekable
&& Eof() && m_signature
) {
1249 m_lasterror
= wxSTREAM_NO_ERROR
;
1250 m_lasterror
= ReadLocal(true);
1256 int wxZipInputStream::GetTotalEntries()
1258 if (m_position
== wxInvalidOffset
)
1260 return m_TotalEntries
;
1263 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1265 wxZipStreamLink
*link
= NULL
;
1267 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1268 link
= new wxZipStreamLink(out
);
1270 m_streamlink
->Release(this);
1271 m_streamlink
= link
->AddRef();
1277 bool wxZipInputStream::LoadEndRecord()
1279 wxCHECK(m_position
== wxInvalidOffset
, false);
1285 // First find the end-of-central-directory record.
1286 if (!FindEndRecord()) {
1287 // failed, so either this is a non-seekable stream (ok), or not a zip
1288 if (m_parentSeekable
) {
1289 m_lasterror
= wxSTREAM_READ_ERROR
;
1290 wxLogError(_("invalid zip file"));
1295 wxFileOffset pos
= m_parent_i_stream
->TellI();
1297 //if (pos != wxInvalidOffset)
1298 if (pos
>= 0 && pos
<= LONG_MAX
)
1299 m_offsetAdjustment
= m_position
= pos
;
1306 // Read in the end record
1307 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1308 if (!endrec
.Read(*m_parent_i_stream
, GetConv())) {
1309 if (!*m_parent_i_stream
) {
1310 m_lasterror
= wxSTREAM_READ_ERROR
;
1313 // TODO: try this out
1314 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1317 m_TotalEntries
= endrec
.GetTotalEntries();
1318 m_Comment
= endrec
.GetComment();
1320 // Now find the central-directory. we have the file offset of
1321 // the CD, so look there first.
1322 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1323 ReadSignature() == CENTRAL_MAGIC
) {
1324 m_signature
= CENTRAL_MAGIC
;
1325 m_position
= endrec
.GetOffset();
1326 m_offsetAdjustment
= 0;
1330 // If it's not there, then it could be that the zip has been appended
1331 // to a self extractor, so take the CD size (also in endrec), subtract
1332 // it from the file offset of the end-central-directory and look there.
1333 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1334 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1335 m_signature
= CENTRAL_MAGIC
;
1336 m_position
= endPos
- endrec
.GetSize();
1337 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1341 wxLogError(_("can't find central directory in zip"));
1342 m_lasterror
= wxSTREAM_READ_ERROR
;
1346 // Find the end-of-central-directory record.
1347 // If found the stream will be positioned just past the 4 signature bytes.
1349 bool wxZipInputStream::FindEndRecord()
1351 // usually it's 22 bytes in size and the last thing in the file
1354 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1358 m_parentSeekable
= true;
1361 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1363 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1366 // unfortunately, the record has a comment field that can be up to 65535
1367 // bytes in length, so if the signature not found then search backwards.
1368 wxFileOffset pos
= m_parent_i_stream
->TellI();
1369 const int BUFSIZE
= 1024;
1370 wxCharBuffer
buf(BUFSIZE
);
1372 memcpy(buf
.data(), magic
, 3);
1373 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1375 while (pos
> minpos
) {
1376 size_t len
= pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
);
1377 memcpy(buf
.data() + len
, buf
, 3);
1380 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1381 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1384 char *p
= buf
.data() + len
;
1386 while (p
-- > buf
.data()) {
1387 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1388 size_t remainder
= buf
.data() + len
- p
;
1390 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1399 wxZipEntry
*wxZipInputStream::GetNextEntry()
1401 if (m_position
== wxInvalidOffset
)
1402 if (!LoadEndRecord())
1405 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1409 _wxZipEntryPtr
entry(new wxZipEntry(m_entry
));
1410 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1411 return entry
.release();
1414 wxStreamError
wxZipInputStream::ReadCentral()
1419 if (m_signature
== END_MAGIC
)
1420 return wxSTREAM_EOF
;
1422 if (m_signature
!= CENTRAL_MAGIC
) {
1423 wxLogError(_("error reading zip central directory"));
1424 return wxSTREAM_READ_ERROR
;
1427 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1428 return wxSTREAM_READ_ERROR
;
1430 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1431 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1433 return wxSTREAM_READ_ERROR
;
1436 m_signature
= ReadSignature();
1438 if (m_offsetAdjustment
)
1439 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1440 m_entry
.SetKey(m_entry
.GetOffset());
1442 return wxSTREAM_NO_ERROR
;
1445 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1451 m_signature
= ReadSignature();
1453 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1454 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1455 m_streamlink
->Release(this);
1456 m_streamlink
= NULL
;
1460 while (m_signature
== CENTRAL_MAGIC
) {
1461 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1462 return wxSTREAM_EOF
;
1464 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1466 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
)
1467 return wxSTREAM_READ_ERROR
;
1469 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1471 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1472 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1473 entry
->SetComment(m_entry
.GetComment());
1474 entry
->SetDiskStart(m_entry
.GetDiskStart());
1475 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1476 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1477 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1479 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1482 m_signature
= ReadSignature();
1485 if (m_signature
== END_MAGIC
) {
1486 if (readEndRec
|| m_streamlink
) {
1488 endrec
.Read(*m_parent_i_stream
, GetConv());
1489 m_Comment
= endrec
.GetComment();
1492 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1493 m_streamlink
->Release(this);
1494 m_streamlink
= NULL
;
1497 return wxSTREAM_EOF
;
1500 if (m_signature
!= LOCAL_MAGIC
) {
1501 wxLogError(_("error reading zip local header"));
1502 return wxSTREAM_READ_ERROR
;
1505 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1507 m_entry
.SetOffset(m_position
);
1508 m_entry
.SetKey(m_position
);
1510 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1511 return wxSTREAM_READ_ERROR
;
1514 return wxSTREAM_NO_ERROR
;
1518 wxUint32
wxZipInputStream::ReadSignature()
1521 m_parent_i_stream
->Read(magic
, 4);
1522 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1525 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1527 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1528 return zipEntry
? OpenEntry(*zipEntry
) : false;
1533 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1535 if (m_position
== wxInvalidOffset
)
1536 if (!LoadEndRecord())
1538 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1540 wxCHECK(!IsOpened(), false);
1545 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1547 // can only open the current entry on a non-seekable stream
1548 wxCHECK(m_parentSeekable
, false);
1551 m_lasterror
= wxSTREAM_READ_ERROR
;
1556 if (m_parentSeekable
) {
1557 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1560 if (ReadSignature() != LOCAL_MAGIC
) {
1561 wxLogError(_("bad zipfile offset to entry"));
1566 if (m_parentSeekable
|| AtHeader()) {
1567 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1568 if (m_parentSeekable
) {
1569 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1571 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1573 m_weaklinks
->RemoveEntry(ref
->GetKey());
1575 if (entry
&& entry
!= ref
) {
1576 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1582 m_lasterror
= m_parent_i_stream
->GetLastError();
1586 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1588 wxASSERT(AfterHeader());
1590 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1596 if (compressedSize
!= wxInvalidOffset
) {
1597 m_store
->Open(compressedSize
);
1601 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1602 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1605 if (compressedSize
!= wxInvalidOffset
&&
1606 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1607 wxZlibInputStream::CanHandleGZip())) {
1608 m_store
->Open(compressedSize
);
1609 m_decomp
= OpenDecompressor(*m_store
);
1611 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1615 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1616 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1620 // Can be overriden to add support for additional decompression methods
1622 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1624 switch (m_entry
.GetMethod()) {
1625 case wxZIP_METHOD_STORE
:
1626 if (m_entry
.GetSize() == wxInvalidOffset
) {
1627 wxLogError(_("stored file length not in Zip header"));
1630 m_store
->Open(m_entry
.GetSize());
1633 case wxZIP_METHOD_DEFLATE
:
1635 m_inflate
= new wxZlibInputStream2(stream
);
1637 m_inflate
->Open(stream
);
1641 wxLogError(_("unsupported Zip compression method"));
1647 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1649 if (decomp
&& decomp
== m_rawin
)
1650 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1651 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1656 // Closes the current entry and positions the underlying stream at the start
1657 // of the next entry
1659 bool wxZipInputStream::CloseEntry()
1663 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1666 if (!m_parentSeekable
) {
1667 if (!IsOpened() && !OpenDecompressor(true))
1670 const int BUFSIZE
= 8192;
1671 wxCharBuffer
buf(BUFSIZE
);
1673 Read(buf
.data(), BUFSIZE
);
1675 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1678 if (m_lasterror
== wxSTREAM_EOF
)
1679 m_lasterror
= wxSTREAM_NO_ERROR
;
1681 CloseDecompressor(m_decomp
);
1683 m_entry
= wxZipEntry();
1690 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1693 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1694 m_lasterror
= wxSTREAM_READ_ERROR
;
1695 if (!IsOk() || !size
)
1698 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1700 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1701 m_lasterror
= m_decomp
->GetLastError();
1704 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1705 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1706 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1709 entry
->SetCrc(m_entry
.GetCrc());
1710 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1711 entry
->SetSize(m_entry
.GetSize());
1717 m_lasterror
= wxSTREAM_READ_ERROR
;
1719 if (m_parent_i_stream
->IsOk()) {
1720 if (m_entry
.GetSize() != TellI())
1721 wxLogError(_("reading zip stream (entry %s): bad length"),
1722 m_entry
.GetName().c_str());
1723 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1724 wxLogError(_("reading zip stream (entry %s): bad crc"),
1725 m_entry
.GetName().c_str());
1727 m_lasterror
= wxSTREAM_EOF
;
1735 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1737 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1739 if (!m_ffile
|| AtHeader())
1740 return wxInvalidOffset
;
1742 // NB: since ZIP files don't natively support seeking, we have to
1743 // implement a brute force workaround -- reading all the data
1744 // between current and the new position (or between beginning of
1745 // the file and new position...)
1747 wxFileOffset nextpos
;
1748 wxFileOffset pos
= TellI();
1752 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1753 case wxFromStart
: nextpos
= seek
; break;
1754 case wxFromEnd
: nextpos
= GetSize() - 1 + seek
; break;
1755 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1759 if ( nextpos
>= pos
)
1761 toskip
= nextpos
- pos
;
1765 wxZipEntry
current(m_entry
);
1767 if (!OpenEntry(current
))
1769 m_lasterror
= wxSTREAM_READ_ERROR
;
1777 const size_t BUFSIZE
= 4096;
1779 char buffer
[BUFSIZE
];
1780 while ( toskip
> 0 )
1782 sz
= wxMin(toskip
, BUFSIZE
);
1793 /////////////////////////////////////////////////////////////////////////////
1796 #include <wx/listimpl.cpp>
1797 WX_DEFINE_LIST(_wxZipEntryList
);
1799 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1801 wxMBConv
& conv
/*=wxConvLocal*/)
1802 : wxArchiveOutputStream(stream
, conv
),
1803 m_store(new wxStoredOutputStream(stream
)),
1806 m_initialData(new char[OUTPUT_LATENCY
]),
1815 m_offsetAdjustment(wxInvalidOffset
)
1819 wxZipOutputStream::~wxZipOutputStream()
1822 WX_CLEAR_LIST(_wxZipEntryList
, m_entries
);
1826 delete [] m_initialData
;
1828 m_backlink
->Release(this);
1831 bool wxZipOutputStream::PutNextEntry(
1832 const wxString
& name
,
1833 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1834 wxFileOffset size
/*=wxInvalidOffset*/)
1836 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1839 bool wxZipOutputStream::PutNextDirEntry(
1840 const wxString
& name
,
1841 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1843 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1845 return PutNextEntry(entry
);
1848 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1849 wxZipInputStream
& inputStream
)
1851 _wxZipEntryPtr
e(entry
);
1854 inputStream
.DoOpen(e
.get(), true) &&
1855 DoCreate(e
.release(), true) &&
1856 Write(inputStream
).IsOk() && inputStream
.Eof();
1859 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1861 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1864 return PutNextEntry(zipEntry
);
1867 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1868 wxArchiveInputStream
& stream
)
1870 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1872 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
1877 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
1880 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
1882 m_Comment
= inputStream
.GetComment();
1884 m_backlink
->Release(this);
1885 m_backlink
= inputStream
.MakeLink(this);
1889 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
1891 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
1894 void wxZipOutputStream::SetLevel(int level
)
1896 if (level
!= m_level
) {
1897 if (m_comp
!= m_deflate
)
1904 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
1912 // write the signature bytes right away
1913 wxDataOutputStream
ds(*m_parent_o_stream
);
1916 // and if this is the first entry test for seekability
1917 if (m_headerOffset
== 0) {
1918 bool logging
= wxLog::IsEnabled();
1920 wxFileOffset here
= m_parent_o_stream
->TellO();
1922 if (here
!= wxInvalidOffset
&& here
>= 4) {
1923 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
1924 m_offsetAdjustment
= here
- 4;
1925 wxLog::EnableLogging(logging
);
1926 m_parent_o_stream
->SeekO(here
);
1931 m_pending
->SetOffset(m_headerOffset
);
1933 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1938 m_lasterror
= wxSTREAM_NO_ERROR
;
1942 // Can be overriden to add support for additional compression methods
1944 wxOutputStream
*wxZipOutputStream::OpenCompressor(
1945 wxOutputStream
& stream
,
1947 const Buffer bufs
[])
1949 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
1951 && (IsParentSeekable()
1952 || entry
.GetCompressedSize() != wxInvalidOffset
1953 || entry
.GetSize() != wxInvalidOffset
)) {
1954 entry
.SetMethod(wxZIP_METHOD_STORE
);
1957 for (int i
= 0; bufs
[i
].m_data
; ++i
)
1958 size
+= bufs
[i
].m_size
;
1959 entry
.SetMethod(size
<= 6 ?
1960 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
1964 switch (entry
.GetMethod()) {
1965 case wxZIP_METHOD_STORE
:
1966 if (entry
.GetCompressedSize() == wxInvalidOffset
)
1967 entry
.SetCompressedSize(entry
.GetSize());
1970 case wxZIP_METHOD_DEFLATE
:
1972 int defbits
= wxZIP_DEFLATE_NORMAL
;
1973 switch (GetLevel()) {
1975 defbits
= wxZIP_DEFLATE_SUPERFAST
;
1977 case 2: case 3: case 4:
1978 defbits
= wxZIP_DEFLATE_FAST
;
1981 defbits
= wxZIP_DEFLATE_EXTRA
;
1984 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
1985 defbits
| wxZIP_SUMS_FOLLOW
);
1988 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
1990 m_deflate
->Open(stream
);
1996 wxLogError(_("unsupported Zip compression method"));
2002 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2004 if (comp
== m_deflate
)
2006 else if (comp
!= m_store
)
2011 // This is called when OUPUT_LATENCY bytes has been written to the
2012 // wxZipOutputStream to actually create the zip entry.
2014 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2016 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2017 _wxZipEntryPtr
spPending(m_pending
);
2021 { m_initialData
, m_initialSize
},
2022 { (const char*)buffer
, size
},
2029 m_comp
= OpenCompressor(*m_store
, *spPending
,
2030 m_initialSize
? bufs
: bufs
+ 1);
2032 if (IsParentSeekable()
2033 || (spPending
->m_Crc
2034 && spPending
->m_CompressedSize
!= wxInvalidOffset
2035 && spPending
->m_Size
!= wxInvalidOffset
))
2036 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2038 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2039 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2041 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2042 m_lasterror
= m_parent_o_stream
->GetLastError();
2045 m_entries
.push_back(spPending
.release());
2046 OnSysWrite(m_initialData
, m_initialSize
);
2052 // This is called to write out the zip entry when Close has been called
2053 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2055 void wxZipOutputStream::CreatePendingEntry()
2057 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2058 _wxZipEntryPtr
spPending(m_pending
);
2060 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2063 // Initially compresses the data to memory, then fall back to 'store'
2064 // if the compressor makes the data larger rather than smaller.
2065 wxMemoryOutputStream mem
;
2066 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2067 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2071 if (comp
!= m_store
) {
2072 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2073 CloseCompressor(comp
);
2078 m_entrySize
= m_initialSize
;
2079 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2081 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2082 m_initialSize
= mem
.GetSize();
2083 mem
.CopyTo(m_initialData
, m_initialSize
);
2085 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2088 spPending
->SetSize(m_entrySize
);
2089 spPending
->SetCrc(m_crcAccumulator
);
2090 spPending
->SetCompressedSize(m_initialSize
);
2093 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2094 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2096 if (m_parent_o_stream
->IsOk()) {
2097 m_entries
.push_back(spPending
.release());
2099 m_store
->Write(m_initialData
, m_initialSize
);
2103 m_lasterror
= m_parent_o_stream
->GetLastError();
2106 // Write the 'central directory' and the 'end-central-directory' records.
2108 bool wxZipOutputStream::Close()
2112 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2117 endrec
.SetEntriesHere(m_entries
.size());
2118 endrec
.SetTotalEntries(m_entries
.size());
2119 endrec
.SetOffset(m_headerOffset
);
2120 endrec
.SetComment(m_Comment
);
2122 _wxZipEntryList::iterator it
;
2123 wxFileOffset size
= 0;
2125 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2126 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2131 endrec
.SetSize(size
);
2132 endrec
.Write(*m_parent_o_stream
, GetConv());
2134 m_lasterror
= m_parent_o_stream
->GetLastError();
2137 m_lasterror
= wxSTREAM_EOF
;
2141 // Finish writing the current entry
2143 bool wxZipOutputStream::CloseEntry()
2145 if (IsOk() && m_pending
)
2146 CreatePendingEntry();
2152 CloseCompressor(m_comp
);
2155 wxFileOffset compressedSize
= m_store
->TellO();
2157 wxZipEntry
& entry
= *m_entries
.back();
2159 // When writing raw the crc and size can't be checked
2161 m_crcAccumulator
= entry
.GetCrc();
2162 m_entrySize
= entry
.GetSize();
2165 // Write the sums in the trailing 'data descriptor' if necessary
2166 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2167 wxASSERT(!IsParentSeekable());
2169 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2170 compressedSize
, m_entrySize
);
2171 m_lasterror
= m_parent_o_stream
->GetLastError();
2174 // If the local header didn't have the correct crc and size written to
2175 // it then seek back and fix it
2176 else if (m_crcAccumulator
!= entry
.GetCrc()
2177 || m_entrySize
!= entry
.GetSize()
2178 || compressedSize
!= entry
.GetCompressedSize())
2180 if (IsParentSeekable()) {
2181 wxFileOffset here
= m_parent_o_stream
->TellO();
2182 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2183 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2184 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2185 compressedSize
, m_entrySize
);
2186 m_parent_o_stream
->SeekO(here
);
2187 m_lasterror
= m_parent_o_stream
->GetLastError();
2189 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2193 m_headerOffset
+= m_headerSize
+ compressedSize
;
2194 m_headerSize
= m_entrySize
= 0;
2199 m_lasterror
= m_parent_o_stream
->GetLastError();
2201 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2202 entry
.GetName().c_str());
2206 void wxZipOutputStream::Sync()
2208 if (IsOk() && m_pending
)
2209 CreatePendingEntry(NULL
, 0);
2211 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2214 m_lasterror
= m_comp
->GetLastError();
2218 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2220 if (IsOk() && m_pending
) {
2221 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2222 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2223 m_initialSize
+= size
;
2226 CreatePendingEntry(buffer
, size
);
2231 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2232 if (!IsOk() || !size
)
2235 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2236 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2237 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2238 m_entrySize
+= m_comp
->LastWrite();
2240 return m_comp
->LastWrite();
2243 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM