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 wxFileOffset
GetLength() 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
, (size_t)(m_len
- m_pos
));
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
)
559 { m_entries
.erase((_wxOffsetZipEntryMap::key_type
)key
); }
560 wxZipEntry
*GetEntry(wxFileOffset key
) const;
561 bool IsEmpty() const { return m_entries
.empty(); }
564 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
567 _wxOffsetZipEntryMap m_entries
;
570 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
572 m_entries
[(_wxOffsetZipEntryMap::key_type
)key
] = entry
;
577 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
579 _wxOffsetZipEntryMap::const_iterator it
=
580 m_entries
.find((_wxOffsetZipEntryMap::key_type
)key
);
581 return it
!= m_entries
.end() ? it
->second
: NULL
;
585 /////////////////////////////////////////////////////////////////////////////
588 wxZipEntry::wxZipEntry(
589 const wxString
& name
/*=wxEmptyString*/,
590 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
591 wxFileOffset size
/*=wxInvalidOffset*/)
593 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
594 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
595 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
597 m_Method(wxZIP_METHOD_DEFAULT
),
600 m_CompressedSize(wxInvalidOffset
),
602 m_Key(wxInvalidOffset
),
603 m_Offset(wxInvalidOffset
),
605 m_InternalAttributes(0),
606 m_ExternalAttributes(0),
616 wxZipEntry::~wxZipEntry()
619 m_backlink
->Release(m_Key
);
621 Release(m_LocalExtra
);
624 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
626 m_SystemMadeBy(e
.m_SystemMadeBy
),
627 m_VersionMadeBy(e
.m_VersionMadeBy
),
628 m_VersionNeeded(e
.m_VersionNeeded
),
630 m_Method(e
.m_Method
),
631 m_DateTime(e
.m_DateTime
),
633 m_CompressedSize(e
.m_CompressedSize
),
637 m_Offset(e
.m_Offset
),
638 m_Comment(e
.m_Comment
),
639 m_DiskStart(e
.m_DiskStart
),
640 m_InternalAttributes(e
.m_InternalAttributes
),
641 m_ExternalAttributes(e
.m_ExternalAttributes
),
642 m_Extra(AddRef(e
.m_Extra
)),
643 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
649 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
652 m_SystemMadeBy
= e
.m_SystemMadeBy
;
653 m_VersionMadeBy
= e
.m_VersionMadeBy
;
654 m_VersionNeeded
= e
.m_VersionNeeded
;
656 m_Method
= e
.m_Method
;
657 m_DateTime
= e
.m_DateTime
;
659 m_CompressedSize
= e
.m_CompressedSize
;
663 m_Offset
= e
.m_Offset
;
664 m_Comment
= e
.m_Comment
;
665 m_DiskStart
= e
.m_DiskStart
;
666 m_InternalAttributes
= e
.m_InternalAttributes
;
667 m_ExternalAttributes
= e
.m_ExternalAttributes
;
668 Copy(m_Extra
, e
.m_Extra
);
669 Copy(m_LocalExtra
, e
.m_LocalExtra
);
670 m_zipnotifier
= NULL
;
672 m_backlink
->Release(m_Key
);
679 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
681 bool isDir
= IsDir() && !m_Name
.empty();
683 switch (wxFileName::GetFormat(format
)) {
686 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
687 for (size_t i
= name
.length() - 1; i
> 0; --i
)
688 if (name
[i
] == _T('/'))
694 return isDir
? m_Name
+ _T("/") : m_Name
;
703 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
705 fn
.Assign(m_Name
, wxPATH_UNIX
);
707 return fn
.GetFullPath(format
);
710 // Static - Internally tars and zips use forward slashes for the path
711 // separator, absolute paths aren't allowed, and directory names have a
712 // trailing slash. This function converts a path into this internal format,
713 // but without a trailing slash for a directory.
715 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
716 wxPathFormat format
/*=wxPATH_NATIVE*/,
717 bool *pIsDir
/*=NULL*/)
721 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
722 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
726 bool isDir
= !internal
.empty() && internal
.Last() == '/';
730 internal
.erase(internal
.length() - 1);
732 while (!internal
.empty() && *internal
.begin() == '/')
733 internal
.erase(0, 1);
734 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
735 internal
.erase(0, 2);
736 if (internal
== _T(".") || internal
== _T(".."))
737 internal
= wxEmptyString
;
742 void wxZipEntry::SetSystemMadeBy(int system
)
744 int mode
= GetMode();
745 bool wasUnix
= IsMadeByUnix();
747 m_SystemMadeBy
= (wxUint8
)system
;
749 if (!wasUnix
&& IsMadeByUnix()) {
752 } else if (wasUnix
&& !IsMadeByUnix()) {
753 m_ExternalAttributes
&= 0xffff;
757 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
760 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
762 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
764 if (IsMadeByUnix()) {
765 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
767 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
769 m_ExternalAttributes
|= wxZIP_S_IFREG
;
773 // Return unix style permission bits
775 int wxZipEntry::GetMode() const
777 // return unix permissions if present
779 return (m_ExternalAttributes
>> 16) & 0777;
781 // otherwise synthesize from the dos attribs
783 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
785 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
791 // Set unix permissions
793 void wxZipEntry::SetMode(int mode
)
795 // Set dos attrib bits to be compatible
797 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
799 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
801 // set the actual unix permission bits if the system type allows
802 if (IsMadeByUnix()) {
803 m_ExternalAttributes
&= ~(0777L << 16);
804 m_ExternalAttributes
|= (mode
& 0777L) << 16;
808 const char *wxZipEntry::GetExtra() const
810 return m_Extra
? m_Extra
->GetData() : NULL
;
813 size_t wxZipEntry::GetExtraLen() const
815 return m_Extra
? m_Extra
->GetSize() : 0;
818 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
820 Unique(m_Extra
, len
);
822 memcpy(m_Extra
->GetData(), extra
, len
);
825 const char *wxZipEntry::GetLocalExtra() const
827 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
830 size_t wxZipEntry::GetLocalExtraLen() const
832 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
835 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
837 Unique(m_LocalExtra
, len
);
839 memcpy(m_LocalExtra
->GetData(), extra
, len
);
842 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
844 wxArchiveEntry::UnsetNotifier();
845 m_zipnotifier
= ¬ifier
;
846 m_zipnotifier
->OnEntryUpdated(*this);
849 void wxZipEntry::Notify()
852 m_zipnotifier
->OnEntryUpdated(*this);
853 else if (GetNotifier())
854 GetNotifier()->OnEntryUpdated(*this);
857 void wxZipEntry::UnsetNotifier()
859 wxArchiveEntry::UnsetNotifier();
860 m_zipnotifier
= NULL
;
863 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
865 wxUint16 nameLen
, extraLen
;
866 wxUint32 compressedSize
, size
, crc
;
868 wxDataInputStream
ds(stream
);
870 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
871 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
872 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
874 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
876 if (sumsValid
|| crc
)
878 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
879 m_CompressedSize
= compressedSize
;
880 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
883 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
885 if (extraLen
|| GetLocalExtraLen()) {
886 Unique(m_LocalExtra
, extraLen
);
888 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
891 return LOCAL_SIZE
+ nameLen
+ extraLen
;
894 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
896 wxString unixName
= GetName(wxPATH_UNIX
);
897 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
898 const char *name
= name_buf
;
899 if (!name
) name
= "";
900 wxUint16 nameLen
= (wxUint16
)strlen(name
);
902 wxDataOutputStream
ds(stream
);
904 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
905 ds
.Write32(GetDateTime().GetAsDOS());
908 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
? (wxUint32
)m_CompressedSize
: 0);
909 ds
.Write32(m_Size
!= wxInvalidOffset
? (wxUint32
)m_Size
: 0);
912 wxUint16 extraLen
= (wxUint16
)GetLocalExtraLen();
913 ds
.Write16(extraLen
);
915 stream
.Write(name
, nameLen
);
917 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
919 return LOCAL_SIZE
+ nameLen
+ extraLen
;
922 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
924 wxUint16 nameLen
, extraLen
, commentLen
;
926 wxDataInputStream
ds(stream
);
928 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
930 SetVersionNeeded(ds
.Read16());
931 SetFlags(ds
.Read16());
932 SetMethod(ds
.Read16());
933 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
935 SetCompressedSize(ds
.Read32());
936 SetSize(ds
.Read32());
938 ds
>> nameLen
>> extraLen
>> commentLen
939 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
940 SetOffset(ds
.Read32());
942 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
944 if (extraLen
|| GetExtraLen()) {
945 Unique(m_Extra
, extraLen
);
947 stream
.Read(m_Extra
->GetData(), extraLen
);
951 m_Comment
= ReadString(stream
, commentLen
, conv
);
955 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
958 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
960 wxString unixName
= GetName(wxPATH_UNIX
);
961 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
962 const char *name
= name_buf
;
963 if (!name
) name
= "";
964 wxUint16 nameLen
= (wxUint16
)strlen(name
);
966 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
967 const char *comment
= comment_buf
;
968 if (!comment
) comment
= "";
969 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
971 wxUint16 extraLen
= (wxUint16
)GetExtraLen();
973 wxDataOutputStream
ds(stream
);
975 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
977 ds
.Write16((wxUint16
)GetVersionNeeded());
978 ds
.Write16((wxUint16
)GetFlags());
979 ds
.Write16((wxUint16
)GetMethod());
980 ds
.Write32(GetDateTime().GetAsDOS());
981 ds
.Write32(GetCrc());
982 ds
.Write32((wxUint32
)GetCompressedSize());
983 ds
.Write32((wxUint32
)GetSize());
985 ds
.Write16(extraLen
);
987 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
988 << m_ExternalAttributes
<< (wxUint32
)GetOffset();
990 stream
.Write(name
, nameLen
);
992 stream
.Write(GetExtra(), extraLen
);
993 stream
.Write(comment
, commentLen
);
995 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
998 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
999 // the 1st value is the signature then it is probably an info-zip record,
1000 // though there is a small chance that it is in fact a pkzip record which
1001 // happens to have the signature as it's CRC.
1003 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1005 wxDataInputStream
ds(stream
);
1007 m_Crc
= ds
.Read32();
1008 m_CompressedSize
= ds
.Read32();
1009 m_Size
= ds
.Read32();
1011 // if 1st value is the signature then this is probably an info-zip record
1012 if (m_Crc
== SUMS_MAGIC
)
1015 stream
.Read(buf
, sizeof(buf
));
1016 wxUint32 u1
= CrackUint32(buf
);
1017 wxUint32 u2
= CrackUint32(buf
+ 4);
1019 // look for the signature of the following record to decide which
1020 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1021 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1023 // it's a pkzip style record after all!
1024 stream
.Ungetch(buf
, sizeof(buf
));
1028 // it's an info-zip record as expected
1029 stream
.Ungetch(buf
+ 4, sizeof(buf
) - 4);
1030 m_Crc
= (wxUint32
)m_CompressedSize
;
1031 m_CompressedSize
= m_Size
;
1033 return SUMS_SIZE
+ 4;
1040 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1041 wxFileOffset compressedSize
, wxFileOffset size
)
1044 m_CompressedSize
= compressedSize
;
1047 wxDataOutputStream
ds(stream
);
1050 ds
.Write32((wxUint32
)compressedSize
);
1051 ds
.Write32((wxUint32
)size
);
1057 /////////////////////////////////////////////////////////////////////////////
1058 // wxZipEndRec - holds the end of central directory record
1065 int GetDiskNumber() const { return m_DiskNumber
; }
1066 int GetStartDisk() const { return m_StartDisk
; }
1067 int GetEntriesHere() const { return m_EntriesHere
; }
1068 int GetTotalEntries() const { return m_TotalEntries
; }
1069 wxFileOffset
GetSize() const { return m_Size
; }
1070 wxFileOffset
GetOffset() const { return m_Offset
; }
1071 wxString
GetComment() const { return m_Comment
; }
1073 void SetDiskNumber(int num
) { m_DiskNumber
= (wxUint16
)num
; }
1074 void SetStartDisk(int num
) { m_StartDisk
= (wxUint16
)num
; }
1075 void SetEntriesHere(int num
) { m_EntriesHere
= (wxUint16
)num
; }
1076 void SetTotalEntries(int num
) { m_TotalEntries
= (wxUint16
)num
; }
1077 void SetSize(wxFileOffset size
) { m_Size
= (wxUint32
)size
; }
1078 void SetOffset(wxFileOffset offset
) { m_Offset
= (wxUint32
)offset
; }
1079 void SetComment(const wxString
& comment
) { m_Comment
= comment
; }
1081 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1082 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1085 wxUint16 m_DiskNumber
;
1086 wxUint16 m_StartDisk
;
1087 wxUint16 m_EntriesHere
;
1088 wxUint16 m_TotalEntries
;
1094 wxZipEndRec::wxZipEndRec()
1104 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1106 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1107 const char *comment
= comment_buf
;
1108 if (!comment
) comment
= "";
1109 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1111 wxDataOutputStream
ds(stream
);
1113 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1114 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1116 stream
.Write(comment
, commentLen
);
1118 return stream
.IsOk();
1121 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1123 wxDataInputStream
ds(stream
);
1124 wxUint16 commentLen
;
1126 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1127 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1130 m_Comment
= ReadString(stream
, commentLen
, conv
);
1133 if (m_DiskNumber
== 0 && m_StartDisk
== 0 &&
1134 m_EntriesHere
== m_TotalEntries
)
1137 wxLogError(_("unsupported zip archive"));
1143 /////////////////////////////////////////////////////////////////////////////
1144 // A weak link from an input stream to an output stream
1146 class wxZipStreamLink
1149 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1151 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1152 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1154 void Release(class wxZipInputStream
*WXUNUSED(s
))
1155 { if (--m_ref
== 0) delete this; }
1156 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1157 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1160 ~wxZipStreamLink() { }
1163 wxZipOutputStream
*m_stream
;
1167 /////////////////////////////////////////////////////////////////////////////
1170 wxDECLARE_SCOPED_PTR(wxZipEntry
, _wxZipEntryPtr
)
1171 wxDEFINE_SCOPED_PTR (wxZipEntry
, _wxZipEntryPtr
)
1175 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1176 wxMBConv
& conv
/*=wxConvLocal*/)
1177 : wxArchiveInputStream(stream
, conv
)
1183 // Compatibility constructor
1185 wxZipInputStream::wxZipInputStream(const wxString
& archive
,
1186 const wxString
& file
)
1187 : wxArchiveInputStream(OpenFile(archive
), wxConvLocal
)
1189 // no error messages
1192 _wxZipEntryPtr entry
;
1194 if (m_ffile
->Ok()) {
1196 entry
.reset(GetNextEntry());
1198 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1201 if (entry
.get() == NULL
)
1202 m_lasterror
= wxSTREAM_READ_ERROR
;
1205 wxInputStream
& wxZipInputStream::OpenFile(const wxString
& archive
)
1208 m_ffile
= new wxFFileInputStream(archive
);
1212 void wxZipInputStream::Init()
1214 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1220 m_parentSeekable
= false;
1221 m_weaklinks
= new wxZipWeakLinks
;
1222 m_streamlink
= NULL
;
1223 m_offsetAdjustment
= 0;
1224 m_position
= wxInvalidOffset
;
1227 m_lasterror
= m_parent_i_stream
->GetLastError();
1230 wxZipInputStream::~wxZipInputStream()
1232 CloseDecompressor(m_decomp
);
1239 m_weaklinks
->Release(this);
1242 m_streamlink
->Release(this);
1245 wxString
wxZipInputStream::GetComment()
1247 if (m_position
== wxInvalidOffset
)
1248 if (!LoadEndRecord())
1249 return wxEmptyString
;
1251 if (!m_parentSeekable
&& Eof() && m_signature
) {
1252 m_lasterror
= wxSTREAM_NO_ERROR
;
1253 m_lasterror
= ReadLocal(true);
1259 int wxZipInputStream::GetTotalEntries()
1261 if (m_position
== wxInvalidOffset
)
1263 return m_TotalEntries
;
1266 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1268 wxZipStreamLink
*link
= NULL
;
1270 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1271 link
= new wxZipStreamLink(out
);
1273 m_streamlink
->Release(this);
1274 m_streamlink
= link
->AddRef();
1280 bool wxZipInputStream::LoadEndRecord()
1282 wxCHECK(m_position
== wxInvalidOffset
, false);
1288 // First find the end-of-central-directory record.
1289 if (!FindEndRecord()) {
1290 // failed, so either this is a non-seekable stream (ok), or not a zip
1291 if (m_parentSeekable
) {
1292 m_lasterror
= wxSTREAM_READ_ERROR
;
1293 wxLogError(_("invalid zip file"));
1298 wxFileOffset pos
= m_parent_i_stream
->TellI();
1300 //if (pos != wxInvalidOffset)
1301 if (pos
>= 0 && pos
<= LONG_MAX
)
1302 m_offsetAdjustment
= m_position
= pos
;
1309 // Read in the end record
1310 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1311 if (!endrec
.Read(*m_parent_i_stream
, GetConv())) {
1312 if (!*m_parent_i_stream
) {
1313 m_lasterror
= wxSTREAM_READ_ERROR
;
1316 // TODO: try this out
1317 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1320 m_TotalEntries
= endrec
.GetTotalEntries();
1321 m_Comment
= endrec
.GetComment();
1323 // Now find the central-directory. we have the file offset of
1324 // the CD, so look there first.
1325 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1326 ReadSignature() == CENTRAL_MAGIC
) {
1327 m_signature
= CENTRAL_MAGIC
;
1328 m_position
= endrec
.GetOffset();
1329 m_offsetAdjustment
= 0;
1333 // If it's not there, then it could be that the zip has been appended
1334 // to a self extractor, so take the CD size (also in endrec), subtract
1335 // it from the file offset of the end-central-directory and look there.
1336 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1337 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1338 m_signature
= CENTRAL_MAGIC
;
1339 m_position
= endPos
- endrec
.GetSize();
1340 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1344 wxLogError(_("can't find central directory in zip"));
1345 m_lasterror
= wxSTREAM_READ_ERROR
;
1349 // Find the end-of-central-directory record.
1350 // If found the stream will be positioned just past the 4 signature bytes.
1352 bool wxZipInputStream::FindEndRecord()
1354 if (!m_parent_i_stream
->IsSeekable())
1357 // usually it's 22 bytes in size and the last thing in the file
1360 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1364 m_parentSeekable
= true;
1367 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1369 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1372 // unfortunately, the record has a comment field that can be up to 65535
1373 // bytes in length, so if the signature not found then search backwards.
1374 wxFileOffset pos
= m_parent_i_stream
->TellI();
1375 const int BUFSIZE
= 1024;
1376 wxCharBuffer
buf(BUFSIZE
);
1378 memcpy(buf
.data(), magic
, 3);
1379 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1381 while (pos
> minpos
) {
1382 size_t len
= (size_t)(pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1383 memcpy(buf
.data() + len
, buf
, 3);
1386 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1387 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1390 char *p
= buf
.data() + len
;
1392 while (p
-- > buf
.data()) {
1393 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1394 size_t remainder
= buf
.data() + len
- p
;
1396 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1405 wxZipEntry
*wxZipInputStream::GetNextEntry()
1407 if (m_position
== wxInvalidOffset
)
1408 if (!LoadEndRecord())
1411 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1415 _wxZipEntryPtr
entry(new wxZipEntry(m_entry
));
1416 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1417 return entry
.release();
1420 wxStreamError
wxZipInputStream::ReadCentral()
1425 if (m_signature
== END_MAGIC
)
1426 return wxSTREAM_EOF
;
1428 if (m_signature
!= CENTRAL_MAGIC
) {
1429 wxLogError(_("error reading zip central directory"));
1430 return wxSTREAM_READ_ERROR
;
1433 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1434 return wxSTREAM_READ_ERROR
;
1436 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1437 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1439 return wxSTREAM_READ_ERROR
;
1442 m_signature
= ReadSignature();
1444 if (m_offsetAdjustment
)
1445 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1446 m_entry
.SetKey(m_entry
.GetOffset());
1448 return wxSTREAM_NO_ERROR
;
1451 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1457 m_signature
= ReadSignature();
1459 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1460 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1461 m_streamlink
->Release(this);
1462 m_streamlink
= NULL
;
1466 while (m_signature
== CENTRAL_MAGIC
) {
1467 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1468 return wxSTREAM_EOF
;
1470 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1472 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
)
1473 return wxSTREAM_READ_ERROR
;
1475 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1477 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1478 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1479 entry
->SetComment(m_entry
.GetComment());
1480 entry
->SetDiskStart(m_entry
.GetDiskStart());
1481 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1482 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1483 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1485 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1488 m_signature
= ReadSignature();
1491 if (m_signature
== END_MAGIC
) {
1492 if (readEndRec
|| m_streamlink
) {
1494 endrec
.Read(*m_parent_i_stream
, GetConv());
1495 m_Comment
= endrec
.GetComment();
1498 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1499 m_streamlink
->Release(this);
1500 m_streamlink
= NULL
;
1503 return wxSTREAM_EOF
;
1506 if (m_signature
!= LOCAL_MAGIC
) {
1507 wxLogError(_("error reading zip local header"));
1508 return wxSTREAM_READ_ERROR
;
1511 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1513 m_entry
.SetOffset(m_position
);
1514 m_entry
.SetKey(m_position
);
1516 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1517 return wxSTREAM_READ_ERROR
;
1520 return wxSTREAM_NO_ERROR
;
1524 wxUint32
wxZipInputStream::ReadSignature()
1527 m_parent_i_stream
->Read(magic
, 4);
1528 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1531 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1533 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1534 return zipEntry
? OpenEntry(*zipEntry
) : false;
1539 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1541 if (m_position
== wxInvalidOffset
)
1542 if (!LoadEndRecord())
1544 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1546 wxCHECK(!IsOpened(), false);
1551 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1553 // can only open the current entry on a non-seekable stream
1554 wxCHECK(m_parentSeekable
, false);
1557 m_lasterror
= wxSTREAM_READ_ERROR
;
1562 if (m_parentSeekable
) {
1563 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1566 if (ReadSignature() != LOCAL_MAGIC
) {
1567 wxLogError(_("bad zipfile offset to entry"));
1572 if (m_parentSeekable
|| AtHeader()) {
1573 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1574 if (m_parentSeekable
) {
1575 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1577 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1579 m_weaklinks
->RemoveEntry(ref
->GetKey());
1581 if (entry
&& entry
!= ref
) {
1582 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1588 m_lasterror
= m_parent_i_stream
->GetLastError();
1592 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1594 wxASSERT(AfterHeader());
1596 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1602 if (compressedSize
!= wxInvalidOffset
) {
1603 m_store
->Open(compressedSize
);
1607 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1608 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1611 if (compressedSize
!= wxInvalidOffset
&&
1612 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1613 wxZlibInputStream::CanHandleGZip())) {
1614 m_store
->Open(compressedSize
);
1615 m_decomp
= OpenDecompressor(*m_store
);
1617 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1621 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1622 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1626 // Can be overriden to add support for additional decompression methods
1628 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1630 switch (m_entry
.GetMethod()) {
1631 case wxZIP_METHOD_STORE
:
1632 if (m_entry
.GetSize() == wxInvalidOffset
) {
1633 wxLogError(_("stored file length not in Zip header"));
1636 m_store
->Open(m_entry
.GetSize());
1639 case wxZIP_METHOD_DEFLATE
:
1641 m_inflate
= new wxZlibInputStream2(stream
);
1643 m_inflate
->Open(stream
);
1647 wxLogError(_("unsupported Zip compression method"));
1653 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1655 if (decomp
&& decomp
== m_rawin
)
1656 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1657 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1662 // Closes the current entry and positions the underlying stream at the start
1663 // of the next entry
1665 bool wxZipInputStream::CloseEntry()
1669 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1672 if (!m_parentSeekable
) {
1673 if (!IsOpened() && !OpenDecompressor(true))
1676 const int BUFSIZE
= 8192;
1677 wxCharBuffer
buf(BUFSIZE
);
1679 Read(buf
.data(), BUFSIZE
);
1681 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1684 if (m_lasterror
== wxSTREAM_EOF
)
1685 m_lasterror
= wxSTREAM_NO_ERROR
;
1687 CloseDecompressor(m_decomp
);
1689 m_entry
= wxZipEntry();
1696 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1699 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1700 m_lasterror
= wxSTREAM_READ_ERROR
;
1701 if (!IsOk() || !size
)
1704 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1706 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1707 m_lasterror
= m_decomp
->GetLastError();
1710 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1711 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1712 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1715 entry
->SetCrc(m_entry
.GetCrc());
1716 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1717 entry
->SetSize(m_entry
.GetSize());
1723 m_lasterror
= wxSTREAM_READ_ERROR
;
1725 if (m_parent_i_stream
->IsOk()) {
1726 if (m_entry
.GetSize() != TellI())
1727 wxLogError(_("reading zip stream (entry %s): bad length"),
1728 m_entry
.GetName().c_str());
1729 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1730 wxLogError(_("reading zip stream (entry %s): bad crc"),
1731 m_entry
.GetName().c_str());
1733 m_lasterror
= wxSTREAM_EOF
;
1741 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1743 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1745 if (!m_ffile
|| AtHeader())
1746 return wxInvalidOffset
;
1748 // NB: since ZIP files don't natively support seeking, we have to
1749 // implement a brute force workaround -- reading all the data
1750 // between current and the new position (or between beginning of
1751 // the file and new position...)
1753 wxFileOffset nextpos
;
1754 wxFileOffset pos
= TellI();
1758 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1759 case wxFromStart
: nextpos
= seek
; break;
1760 case wxFromEnd
: nextpos
= GetLength() - 1 + seek
; break;
1761 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1765 if ( nextpos
>= pos
)
1767 toskip
= (size_t)(nextpos
- pos
);
1771 wxZipEntry
current(m_entry
);
1773 if (!OpenEntry(current
))
1775 m_lasterror
= wxSTREAM_READ_ERROR
;
1778 toskip
= (size_t)nextpos
;
1783 const size_t BUFSIZE
= 4096;
1785 char buffer
[BUFSIZE
];
1786 while ( toskip
> 0 )
1788 sz
= wxMin(toskip
, BUFSIZE
);
1799 /////////////////////////////////////////////////////////////////////////////
1802 #include "wx/listimpl.cpp"
1803 WX_DEFINE_LIST(_wxZipEntryList
);
1805 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1807 wxMBConv
& conv
/*=wxConvLocal*/)
1808 : wxArchiveOutputStream(stream
, conv
),
1809 m_store(new wxStoredOutputStream(stream
)),
1812 m_initialData(new char[OUTPUT_LATENCY
]),
1821 m_offsetAdjustment(wxInvalidOffset
)
1825 wxZipOutputStream::~wxZipOutputStream()
1828 WX_CLEAR_LIST(_wxZipEntryList
, m_entries
);
1832 delete [] m_initialData
;
1834 m_backlink
->Release(this);
1837 bool wxZipOutputStream::PutNextEntry(
1838 const wxString
& name
,
1839 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1840 wxFileOffset size
/*=wxInvalidOffset*/)
1842 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1845 bool wxZipOutputStream::PutNextDirEntry(
1846 const wxString
& name
,
1847 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1849 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1851 return PutNextEntry(entry
);
1854 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1855 wxZipInputStream
& inputStream
)
1857 _wxZipEntryPtr
e(entry
);
1860 inputStream
.DoOpen(e
.get(), true) &&
1861 DoCreate(e
.release(), true) &&
1862 Write(inputStream
).IsOk() && inputStream
.Eof();
1865 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1867 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1870 return PutNextEntry(zipEntry
);
1873 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1874 wxArchiveInputStream
& stream
)
1876 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1878 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
1883 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
1886 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
1888 m_Comment
= inputStream
.GetComment();
1890 m_backlink
->Release(this);
1891 m_backlink
= inputStream
.MakeLink(this);
1895 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
1897 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
1900 void wxZipOutputStream::SetLevel(int level
)
1902 if (level
!= m_level
) {
1903 if (m_comp
!= m_deflate
)
1910 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
1918 // write the signature bytes right away
1919 wxDataOutputStream
ds(*m_parent_o_stream
);
1922 // and if this is the first entry test for seekability
1923 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
1924 bool logging
= wxLog::IsEnabled();
1926 wxFileOffset here
= m_parent_o_stream
->TellO();
1928 if (here
!= wxInvalidOffset
&& here
>= 4) {
1929 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
1930 m_offsetAdjustment
= here
- 4;
1931 wxLog::EnableLogging(logging
);
1932 m_parent_o_stream
->SeekO(here
);
1937 m_pending
->SetOffset(m_headerOffset
);
1939 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1944 m_lasterror
= wxSTREAM_NO_ERROR
;
1948 // Can be overriden to add support for additional compression methods
1950 wxOutputStream
*wxZipOutputStream::OpenCompressor(
1951 wxOutputStream
& stream
,
1953 const Buffer bufs
[])
1955 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
1957 && (IsParentSeekable()
1958 || entry
.GetCompressedSize() != wxInvalidOffset
1959 || entry
.GetSize() != wxInvalidOffset
)) {
1960 entry
.SetMethod(wxZIP_METHOD_STORE
);
1963 for (int i
= 0; bufs
[i
].m_data
; ++i
)
1964 size
+= bufs
[i
].m_size
;
1965 entry
.SetMethod(size
<= 6 ?
1966 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
1970 switch (entry
.GetMethod()) {
1971 case wxZIP_METHOD_STORE
:
1972 if (entry
.GetCompressedSize() == wxInvalidOffset
)
1973 entry
.SetCompressedSize(entry
.GetSize());
1976 case wxZIP_METHOD_DEFLATE
:
1978 int defbits
= wxZIP_DEFLATE_NORMAL
;
1979 switch (GetLevel()) {
1981 defbits
= wxZIP_DEFLATE_SUPERFAST
;
1983 case 2: case 3: case 4:
1984 defbits
= wxZIP_DEFLATE_FAST
;
1987 defbits
= wxZIP_DEFLATE_EXTRA
;
1990 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
1991 defbits
| wxZIP_SUMS_FOLLOW
);
1994 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
1996 m_deflate
->Open(stream
);
2002 wxLogError(_("unsupported Zip compression method"));
2008 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2010 if (comp
== m_deflate
)
2012 else if (comp
!= m_store
)
2017 // This is called when OUPUT_LATENCY bytes has been written to the
2018 // wxZipOutputStream to actually create the zip entry.
2020 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2022 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2023 _wxZipEntryPtr
spPending(m_pending
);
2027 { m_initialData
, m_initialSize
},
2028 { (const char*)buffer
, size
},
2035 m_comp
= OpenCompressor(*m_store
, *spPending
,
2036 m_initialSize
? bufs
: bufs
+ 1);
2038 if (IsParentSeekable()
2039 || (spPending
->m_Crc
2040 && spPending
->m_CompressedSize
!= wxInvalidOffset
2041 && spPending
->m_Size
!= wxInvalidOffset
))
2042 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2044 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2045 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2047 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2048 m_lasterror
= m_parent_o_stream
->GetLastError();
2051 m_entries
.push_back(spPending
.release());
2052 OnSysWrite(m_initialData
, m_initialSize
);
2058 // This is called to write out the zip entry when Close has been called
2059 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2061 void wxZipOutputStream::CreatePendingEntry()
2063 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2064 _wxZipEntryPtr
spPending(m_pending
);
2066 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2069 // Initially compresses the data to memory, then fall back to 'store'
2070 // if the compressor makes the data larger rather than smaller.
2071 wxMemoryOutputStream mem
;
2072 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2073 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2077 if (comp
!= m_store
) {
2078 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2079 CloseCompressor(comp
);
2084 m_entrySize
= m_initialSize
;
2085 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2087 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2088 m_initialSize
= mem
.GetSize();
2089 mem
.CopyTo(m_initialData
, m_initialSize
);
2091 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2094 spPending
->SetSize(m_entrySize
);
2095 spPending
->SetCrc(m_crcAccumulator
);
2096 spPending
->SetCompressedSize(m_initialSize
);
2099 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2100 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2102 if (m_parent_o_stream
->IsOk()) {
2103 m_entries
.push_back(spPending
.release());
2105 m_store
->Write(m_initialData
, m_initialSize
);
2109 m_lasterror
= m_parent_o_stream
->GetLastError();
2112 // Write the 'central directory' and the 'end-central-directory' records.
2114 bool wxZipOutputStream::Close()
2118 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2123 endrec
.SetEntriesHere(m_entries
.size());
2124 endrec
.SetTotalEntries(m_entries
.size());
2125 endrec
.SetOffset(m_headerOffset
);
2126 endrec
.SetComment(m_Comment
);
2128 _wxZipEntryList::iterator it
;
2129 wxFileOffset size
= 0;
2131 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2132 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2137 endrec
.SetSize(size
);
2138 endrec
.Write(*m_parent_o_stream
, GetConv());
2140 m_lasterror
= m_parent_o_stream
->GetLastError();
2143 m_lasterror
= wxSTREAM_EOF
;
2147 // Finish writing the current entry
2149 bool wxZipOutputStream::CloseEntry()
2151 if (IsOk() && m_pending
)
2152 CreatePendingEntry();
2158 CloseCompressor(m_comp
);
2161 wxFileOffset compressedSize
= m_store
->TellO();
2163 wxZipEntry
& entry
= *m_entries
.back();
2165 // When writing raw the crc and size can't be checked
2167 m_crcAccumulator
= entry
.GetCrc();
2168 m_entrySize
= entry
.GetSize();
2171 // Write the sums in the trailing 'data descriptor' if necessary
2172 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2173 wxASSERT(!IsParentSeekable());
2175 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2176 compressedSize
, m_entrySize
);
2177 m_lasterror
= m_parent_o_stream
->GetLastError();
2180 // If the local header didn't have the correct crc and size written to
2181 // it then seek back and fix it
2182 else if (m_crcAccumulator
!= entry
.GetCrc()
2183 || m_entrySize
!= entry
.GetSize()
2184 || compressedSize
!= entry
.GetCompressedSize())
2186 if (IsParentSeekable()) {
2187 wxFileOffset here
= m_parent_o_stream
->TellO();
2188 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2189 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2190 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2191 compressedSize
, m_entrySize
);
2192 m_parent_o_stream
->SeekO(here
);
2193 m_lasterror
= m_parent_o_stream
->GetLastError();
2195 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2199 m_headerOffset
+= m_headerSize
+ compressedSize
;
2206 m_lasterror
= m_parent_o_stream
->GetLastError();
2208 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2209 entry
.GetName().c_str());
2213 void wxZipOutputStream::Sync()
2215 if (IsOk() && m_pending
)
2216 CreatePendingEntry(NULL
, 0);
2218 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2221 m_lasterror
= m_comp
->GetLastError();
2225 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2227 if (IsOk() && m_pending
) {
2228 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2229 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2230 m_initialSize
+= size
;
2233 CreatePendingEntry(buffer
, size
);
2238 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2239 if (!IsOk() || !size
)
2242 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2243 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2244 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2245 m_entrySize
+= m_comp
->LastWrite();
2247 return m_comp
->LastWrite();
2250 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM