1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
6 // Copyright: (c) Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
21 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
23 #include "wx/zipstrm.h"
26 #include "wx/datstrm.h"
27 #include "wx/zstream.h"
28 #include "wx/mstream.h"
30 #include "wx/buffer.h"
31 #include "wx/ptr_scpd.h"
32 #include "wx/wfstream.h"
36 // value for the 'version needed to extract' field (20 means 2.0)
38 VERSION_NEEDED_TO_EXTRACT
= 20
41 // signatures for the various records (PKxx)
43 CENTRAL_MAGIC
= 0x02014b50, // central directory record
44 LOCAL_MAGIC
= 0x04034b50, // local header
45 END_MAGIC
= 0x06054b50, // end of central directory record
46 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
49 // unix file attributes. zip stores them in the high 16 bits of the
50 // 'external attributes' field, hence the extra zeros.
52 wxZIP_S_IFMT
= 0xF0000000,
53 wxZIP_S_IFDIR
= 0x40000000,
54 wxZIP_S_IFREG
= 0x80000000
57 // minimum sizes for the various records
65 // The number of bytes that must be written to an wxZipOutputStream before
66 // a zip entry is created. The purpose of this latency is so that
67 // OpenCompressor() can see a little data before deciding which compressor
73 // Some offsets into the local header
78 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
79 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
81 wxFORCE_LINK_THIS_MODULE(zipstrm
)
84 /////////////////////////////////////////////////////////////////////////////
87 // read a string of a given length
89 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
92 wxCharBuffer
buf(len
);
93 stream
.Read(buf
.data(), len
);
94 wxString
str(buf
, conv
);
99 wxStringBuffer
buf(str
, len
);
100 stream
.Read(buf
, len
);
107 // Decode a little endian wxUint32 number from a character array
109 static inline wxUint32
CrackUint32(const char *m
)
111 const unsigned char *n
= (const unsigned char*)m
;
112 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
115 // Temporarily lower the logging level in debug mode to avoid a warning
116 // from SeekI about seeking on a stream with data written back to it.
118 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
121 wxLogLevel level
= wxLog::GetLogLevel();
122 wxLog::SetLogLevel(wxLOG_Debug
- 1);
123 wxFileOffset result
= stream
.SeekI(pos
);
124 wxLog::SetLogLevel(level
);
127 return stream
.SeekI(pos
);
132 /////////////////////////////////////////////////////////////////////////////
133 // Stored input stream
134 // Trival decompressor for files which are 'stored' in the zip file.
136 class wxStoredInputStream
: public wxFilterInputStream
139 wxStoredInputStream(wxInputStream
& stream
);
141 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
142 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
144 virtual char Peek() { return wxInputStream::Peek(); }
145 virtual wxFileOffset
GetLength() const { return m_len
; }
148 virtual size_t OnSysRead(void *buffer
, size_t size
);
149 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
155 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
158 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
159 : wxFilterInputStream(stream
),
165 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
167 size_t count
= wx_truncate_cast(size_t,
168 wxMin(size
+ wxFileOffset(0), m_len
- m_pos
+ size_t(0)));
169 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
173 m_lasterror
= wxSTREAM_EOF
;
174 else if (!*m_parent_i_stream
)
175 m_lasterror
= wxSTREAM_READ_ERROR
;
181 /////////////////////////////////////////////////////////////////////////////
182 // Stored output stream
183 // Trival compressor for files which are 'stored' in the zip file.
185 class wxStoredOutputStream
: public wxFilterOutputStream
188 wxStoredOutputStream(wxOutputStream
& stream
) :
189 wxFilterOutputStream(stream
), m_pos(0) { }
193 m_lasterror
= wxSTREAM_NO_ERROR
;
198 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
199 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
203 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
206 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
208 if (!IsOk() || !size
)
210 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
212 m_lasterror
= wxSTREAM_WRITE_ERROR
;
218 /////////////////////////////////////////////////////////////////////////////
221 // Used to handle the unusal case of raw copying an entry of unknown
222 // length. This can only happen when the zip being copied from is being
223 // read from a non-seekable stream, and also was original written to a
224 // non-seekable stream.
226 // In this case there's no option but to decompress the stream to find
227 // it's length, but we can still write the raw compressed data to avoid the
228 // compression overhead (which is the greater one).
230 // Usage is like this:
231 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
232 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
234 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
235 // is something like the unix 'tee' command; it is a transparent filter, but
236 // allows the data read to be read a second time via an extra method 'GetData'.
238 // The wxRawInputStream then draws data through the tee using a decompressor
239 // then instead of returning the decompressed data, retuns the raw data
240 // from wxTeeInputStream::GetData().
242 class wxTeeInputStream
: public wxFilterInputStream
245 wxTeeInputStream(wxInputStream
& stream
);
247 size_t GetCount() const { return m_end
- m_start
; }
248 size_t GetData(char *buffer
, size_t size
);
253 wxInputStream
& Read(void *buffer
, size_t size
);
256 virtual size_t OnSysRead(void *buffer
, size_t size
);
257 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
261 wxMemoryBuffer m_buf
;
265 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
268 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
269 : wxFilterInputStream(stream
),
270 m_pos(0), m_buf(8192), m_start(0), m_end(0)
274 void wxTeeInputStream::Open()
276 m_pos
= m_start
= m_end
= 0;
277 m_lasterror
= wxSTREAM_NO_ERROR
;
280 bool wxTeeInputStream::Final()
282 bool final
= m_end
== m_buf
.GetDataLen();
283 m_end
= m_buf
.GetDataLen();
287 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
289 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
290 m_end
= m_buf
.GetDataLen();
291 m_buf
.AppendData(buffer
, count
);
295 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
297 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
298 m_lasterror
= m_parent_i_stream
->GetLastError();
302 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
305 size_t len
= m_buf
.GetDataLen();
306 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
307 m_buf
.SetDataLen(len
);
309 wxFAIL
; // we've already returned data that's now being ungot
312 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
319 if (size
> GetCount())
322 memcpy(buffer
, m_buf
+ m_start
, size
);
324 wxASSERT(m_start
<= m_end
);
327 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
328 size_t len
= m_buf
.GetDataLen();
329 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
331 memmove(buf
, buf
+ m_end
, len
);
332 m_buf
.UngetWriteBuf(len
);
339 class wxRawInputStream
: public wxFilterInputStream
342 wxRawInputStream(wxInputStream
& stream
);
343 virtual ~wxRawInputStream() { delete m_tee
; }
345 wxInputStream
* Open(wxInputStream
*decomp
);
346 wxInputStream
& GetTee() const { return *m_tee
; }
349 virtual size_t OnSysRead(void *buffer
, size_t size
);
350 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
354 wxTeeInputStream
*m_tee
;
356 enum { BUFSIZE
= 8192 };
357 wxCharBuffer m_dummy
;
359 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
362 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
363 : wxFilterInputStream(stream
),
365 m_tee(new wxTeeInputStream(stream
)),
370 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
373 m_parent_i_stream
= decomp
;
375 m_lasterror
= wxSTREAM_NO_ERROR
;
383 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
385 char *buf
= (char*)buffer
;
388 while (count
< size
&& IsOk())
390 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
391 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
393 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
396 if (n
== 0 && m_tee
->Final())
397 m_lasterror
= m_parent_i_stream
->GetLastError();
405 /////////////////////////////////////////////////////////////////////////////
406 // Zlib streams than can be reused without recreating.
408 class wxZlibOutputStream2
: public wxZlibOutputStream
411 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
412 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
414 bool Open(wxOutputStream
& stream
);
415 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
418 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
420 wxCHECK(m_pos
== wxInvalidOffset
, false);
422 m_deflate
->next_out
= m_z_buffer
;
423 m_deflate
->avail_out
= m_z_size
;
425 m_lasterror
= wxSTREAM_NO_ERROR
;
426 m_parent_o_stream
= &stream
;
428 if (deflateReset(m_deflate
) != Z_OK
) {
429 wxLogError(_("can't re-initialize zlib deflate stream"));
430 m_lasterror
= wxSTREAM_WRITE_ERROR
;
437 class wxZlibInputStream2
: public wxZlibInputStream
440 wxZlibInputStream2(wxInputStream
& stream
) :
441 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
443 bool Open(wxInputStream
& stream
);
446 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
448 m_inflate
->avail_in
= 0;
450 m_lasterror
= wxSTREAM_NO_ERROR
;
451 m_parent_i_stream
= &stream
;
453 if (inflateReset(m_inflate
) != Z_OK
) {
454 wxLogError(_("can't re-initialize zlib inflate stream"));
455 m_lasterror
= wxSTREAM_READ_ERROR
;
463 /////////////////////////////////////////////////////////////////////////////
464 // Class to hold wxZipEntry's Extra and LocalExtra fields
469 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
471 wxZipMemory
*AddRef() { m_ref
++; return this; }
472 void Release() { if (--m_ref
== 0) delete this; }
474 char *GetData() const { return m_data
; }
475 size_t GetSize() const { return m_size
; }
476 size_t GetCapacity() const { return m_capacity
; }
478 wxZipMemory
*Unique(size_t size
);
481 ~wxZipMemory() { delete [] m_data
; }
489 wxZipMemory
*wxZipMemory::Unique(size_t size
)
495 zm
= new wxZipMemory
;
500 if (zm
->m_capacity
< size
) {
501 delete [] zm
->m_data
;
502 zm
->m_data
= new char[size
];
503 zm
->m_capacity
= size
;
510 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
517 static inline void Release(wxZipMemory
*zm
)
523 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
529 static void Unique(wxZipMemory
*& zm
, size_t size
)
532 zm
= new wxZipMemory
;
534 zm
= zm
->Unique(size
);
538 /////////////////////////////////////////////////////////////////////////////
539 // Collection of weak references to entries
541 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
542 wxIntegerEqual
, wx__OffsetZipEntryMap
);
547 wxZipWeakLinks() : m_ref(1) { }
549 void Release(const wxZipInputStream
* WXUNUSED(x
))
550 { if (--m_ref
== 0) delete this; }
551 void Release(wxFileOffset key
)
552 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
554 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
555 void RemoveEntry(wxFileOffset key
)
556 { m_entries
.erase(wx_truncate_cast(key_type
, key
)); }
557 wxZipEntry
*GetEntry(wxFileOffset key
) const;
558 bool IsEmpty() const { return m_entries
.empty(); }
561 typedef wx__OffsetZipEntryMap::key_type key_type
;
563 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
566 wx__OffsetZipEntryMap m_entries
;
569 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
571 m_entries
[wx_truncate_cast(key_type
, key
)] = entry
;
576 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
578 wx__OffsetZipEntryMap::const_iterator it
=
579 m_entries
.find(wx_truncate_cast(key_type
, key
));
580 return it
!= m_entries
.end() ? it
->second
: NULL
;
584 /////////////////////////////////////////////////////////////////////////////
587 wxZipEntry::wxZipEntry(
588 const wxString
& name
/*=wxEmptyString*/,
589 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
590 wxFileOffset size
/*=wxInvalidOffset*/)
592 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
593 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
594 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
596 m_Method(wxZIP_METHOD_DEFAULT
),
599 m_CompressedSize(wxInvalidOffset
),
601 m_Key(wxInvalidOffset
),
602 m_Offset(wxInvalidOffset
),
604 m_InternalAttributes(0),
605 m_ExternalAttributes(0),
615 wxZipEntry::~wxZipEntry()
618 m_backlink
->Release(m_Key
);
620 Release(m_LocalExtra
);
623 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
625 m_SystemMadeBy(e
.m_SystemMadeBy
),
626 m_VersionMadeBy(e
.m_VersionMadeBy
),
627 m_VersionNeeded(e
.m_VersionNeeded
),
629 m_Method(e
.m_Method
),
630 m_DateTime(e
.m_DateTime
),
632 m_CompressedSize(e
.m_CompressedSize
),
636 m_Offset(e
.m_Offset
),
637 m_Comment(e
.m_Comment
),
638 m_DiskStart(e
.m_DiskStart
),
639 m_InternalAttributes(e
.m_InternalAttributes
),
640 m_ExternalAttributes(e
.m_ExternalAttributes
),
641 m_Extra(AddRef(e
.m_Extra
)),
642 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
648 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
651 m_SystemMadeBy
= e
.m_SystemMadeBy
;
652 m_VersionMadeBy
= e
.m_VersionMadeBy
;
653 m_VersionNeeded
= e
.m_VersionNeeded
;
655 m_Method
= e
.m_Method
;
656 m_DateTime
= e
.m_DateTime
;
658 m_CompressedSize
= e
.m_CompressedSize
;
662 m_Offset
= e
.m_Offset
;
663 m_Comment
= e
.m_Comment
;
664 m_DiskStart
= e
.m_DiskStart
;
665 m_InternalAttributes
= e
.m_InternalAttributes
;
666 m_ExternalAttributes
= e
.m_ExternalAttributes
;
667 Copy(m_Extra
, e
.m_Extra
);
668 Copy(m_LocalExtra
, e
.m_LocalExtra
);
669 m_zipnotifier
= NULL
;
671 m_backlink
->Release(m_Key
);
678 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
680 bool isDir
= IsDir() && !m_Name
.empty();
682 // optimisations for common (and easy) cases
683 switch (wxFileName::GetFormat(format
)) {
686 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
687 for (size_t i
= name
.length() - 1; i
> 0; --i
)
688 if (name
[i
] == _T('/'))
694 return isDir
? m_Name
+ _T("/") : m_Name
;
703 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
705 fn
.Assign(m_Name
, wxPATH_UNIX
);
707 return fn
.GetFullPath(format
);
710 // Static - Internally tars and zips use forward slashes for the path
711 // separator, absolute paths aren't allowed, and directory names have a
712 // trailing slash. This function converts a path into this internal format,
713 // but without a trailing slash for a directory.
715 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
716 wxPathFormat format
/*=wxPATH_NATIVE*/,
717 bool *pIsDir
/*=NULL*/)
721 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
722 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
726 bool isDir
= !internal
.empty() && internal
.Last() == '/';
730 internal
.erase(internal
.length() - 1);
732 while (!internal
.empty() && *internal
.begin() == '/')
733 internal
.erase(0, 1);
734 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
735 internal
.erase(0, 2);
736 if (internal
== _T(".") || internal
== _T(".."))
737 internal
= wxEmptyString
;
742 void wxZipEntry::SetSystemMadeBy(int system
)
744 int mode
= GetMode();
745 bool wasUnix
= IsMadeByUnix();
747 m_SystemMadeBy
= (wxUint8
)system
;
749 if (!wasUnix
&& IsMadeByUnix()) {
752 } else if (wasUnix
&& !IsMadeByUnix()) {
753 m_ExternalAttributes
&= 0xffff;
757 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
760 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
762 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
764 if (IsMadeByUnix()) {
765 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
767 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
769 m_ExternalAttributes
|= wxZIP_S_IFREG
;
773 // Return unix style permission bits
775 int wxZipEntry::GetMode() const
777 // return unix permissions if present
779 return (m_ExternalAttributes
>> 16) & 0777;
781 // otherwise synthesize from the dos attribs
783 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
785 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
791 // Set unix permissions
793 void wxZipEntry::SetMode(int mode
)
795 // Set dos attrib bits to be compatible
797 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
799 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
801 // set the actual unix permission bits if the system type allows
802 if (IsMadeByUnix()) {
803 m_ExternalAttributes
&= ~(0777L << 16);
804 m_ExternalAttributes
|= (mode
& 0777L) << 16;
808 const char *wxZipEntry::GetExtra() const
810 return m_Extra
? m_Extra
->GetData() : NULL
;
813 size_t wxZipEntry::GetExtraLen() const
815 return m_Extra
? m_Extra
->GetSize() : 0;
818 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
820 Unique(m_Extra
, len
);
822 memcpy(m_Extra
->GetData(), extra
, len
);
825 const char *wxZipEntry::GetLocalExtra() const
827 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
830 size_t wxZipEntry::GetLocalExtraLen() const
832 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
835 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
837 Unique(m_LocalExtra
, len
);
839 memcpy(m_LocalExtra
->GetData(), extra
, len
);
842 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
844 wxArchiveEntry::UnsetNotifier();
845 m_zipnotifier
= ¬ifier
;
846 m_zipnotifier
->OnEntryUpdated(*this);
849 void wxZipEntry::Notify()
852 m_zipnotifier
->OnEntryUpdated(*this);
853 else if (GetNotifier())
854 GetNotifier()->OnEntryUpdated(*this);
857 void wxZipEntry::UnsetNotifier()
859 wxArchiveEntry::UnsetNotifier();
860 m_zipnotifier
= NULL
;
863 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
865 wxUint16 nameLen
, extraLen
;
866 wxUint32 compressedSize
, size
, crc
;
868 wxDataInputStream
ds(stream
);
870 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
871 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
872 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
874 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
876 if (sumsValid
|| crc
)
878 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
879 m_CompressedSize
= compressedSize
;
880 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
883 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
885 if (extraLen
|| GetLocalExtraLen()) {
886 Unique(m_LocalExtra
, extraLen
);
888 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
891 return LOCAL_SIZE
+ nameLen
+ extraLen
;
894 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
896 wxString unixName
= GetName(wxPATH_UNIX
);
897 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
898 const char *name
= name_buf
;
899 if (!name
) name
= "";
900 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
902 wxDataOutputStream
ds(stream
);
904 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
905 ds
.Write32(GetDateTime().GetAsDOS());
908 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
?
909 wx_truncate_cast(wxUint32
, m_CompressedSize
) : 0);
910 ds
.Write32(m_Size
!= wxInvalidOffset
?
911 wx_truncate_cast(wxUint32
, m_Size
) : 0);
914 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetLocalExtraLen());
915 ds
.Write16(extraLen
);
917 stream
.Write(name
, nameLen
);
919 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
921 return LOCAL_SIZE
+ nameLen
+ extraLen
;
924 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
926 wxUint16 nameLen
, extraLen
, commentLen
;
928 wxDataInputStream
ds(stream
);
930 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
932 SetVersionNeeded(ds
.Read16());
933 SetFlags(ds
.Read16());
934 SetMethod(ds
.Read16());
935 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
937 SetCompressedSize(ds
.Read32());
938 SetSize(ds
.Read32());
940 ds
>> nameLen
>> extraLen
>> commentLen
941 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
942 SetOffset(ds
.Read32());
944 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
946 if (extraLen
|| GetExtraLen()) {
947 Unique(m_Extra
, extraLen
);
949 stream
.Read(m_Extra
->GetData(), extraLen
);
953 m_Comment
= ReadString(stream
, commentLen
, conv
);
957 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
960 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
962 wxString unixName
= GetName(wxPATH_UNIX
);
963 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
964 const char *name
= name_buf
;
965 if (!name
) name
= "";
966 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
968 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
969 const char *comment
= comment_buf
;
970 if (!comment
) comment
= "";
971 wxUint16 commentLen
= wx_truncate_cast(wxUint16
, strlen(comment
));
973 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetExtraLen());
975 wxDataOutputStream
ds(stream
);
977 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
979 ds
.Write16(wx_truncate_cast(wxUint16
, GetVersionNeeded()));
980 ds
.Write16(wx_truncate_cast(wxUint16
, GetFlags()));
981 ds
.Write16(wx_truncate_cast(wxUint16
, GetMethod()));
982 ds
.Write32(GetDateTime().GetAsDOS());
983 ds
.Write32(GetCrc());
984 ds
.Write32(wx_truncate_cast(wxUint32
, GetCompressedSize()));
985 ds
.Write32(wx_truncate_cast(wxUint32
, GetSize()));
987 ds
.Write16(extraLen
);
989 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
990 << m_ExternalAttributes
<< wx_truncate_cast(wxUint32
, GetOffset());
992 stream
.Write(name
, nameLen
);
994 stream
.Write(GetExtra(), extraLen
);
995 stream
.Write(comment
, commentLen
);
997 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1000 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1001 // the 1st value is the signature then it is probably an info-zip record,
1002 // though there is a small chance that it is in fact a pkzip record which
1003 // happens to have the signature as it's CRC.
1005 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1007 wxDataInputStream
ds(stream
);
1009 m_Crc
= ds
.Read32();
1010 m_CompressedSize
= ds
.Read32();
1011 m_Size
= ds
.Read32();
1013 // if 1st value is the signature then this is probably an info-zip record
1014 if (m_Crc
== SUMS_MAGIC
)
1017 stream
.Read(buf
, sizeof(buf
));
1018 wxUint32 u1
= CrackUint32(buf
);
1019 wxUint32 u2
= CrackUint32(buf
+ 4);
1021 // look for the signature of the following record to decide which
1022 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1023 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1025 // it's a pkzip style record after all!
1026 stream
.Ungetch(buf
, sizeof(buf
));
1030 // it's an info-zip record as expected
1031 stream
.Ungetch(buf
+ 4, sizeof(buf
) - 4);
1032 m_Crc
= wx_truncate_cast(wxUint32
, m_CompressedSize
);
1033 m_CompressedSize
= m_Size
;
1035 return SUMS_SIZE
+ 4;
1042 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1043 wxFileOffset compressedSize
, wxFileOffset size
)
1046 m_CompressedSize
= compressedSize
;
1049 wxDataOutputStream
ds(stream
);
1052 ds
.Write32(wx_truncate_cast(wxUint32
, compressedSize
));
1053 ds
.Write32(wx_truncate_cast(wxUint32
, size
));
1059 /////////////////////////////////////////////////////////////////////////////
1060 // wxZipEndRec - holds the end of central directory record
1067 int GetDiskNumber() const { return m_DiskNumber
; }
1068 int GetStartDisk() const { return m_StartDisk
; }
1069 int GetEntriesHere() const { return m_EntriesHere
; }
1070 int GetTotalEntries() const { return m_TotalEntries
; }
1071 wxFileOffset
GetSize() const { return m_Size
; }
1072 wxFileOffset
GetOffset() const { return m_Offset
; }
1073 wxString
GetComment() const { return m_Comment
; }
1075 void SetDiskNumber(int num
)
1076 { m_DiskNumber
= wx_truncate_cast(wxUint16
, num
); }
1077 void SetStartDisk(int num
)
1078 { m_StartDisk
= wx_truncate_cast(wxUint16
, num
); }
1079 void SetEntriesHere(int num
)
1080 { m_EntriesHere
= wx_truncate_cast(wxUint16
, num
); }
1081 void SetTotalEntries(int num
)
1082 { m_TotalEntries
= wx_truncate_cast(wxUint16
, num
); }
1083 void SetSize(wxFileOffset size
)
1084 { m_Size
= wx_truncate_cast(wxUint32
, size
); }
1085 void SetOffset(wxFileOffset offset
)
1086 { m_Offset
= wx_truncate_cast(wxUint32
, offset
); }
1087 void SetComment(const wxString
& comment
)
1088 { m_Comment
= comment
; }
1090 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1091 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1094 wxUint16 m_DiskNumber
;
1095 wxUint16 m_StartDisk
;
1096 wxUint16 m_EntriesHere
;
1097 wxUint16 m_TotalEntries
;
1103 wxZipEndRec::wxZipEndRec()
1113 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1115 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1116 const char *comment
= comment_buf
;
1117 if (!comment
) comment
= "";
1118 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1120 wxDataOutputStream
ds(stream
);
1122 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1123 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1125 stream
.Write(comment
, commentLen
);
1127 return stream
.IsOk();
1130 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1132 wxDataInputStream
ds(stream
);
1133 wxUint16 commentLen
;
1135 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1136 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1139 m_Comment
= ReadString(stream
, commentLen
, conv
);
1142 if (m_DiskNumber
== 0 && m_StartDisk
== 0 &&
1143 m_EntriesHere
== m_TotalEntries
)
1146 wxLogError(_("unsupported zip archive"));
1152 /////////////////////////////////////////////////////////////////////////////
1153 // A weak link from an input stream to an output stream
1155 class wxZipStreamLink
1158 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1160 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1161 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1163 void Release(class wxZipInputStream
*WXUNUSED(s
))
1164 { if (--m_ref
== 0) delete this; }
1165 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1166 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1169 ~wxZipStreamLink() { }
1172 wxZipOutputStream
*m_stream
;
1176 /////////////////////////////////////////////////////////////////////////////
1179 // leave the default wxZipEntryPtr free for users
1180 wxDECLARE_SCOPED_PTR(wxZipEntry
, wx__ZipEntryPtr
)
1181 wxDEFINE_SCOPED_PTR (wxZipEntry
, wx__ZipEntryPtr
)
1185 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1186 wxMBConv
& conv
/*=wxConvLocal*/)
1187 : wxArchiveInputStream(stream
, conv
)
1192 #if 1 //WXWIN_COMPATIBILITY_2_6
1194 // Part of the compatibility constructor, which has been made inline to
1195 // avoid a problem with it not being exported by mingw 3.2.3
1197 void wxZipInputStream::Init(const wxString
& file
)
1199 // no error messages
1202 m_allowSeeking
= true;
1203 m_ffile
= wx_static_cast(wxFFileInputStream
*, m_parent_i_stream
);
1204 wx__ZipEntryPtr entry
;
1206 if (m_ffile
->Ok()) {
1208 entry
.reset(GetNextEntry());
1210 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1213 if (entry
.get() == NULL
)
1214 m_lasterror
= wxSTREAM_READ_ERROR
;
1217 wxInputStream
& wxZipInputStream::OpenFile(const wxString
& archive
)
1220 return *new wxFFileInputStream(archive
);
1223 #endif // WXWIN_COMPATIBILITY_2_6
1225 void wxZipInputStream::Init()
1227 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1233 m_parentSeekable
= false;
1234 m_weaklinks
= new wxZipWeakLinks
;
1235 m_streamlink
= NULL
;
1236 m_offsetAdjustment
= 0;
1237 m_position
= wxInvalidOffset
;
1240 m_lasterror
= m_parent_i_stream
->GetLastError();
1242 #if 1 //WXWIN_COMPATIBILITY_2_6
1243 m_allowSeeking
= false;
1247 wxZipInputStream::~wxZipInputStream()
1249 CloseDecompressor(m_decomp
);
1256 m_weaklinks
->Release(this);
1259 m_streamlink
->Release(this);
1262 wxString
wxZipInputStream::GetComment()
1264 if (m_position
== wxInvalidOffset
)
1265 if (!LoadEndRecord())
1266 return wxEmptyString
;
1268 if (!m_parentSeekable
&& Eof() && m_signature
) {
1269 m_lasterror
= wxSTREAM_NO_ERROR
;
1270 m_lasterror
= ReadLocal(true);
1276 int wxZipInputStream::GetTotalEntries()
1278 if (m_position
== wxInvalidOffset
)
1280 return m_TotalEntries
;
1283 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1285 wxZipStreamLink
*link
= NULL
;
1287 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1288 link
= new wxZipStreamLink(out
);
1290 m_streamlink
->Release(this);
1291 m_streamlink
= link
->AddRef();
1297 bool wxZipInputStream::LoadEndRecord()
1299 wxCHECK(m_position
== wxInvalidOffset
, false);
1305 // First find the end-of-central-directory record.
1306 if (!FindEndRecord()) {
1307 // failed, so either this is a non-seekable stream (ok), or not a zip
1308 if (m_parentSeekable
) {
1309 m_lasterror
= wxSTREAM_READ_ERROR
;
1310 wxLogError(_("invalid zip file"));
1315 wxFileOffset pos
= m_parent_i_stream
->TellI();
1317 //if (pos != wxInvalidOffset)
1318 if (pos
>= 0 && pos
<= LONG_MAX
)
1319 m_offsetAdjustment
= m_position
= pos
;
1326 // Read in the end record
1327 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1328 if (!endrec
.Read(*m_parent_i_stream
, GetConv())) {
1329 if (!*m_parent_i_stream
) {
1330 m_lasterror
= wxSTREAM_READ_ERROR
;
1333 // TODO: try this out
1334 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1337 m_TotalEntries
= endrec
.GetTotalEntries();
1338 m_Comment
= endrec
.GetComment();
1340 // Now find the central-directory. we have the file offset of
1341 // the CD, so look there first.
1342 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1343 ReadSignature() == CENTRAL_MAGIC
) {
1344 m_signature
= CENTRAL_MAGIC
;
1345 m_position
= endrec
.GetOffset();
1346 m_offsetAdjustment
= 0;
1350 // If it's not there, then it could be that the zip has been appended
1351 // to a self extractor, so take the CD size (also in endrec), subtract
1352 // it from the file offset of the end-central-directory and look there.
1353 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1354 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1355 m_signature
= CENTRAL_MAGIC
;
1356 m_position
= endPos
- endrec
.GetSize();
1357 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1361 wxLogError(_("can't find central directory in zip"));
1362 m_lasterror
= wxSTREAM_READ_ERROR
;
1366 // Find the end-of-central-directory record.
1367 // If found the stream will be positioned just past the 4 signature bytes.
1369 bool wxZipInputStream::FindEndRecord()
1371 if (!m_parent_i_stream
->IsSeekable())
1374 // usually it's 22 bytes in size and the last thing in the file
1377 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1381 m_parentSeekable
= true;
1384 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1386 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1389 // unfortunately, the record has a comment field that can be up to 65535
1390 // bytes in length, so if the signature not found then search backwards.
1391 wxFileOffset pos
= m_parent_i_stream
->TellI();
1392 const int BUFSIZE
= 1024;
1393 wxCharBuffer
buf(BUFSIZE
);
1395 memcpy(buf
.data(), magic
, 3);
1396 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1398 while (pos
> minpos
) {
1399 size_t len
= wx_truncate_cast(size_t,
1400 pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1401 memcpy(buf
.data() + len
, buf
, 3);
1404 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1405 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1408 char *p
= buf
.data() + len
;
1410 while (p
-- > buf
.data()) {
1411 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1412 size_t remainder
= buf
.data() + len
- p
;
1414 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1423 wxZipEntry
*wxZipInputStream::GetNextEntry()
1425 if (m_position
== wxInvalidOffset
)
1426 if (!LoadEndRecord())
1429 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1433 wx__ZipEntryPtr
entry(new wxZipEntry(m_entry
));
1434 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1435 return entry
.release();
1438 wxStreamError
wxZipInputStream::ReadCentral()
1443 if (m_signature
== END_MAGIC
)
1444 return wxSTREAM_EOF
;
1446 if (m_signature
!= CENTRAL_MAGIC
) {
1447 wxLogError(_("error reading zip central directory"));
1448 return wxSTREAM_READ_ERROR
;
1451 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1452 return wxSTREAM_READ_ERROR
;
1454 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1455 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1457 return wxSTREAM_READ_ERROR
;
1460 m_signature
= ReadSignature();
1462 if (m_offsetAdjustment
)
1463 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1464 m_entry
.SetKey(m_entry
.GetOffset());
1466 return wxSTREAM_NO_ERROR
;
1469 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1475 m_signature
= ReadSignature();
1477 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1478 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1479 m_streamlink
->Release(this);
1480 m_streamlink
= NULL
;
1484 while (m_signature
== CENTRAL_MAGIC
) {
1485 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1486 return wxSTREAM_EOF
;
1488 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1490 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
)
1491 return wxSTREAM_READ_ERROR
;
1493 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1495 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1496 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1497 entry
->SetComment(m_entry
.GetComment());
1498 entry
->SetDiskStart(m_entry
.GetDiskStart());
1499 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1500 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1501 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1503 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1506 m_signature
= ReadSignature();
1509 if (m_signature
== END_MAGIC
) {
1510 if (readEndRec
|| m_streamlink
) {
1512 endrec
.Read(*m_parent_i_stream
, GetConv());
1513 m_Comment
= endrec
.GetComment();
1516 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1517 m_streamlink
->Release(this);
1518 m_streamlink
= NULL
;
1521 return wxSTREAM_EOF
;
1524 if (m_signature
!= LOCAL_MAGIC
) {
1525 wxLogError(_("error reading zip local header"));
1526 return wxSTREAM_READ_ERROR
;
1529 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1531 m_entry
.SetOffset(m_position
);
1532 m_entry
.SetKey(m_position
);
1534 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1535 return wxSTREAM_READ_ERROR
;
1538 return wxSTREAM_NO_ERROR
;
1542 wxUint32
wxZipInputStream::ReadSignature()
1545 m_parent_i_stream
->Read(magic
, 4);
1546 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1549 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1551 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1552 return zipEntry
? OpenEntry(*zipEntry
) : false;
1557 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1559 if (m_position
== wxInvalidOffset
)
1560 if (!LoadEndRecord())
1562 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1564 wxCHECK(!IsOpened(), false);
1569 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1571 // can only open the current entry on a non-seekable stream
1572 wxCHECK(m_parentSeekable
, false);
1575 m_lasterror
= wxSTREAM_READ_ERROR
;
1580 if (m_parentSeekable
) {
1581 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1584 if (ReadSignature() != LOCAL_MAGIC
) {
1585 wxLogError(_("bad zipfile offset to entry"));
1590 if (m_parentSeekable
|| AtHeader()) {
1591 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1592 if (m_parentSeekable
) {
1593 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1595 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1597 m_weaklinks
->RemoveEntry(ref
->GetKey());
1599 if (entry
&& entry
!= ref
) {
1600 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1606 m_lasterror
= m_parent_i_stream
->GetLastError();
1610 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1612 wxASSERT(AfterHeader());
1614 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1620 if (compressedSize
!= wxInvalidOffset
) {
1621 m_store
->Open(compressedSize
);
1625 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1626 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1629 if (compressedSize
!= wxInvalidOffset
&&
1630 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1631 wxZlibInputStream::CanHandleGZip())) {
1632 m_store
->Open(compressedSize
);
1633 m_decomp
= OpenDecompressor(*m_store
);
1635 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1639 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1640 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1644 // Can be overriden to add support for additional decompression methods
1646 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1648 switch (m_entry
.GetMethod()) {
1649 case wxZIP_METHOD_STORE
:
1650 if (m_entry
.GetSize() == wxInvalidOffset
) {
1651 wxLogError(_("stored file length not in Zip header"));
1654 m_store
->Open(m_entry
.GetSize());
1657 case wxZIP_METHOD_DEFLATE
:
1659 m_inflate
= new wxZlibInputStream2(stream
);
1661 m_inflate
->Open(stream
);
1665 wxLogError(_("unsupported Zip compression method"));
1671 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1673 if (decomp
&& decomp
== m_rawin
)
1674 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1675 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1680 // Closes the current entry and positions the underlying stream at the start
1681 // of the next entry
1683 bool wxZipInputStream::CloseEntry()
1687 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1690 if (!m_parentSeekable
) {
1691 if (!IsOpened() && !OpenDecompressor(true))
1694 const int BUFSIZE
= 8192;
1695 wxCharBuffer
buf(BUFSIZE
);
1697 Read(buf
.data(), BUFSIZE
);
1699 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1702 if (m_lasterror
== wxSTREAM_EOF
)
1703 m_lasterror
= wxSTREAM_NO_ERROR
;
1705 CloseDecompressor(m_decomp
);
1707 m_entry
= wxZipEntry();
1714 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1717 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1718 m_lasterror
= wxSTREAM_READ_ERROR
;
1719 if (!IsOk() || !size
)
1722 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1724 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1725 m_lasterror
= m_decomp
->GetLastError();
1728 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1729 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1730 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1733 entry
->SetCrc(m_entry
.GetCrc());
1734 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1735 entry
->SetSize(m_entry
.GetSize());
1741 m_lasterror
= wxSTREAM_READ_ERROR
;
1743 if (m_parent_i_stream
->IsOk()) {
1744 if (m_entry
.GetSize() != TellI())
1745 wxLogError(_("reading zip stream (entry %s): bad length"),
1746 m_entry
.GetName().c_str());
1747 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1748 wxLogError(_("reading zip stream (entry %s): bad crc"),
1749 m_entry
.GetName().c_str());
1751 m_lasterror
= wxSTREAM_EOF
;
1759 #if 1 //WXWIN_COMPATIBILITY_2_6
1761 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1763 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1765 // seeking works when the stream is created with the compatibility
1767 if (!m_allowSeeking
)
1768 return wxInvalidOffset
;
1770 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1771 m_lasterror
= wxSTREAM_READ_ERROR
;
1773 return wxInvalidOffset
;
1775 // NB: since ZIP files don't natively support seeking, we have to
1776 // implement a brute force workaround -- reading all the data
1777 // between current and the new position (or between beginning of
1778 // the file and new position...)
1780 wxFileOffset nextpos
;
1781 wxFileOffset pos
= TellI();
1785 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1786 case wxFromStart
: nextpos
= seek
; break;
1787 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1788 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1791 wxFileOffset toskip
wxDUMMY_INITIALIZE(0);
1792 if ( nextpos
>= pos
)
1794 toskip
= nextpos
- pos
;
1798 wxZipEntry
current(m_entry
);
1800 if (!OpenEntry(current
))
1802 m_lasterror
= wxSTREAM_READ_ERROR
;
1810 const int BUFSIZE
= 4096;
1812 char buffer
[BUFSIZE
];
1813 while ( toskip
> 0 )
1815 sz
= wx_truncate_cast(size_t, wxMin(toskip
, BUFSIZE
));
1825 #endif // WXWIN_COMPATIBILITY_2_6
1828 /////////////////////////////////////////////////////////////////////////////
1831 #include "wx/listimpl.cpp"
1832 WX_DEFINE_LIST(wx__ZipEntryList
)
1834 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1836 wxMBConv
& conv
/*=wxConvLocal*/)
1837 : wxArchiveOutputStream(stream
, conv
),
1838 m_store(new wxStoredOutputStream(stream
)),
1841 m_initialData(new char[OUTPUT_LATENCY
]),
1850 m_offsetAdjustment(wxInvalidOffset
)
1854 wxZipOutputStream::~wxZipOutputStream()
1857 WX_CLEAR_LIST(wx__ZipEntryList
, m_entries
);
1861 delete [] m_initialData
;
1863 m_backlink
->Release(this);
1866 bool wxZipOutputStream::PutNextEntry(
1867 const wxString
& name
,
1868 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1869 wxFileOffset size
/*=wxInvalidOffset*/)
1871 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1874 bool wxZipOutputStream::PutNextDirEntry(
1875 const wxString
& name
,
1876 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1878 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1880 return PutNextEntry(entry
);
1883 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1884 wxZipInputStream
& inputStream
)
1886 wx__ZipEntryPtr
e(entry
);
1889 inputStream
.DoOpen(e
.get(), true) &&
1890 DoCreate(e
.release(), true) &&
1891 Write(inputStream
).IsOk() && inputStream
.Eof();
1894 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1896 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1899 return PutNextEntry(zipEntry
);
1902 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1903 wxArchiveInputStream
& stream
)
1905 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1907 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
1912 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
1915 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
1917 m_Comment
= inputStream
.GetComment();
1919 m_backlink
->Release(this);
1920 m_backlink
= inputStream
.MakeLink(this);
1924 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
1926 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
1929 void wxZipOutputStream::SetLevel(int level
)
1931 if (level
!= m_level
) {
1932 if (m_comp
!= m_deflate
)
1939 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
1947 // write the signature bytes right away
1948 wxDataOutputStream
ds(*m_parent_o_stream
);
1951 // and if this is the first entry test for seekability
1952 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
1954 bool logging
= wxLog::IsEnabled();
1957 wxFileOffset here
= m_parent_o_stream
->TellO();
1959 if (here
!= wxInvalidOffset
&& here
>= 4) {
1960 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
1961 m_offsetAdjustment
= here
- 4;
1963 wxLog::EnableLogging(logging
);
1965 m_parent_o_stream
->SeekO(here
);
1970 m_pending
->SetOffset(m_headerOffset
);
1972 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1977 m_lasterror
= wxSTREAM_NO_ERROR
;
1981 // Can be overriden to add support for additional compression methods
1983 wxOutputStream
*wxZipOutputStream::OpenCompressor(
1984 wxOutputStream
& stream
,
1986 const Buffer bufs
[])
1988 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
1990 && (IsParentSeekable()
1991 || entry
.GetCompressedSize() != wxInvalidOffset
1992 || entry
.GetSize() != wxInvalidOffset
)) {
1993 entry
.SetMethod(wxZIP_METHOD_STORE
);
1996 for (int i
= 0; bufs
[i
].m_data
; ++i
)
1997 size
+= bufs
[i
].m_size
;
1998 entry
.SetMethod(size
<= 6 ?
1999 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
2003 switch (entry
.GetMethod()) {
2004 case wxZIP_METHOD_STORE
:
2005 if (entry
.GetCompressedSize() == wxInvalidOffset
)
2006 entry
.SetCompressedSize(entry
.GetSize());
2009 case wxZIP_METHOD_DEFLATE
:
2011 int defbits
= wxZIP_DEFLATE_NORMAL
;
2012 switch (GetLevel()) {
2014 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2016 case 2: case 3: case 4:
2017 defbits
= wxZIP_DEFLATE_FAST
;
2020 defbits
= wxZIP_DEFLATE_EXTRA
;
2023 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2024 defbits
| wxZIP_SUMS_FOLLOW
);
2027 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2029 m_deflate
->Open(stream
);
2035 wxLogError(_("unsupported Zip compression method"));
2041 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2043 if (comp
== m_deflate
)
2045 else if (comp
!= m_store
)
2050 // This is called when OUPUT_LATENCY bytes has been written to the
2051 // wxZipOutputStream to actually create the zip entry.
2053 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2055 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2056 wx__ZipEntryPtr
spPending(m_pending
);
2060 { m_initialData
, m_initialSize
},
2061 { (const char*)buffer
, size
},
2068 m_comp
= OpenCompressor(*m_store
, *spPending
,
2069 m_initialSize
? bufs
: bufs
+ 1);
2071 if (IsParentSeekable()
2072 || (spPending
->m_Crc
2073 && spPending
->m_CompressedSize
!= wxInvalidOffset
2074 && spPending
->m_Size
!= wxInvalidOffset
))
2075 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2077 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2078 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2080 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2081 m_lasterror
= m_parent_o_stream
->GetLastError();
2084 m_entries
.push_back(spPending
.release());
2085 OnSysWrite(m_initialData
, m_initialSize
);
2091 // This is called to write out the zip entry when Close has been called
2092 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2094 void wxZipOutputStream::CreatePendingEntry()
2096 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2097 wx__ZipEntryPtr
spPending(m_pending
);
2099 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2102 // Initially compresses the data to memory, then fall back to 'store'
2103 // if the compressor makes the data larger rather than smaller.
2104 wxMemoryOutputStream mem
;
2105 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2106 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2110 if (comp
!= m_store
) {
2111 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2112 CloseCompressor(comp
);
2117 m_entrySize
= m_initialSize
;
2118 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2120 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2121 m_initialSize
= mem
.GetSize();
2122 mem
.CopyTo(m_initialData
, m_initialSize
);
2124 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2127 spPending
->SetSize(m_entrySize
);
2128 spPending
->SetCrc(m_crcAccumulator
);
2129 spPending
->SetCompressedSize(m_initialSize
);
2132 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2133 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2135 if (m_parent_o_stream
->IsOk()) {
2136 m_entries
.push_back(spPending
.release());
2138 m_store
->Write(m_initialData
, m_initialSize
);
2142 m_lasterror
= m_parent_o_stream
->GetLastError();
2145 // Write the 'central directory' and the 'end-central-directory' records.
2147 bool wxZipOutputStream::Close()
2151 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2156 endrec
.SetEntriesHere(m_entries
.size());
2157 endrec
.SetTotalEntries(m_entries
.size());
2158 endrec
.SetOffset(m_headerOffset
);
2159 endrec
.SetComment(m_Comment
);
2161 wx__ZipEntryList::iterator it
;
2162 wxFileOffset size
= 0;
2164 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2165 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2170 endrec
.SetSize(size
);
2171 endrec
.Write(*m_parent_o_stream
, GetConv());
2173 m_lasterror
= m_parent_o_stream
->GetLastError();
2176 m_lasterror
= wxSTREAM_EOF
;
2180 // Finish writing the current entry
2182 bool wxZipOutputStream::CloseEntry()
2184 if (IsOk() && m_pending
)
2185 CreatePendingEntry();
2191 CloseCompressor(m_comp
);
2194 wxFileOffset compressedSize
= m_store
->TellO();
2196 wxZipEntry
& entry
= *m_entries
.back();
2198 // When writing raw the crc and size can't be checked
2200 m_crcAccumulator
= entry
.GetCrc();
2201 m_entrySize
= entry
.GetSize();
2204 // Write the sums in the trailing 'data descriptor' if necessary
2205 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2206 wxASSERT(!IsParentSeekable());
2208 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2209 compressedSize
, m_entrySize
);
2210 m_lasterror
= m_parent_o_stream
->GetLastError();
2213 // If the local header didn't have the correct crc and size written to
2214 // it then seek back and fix it
2215 else if (m_crcAccumulator
!= entry
.GetCrc()
2216 || m_entrySize
!= entry
.GetSize()
2217 || compressedSize
!= entry
.GetCompressedSize())
2219 if (IsParentSeekable()) {
2220 wxFileOffset here
= m_parent_o_stream
->TellO();
2221 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2222 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2223 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2224 compressedSize
, m_entrySize
);
2225 m_parent_o_stream
->SeekO(here
);
2226 m_lasterror
= m_parent_o_stream
->GetLastError();
2228 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2232 m_headerOffset
+= m_headerSize
+ compressedSize
;
2239 m_lasterror
= m_parent_o_stream
->GetLastError();
2241 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2242 entry
.GetName().c_str());
2246 void wxZipOutputStream::Sync()
2248 if (IsOk() && m_pending
)
2249 CreatePendingEntry(NULL
, 0);
2251 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2254 m_lasterror
= m_comp
->GetLastError();
2258 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2260 if (IsOk() && m_pending
) {
2261 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2262 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2263 m_initialSize
+= size
;
2266 CreatePendingEntry(buffer
, size
);
2271 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2272 if (!IsOk() || !size
)
2275 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2276 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2277 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2278 m_entrySize
+= m_comp
->LastWrite();
2280 return m_comp
->LastWrite();
2283 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM