1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/zipstrm.cpp
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
6 // Copyright: (c) Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
17 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
25 #include "wx/zipstrm.h"
26 #include "wx/datstrm.h"
27 #include "wx/zstream.h"
28 #include "wx/mstream.h"
29 #include "wx/buffer.h"
30 #include "wx/ptr_scpd.h"
31 #include "wx/wfstream.h"
35 // value for the 'version needed to extract' field (20 means 2.0)
37 VERSION_NEEDED_TO_EXTRACT
= 20
40 // signatures for the various records (PKxx)
42 CENTRAL_MAGIC
= 0x02014b50, // central directory record
43 LOCAL_MAGIC
= 0x04034b50, // local header
44 END_MAGIC
= 0x06054b50, // end of central directory record
45 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
48 // unix file attributes. zip stores them in the high 16 bits of the
49 // 'external attributes' field, hence the extra zeros.
51 wxZIP_S_IFMT
= 0xF0000000,
52 wxZIP_S_IFDIR
= 0x40000000,
53 wxZIP_S_IFREG
= 0x80000000
56 // minimum sizes for the various records
64 // The number of bytes that must be written to an wxZipOutputStream before
65 // a zip entry is created. The purpose of this latency is so that
66 // OpenCompressor() can see a little data before deciding which compressor
72 // Some offsets into the local header
77 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
78 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
80 wxFORCE_LINK_THIS_MODULE(zipstrm
)
83 /////////////////////////////////////////////////////////////////////////////
86 // read a string of a given length
88 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
91 wxCharBuffer
buf(len
);
92 stream
.Read(buf
.data(), len
);
93 wxString
str(buf
, conv
);
98 wxStringBuffer
buf(str
, len
);
99 stream
.Read(buf
, len
);
106 // Decode a little endian wxUint32 number from a character array
108 static inline wxUint32
CrackUint32(const char *m
)
110 const unsigned char *n
= (const unsigned char*)m
;
111 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
114 // Decode a little endian wxUint16 number from a character array
116 static inline wxUint16
CrackUint16(const char *m
)
118 const unsigned char *n
= (const unsigned char*)m
;
119 return (n
[1] << 8) | n
[0];
122 // Temporarily lower the logging level in debug mode to avoid a warning
123 // from SeekI about seeking on a stream with data written back to it.
125 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
127 #if defined(__WXDEBUG__) && wxUSE_LOG
128 wxLogLevel level
= wxLog::GetLogLevel();
129 wxLog::SetLogLevel(wxLOG_Debug
- 1);
130 wxFileOffset result
= stream
.SeekI(pos
);
131 wxLog::SetLogLevel(level
);
134 return stream
.SeekI(pos
);
139 /////////////////////////////////////////////////////////////////////////////
145 wxZipHeader(wxInputStream
& stream
, size_t size
);
147 inline wxUint8
Read8();
148 inline wxUint16
Read16();
149 inline wxUint32
Read32();
151 const char *GetData() const { return m_data
; }
152 size_t GetSize() const { return m_size
; }
153 operator bool() const { return m_ok
; }
155 size_t Seek(size_t pos
) { m_pos
= pos
; return m_pos
; }
156 size_t Skip(size_t size
) { m_pos
+= size
; return m_pos
; }
158 wxZipHeader
& operator>>(wxUint8
& n
) { n
= Read8(); return *this; }
159 wxZipHeader
& operator>>(wxUint16
& n
) { n
= Read16(); return *this; }
160 wxZipHeader
& operator>>(wxUint32
& n
) { n
= Read32(); return *this; }
169 wxZipHeader::wxZipHeader(wxInputStream
& stream
, size_t size
)
174 wxCHECK_RET(size
<= sizeof(m_data
), _T("buffer too small"));
175 m_size
= stream
.Read(m_data
, size
).LastRead();
176 m_ok
= m_size
== size
;
179 wxUint8
wxZipHeader::Read8()
181 wxASSERT(m_pos
< m_size
);
182 return m_data
[m_pos
++];
185 wxUint16
wxZipHeader::Read16()
187 wxASSERT(m_pos
+ 2 <= m_size
);
188 wxUint16 n
= CrackUint16(m_data
+ m_pos
);
193 wxUint32
wxZipHeader::Read32()
195 wxASSERT(m_pos
+ 4 <= m_size
);
196 wxUint32 n
= CrackUint32(m_data
+ m_pos
);
202 /////////////////////////////////////////////////////////////////////////////
203 // Stored input stream
204 // Trival decompressor for files which are 'stored' in the zip file.
206 class wxStoredInputStream
: public wxFilterInputStream
209 wxStoredInputStream(wxInputStream
& stream
);
211 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
212 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
214 virtual char Peek() { return wxInputStream::Peek(); }
215 virtual wxFileOffset
GetLength() const { return m_len
; }
218 virtual size_t OnSysRead(void *buffer
, size_t size
);
219 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
225 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
228 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
229 : wxFilterInputStream(stream
),
235 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
237 size_t count
= wx_truncate_cast(size_t,
238 wxMin(size
+ wxFileOffset(0), m_len
- m_pos
+ size_t(0)));
239 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
243 m_lasterror
= m_pos
== m_len
? wxSTREAM_EOF
: wxSTREAM_READ_ERROR
;
249 /////////////////////////////////////////////////////////////////////////////
250 // Stored output stream
251 // Trival compressor for files which are 'stored' in the zip file.
253 class wxStoredOutputStream
: public wxFilterOutputStream
256 wxStoredOutputStream(wxOutputStream
& stream
) :
257 wxFilterOutputStream(stream
), m_pos(0) { }
261 m_lasterror
= wxSTREAM_NO_ERROR
;
266 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
267 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
271 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
274 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
276 if (!IsOk() || !size
)
278 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
280 m_lasterror
= wxSTREAM_WRITE_ERROR
;
286 /////////////////////////////////////////////////////////////////////////////
289 // Used to handle the unusal case of raw copying an entry of unknown
290 // length. This can only happen when the zip being copied from is being
291 // read from a non-seekable stream, and also was original written to a
292 // non-seekable stream.
294 // In this case there's no option but to decompress the stream to find
295 // it's length, but we can still write the raw compressed data to avoid the
296 // compression overhead (which is the greater one).
298 // Usage is like this:
299 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
300 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
302 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
303 // is something like the unix 'tee' command; it is a transparent filter, but
304 // allows the data read to be read a second time via an extra method 'GetData'.
306 // The wxRawInputStream then draws data through the tee using a decompressor
307 // then instead of returning the decompressed data, retuns the raw data
308 // from wxTeeInputStream::GetData().
310 class wxTeeInputStream
: public wxFilterInputStream
313 wxTeeInputStream(wxInputStream
& stream
);
315 size_t GetCount() const { return m_end
- m_start
; }
316 size_t GetData(char *buffer
, size_t size
);
321 wxInputStream
& Read(void *buffer
, size_t size
);
324 virtual size_t OnSysRead(void *buffer
, size_t size
);
325 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
329 wxMemoryBuffer m_buf
;
333 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
336 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
337 : wxFilterInputStream(stream
),
338 m_pos(0), m_buf(8192), m_start(0), m_end(0)
342 void wxTeeInputStream::Open()
344 m_pos
= m_start
= m_end
= 0;
345 m_lasterror
= wxSTREAM_NO_ERROR
;
348 bool wxTeeInputStream::Final()
350 bool final
= m_end
== m_buf
.GetDataLen();
351 m_end
= m_buf
.GetDataLen();
355 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
357 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
358 m_end
= m_buf
.GetDataLen();
359 m_buf
.AppendData(buffer
, count
);
363 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
365 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
367 m_lasterror
= m_parent_i_stream
->GetLastError();
371 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
374 size_t len
= m_buf
.GetDataLen();
375 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
376 m_buf
.SetDataLen(len
);
378 wxFAIL
; // we've already returned data that's now being ungot
381 m_parent_i_stream
->Reset();
382 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
389 if (size
> GetCount())
392 memcpy(buffer
, m_buf
+ m_start
, size
);
394 wxASSERT(m_start
<= m_end
);
397 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
398 size_t len
= m_buf
.GetDataLen();
399 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
401 memmove(buf
, buf
+ m_end
, len
);
402 m_buf
.UngetWriteBuf(len
);
409 class wxRawInputStream
: public wxFilterInputStream
412 wxRawInputStream(wxInputStream
& stream
);
413 virtual ~wxRawInputStream() { delete m_tee
; }
415 wxInputStream
* Open(wxInputStream
*decomp
);
416 wxInputStream
& GetTee() const { return *m_tee
; }
419 virtual size_t OnSysRead(void *buffer
, size_t size
);
420 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
424 wxTeeInputStream
*m_tee
;
426 enum { BUFSIZE
= 8192 };
427 wxCharBuffer m_dummy
;
429 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
432 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
433 : wxFilterInputStream(stream
),
435 m_tee(new wxTeeInputStream(stream
)),
440 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
443 m_parent_i_stream
= decomp
;
445 m_lasterror
= wxSTREAM_NO_ERROR
;
453 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
455 char *buf
= (char*)buffer
;
458 while (count
< size
&& IsOk())
460 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
461 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
463 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
466 if (n
== 0 && m_tee
->Final())
467 m_lasterror
= m_parent_i_stream
->GetLastError();
475 /////////////////////////////////////////////////////////////////////////////
476 // Zlib streams than can be reused without recreating.
478 class wxZlibOutputStream2
: public wxZlibOutputStream
481 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
482 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
484 bool Open(wxOutputStream
& stream
);
485 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
488 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
490 wxCHECK(m_pos
== wxInvalidOffset
, false);
492 m_deflate
->next_out
= m_z_buffer
;
493 m_deflate
->avail_out
= m_z_size
;
495 m_lasterror
= wxSTREAM_NO_ERROR
;
496 m_parent_o_stream
= &stream
;
498 if (deflateReset(m_deflate
) != Z_OK
) {
499 wxLogError(_("can't re-initialize zlib deflate stream"));
500 m_lasterror
= wxSTREAM_WRITE_ERROR
;
507 class wxZlibInputStream2
: public wxZlibInputStream
510 wxZlibInputStream2(wxInputStream
& stream
) :
511 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
513 bool Open(wxInputStream
& stream
);
516 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
518 m_inflate
->avail_in
= 0;
520 m_lasterror
= wxSTREAM_NO_ERROR
;
521 m_parent_i_stream
= &stream
;
523 if (inflateReset(m_inflate
) != Z_OK
) {
524 wxLogError(_("can't re-initialize zlib inflate stream"));
525 m_lasterror
= wxSTREAM_READ_ERROR
;
533 /////////////////////////////////////////////////////////////////////////////
534 // Class to hold wxZipEntry's Extra and LocalExtra fields
539 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
541 wxZipMemory
*AddRef() { m_ref
++; return this; }
542 void Release() { if (--m_ref
== 0) delete this; }
544 char *GetData() const { return m_data
; }
545 size_t GetSize() const { return m_size
; }
546 size_t GetCapacity() const { return m_capacity
; }
548 wxZipMemory
*Unique(size_t size
);
551 ~wxZipMemory() { delete [] m_data
; }
558 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipMemory
)
561 wxZipMemory
*wxZipMemory::Unique(size_t size
)
567 zm
= new wxZipMemory
;
572 if (zm
->m_capacity
< size
) {
573 delete [] zm
->m_data
;
574 zm
->m_data
= new char[size
];
575 zm
->m_capacity
= size
;
582 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
589 static inline void Release(wxZipMemory
*zm
)
595 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
601 static void Unique(wxZipMemory
*& zm
, size_t size
)
604 zm
= new wxZipMemory
;
606 zm
= zm
->Unique(size
);
610 /////////////////////////////////////////////////////////////////////////////
611 // Collection of weak references to entries
613 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
614 wxIntegerEqual
, wx__OffsetZipEntryMap
);
619 wxZipWeakLinks() : m_ref(1) { }
621 void Release(const wxZipInputStream
* WXUNUSED(x
))
622 { if (--m_ref
== 0) delete this; }
623 void Release(wxFileOffset key
)
624 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
626 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
627 void RemoveEntry(wxFileOffset key
)
628 { m_entries
.erase(wx_truncate_cast(key_type
, key
)); }
629 wxZipEntry
*GetEntry(wxFileOffset key
) const;
630 bool IsEmpty() const { return m_entries
.empty(); }
633 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
635 typedef wx__OffsetZipEntryMap::key_type key_type
;
638 wx__OffsetZipEntryMap m_entries
;
640 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipWeakLinks
)
643 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
645 m_entries
[wx_truncate_cast(key_type
, key
)] = entry
;
650 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
652 wx__OffsetZipEntryMap::const_iterator it
=
653 m_entries
.find(wx_truncate_cast(key_type
, key
));
654 return it
!= m_entries
.end() ? it
->second
: NULL
;
658 /////////////////////////////////////////////////////////////////////////////
661 wxZipEntry::wxZipEntry(
662 const wxString
& name
/*=wxEmptyString*/,
663 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
664 wxFileOffset size
/*=wxInvalidOffset*/)
666 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
667 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
668 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
670 m_Method(wxZIP_METHOD_DEFAULT
),
673 m_CompressedSize(wxInvalidOffset
),
675 m_Key(wxInvalidOffset
),
676 m_Offset(wxInvalidOffset
),
678 m_InternalAttributes(0),
679 m_ExternalAttributes(0),
689 wxZipEntry::~wxZipEntry()
692 m_backlink
->Release(m_Key
);
694 Release(m_LocalExtra
);
697 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
699 m_SystemMadeBy(e
.m_SystemMadeBy
),
700 m_VersionMadeBy(e
.m_VersionMadeBy
),
701 m_VersionNeeded(e
.m_VersionNeeded
),
703 m_Method(e
.m_Method
),
704 m_DateTime(e
.m_DateTime
),
706 m_CompressedSize(e
.m_CompressedSize
),
710 m_Offset(e
.m_Offset
),
711 m_Comment(e
.m_Comment
),
712 m_DiskStart(e
.m_DiskStart
),
713 m_InternalAttributes(e
.m_InternalAttributes
),
714 m_ExternalAttributes(e
.m_ExternalAttributes
),
715 m_Extra(AddRef(e
.m_Extra
)),
716 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
722 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
725 m_SystemMadeBy
= e
.m_SystemMadeBy
;
726 m_VersionMadeBy
= e
.m_VersionMadeBy
;
727 m_VersionNeeded
= e
.m_VersionNeeded
;
729 m_Method
= e
.m_Method
;
730 m_DateTime
= e
.m_DateTime
;
732 m_CompressedSize
= e
.m_CompressedSize
;
736 m_Offset
= e
.m_Offset
;
737 m_Comment
= e
.m_Comment
;
738 m_DiskStart
= e
.m_DiskStart
;
739 m_InternalAttributes
= e
.m_InternalAttributes
;
740 m_ExternalAttributes
= e
.m_ExternalAttributes
;
741 Copy(m_Extra
, e
.m_Extra
);
742 Copy(m_LocalExtra
, e
.m_LocalExtra
);
743 m_zipnotifier
= NULL
;
745 m_backlink
->Release(m_Key
);
752 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
754 bool isDir
= IsDir() && !m_Name
.empty();
756 // optimisations for common (and easy) cases
757 switch (wxFileName::GetFormat(format
)) {
760 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
761 for (size_t i
= name
.length() - 1; i
> 0; --i
)
762 if (name
[i
] == _T('/'))
768 return isDir
? m_Name
+ _T("/") : m_Name
;
777 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
779 fn
.Assign(m_Name
, wxPATH_UNIX
);
781 return fn
.GetFullPath(format
);
784 // Static - Internally tars and zips use forward slashes for the path
785 // separator, absolute paths aren't allowed, and directory names have a
786 // trailing slash. This function converts a path into this internal format,
787 // but without a trailing slash for a directory.
789 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
790 wxPathFormat format
/*=wxPATH_NATIVE*/,
791 bool *pIsDir
/*=NULL*/)
795 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
796 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
800 bool isDir
= !internal
.empty() && internal
.Last() == '/';
804 internal
.erase(internal
.length() - 1);
806 while (!internal
.empty() && *internal
.begin() == '/')
807 internal
.erase(0, 1);
808 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
809 internal
.erase(0, 2);
810 if (internal
== _T(".") || internal
== _T(".."))
811 internal
= wxEmptyString
;
816 void wxZipEntry::SetSystemMadeBy(int system
)
818 int mode
= GetMode();
819 bool wasUnix
= IsMadeByUnix();
821 m_SystemMadeBy
= (wxUint8
)system
;
823 if (!wasUnix
&& IsMadeByUnix()) {
826 } else if (wasUnix
&& !IsMadeByUnix()) {
827 m_ExternalAttributes
&= 0xffff;
831 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
834 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
836 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
838 if (IsMadeByUnix()) {
839 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
841 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
843 m_ExternalAttributes
|= wxZIP_S_IFREG
;
847 // Return unix style permission bits
849 int wxZipEntry::GetMode() const
851 // return unix permissions if present
853 return (m_ExternalAttributes
>> 16) & 0777;
855 // otherwise synthesize from the dos attribs
857 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
859 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
865 // Set unix permissions
867 void wxZipEntry::SetMode(int mode
)
869 // Set dos attrib bits to be compatible
871 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
873 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
875 // set the actual unix permission bits if the system type allows
876 if (IsMadeByUnix()) {
877 m_ExternalAttributes
&= ~(0777L << 16);
878 m_ExternalAttributes
|= (mode
& 0777L) << 16;
882 const char *wxZipEntry::GetExtra() const
884 return m_Extra
? m_Extra
->GetData() : NULL
;
887 size_t wxZipEntry::GetExtraLen() const
889 return m_Extra
? m_Extra
->GetSize() : 0;
892 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
894 Unique(m_Extra
, len
);
896 memcpy(m_Extra
->GetData(), extra
, len
);
899 const char *wxZipEntry::GetLocalExtra() const
901 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
904 size_t wxZipEntry::GetLocalExtraLen() const
906 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
909 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
911 Unique(m_LocalExtra
, len
);
913 memcpy(m_LocalExtra
->GetData(), extra
, len
);
916 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
918 wxArchiveEntry::UnsetNotifier();
919 m_zipnotifier
= ¬ifier
;
920 m_zipnotifier
->OnEntryUpdated(*this);
923 void wxZipEntry::Notify()
926 m_zipnotifier
->OnEntryUpdated(*this);
927 else if (GetNotifier())
928 GetNotifier()->OnEntryUpdated(*this);
931 void wxZipEntry::UnsetNotifier()
933 wxArchiveEntry::UnsetNotifier();
934 m_zipnotifier
= NULL
;
937 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
939 wxUint16 nameLen
, extraLen
;
940 wxUint32 compressedSize
, size
, crc
;
942 wxZipHeader
ds(stream
, LOCAL_SIZE
- 4);
946 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
947 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
948 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
950 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
952 if (sumsValid
|| crc
)
954 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
955 m_CompressedSize
= compressedSize
;
956 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
959 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
960 if (stream
.LastRead() != nameLen
+ 0u)
963 if (extraLen
|| GetLocalExtraLen()) {
964 Unique(m_LocalExtra
, extraLen
);
966 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
967 if (stream
.LastRead() != extraLen
+ 0u)
972 return LOCAL_SIZE
+ nameLen
+ extraLen
;
975 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
977 wxString unixName
= GetName(wxPATH_UNIX
);
978 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
979 const char *name
= name_buf
;
980 if (!name
) name
= "";
981 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
983 wxDataOutputStream
ds(stream
);
985 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
986 ds
.Write32(GetDateTime().GetAsDOS());
989 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
?
990 wx_truncate_cast(wxUint32
, m_CompressedSize
) : 0);
991 ds
.Write32(m_Size
!= wxInvalidOffset
?
992 wx_truncate_cast(wxUint32
, m_Size
) : 0);
995 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetLocalExtraLen());
996 ds
.Write16(extraLen
);
998 stream
.Write(name
, nameLen
);
1000 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
1002 return LOCAL_SIZE
+ nameLen
+ extraLen
;
1005 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
1007 wxUint16 nameLen
, extraLen
, commentLen
;
1009 wxZipHeader
ds(stream
, CENTRAL_SIZE
- 4);
1013 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
1015 SetVersionNeeded(ds
.Read16());
1016 SetFlags(ds
.Read16());
1017 SetMethod(ds
.Read16());
1018 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
1019 SetCrc(ds
.Read32());
1020 SetCompressedSize(ds
.Read32());
1021 SetSize(ds
.Read32());
1023 ds
>> nameLen
>> extraLen
>> commentLen
1024 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
1025 SetOffset(ds
.Read32());
1027 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
1028 if (stream
.LastRead() != nameLen
+ 0u)
1031 if (extraLen
|| GetExtraLen()) {
1032 Unique(m_Extra
, extraLen
);
1034 stream
.Read(m_Extra
->GetData(), extraLen
);
1035 if (stream
.LastRead() != extraLen
+ 0u)
1041 m_Comment
= ReadString(stream
, commentLen
, conv
);
1042 if (stream
.LastRead() != commentLen
+ 0u)
1048 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1051 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
1053 wxString unixName
= GetName(wxPATH_UNIX
);
1054 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
1055 const char *name
= name_buf
;
1056 if (!name
) name
= "";
1057 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
1059 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1060 const char *comment
= comment_buf
;
1061 if (!comment
) comment
= "";
1062 wxUint16 commentLen
= wx_truncate_cast(wxUint16
, strlen(comment
));
1064 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetExtraLen());
1066 wxDataOutputStream
ds(stream
);
1068 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
1070 ds
.Write16(wx_truncate_cast(wxUint16
, GetVersionNeeded()));
1071 ds
.Write16(wx_truncate_cast(wxUint16
, GetFlags()));
1072 ds
.Write16(wx_truncate_cast(wxUint16
, GetMethod()));
1073 ds
.Write32(GetDateTime().GetAsDOS());
1074 ds
.Write32(GetCrc());
1075 ds
.Write32(wx_truncate_cast(wxUint32
, GetCompressedSize()));
1076 ds
.Write32(wx_truncate_cast(wxUint32
, GetSize()));
1077 ds
.Write16(nameLen
);
1078 ds
.Write16(extraLen
);
1080 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
1081 << m_ExternalAttributes
<< wx_truncate_cast(wxUint32
, GetOffset());
1083 stream
.Write(name
, nameLen
);
1085 stream
.Write(GetExtra(), extraLen
);
1086 stream
.Write(comment
, commentLen
);
1088 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1091 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1092 // the 1st value is the signature then it is probably an info-zip record,
1093 // though there is a small chance that it is in fact a pkzip record which
1094 // happens to have the signature as it's CRC.
1096 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1098 wxZipHeader
ds(stream
, SUMS_SIZE
);
1102 m_Crc
= ds
.Read32();
1103 m_CompressedSize
= ds
.Read32();
1104 m_Size
= ds
.Read32();
1106 // if 1st value is the signature then this is probably an info-zip record
1107 if (m_Crc
== SUMS_MAGIC
)
1109 wxZipHeader
buf(stream
, 8);
1110 wxUint32 u1
= buf
.GetSize() >= 4 ? buf
.Read32() : (wxUint32
)LOCAL_MAGIC
;
1111 wxUint32 u2
= buf
.GetSize() == 8 ? buf
.Read32() : 0;
1113 // look for the signature of the following record to decide which
1114 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1115 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1117 // it's a pkzip style record after all!
1118 if (buf
.GetSize() > 0)
1119 stream
.Ungetch(buf
.GetData(), buf
.GetSize());
1123 // it's an info-zip record as expected
1124 if (buf
.GetSize() > 4)
1125 stream
.Ungetch(buf
.GetData() + 4, buf
.GetSize() - 4);
1126 m_Crc
= wx_truncate_cast(wxUint32
, m_CompressedSize
);
1127 m_CompressedSize
= m_Size
;
1129 return SUMS_SIZE
+ 4;
1136 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1137 wxFileOffset compressedSize
, wxFileOffset size
)
1140 m_CompressedSize
= compressedSize
;
1143 wxDataOutputStream
ds(stream
);
1146 ds
.Write32(wx_truncate_cast(wxUint32
, compressedSize
));
1147 ds
.Write32(wx_truncate_cast(wxUint32
, size
));
1153 /////////////////////////////////////////////////////////////////////////////
1154 // wxZipEndRec - holds the end of central directory record
1161 int GetDiskNumber() const { return m_DiskNumber
; }
1162 int GetStartDisk() const { return m_StartDisk
; }
1163 int GetEntriesHere() const { return m_EntriesHere
; }
1164 int GetTotalEntries() const { return m_TotalEntries
; }
1165 wxFileOffset
GetSize() const { return m_Size
; }
1166 wxFileOffset
GetOffset() const { return m_Offset
; }
1167 wxString
GetComment() const { return m_Comment
; }
1169 void SetDiskNumber(int num
)
1170 { m_DiskNumber
= wx_truncate_cast(wxUint16
, num
); }
1171 void SetStartDisk(int num
)
1172 { m_StartDisk
= wx_truncate_cast(wxUint16
, num
); }
1173 void SetEntriesHere(int num
)
1174 { m_EntriesHere
= wx_truncate_cast(wxUint16
, num
); }
1175 void SetTotalEntries(int num
)
1176 { m_TotalEntries
= wx_truncate_cast(wxUint16
, num
); }
1177 void SetSize(wxFileOffset size
)
1178 { m_Size
= wx_truncate_cast(wxUint32
, size
); }
1179 void SetOffset(wxFileOffset offset
)
1180 { m_Offset
= wx_truncate_cast(wxUint32
, offset
); }
1181 void SetComment(const wxString
& comment
)
1182 { m_Comment
= comment
; }
1184 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1185 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1188 wxUint16 m_DiskNumber
;
1189 wxUint16 m_StartDisk
;
1190 wxUint16 m_EntriesHere
;
1191 wxUint16 m_TotalEntries
;
1197 wxZipEndRec::wxZipEndRec()
1207 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1209 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1210 const char *comment
= comment_buf
;
1211 if (!comment
) comment
= "";
1212 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1214 wxDataOutputStream
ds(stream
);
1216 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1217 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1219 stream
.Write(comment
, commentLen
);
1221 return stream
.IsOk();
1224 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1226 wxZipHeader
ds(stream
, END_SIZE
- 4);
1230 wxUint16 commentLen
;
1232 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1233 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1236 m_Comment
= ReadString(stream
, commentLen
, conv
);
1237 if (stream
.LastRead() != commentLen
+ 0u)
1241 if (m_DiskNumber
!= 0 || m_StartDisk
!= 0 ||
1242 m_EntriesHere
!= m_TotalEntries
)
1243 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1249 /////////////////////////////////////////////////////////////////////////////
1250 // A weak link from an input stream to an output stream
1252 class wxZipStreamLink
1255 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1257 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1258 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1260 void Release(class wxZipInputStream
*WXUNUSED(s
))
1261 { if (--m_ref
== 0) delete this; }
1262 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1263 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1266 ~wxZipStreamLink() { }
1269 wxZipOutputStream
*m_stream
;
1271 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipStreamLink
)
1275 /////////////////////////////////////////////////////////////////////////////
1278 // leave the default wxZipEntryPtr free for users
1279 wxDECLARE_SCOPED_PTR(wxZipEntry
, wx__ZipEntryPtr
)
1280 wxDEFINE_SCOPED_PTR (wxZipEntry
, wx__ZipEntryPtr
)
1284 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1285 wxMBConv
& conv
/*=wxConvLocal*/)
1286 : wxArchiveInputStream(stream
, conv
)
1291 #if 1 //WXWIN_COMPATIBILITY_2_6
1293 // Part of the compatibility constructor, which has been made inline to
1294 // avoid a problem with it not being exported by mingw 3.2.3
1296 void wxZipInputStream::Init(const wxString
& file
)
1298 // no error messages
1301 m_allowSeeking
= true;
1302 m_ffile
= wx_static_cast(wxFFileInputStream
*, m_parent_i_stream
);
1303 wx__ZipEntryPtr entry
;
1305 if (m_ffile
->Ok()) {
1307 entry
.reset(GetNextEntry());
1309 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1312 if (entry
.get() == NULL
)
1313 m_lasterror
= wxSTREAM_READ_ERROR
;
1316 wxInputStream
& wxZipInputStream::OpenFile(const wxString
& archive
)
1319 return *new wxFFileInputStream(archive
);
1322 #endif // WXWIN_COMPATIBILITY_2_6
1324 void wxZipInputStream::Init()
1326 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1332 m_parentSeekable
= false;
1333 m_weaklinks
= new wxZipWeakLinks
;
1334 m_streamlink
= NULL
;
1335 m_offsetAdjustment
= 0;
1336 m_position
= wxInvalidOffset
;
1339 m_lasterror
= m_parent_i_stream
->GetLastError();
1341 #if 1 //WXWIN_COMPATIBILITY_2_6
1342 m_allowSeeking
= false;
1346 wxZipInputStream::~wxZipInputStream()
1348 CloseDecompressor(m_decomp
);
1355 m_weaklinks
->Release(this);
1358 m_streamlink
->Release(this);
1361 wxString
wxZipInputStream::GetComment()
1363 if (m_position
== wxInvalidOffset
)
1364 if (!LoadEndRecord())
1365 return wxEmptyString
;
1367 if (!m_parentSeekable
&& Eof() && m_signature
) {
1368 m_lasterror
= wxSTREAM_NO_ERROR
;
1369 m_lasterror
= ReadLocal(true);
1375 int wxZipInputStream::GetTotalEntries()
1377 if (m_position
== wxInvalidOffset
)
1379 return m_TotalEntries
;
1382 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1384 wxZipStreamLink
*link
= NULL
;
1386 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1387 link
= new wxZipStreamLink(out
);
1389 m_streamlink
->Release(this);
1390 m_streamlink
= link
->AddRef();
1396 bool wxZipInputStream::LoadEndRecord()
1398 wxCHECK(m_position
== wxInvalidOffset
, false);
1404 // First find the end-of-central-directory record.
1405 if (!FindEndRecord()) {
1406 // failed, so either this is a non-seekable stream (ok), or not a zip
1407 if (m_parentSeekable
) {
1408 m_lasterror
= wxSTREAM_READ_ERROR
;
1409 wxLogError(_("invalid zip file"));
1414 wxFileOffset pos
= m_parent_i_stream
->TellI();
1415 if (pos
!= wxInvalidOffset
)
1416 m_offsetAdjustment
= m_position
= pos
;
1423 // Read in the end record
1424 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1425 if (!endrec
.Read(*m_parent_i_stream
, GetConv()))
1428 m_TotalEntries
= endrec
.GetTotalEntries();
1429 m_Comment
= endrec
.GetComment();
1431 // Now find the central-directory. we have the file offset of
1432 // the CD, so look there first.
1433 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1434 ReadSignature() == CENTRAL_MAGIC
) {
1435 m_signature
= CENTRAL_MAGIC
;
1436 m_position
= endrec
.GetOffset();
1437 m_offsetAdjustment
= 0;
1441 // If it's not there, then it could be that the zip has been appended
1442 // to a self extractor, so take the CD size (also in endrec), subtract
1443 // it from the file offset of the end-central-directory and look there.
1444 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1445 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1446 m_signature
= CENTRAL_MAGIC
;
1447 m_position
= endPos
- endrec
.GetSize();
1448 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1452 wxLogError(_("can't find central directory in zip"));
1453 m_lasterror
= wxSTREAM_READ_ERROR
;
1457 // Find the end-of-central-directory record.
1458 // If found the stream will be positioned just past the 4 signature bytes.
1460 bool wxZipInputStream::FindEndRecord()
1462 if (!m_parent_i_stream
->IsSeekable())
1465 // usually it's 22 bytes in size and the last thing in the file
1468 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1472 m_parentSeekable
= true;
1475 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1477 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1480 // unfortunately, the record has a comment field that can be up to 65535
1481 // bytes in length, so if the signature not found then search backwards.
1482 wxFileOffset pos
= m_parent_i_stream
->TellI();
1483 const int BUFSIZE
= 1024;
1484 wxCharBuffer
buf(BUFSIZE
);
1486 memcpy(buf
.data(), magic
, 3);
1487 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1489 while (pos
> minpos
) {
1490 size_t len
= wx_truncate_cast(size_t,
1491 pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1492 memcpy(buf
.data() + len
, buf
, 3);
1495 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1496 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1499 char *p
= buf
.data() + len
;
1501 while (p
-- > buf
.data()) {
1502 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1503 size_t remainder
= buf
.data() + len
- p
;
1505 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1514 wxZipEntry
*wxZipInputStream::GetNextEntry()
1516 if (m_position
== wxInvalidOffset
)
1517 if (!LoadEndRecord())
1520 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1524 wx__ZipEntryPtr
entry(new wxZipEntry(m_entry
));
1525 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1526 return entry
.release();
1529 wxStreamError
wxZipInputStream::ReadCentral()
1534 if (m_signature
== END_MAGIC
)
1535 return wxSTREAM_EOF
;
1537 if (m_signature
!= CENTRAL_MAGIC
) {
1538 wxLogError(_("error reading zip central directory"));
1539 return wxSTREAM_READ_ERROR
;
1542 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1543 return wxSTREAM_READ_ERROR
;
1545 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1548 return wxSTREAM_READ_ERROR
;
1552 m_signature
= ReadSignature();
1554 if (m_offsetAdjustment
)
1555 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1556 m_entry
.SetKey(m_entry
.GetOffset());
1558 return wxSTREAM_NO_ERROR
;
1561 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1567 m_signature
= ReadSignature();
1569 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1570 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1571 m_streamlink
->Release(this);
1572 m_streamlink
= NULL
;
1576 while (m_signature
== CENTRAL_MAGIC
) {
1577 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1578 return wxSTREAM_EOF
;
1580 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1584 return wxSTREAM_READ_ERROR
;
1586 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1588 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1589 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1590 entry
->SetComment(m_entry
.GetComment());
1591 entry
->SetDiskStart(m_entry
.GetDiskStart());
1592 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1593 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1594 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1596 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1599 m_signature
= ReadSignature();
1602 if (m_signature
== END_MAGIC
) {
1603 if (readEndRec
|| m_streamlink
) {
1605 endrec
.Read(*m_parent_i_stream
, GetConv());
1606 m_Comment
= endrec
.GetComment();
1609 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1610 m_streamlink
->Release(this);
1611 m_streamlink
= NULL
;
1614 return wxSTREAM_EOF
;
1617 if (m_signature
!= LOCAL_MAGIC
) {
1618 wxLogError(_("error reading zip local header"));
1619 return wxSTREAM_READ_ERROR
;
1622 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1624 m_entry
.SetOffset(m_position
);
1625 m_entry
.SetKey(m_position
);
1627 if (!m_headerSize
) {
1628 return wxSTREAM_READ_ERROR
;
1631 return wxSTREAM_NO_ERROR
;
1635 wxUint32
wxZipInputStream::ReadSignature()
1638 m_parent_i_stream
->Read(magic
, 4);
1639 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1642 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1644 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1645 return zipEntry
? OpenEntry(*zipEntry
) : false;
1650 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1652 if (m_position
== wxInvalidOffset
)
1653 if (!LoadEndRecord())
1655 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1663 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1665 // can only open the current entry on a non-seekable stream
1666 wxCHECK(m_parentSeekable
, false);
1669 m_lasterror
= wxSTREAM_READ_ERROR
;
1674 if (m_parentSeekable
) {
1675 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1678 if (ReadSignature() != LOCAL_MAGIC
) {
1679 wxLogError(_("bad zipfile offset to entry"));
1684 if (m_parentSeekable
|| AtHeader()) {
1685 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1686 if (m_headerSize
&& m_parentSeekable
) {
1687 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1689 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1691 m_weaklinks
->RemoveEntry(ref
->GetKey());
1693 if (entry
&& entry
!= ref
) {
1694 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1701 m_lasterror
= wxSTREAM_NO_ERROR
;
1705 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1707 wxASSERT(AfterHeader());
1709 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1715 if (compressedSize
!= wxInvalidOffset
) {
1716 m_store
->Open(compressedSize
);
1720 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1721 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1724 if (compressedSize
!= wxInvalidOffset
&&
1725 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1726 wxZlibInputStream::CanHandleGZip())) {
1727 m_store
->Open(compressedSize
);
1728 m_decomp
= OpenDecompressor(*m_store
);
1730 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1734 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1735 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1739 // Can be overriden to add support for additional decompression methods
1741 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1743 switch (m_entry
.GetMethod()) {
1744 case wxZIP_METHOD_STORE
:
1745 if (m_entry
.GetSize() == wxInvalidOffset
) {
1746 wxLogError(_("stored file length not in Zip header"));
1749 m_store
->Open(m_entry
.GetSize());
1752 case wxZIP_METHOD_DEFLATE
:
1754 m_inflate
= new wxZlibInputStream2(stream
);
1756 m_inflate
->Open(stream
);
1760 wxLogError(_("unsupported Zip compression method"));
1766 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1768 if (decomp
&& decomp
== m_rawin
)
1769 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1770 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1775 // Closes the current entry and positions the underlying stream at the start
1776 // of the next entry
1778 bool wxZipInputStream::CloseEntry()
1782 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1785 if (!m_parentSeekable
) {
1786 if (!IsOpened() && !OpenDecompressor(true))
1789 const int BUFSIZE
= 8192;
1790 wxCharBuffer
buf(BUFSIZE
);
1792 Read(buf
.data(), BUFSIZE
);
1794 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1797 if (m_lasterror
== wxSTREAM_EOF
)
1798 m_lasterror
= wxSTREAM_NO_ERROR
;
1800 CloseDecompressor(m_decomp
);
1802 m_entry
= wxZipEntry();
1809 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1812 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1813 m_lasterror
= wxSTREAM_READ_ERROR
;
1814 if (!IsOk() || !size
)
1817 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1819 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1821 m_lasterror
= m_decomp
->GetLastError();
1824 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1825 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1826 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1829 entry
->SetCrc(m_entry
.GetCrc());
1830 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1831 entry
->SetSize(m_entry
.GetSize());
1837 m_lasterror
= wxSTREAM_READ_ERROR
;
1839 if (m_entry
.GetSize() != TellI())
1840 wxLogError(_("reading zip stream (entry %s): bad length"),
1841 m_entry
.GetName().c_str());
1842 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1843 wxLogError(_("reading zip stream (entry %s): bad crc"),
1844 m_entry
.GetName().c_str());
1846 m_lasterror
= wxSTREAM_EOF
;
1853 #if 1 //WXWIN_COMPATIBILITY_2_6
1855 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1857 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1859 // seeking works when the stream is created with the compatibility
1861 if (!m_allowSeeking
)
1862 return wxInvalidOffset
;
1864 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1865 m_lasterror
= wxSTREAM_READ_ERROR
;
1867 return wxInvalidOffset
;
1869 // NB: since ZIP files don't natively support seeking, we have to
1870 // implement a brute force workaround -- reading all the data
1871 // between current and the new position (or between beginning of
1872 // the file and new position...)
1874 wxFileOffset nextpos
;
1875 wxFileOffset pos
= TellI();
1879 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1880 case wxFromStart
: nextpos
= seek
; break;
1881 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1882 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1885 wxFileOffset toskip
wxDUMMY_INITIALIZE(0);
1886 if ( nextpos
>= pos
)
1888 toskip
= nextpos
- pos
;
1892 wxZipEntry
current(m_entry
);
1893 if (!OpenEntry(current
))
1895 m_lasterror
= wxSTREAM_READ_ERROR
;
1903 const int BUFSIZE
= 4096;
1905 char buffer
[BUFSIZE
];
1906 while ( toskip
> 0 )
1908 sz
= wx_truncate_cast(size_t, wxMin(toskip
, BUFSIZE
));
1918 #endif // WXWIN_COMPATIBILITY_2_6
1921 /////////////////////////////////////////////////////////////////////////////
1924 #include "wx/listimpl.cpp"
1925 WX_DEFINE_LIST(wx__ZipEntryList
)
1927 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1929 wxMBConv
& conv
/*=wxConvLocal*/)
1930 : wxArchiveOutputStream(stream
, conv
),
1931 m_store(new wxStoredOutputStream(stream
)),
1934 m_initialData(new char[OUTPUT_LATENCY
]),
1943 m_offsetAdjustment(wxInvalidOffset
)
1947 wxZipOutputStream::~wxZipOutputStream()
1950 WX_CLEAR_LIST(wx__ZipEntryList
, m_entries
);
1954 delete [] m_initialData
;
1956 m_backlink
->Release(this);
1959 bool wxZipOutputStream::PutNextEntry(
1960 const wxString
& name
,
1961 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1962 wxFileOffset size
/*=wxInvalidOffset*/)
1964 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1967 bool wxZipOutputStream::PutNextDirEntry(
1968 const wxString
& name
,
1969 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1971 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1973 return PutNextEntry(entry
);
1976 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1977 wxZipInputStream
& inputStream
)
1979 wx__ZipEntryPtr
e(entry
);
1982 inputStream
.DoOpen(e
.get(), true) &&
1983 DoCreate(e
.release(), true) &&
1984 Write(inputStream
).IsOk() && inputStream
.Eof();
1987 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1989 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1992 return PutNextEntry(zipEntry
);
1995 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1996 wxArchiveInputStream
& stream
)
1998 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2000 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
2005 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
2008 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
2010 m_Comment
= inputStream
.GetComment();
2012 m_backlink
->Release(this);
2013 m_backlink
= inputStream
.MakeLink(this);
2017 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
2019 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
2022 void wxZipOutputStream::SetLevel(int level
)
2024 if (level
!= m_level
) {
2025 if (m_comp
!= m_deflate
)
2032 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
2040 // write the signature bytes right away
2041 wxDataOutputStream
ds(*m_parent_o_stream
);
2044 // and if this is the first entry test for seekability
2045 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
2047 bool logging
= wxLog::IsEnabled();
2050 wxFileOffset here
= m_parent_o_stream
->TellO();
2052 if (here
!= wxInvalidOffset
&& here
>= 4) {
2053 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
2054 m_offsetAdjustment
= here
- 4;
2056 wxLog::EnableLogging(logging
);
2058 m_parent_o_stream
->SeekO(here
);
2063 m_pending
->SetOffset(m_headerOffset
);
2065 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
2070 m_lasterror
= wxSTREAM_NO_ERROR
;
2074 // Can be overriden to add support for additional compression methods
2076 wxOutputStream
*wxZipOutputStream::OpenCompressor(
2077 wxOutputStream
& stream
,
2079 const Buffer bufs
[])
2081 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
2083 && (IsParentSeekable()
2084 || entry
.GetCompressedSize() != wxInvalidOffset
2085 || entry
.GetSize() != wxInvalidOffset
)) {
2086 entry
.SetMethod(wxZIP_METHOD_STORE
);
2089 for (int i
= 0; bufs
[i
].m_data
; ++i
)
2090 size
+= bufs
[i
].m_size
;
2091 entry
.SetMethod(size
<= 6 ?
2092 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
2096 switch (entry
.GetMethod()) {
2097 case wxZIP_METHOD_STORE
:
2098 if (entry
.GetCompressedSize() == wxInvalidOffset
)
2099 entry
.SetCompressedSize(entry
.GetSize());
2102 case wxZIP_METHOD_DEFLATE
:
2104 int defbits
= wxZIP_DEFLATE_NORMAL
;
2105 switch (GetLevel()) {
2107 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2109 case 2: case 3: case 4:
2110 defbits
= wxZIP_DEFLATE_FAST
;
2113 defbits
= wxZIP_DEFLATE_EXTRA
;
2116 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2117 defbits
| wxZIP_SUMS_FOLLOW
);
2120 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2122 m_deflate
->Open(stream
);
2128 wxLogError(_("unsupported Zip compression method"));
2134 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2136 if (comp
== m_deflate
)
2138 else if (comp
!= m_store
)
2143 // This is called when OUPUT_LATENCY bytes has been written to the
2144 // wxZipOutputStream to actually create the zip entry.
2146 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2148 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2149 wx__ZipEntryPtr
spPending(m_pending
);
2153 { m_initialData
, m_initialSize
},
2154 { (const char*)buffer
, size
},
2161 m_comp
= OpenCompressor(*m_store
, *spPending
,
2162 m_initialSize
? bufs
: bufs
+ 1);
2164 if (IsParentSeekable()
2165 || (spPending
->m_Crc
2166 && spPending
->m_CompressedSize
!= wxInvalidOffset
2167 && spPending
->m_Size
!= wxInvalidOffset
))
2168 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2170 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2171 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2173 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2174 m_lasterror
= m_parent_o_stream
->GetLastError();
2177 m_entries
.push_back(spPending
.release());
2178 OnSysWrite(m_initialData
, m_initialSize
);
2184 // This is called to write out the zip entry when Close has been called
2185 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2187 void wxZipOutputStream::CreatePendingEntry()
2189 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2190 wx__ZipEntryPtr
spPending(m_pending
);
2192 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2195 // Initially compresses the data to memory, then fall back to 'store'
2196 // if the compressor makes the data larger rather than smaller.
2197 wxMemoryOutputStream mem
;
2198 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2199 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2203 if (comp
!= m_store
) {
2204 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2205 CloseCompressor(comp
);
2210 m_entrySize
= m_initialSize
;
2211 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2213 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2214 m_initialSize
= mem
.GetSize();
2215 mem
.CopyTo(m_initialData
, m_initialSize
);
2217 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2220 spPending
->SetSize(m_entrySize
);
2221 spPending
->SetCrc(m_crcAccumulator
);
2222 spPending
->SetCompressedSize(m_initialSize
);
2225 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2226 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2228 if (m_parent_o_stream
->IsOk()) {
2229 m_entries
.push_back(spPending
.release());
2231 m_store
->Write(m_initialData
, m_initialSize
);
2235 m_lasterror
= m_parent_o_stream
->GetLastError();
2238 // Write the 'central directory' and the 'end-central-directory' records.
2240 bool wxZipOutputStream::Close()
2244 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2249 endrec
.SetEntriesHere(m_entries
.size());
2250 endrec
.SetTotalEntries(m_entries
.size());
2251 endrec
.SetOffset(m_headerOffset
);
2252 endrec
.SetComment(m_Comment
);
2254 wx__ZipEntryList::iterator it
;
2255 wxFileOffset size
= 0;
2257 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2258 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2263 endrec
.SetSize(size
);
2264 endrec
.Write(*m_parent_o_stream
, GetConv());
2266 m_lasterror
= m_parent_o_stream
->GetLastError();
2269 m_lasterror
= wxSTREAM_EOF
;
2273 // Finish writing the current entry
2275 bool wxZipOutputStream::CloseEntry()
2277 if (IsOk() && m_pending
)
2278 CreatePendingEntry();
2284 CloseCompressor(m_comp
);
2287 wxFileOffset compressedSize
= m_store
->TellO();
2289 wxZipEntry
& entry
= *m_entries
.back();
2291 // When writing raw the crc and size can't be checked
2293 m_crcAccumulator
= entry
.GetCrc();
2294 m_entrySize
= entry
.GetSize();
2297 // Write the sums in the trailing 'data descriptor' if necessary
2298 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2299 wxASSERT(!IsParentSeekable());
2301 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2302 compressedSize
, m_entrySize
);
2303 m_lasterror
= m_parent_o_stream
->GetLastError();
2306 // If the local header didn't have the correct crc and size written to
2307 // it then seek back and fix it
2308 else if (m_crcAccumulator
!= entry
.GetCrc()
2309 || m_entrySize
!= entry
.GetSize()
2310 || compressedSize
!= entry
.GetCompressedSize())
2312 if (IsParentSeekable()) {
2313 wxFileOffset here
= m_parent_o_stream
->TellO();
2314 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2315 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2316 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2317 compressedSize
, m_entrySize
);
2318 m_parent_o_stream
->SeekO(here
);
2319 m_lasterror
= m_parent_o_stream
->GetLastError();
2321 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2325 m_headerOffset
+= m_headerSize
+ compressedSize
;
2332 m_lasterror
= m_parent_o_stream
->GetLastError();
2334 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2335 entry
.GetName().c_str());
2339 void wxZipOutputStream::Sync()
2341 if (IsOk() && m_pending
)
2342 CreatePendingEntry(NULL
, 0);
2344 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2347 m_lasterror
= m_comp
->GetLastError();
2351 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2353 if (IsOk() && m_pending
) {
2354 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2355 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2356 m_initialSize
+= size
;
2359 CreatePendingEntry(buffer
, size
);
2364 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2365 if (!IsOk() || !size
)
2368 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2369 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2370 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2371 m_entrySize
+= m_comp
->LastWrite();
2373 return m_comp
->LastWrite();
2376 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM