1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
6 // Copyright: (c) Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
21 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
23 #include "wx/zipstrm.h"
26 #include "wx/datstrm.h"
27 #include "wx/zstream.h"
28 #include "wx/mstream.h"
30 #include "wx/buffer.h"
31 #include "wx/ptr_scpd.h"
32 #include "wx/wfstream.h"
36 // value for the 'version needed to extract' field (20 means 2.0)
38 VERSION_NEEDED_TO_EXTRACT
= 20
41 // signatures for the various records (PKxx)
43 CENTRAL_MAGIC
= 0x02014b50, // central directory record
44 LOCAL_MAGIC
= 0x04034b50, // local header
45 END_MAGIC
= 0x06054b50, // end of central directory record
46 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
49 // unix file attributes. zip stores them in the high 16 bits of the
50 // 'external attributes' field, hence the extra zeros.
52 wxZIP_S_IFMT
= 0xF0000000,
53 wxZIP_S_IFDIR
= 0x40000000,
54 wxZIP_S_IFREG
= 0x80000000
57 // minimum sizes for the various records
65 // The number of bytes that must be written to an wxZipOutputStream before
66 // a zip entry is created. The purpose of this latency is so that
67 // OpenCompressor() can see a little data before deciding which compressor
73 // Some offsets into the local header
78 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
79 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
81 wxFORCE_LINK_THIS_MODULE(zipstrm
)
84 /////////////////////////////////////////////////////////////////////////////
87 // read a string of a given length
89 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
92 wxCharBuffer
buf(len
);
93 stream
.Read(buf
.data(), len
);
94 wxString
str(buf
, conv
);
99 wxStringBuffer
buf(str
, len
);
100 stream
.Read(buf
, len
);
107 // Decode a little endian wxUint32 number from a character array
109 static inline wxUint32
CrackUint32(const char *m
)
111 const unsigned char *n
= (const unsigned char*)m
;
112 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
115 // Temporarily lower the logging level in debug mode to avoid a warning
116 // from SeekI about seeking on a stream with data written back to it.
118 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
121 wxLogLevel level
= wxLog::GetLogLevel();
122 wxLog::SetLogLevel(wxLOG_Debug
- 1);
123 wxFileOffset result
= stream
.SeekI(pos
);
124 wxLog::SetLogLevel(level
);
127 return stream
.SeekI(pos
);
132 /////////////////////////////////////////////////////////////////////////////
133 // Stored input stream
134 // Trival decompressor for files which are 'stored' in the zip file.
136 class wxStoredInputStream
: public wxFilterInputStream
139 wxStoredInputStream(wxInputStream
& stream
);
141 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
142 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
144 virtual char Peek() { return wxInputStream::Peek(); }
145 virtual wxFileOffset
GetLength() const { return m_len
; }
148 virtual size_t OnSysRead(void *buffer
, size_t size
);
149 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
155 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
158 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
159 : wxFilterInputStream(stream
),
165 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
167 size_t count
= wxMin(size
, wx_truncate_cast(size_t, m_len
- m_pos
));
168 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
172 m_lasterror
= wxSTREAM_EOF
;
173 else if (!*m_parent_i_stream
)
174 m_lasterror
= wxSTREAM_READ_ERROR
;
180 /////////////////////////////////////////////////////////////////////////////
181 // Stored output stream
182 // Trival compressor for files which are 'stored' in the zip file.
184 class wxStoredOutputStream
: public wxFilterOutputStream
187 wxStoredOutputStream(wxOutputStream
& stream
) :
188 wxFilterOutputStream(stream
), m_pos(0) { }
192 m_lasterror
= wxSTREAM_NO_ERROR
;
197 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
198 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
202 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
205 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
207 if (!IsOk() || !size
)
209 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
211 m_lasterror
= wxSTREAM_WRITE_ERROR
;
217 /////////////////////////////////////////////////////////////////////////////
220 // Used to handle the unusal case of raw copying an entry of unknown
221 // length. This can only happen when the zip being copied from is being
222 // read from a non-seekable stream, and also was original written to a
223 // non-seekable stream.
225 // In this case there's no option but to decompress the stream to find
226 // it's length, but we can still write the raw compressed data to avoid the
227 // compression overhead (which is the greater one).
229 // Usage is like this:
230 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
231 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
233 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
234 // is something like the unix 'tee' command; it is a transparent filter, but
235 // allows the data read to be read a second time via an extra method 'GetData'.
237 // The wxRawInputStream then draws data through the tee using a decompressor
238 // then instead of returning the decompressed data, retuns the raw data
239 // from wxTeeInputStream::GetData().
241 class wxTeeInputStream
: public wxFilterInputStream
244 wxTeeInputStream(wxInputStream
& stream
);
246 size_t GetCount() const { return m_end
- m_start
; }
247 size_t GetData(char *buffer
, size_t size
);
252 wxInputStream
& Read(void *buffer
, size_t size
);
255 virtual size_t OnSysRead(void *buffer
, size_t size
);
256 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
260 wxMemoryBuffer m_buf
;
264 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
267 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
268 : wxFilterInputStream(stream
),
269 m_pos(0), m_buf(8192), m_start(0), m_end(0)
273 void wxTeeInputStream::Open()
275 m_pos
= m_start
= m_end
= 0;
276 m_lasterror
= wxSTREAM_NO_ERROR
;
279 bool wxTeeInputStream::Final()
281 bool final
= m_end
== m_buf
.GetDataLen();
282 m_end
= m_buf
.GetDataLen();
286 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
288 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
289 m_end
= m_buf
.GetDataLen();
290 m_buf
.AppendData(buffer
, count
);
294 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
296 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
297 m_lasterror
= m_parent_i_stream
->GetLastError();
301 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
304 size_t len
= m_buf
.GetDataLen();
305 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
306 m_buf
.SetDataLen(len
);
308 wxFAIL
; // we've already returned data that's now being ungot
311 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
318 if (size
> GetCount())
321 memcpy(buffer
, m_buf
+ m_start
, size
);
323 wxASSERT(m_start
<= m_end
);
326 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
327 size_t len
= m_buf
.GetDataLen();
328 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
330 memmove(buf
, buf
+ m_end
, len
);
331 m_buf
.UngetWriteBuf(len
);
338 class wxRawInputStream
: public wxFilterInputStream
341 wxRawInputStream(wxInputStream
& stream
);
342 virtual ~wxRawInputStream() { delete m_tee
; }
344 wxInputStream
* Open(wxInputStream
*decomp
);
345 wxInputStream
& GetTee() const { return *m_tee
; }
348 virtual size_t OnSysRead(void *buffer
, size_t size
);
349 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
353 wxTeeInputStream
*m_tee
;
355 enum { BUFSIZE
= 8192 };
356 wxCharBuffer m_dummy
;
358 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
361 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
362 : wxFilterInputStream(stream
),
364 m_tee(new wxTeeInputStream(stream
)),
369 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
372 m_parent_i_stream
= decomp
;
374 m_lasterror
= wxSTREAM_NO_ERROR
;
382 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
384 char *buf
= (char*)buffer
;
387 while (count
< size
&& IsOk())
389 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
390 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
392 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
395 if (n
== 0 && m_tee
->Final())
396 m_lasterror
= m_parent_i_stream
->GetLastError();
404 /////////////////////////////////////////////////////////////////////////////
405 // Zlib streams than can be reused without recreating.
407 class wxZlibOutputStream2
: public wxZlibOutputStream
410 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
411 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
413 bool Open(wxOutputStream
& stream
);
414 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
417 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
419 wxCHECK(m_pos
== wxInvalidOffset
, false);
421 m_deflate
->next_out
= m_z_buffer
;
422 m_deflate
->avail_out
= m_z_size
;
424 m_lasterror
= wxSTREAM_NO_ERROR
;
425 m_parent_o_stream
= &stream
;
427 if (deflateReset(m_deflate
) != Z_OK
) {
428 wxLogError(_("can't re-initialize zlib deflate stream"));
429 m_lasterror
= wxSTREAM_WRITE_ERROR
;
436 class wxZlibInputStream2
: public wxZlibInputStream
439 wxZlibInputStream2(wxInputStream
& stream
) :
440 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
442 bool Open(wxInputStream
& stream
);
445 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
447 m_inflate
->avail_in
= 0;
449 m_lasterror
= wxSTREAM_NO_ERROR
;
450 m_parent_i_stream
= &stream
;
452 if (inflateReset(m_inflate
) != Z_OK
) {
453 wxLogError(_("can't re-initialize zlib inflate stream"));
454 m_lasterror
= wxSTREAM_READ_ERROR
;
462 /////////////////////////////////////////////////////////////////////////////
463 // Class to hold wxZipEntry's Extra and LocalExtra fields
468 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
470 wxZipMemory
*AddRef() { m_ref
++; return this; }
471 void Release() { if (--m_ref
== 0) delete this; }
473 char *GetData() const { return m_data
; }
474 size_t GetSize() const { return m_size
; }
475 size_t GetCapacity() const { return m_capacity
; }
477 wxZipMemory
*Unique(size_t size
);
480 ~wxZipMemory() { delete [] m_data
; }
488 wxZipMemory
*wxZipMemory::Unique(size_t size
)
494 zm
= new wxZipMemory
;
499 if (zm
->m_capacity
< size
) {
500 delete [] zm
->m_data
;
501 zm
->m_data
= new char[size
];
502 zm
->m_capacity
= size
;
509 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
516 static inline void Release(wxZipMemory
*zm
)
522 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
528 static void Unique(wxZipMemory
*& zm
, size_t size
)
531 zm
= new wxZipMemory
;
533 zm
= zm
->Unique(size
);
537 /////////////////////////////////////////////////////////////////////////////
538 // Collection of weak references to entries
540 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
541 wxIntegerEqual
, wx__OffsetZipEntryMap
);
546 wxZipWeakLinks() : m_ref(1) { }
548 void Release(const wxZipInputStream
* WXUNUSED(x
))
549 { if (--m_ref
== 0) delete this; }
550 void Release(wxFileOffset key
)
551 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
553 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
554 void RemoveEntry(wxFileOffset key
)
555 { m_entries
.erase((wx__OffsetZipEntryMap::key_type
)key
); }
556 wxZipEntry
*GetEntry(wxFileOffset key
) const;
557 bool IsEmpty() const { return m_entries
.empty(); }
560 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
563 wx__OffsetZipEntryMap m_entries
;
566 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
568 m_entries
[(wx__OffsetZipEntryMap::key_type
)key
] = entry
;
573 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
575 wx__OffsetZipEntryMap::const_iterator it
=
576 m_entries
.find((wx__OffsetZipEntryMap::key_type
)key
);
577 return it
!= m_entries
.end() ? it
->second
: NULL
;
581 /////////////////////////////////////////////////////////////////////////////
584 wxZipEntry::wxZipEntry(
585 const wxString
& name
/*=wxEmptyString*/,
586 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
587 wxFileOffset size
/*=wxInvalidOffset*/)
589 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
590 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
591 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
593 m_Method(wxZIP_METHOD_DEFAULT
),
596 m_CompressedSize(wxInvalidOffset
),
598 m_Key(wxInvalidOffset
),
599 m_Offset(wxInvalidOffset
),
601 m_InternalAttributes(0),
602 m_ExternalAttributes(0),
612 wxZipEntry::~wxZipEntry()
615 m_backlink
->Release(m_Key
);
617 Release(m_LocalExtra
);
620 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
622 m_SystemMadeBy(e
.m_SystemMadeBy
),
623 m_VersionMadeBy(e
.m_VersionMadeBy
),
624 m_VersionNeeded(e
.m_VersionNeeded
),
626 m_Method(e
.m_Method
),
627 m_DateTime(e
.m_DateTime
),
629 m_CompressedSize(e
.m_CompressedSize
),
633 m_Offset(e
.m_Offset
),
634 m_Comment(e
.m_Comment
),
635 m_DiskStart(e
.m_DiskStart
),
636 m_InternalAttributes(e
.m_InternalAttributes
),
637 m_ExternalAttributes(e
.m_ExternalAttributes
),
638 m_Extra(AddRef(e
.m_Extra
)),
639 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
645 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
648 m_SystemMadeBy
= e
.m_SystemMadeBy
;
649 m_VersionMadeBy
= e
.m_VersionMadeBy
;
650 m_VersionNeeded
= e
.m_VersionNeeded
;
652 m_Method
= e
.m_Method
;
653 m_DateTime
= e
.m_DateTime
;
655 m_CompressedSize
= e
.m_CompressedSize
;
659 m_Offset
= e
.m_Offset
;
660 m_Comment
= e
.m_Comment
;
661 m_DiskStart
= e
.m_DiskStart
;
662 m_InternalAttributes
= e
.m_InternalAttributes
;
663 m_ExternalAttributes
= e
.m_ExternalAttributes
;
664 Copy(m_Extra
, e
.m_Extra
);
665 Copy(m_LocalExtra
, e
.m_LocalExtra
);
666 m_zipnotifier
= NULL
;
668 m_backlink
->Release(m_Key
);
675 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
677 bool isDir
= IsDir() && !m_Name
.empty();
679 // optimisations for common (and easy) cases
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
= (wxUint8
)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
= (wxUint16
)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
? (wxUint32
)m_CompressedSize
: 0);
906 ds
.Write32(m_Size
!= wxInvalidOffset
? (wxUint32
)m_Size
: 0);
909 wxUint16 extraLen
= (wxUint16
)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
= (wxUint16
)strlen(name
);
963 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
964 const char *comment
= comment_buf
;
965 if (!comment
) comment
= "";
966 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
968 wxUint16 extraLen
= (wxUint16
)GetExtraLen();
970 wxDataOutputStream
ds(stream
);
972 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
974 ds
.Write16((wxUint16
)GetVersionNeeded());
975 ds
.Write16((wxUint16
)GetFlags());
976 ds
.Write16((wxUint16
)GetMethod());
977 ds
.Write32(GetDateTime().GetAsDOS());
978 ds
.Write32(GetCrc());
979 ds
.Write32((wxUint32
)GetCompressedSize());
980 ds
.Write32((wxUint32
)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
= (wxUint32
)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((wxUint32
)compressedSize
);
1048 ds
.Write32((wxUint32
)size
);
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
= (wxUint16
)num
; }
1071 void SetStartDisk(int num
) { m_StartDisk
= (wxUint16
)num
; }
1072 void SetEntriesHere(int num
) { m_EntriesHere
= (wxUint16
)num
; }
1073 void SetTotalEntries(int num
) { m_TotalEntries
= (wxUint16
)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
= (wxUint16
)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 // leave the default wxZipEntryPtr free for users
1168 wxDECLARE_SCOPED_PTR(wxZipEntry
, wx__ZipEntryPtr
)
1169 wxDEFINE_SCOPED_PTR (wxZipEntry
, wx__ZipEntryPtr
)
1173 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1174 wxMBConv
& conv
/*=wxConvLocal*/)
1175 : wxArchiveInputStream(stream
, conv
)
1180 #if 1 //WXWIN_COMPATIBILITY_2_6
1182 // Part of the compatibility constructor, which has been made inline to
1183 // avoid a problem with it not being exported by mingw 3.2.3
1185 void wxZipInputStream::Init(const wxString
& file
)
1187 // no error messages
1190 m_allowSeeking
= true;
1191 m_ffile
= wx_static_cast(wxFFileInputStream
*, m_parent_i_stream
);
1192 wx__ZipEntryPtr 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 return *new wxFFileInputStream(archive
);
1211 #endif // WXWIN_COMPATIBILITY_2_6
1213 void wxZipInputStream::Init()
1215 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1221 m_parentSeekable
= false;
1222 m_weaklinks
= new wxZipWeakLinks
;
1223 m_streamlink
= NULL
;
1224 m_offsetAdjustment
= 0;
1225 m_position
= wxInvalidOffset
;
1228 m_lasterror
= m_parent_i_stream
->GetLastError();
1230 #if 1 //WXWIN_COMPATIBILITY_2_6
1231 m_allowSeeking
= false;
1235 wxZipInputStream::~wxZipInputStream()
1237 CloseDecompressor(m_decomp
);
1244 m_weaklinks
->Release(this);
1247 m_streamlink
->Release(this);
1250 wxString
wxZipInputStream::GetComment()
1252 if (m_position
== wxInvalidOffset
)
1253 if (!LoadEndRecord())
1254 return wxEmptyString
;
1256 if (!m_parentSeekable
&& Eof() && m_signature
) {
1257 m_lasterror
= wxSTREAM_NO_ERROR
;
1258 m_lasterror
= ReadLocal(true);
1264 int wxZipInputStream::GetTotalEntries()
1266 if (m_position
== wxInvalidOffset
)
1268 return m_TotalEntries
;
1271 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1273 wxZipStreamLink
*link
= NULL
;
1275 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1276 link
= new wxZipStreamLink(out
);
1278 m_streamlink
->Release(this);
1279 m_streamlink
= link
->AddRef();
1285 bool wxZipInputStream::LoadEndRecord()
1287 wxCHECK(m_position
== wxInvalidOffset
, false);
1293 // First find the end-of-central-directory record.
1294 if (!FindEndRecord()) {
1295 // failed, so either this is a non-seekable stream (ok), or not a zip
1296 if (m_parentSeekable
) {
1297 m_lasterror
= wxSTREAM_READ_ERROR
;
1298 wxLogError(_("invalid zip file"));
1303 wxFileOffset pos
= m_parent_i_stream
->TellI();
1305 //if (pos != wxInvalidOffset)
1306 if (pos
>= 0 && pos
<= LONG_MAX
)
1307 m_offsetAdjustment
= m_position
= pos
;
1314 // Read in the end record
1315 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1316 if (!endrec
.Read(*m_parent_i_stream
, GetConv())) {
1317 if (!*m_parent_i_stream
) {
1318 m_lasterror
= wxSTREAM_READ_ERROR
;
1321 // TODO: try this out
1322 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1325 m_TotalEntries
= endrec
.GetTotalEntries();
1326 m_Comment
= endrec
.GetComment();
1328 // Now find the central-directory. we have the file offset of
1329 // the CD, so look there first.
1330 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1331 ReadSignature() == CENTRAL_MAGIC
) {
1332 m_signature
= CENTRAL_MAGIC
;
1333 m_position
= endrec
.GetOffset();
1334 m_offsetAdjustment
= 0;
1338 // If it's not there, then it could be that the zip has been appended
1339 // to a self extractor, so take the CD size (also in endrec), subtract
1340 // it from the file offset of the end-central-directory and look there.
1341 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1342 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1343 m_signature
= CENTRAL_MAGIC
;
1344 m_position
= endPos
- endrec
.GetSize();
1345 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1349 wxLogError(_("can't find central directory in zip"));
1350 m_lasterror
= wxSTREAM_READ_ERROR
;
1354 // Find the end-of-central-directory record.
1355 // If found the stream will be positioned just past the 4 signature bytes.
1357 bool wxZipInputStream::FindEndRecord()
1359 if (!m_parent_i_stream
->IsSeekable())
1362 // usually it's 22 bytes in size and the last thing in the file
1365 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1369 m_parentSeekable
= true;
1372 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1374 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1377 // unfortunately, the record has a comment field that can be up to 65535
1378 // bytes in length, so if the signature not found then search backwards.
1379 wxFileOffset pos
= m_parent_i_stream
->TellI();
1380 const int BUFSIZE
= 1024;
1381 wxCharBuffer
buf(BUFSIZE
);
1383 memcpy(buf
.data(), magic
, 3);
1384 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1386 while (pos
> minpos
) {
1387 size_t len
= (size_t)(pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1388 memcpy(buf
.data() + len
, buf
, 3);
1391 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1392 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1395 char *p
= buf
.data() + len
;
1397 while (p
-- > buf
.data()) {
1398 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1399 size_t remainder
= buf
.data() + len
- p
;
1401 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1410 wxZipEntry
*wxZipInputStream::GetNextEntry()
1412 if (m_position
== wxInvalidOffset
)
1413 if (!LoadEndRecord())
1416 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1420 wx__ZipEntryPtr
entry(new wxZipEntry(m_entry
));
1421 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1422 return entry
.release();
1425 wxStreamError
wxZipInputStream::ReadCentral()
1430 if (m_signature
== END_MAGIC
)
1431 return wxSTREAM_EOF
;
1433 if (m_signature
!= CENTRAL_MAGIC
) {
1434 wxLogError(_("error reading zip central directory"));
1435 return wxSTREAM_READ_ERROR
;
1438 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1439 return wxSTREAM_READ_ERROR
;
1441 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1442 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1444 return wxSTREAM_READ_ERROR
;
1447 m_signature
= ReadSignature();
1449 if (m_offsetAdjustment
)
1450 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1451 m_entry
.SetKey(m_entry
.GetOffset());
1453 return wxSTREAM_NO_ERROR
;
1456 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1462 m_signature
= ReadSignature();
1464 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1465 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1466 m_streamlink
->Release(this);
1467 m_streamlink
= NULL
;
1471 while (m_signature
== CENTRAL_MAGIC
) {
1472 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1473 return wxSTREAM_EOF
;
1475 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1477 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
)
1478 return wxSTREAM_READ_ERROR
;
1480 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1482 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1483 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1484 entry
->SetComment(m_entry
.GetComment());
1485 entry
->SetDiskStart(m_entry
.GetDiskStart());
1486 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1487 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1488 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1490 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1493 m_signature
= ReadSignature();
1496 if (m_signature
== END_MAGIC
) {
1497 if (readEndRec
|| m_streamlink
) {
1499 endrec
.Read(*m_parent_i_stream
, GetConv());
1500 m_Comment
= endrec
.GetComment();
1503 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1504 m_streamlink
->Release(this);
1505 m_streamlink
= NULL
;
1508 return wxSTREAM_EOF
;
1511 if (m_signature
!= LOCAL_MAGIC
) {
1512 wxLogError(_("error reading zip local header"));
1513 return wxSTREAM_READ_ERROR
;
1516 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1518 m_entry
.SetOffset(m_position
);
1519 m_entry
.SetKey(m_position
);
1521 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1522 return wxSTREAM_READ_ERROR
;
1525 return wxSTREAM_NO_ERROR
;
1529 wxUint32
wxZipInputStream::ReadSignature()
1532 m_parent_i_stream
->Read(magic
, 4);
1533 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1536 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1538 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1539 return zipEntry
? OpenEntry(*zipEntry
) : false;
1544 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1546 if (m_position
== wxInvalidOffset
)
1547 if (!LoadEndRecord())
1549 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1551 wxCHECK(!IsOpened(), false);
1556 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1558 // can only open the current entry on a non-seekable stream
1559 wxCHECK(m_parentSeekable
, false);
1562 m_lasterror
= wxSTREAM_READ_ERROR
;
1567 if (m_parentSeekable
) {
1568 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1571 if (ReadSignature() != LOCAL_MAGIC
) {
1572 wxLogError(_("bad zipfile offset to entry"));
1577 if (m_parentSeekable
|| AtHeader()) {
1578 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1579 if (m_parentSeekable
) {
1580 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1582 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1584 m_weaklinks
->RemoveEntry(ref
->GetKey());
1586 if (entry
&& entry
!= ref
) {
1587 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1593 m_lasterror
= m_parent_i_stream
->GetLastError();
1597 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1599 wxASSERT(AfterHeader());
1601 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1607 if (compressedSize
!= wxInvalidOffset
) {
1608 m_store
->Open(compressedSize
);
1612 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1613 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1616 if (compressedSize
!= wxInvalidOffset
&&
1617 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1618 wxZlibInputStream::CanHandleGZip())) {
1619 m_store
->Open(compressedSize
);
1620 m_decomp
= OpenDecompressor(*m_store
);
1622 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1626 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1627 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1631 // Can be overriden to add support for additional decompression methods
1633 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1635 switch (m_entry
.GetMethod()) {
1636 case wxZIP_METHOD_STORE
:
1637 if (m_entry
.GetSize() == wxInvalidOffset
) {
1638 wxLogError(_("stored file length not in Zip header"));
1641 m_store
->Open(m_entry
.GetSize());
1644 case wxZIP_METHOD_DEFLATE
:
1646 m_inflate
= new wxZlibInputStream2(stream
);
1648 m_inflate
->Open(stream
);
1652 wxLogError(_("unsupported Zip compression method"));
1658 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1660 if (decomp
&& decomp
== m_rawin
)
1661 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1662 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1667 // Closes the current entry and positions the underlying stream at the start
1668 // of the next entry
1670 bool wxZipInputStream::CloseEntry()
1674 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1677 if (!m_parentSeekable
) {
1678 if (!IsOpened() && !OpenDecompressor(true))
1681 const int BUFSIZE
= 8192;
1682 wxCharBuffer
buf(BUFSIZE
);
1684 Read(buf
.data(), BUFSIZE
);
1686 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1689 if (m_lasterror
== wxSTREAM_EOF
)
1690 m_lasterror
= wxSTREAM_NO_ERROR
;
1692 CloseDecompressor(m_decomp
);
1694 m_entry
= wxZipEntry();
1701 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1704 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1705 m_lasterror
= wxSTREAM_READ_ERROR
;
1706 if (!IsOk() || !size
)
1709 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1711 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1712 m_lasterror
= m_decomp
->GetLastError();
1715 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1716 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1717 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1720 entry
->SetCrc(m_entry
.GetCrc());
1721 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1722 entry
->SetSize(m_entry
.GetSize());
1728 m_lasterror
= wxSTREAM_READ_ERROR
;
1730 if (m_parent_i_stream
->IsOk()) {
1731 if (m_entry
.GetSize() != TellI())
1732 wxLogError(_("reading zip stream (entry %s): bad length"),
1733 m_entry
.GetName().c_str());
1734 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1735 wxLogError(_("reading zip stream (entry %s): bad crc"),
1736 m_entry
.GetName().c_str());
1738 m_lasterror
= wxSTREAM_EOF
;
1746 #if 1 //WXWIN_COMPATIBILITY_2_6
1748 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1750 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1752 // seeking works when the stream is created with the compatibility
1754 if (!m_allowSeeking
)
1755 return wxInvalidOffset
;
1757 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1758 m_lasterror
= wxSTREAM_READ_ERROR
;
1760 return wxInvalidOffset
;
1762 // NB: since ZIP files don't natively support seeking, we have to
1763 // implement a brute force workaround -- reading all the data
1764 // between current and the new position (or between beginning of
1765 // the file and new position...)
1767 wxFileOffset nextpos
;
1768 wxFileOffset pos
= TellI();
1772 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1773 case wxFromStart
: nextpos
= seek
; break;
1774 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1775 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1778 size_t toskip
wxDUMMY_INITIALIZE(0);
1779 if ( nextpos
>= pos
)
1781 toskip
= (size_t)(nextpos
- pos
);
1785 wxZipEntry
current(m_entry
);
1787 if (!OpenEntry(current
))
1789 m_lasterror
= wxSTREAM_READ_ERROR
;
1792 toskip
= (size_t)nextpos
;
1797 const size_t BUFSIZE
= 4096;
1799 char buffer
[BUFSIZE
];
1800 while ( toskip
> 0 )
1802 sz
= wxMin(toskip
, BUFSIZE
);
1812 #endif // WXWIN_COMPATIBILITY_2_6
1815 /////////////////////////////////////////////////////////////////////////////
1818 #include "wx/listimpl.cpp"
1819 WX_DEFINE_LIST(wx__ZipEntryList
)
1821 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1823 wxMBConv
& conv
/*=wxConvLocal*/)
1824 : wxArchiveOutputStream(stream
, conv
),
1825 m_store(new wxStoredOutputStream(stream
)),
1828 m_initialData(new char[OUTPUT_LATENCY
]),
1837 m_offsetAdjustment(wxInvalidOffset
)
1841 wxZipOutputStream::~wxZipOutputStream()
1844 WX_CLEAR_LIST(wx__ZipEntryList
, m_entries
);
1848 delete [] m_initialData
;
1850 m_backlink
->Release(this);
1853 bool wxZipOutputStream::PutNextEntry(
1854 const wxString
& name
,
1855 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1856 wxFileOffset size
/*=wxInvalidOffset*/)
1858 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1861 bool wxZipOutputStream::PutNextDirEntry(
1862 const wxString
& name
,
1863 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1865 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1867 return PutNextEntry(entry
);
1870 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1871 wxZipInputStream
& inputStream
)
1873 wx__ZipEntryPtr
e(entry
);
1876 inputStream
.DoOpen(e
.get(), true) &&
1877 DoCreate(e
.release(), true) &&
1878 Write(inputStream
).IsOk() && inputStream
.Eof();
1881 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1883 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1886 return PutNextEntry(zipEntry
);
1889 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1890 wxArchiveInputStream
& stream
)
1892 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1894 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
1899 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
1902 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
1904 m_Comment
= inputStream
.GetComment();
1906 m_backlink
->Release(this);
1907 m_backlink
= inputStream
.MakeLink(this);
1911 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
1913 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
1916 void wxZipOutputStream::SetLevel(int level
)
1918 if (level
!= m_level
) {
1919 if (m_comp
!= m_deflate
)
1926 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
1934 // write the signature bytes right away
1935 wxDataOutputStream
ds(*m_parent_o_stream
);
1938 // and if this is the first entry test for seekability
1939 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
1941 bool logging
= wxLog::IsEnabled();
1944 wxFileOffset here
= m_parent_o_stream
->TellO();
1946 if (here
!= wxInvalidOffset
&& here
>= 4) {
1947 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
1948 m_offsetAdjustment
= here
- 4;
1950 wxLog::EnableLogging(logging
);
1952 m_parent_o_stream
->SeekO(here
);
1957 m_pending
->SetOffset(m_headerOffset
);
1959 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1964 m_lasterror
= wxSTREAM_NO_ERROR
;
1968 // Can be overriden to add support for additional compression methods
1970 wxOutputStream
*wxZipOutputStream::OpenCompressor(
1971 wxOutputStream
& stream
,
1973 const Buffer bufs
[])
1975 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
1977 && (IsParentSeekable()
1978 || entry
.GetCompressedSize() != wxInvalidOffset
1979 || entry
.GetSize() != wxInvalidOffset
)) {
1980 entry
.SetMethod(wxZIP_METHOD_STORE
);
1983 for (int i
= 0; bufs
[i
].m_data
; ++i
)
1984 size
+= bufs
[i
].m_size
;
1985 entry
.SetMethod(size
<= 6 ?
1986 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
1990 switch (entry
.GetMethod()) {
1991 case wxZIP_METHOD_STORE
:
1992 if (entry
.GetCompressedSize() == wxInvalidOffset
)
1993 entry
.SetCompressedSize(entry
.GetSize());
1996 case wxZIP_METHOD_DEFLATE
:
1998 int defbits
= wxZIP_DEFLATE_NORMAL
;
1999 switch (GetLevel()) {
2001 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2003 case 2: case 3: case 4:
2004 defbits
= wxZIP_DEFLATE_FAST
;
2007 defbits
= wxZIP_DEFLATE_EXTRA
;
2010 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2011 defbits
| wxZIP_SUMS_FOLLOW
);
2014 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2016 m_deflate
->Open(stream
);
2022 wxLogError(_("unsupported Zip compression method"));
2028 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2030 if (comp
== m_deflate
)
2032 else if (comp
!= m_store
)
2037 // This is called when OUPUT_LATENCY bytes has been written to the
2038 // wxZipOutputStream to actually create the zip entry.
2040 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2042 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2043 wx__ZipEntryPtr
spPending(m_pending
);
2047 { m_initialData
, m_initialSize
},
2048 { (const char*)buffer
, size
},
2055 m_comp
= OpenCompressor(*m_store
, *spPending
,
2056 m_initialSize
? bufs
: bufs
+ 1);
2058 if (IsParentSeekable()
2059 || (spPending
->m_Crc
2060 && spPending
->m_CompressedSize
!= wxInvalidOffset
2061 && spPending
->m_Size
!= wxInvalidOffset
))
2062 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2064 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2065 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2067 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2068 m_lasterror
= m_parent_o_stream
->GetLastError();
2071 m_entries
.push_back(spPending
.release());
2072 OnSysWrite(m_initialData
, m_initialSize
);
2078 // This is called to write out the zip entry when Close has been called
2079 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2081 void wxZipOutputStream::CreatePendingEntry()
2083 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2084 wx__ZipEntryPtr
spPending(m_pending
);
2086 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2089 // Initially compresses the data to memory, then fall back to 'store'
2090 // if the compressor makes the data larger rather than smaller.
2091 wxMemoryOutputStream mem
;
2092 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2093 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2097 if (comp
!= m_store
) {
2098 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2099 CloseCompressor(comp
);
2104 m_entrySize
= m_initialSize
;
2105 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2107 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2108 m_initialSize
= mem
.GetSize();
2109 mem
.CopyTo(m_initialData
, m_initialSize
);
2111 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2114 spPending
->SetSize(m_entrySize
);
2115 spPending
->SetCrc(m_crcAccumulator
);
2116 spPending
->SetCompressedSize(m_initialSize
);
2119 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2120 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2122 if (m_parent_o_stream
->IsOk()) {
2123 m_entries
.push_back(spPending
.release());
2125 m_store
->Write(m_initialData
, m_initialSize
);
2129 m_lasterror
= m_parent_o_stream
->GetLastError();
2132 // Write the 'central directory' and the 'end-central-directory' records.
2134 bool wxZipOutputStream::Close()
2138 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2143 endrec
.SetEntriesHere(m_entries
.size());
2144 endrec
.SetTotalEntries(m_entries
.size());
2145 endrec
.SetOffset(m_headerOffset
);
2146 endrec
.SetComment(m_Comment
);
2148 wx__ZipEntryList::iterator it
;
2149 wxFileOffset size
= 0;
2151 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2152 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2157 endrec
.SetSize(size
);
2158 endrec
.Write(*m_parent_o_stream
, GetConv());
2160 m_lasterror
= m_parent_o_stream
->GetLastError();
2163 m_lasterror
= wxSTREAM_EOF
;
2167 // Finish writing the current entry
2169 bool wxZipOutputStream::CloseEntry()
2171 if (IsOk() && m_pending
)
2172 CreatePendingEntry();
2178 CloseCompressor(m_comp
);
2181 wxFileOffset compressedSize
= m_store
->TellO();
2183 wxZipEntry
& entry
= *m_entries
.back();
2185 // When writing raw the crc and size can't be checked
2187 m_crcAccumulator
= entry
.GetCrc();
2188 m_entrySize
= entry
.GetSize();
2191 // Write the sums in the trailing 'data descriptor' if necessary
2192 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2193 wxASSERT(!IsParentSeekable());
2195 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2196 compressedSize
, m_entrySize
);
2197 m_lasterror
= m_parent_o_stream
->GetLastError();
2200 // If the local header didn't have the correct crc and size written to
2201 // it then seek back and fix it
2202 else if (m_crcAccumulator
!= entry
.GetCrc()
2203 || m_entrySize
!= entry
.GetSize()
2204 || compressedSize
!= entry
.GetCompressedSize())
2206 if (IsParentSeekable()) {
2207 wxFileOffset here
= m_parent_o_stream
->TellO();
2208 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2209 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2210 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2211 compressedSize
, m_entrySize
);
2212 m_parent_o_stream
->SeekO(here
);
2213 m_lasterror
= m_parent_o_stream
->GetLastError();
2215 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2219 m_headerOffset
+= m_headerSize
+ compressedSize
;
2226 m_lasterror
= m_parent_o_stream
->GetLastError();
2228 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2229 entry
.GetName().c_str());
2233 void wxZipOutputStream::Sync()
2235 if (IsOk() && m_pending
)
2236 CreatePendingEntry(NULL
, 0);
2238 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2241 m_lasterror
= m_comp
->GetLastError();
2245 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2247 if (IsOk() && m_pending
) {
2248 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2249 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2250 m_initialSize
+= size
;
2253 CreatePendingEntry(buffer
, size
);
2258 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2259 if (!IsOk() || !size
)
2262 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2263 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2264 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2265 m_entrySize
+= m_comp
->LastWrite();
2267 return m_comp
->LastWrite();
2270 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM