1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
6 // Copyright: (c) Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
11 #pragma implementation "zipstrm.h"
14 // For compilers that support precompilation, includes "wx.h".
15 #include "wx/wxprec.h"
25 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
27 #include "wx/zipstrm.h"
30 #include "wx/datstrm.h"
31 #include "wx/zstream.h"
32 #include "wx/mstream.h"
34 #include "wx/buffer.h"
35 #include "wx/ptr_scpd.h"
36 #include "wx/wfstream.h"
39 // value for the 'version needed to extract' field (20 means 2.0)
41 VERSION_NEEDED_TO_EXTRACT
= 20
44 // signatures for the various records (PKxx)
46 CENTRAL_MAGIC
= 0x02014b50, // central directory record
47 LOCAL_MAGIC
= 0x04034b50, // local header
48 END_MAGIC
= 0x06054b50, // end of central directory record
49 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
52 // unix file attributes. zip stores them in the high 16 bits of the
53 // 'external attributes' field, hence the extra zeros.
55 wxZIP_S_IFMT
= 0xF0000000,
56 wxZIP_S_IFDIR
= 0x40000000,
57 wxZIP_S_IFREG
= 0x80000000
60 // minimum sizes for the various records
68 // The number of bytes that must be written to an wxZipOutputStream before
69 // a zip entry is created. The purpose of this latency is so that
70 // OpenCompressor() can see a little data before deciding which compressor
76 // Some offsets into the local header
81 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
82 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
84 //FORCE_LINK_ME(zipstrm)
85 int _wx_link_dummy_func_zipstrm();
86 int _wx_link_dummy_func_zipstrm()
92 /////////////////////////////////////////////////////////////////////////////
95 // read a string of a given length
97 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
100 wxCharBuffer
buf(len
);
101 stream
.Read(buf
.data(), len
);
102 wxString
str(buf
, conv
);
107 wxStringBuffer
buf(str
, len
);
108 stream
.Read(buf
, len
);
115 // Decode a little endian wxUint32 number from a character array
117 static inline wxUint32
CrackUint32(const char *m
)
119 const unsigned char *n
= (const unsigned char*)m
;
120 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
123 // Temporarily lower the logging level in debug mode to avoid a warning
124 // from SeekI about seeking on a stream with data written back to it.
126 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
129 wxLogLevel level
= wxLog::GetLogLevel();
130 wxLog::SetLogLevel(wxLOG_Debug
- 1);
131 wxFileOffset result
= stream
.SeekI(pos
);
132 wxLog::SetLogLevel(level
);
135 return stream
.SeekI(pos
);
140 /////////////////////////////////////////////////////////////////////////////
141 // Stored input stream
142 // Trival decompressor for files which are 'stored' in the zip file.
144 class wxStoredInputStream
: public wxFilterInputStream
147 wxStoredInputStream(wxInputStream
& stream
);
149 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
150 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
152 virtual char Peek() { return wxInputStream::Peek(); }
153 virtual wxFileOffset
GetLength() const { return m_len
; }
156 virtual size_t OnSysRead(void *buffer
, size_t size
);
157 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
163 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
166 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
167 : wxFilterInputStream(stream
),
173 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
175 size_t count
= wxMin(size
, (size_t)(m_len
- m_pos
));
176 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
180 m_lasterror
= wxSTREAM_EOF
;
181 else if (!*m_parent_i_stream
)
182 m_lasterror
= wxSTREAM_READ_ERROR
;
188 /////////////////////////////////////////////////////////////////////////////
189 // Stored output stream
190 // Trival compressor for files which are 'stored' in the zip file.
192 class wxStoredOutputStream
: public wxFilterOutputStream
195 wxStoredOutputStream(wxOutputStream
& stream
) :
196 wxFilterOutputStream(stream
), m_pos(0) { }
200 m_lasterror
= wxSTREAM_NO_ERROR
;
205 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
206 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
210 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
213 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
215 if (!IsOk() || !size
)
217 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
219 m_lasterror
= wxSTREAM_WRITE_ERROR
;
225 /////////////////////////////////////////////////////////////////////////////
228 // Used to handle the unusal case of raw copying an entry of unknown
229 // length. This can only happen when the zip being copied from is being
230 // read from a non-seekable stream, and also was original written to a
231 // non-seekable stream.
233 // In this case there's no option but to decompress the stream to find
234 // it's length, but we can still write the raw compressed data to avoid the
235 // compression overhead (which is the greater one).
237 // Usage is like this:
238 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
239 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
241 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
242 // is something like the unix 'tee' command; it is a transparent filter, but
243 // allows the data read to be read a second time via an extra method 'GetData'.
245 // The wxRawInputStream then draws data through the tee using a decompressor
246 // then instead of returning the decompressed data, retuns the raw data
247 // from wxTeeInputStream::GetData().
249 class wxTeeInputStream
: public wxFilterInputStream
252 wxTeeInputStream(wxInputStream
& stream
);
254 size_t GetCount() const { return m_end
- m_start
; }
255 size_t GetData(char *buffer
, size_t size
);
260 wxInputStream
& Read(void *buffer
, size_t size
);
263 virtual size_t OnSysRead(void *buffer
, size_t size
);
264 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
268 wxMemoryBuffer m_buf
;
272 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
275 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
276 : wxFilterInputStream(stream
),
277 m_pos(0), m_buf(8192), m_start(0), m_end(0)
281 void wxTeeInputStream::Open()
283 m_pos
= m_start
= m_end
= 0;
284 m_lasterror
= wxSTREAM_NO_ERROR
;
287 bool wxTeeInputStream::Final()
289 bool final
= m_end
== m_buf
.GetDataLen();
290 m_end
= m_buf
.GetDataLen();
294 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
296 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
297 m_end
= m_buf
.GetDataLen();
298 m_buf
.AppendData(buffer
, count
);
302 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
304 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
305 m_lasterror
= m_parent_i_stream
->GetLastError();
309 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
312 size_t len
= m_buf
.GetDataLen();
313 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
314 m_buf
.SetDataLen(len
);
316 wxFAIL
; // we've already returned data that's now being ungot
319 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
326 if (size
> GetCount())
329 memcpy(buffer
, m_buf
+ m_start
, size
);
331 wxASSERT(m_start
<= m_end
);
334 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
335 size_t len
= m_buf
.GetDataLen();
336 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
338 memmove(buf
, buf
+ m_end
, len
);
339 m_buf
.UngetWriteBuf(len
);
346 class wxRawInputStream
: public wxFilterInputStream
349 wxRawInputStream(wxInputStream
& stream
);
350 virtual ~wxRawInputStream() { delete m_tee
; }
352 wxInputStream
* Open(wxInputStream
*decomp
);
353 wxInputStream
& GetTee() const { return *m_tee
; }
356 virtual size_t OnSysRead(void *buffer
, size_t size
);
357 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
361 wxTeeInputStream
*m_tee
;
363 enum { BUFSIZE
= 8192 };
364 wxCharBuffer m_dummy
;
366 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
369 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
370 : wxFilterInputStream(stream
),
372 m_tee(new wxTeeInputStream(stream
)),
377 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
380 m_parent_i_stream
= decomp
;
382 m_lasterror
= wxSTREAM_NO_ERROR
;
390 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
392 char *buf
= (char*)buffer
;
395 while (count
< size
&& IsOk())
397 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
398 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
400 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
403 if (n
== 0 && m_tee
->Final())
404 m_lasterror
= m_parent_i_stream
->GetLastError();
412 /////////////////////////////////////////////////////////////////////////////
413 // Zlib streams than can be reused without recreating.
415 class wxZlibOutputStream2
: public wxZlibOutputStream
418 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
419 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
421 bool Open(wxOutputStream
& stream
);
422 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
425 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
427 wxCHECK(m_pos
== wxInvalidOffset
, false);
429 m_deflate
->next_out
= m_z_buffer
;
430 m_deflate
->avail_out
= m_z_size
;
432 m_lasterror
= wxSTREAM_NO_ERROR
;
433 m_parent_o_stream
= &stream
;
435 if (deflateReset(m_deflate
) != Z_OK
) {
436 wxLogError(_("can't re-initialize zlib deflate stream"));
437 m_lasterror
= wxSTREAM_WRITE_ERROR
;
444 class wxZlibInputStream2
: public wxZlibInputStream
447 wxZlibInputStream2(wxInputStream
& stream
) :
448 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
450 bool Open(wxInputStream
& stream
);
453 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
455 m_inflate
->avail_in
= 0;
457 m_lasterror
= wxSTREAM_NO_ERROR
;
458 m_parent_i_stream
= &stream
;
460 if (inflateReset(m_inflate
) != Z_OK
) {
461 wxLogError(_("can't re-initialize zlib inflate stream"));
462 m_lasterror
= wxSTREAM_READ_ERROR
;
470 /////////////////////////////////////////////////////////////////////////////
471 // Class to hold wxZipEntry's Extra and LocalExtra fields
476 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
478 wxZipMemory
*AddRef() { m_ref
++; return this; }
479 void Release() { if (--m_ref
== 0) delete this; }
481 char *GetData() const { return m_data
; }
482 size_t GetSize() const { return m_size
; }
483 size_t GetCapacity() const { return m_capacity
; }
485 wxZipMemory
*Unique(size_t size
);
488 ~wxZipMemory() { delete m_data
; }
496 wxZipMemory
*wxZipMemory::Unique(size_t size
)
502 zm
= new wxZipMemory
;
507 if (zm
->m_capacity
< size
) {
509 zm
->m_data
= new char[size
];
510 zm
->m_capacity
= size
;
517 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
524 static inline void Release(wxZipMemory
*zm
)
530 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
536 static void Unique(wxZipMemory
*& zm
, size_t size
)
539 zm
= new wxZipMemory
;
541 zm
= zm
->Unique(size
);
545 /////////////////////////////////////////////////////////////////////////////
546 // Collection of weak references to entries
548 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
549 wxIntegerEqual
, _wxOffsetZipEntryMap
);
554 wxZipWeakLinks() : m_ref(1) { }
556 void Release(const wxZipInputStream
* WXUNUSED(x
))
557 { if (--m_ref
== 0) delete this; }
558 void Release(wxFileOffset key
)
559 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
561 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
562 void RemoveEntry(wxFileOffset key
)
563 { m_entries
.erase((_wxOffsetZipEntryMap::key_type
)key
); }
564 wxZipEntry
*GetEntry(wxFileOffset key
) const;
565 bool IsEmpty() const { return m_entries
.empty(); }
568 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
571 _wxOffsetZipEntryMap m_entries
;
574 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
576 m_entries
[(_wxOffsetZipEntryMap::key_type
)key
] = entry
;
581 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
583 _wxOffsetZipEntryMap::const_iterator it
=
584 m_entries
.find((_wxOffsetZipEntryMap::key_type
)key
);
585 return it
!= m_entries
.end() ? it
->second
: NULL
;
589 /////////////////////////////////////////////////////////////////////////////
592 wxZipEntry::wxZipEntry(
593 const wxString
& name
/*=wxEmptyString*/,
594 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
595 wxFileOffset size
/*=wxInvalidOffset*/)
597 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
598 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
599 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
601 m_Method(wxZIP_METHOD_DEFAULT
),
604 m_CompressedSize(wxInvalidOffset
),
606 m_Key(wxInvalidOffset
),
607 m_Offset(wxInvalidOffset
),
609 m_InternalAttributes(0),
610 m_ExternalAttributes(0),
620 wxZipEntry::~wxZipEntry()
623 m_backlink
->Release(m_Key
);
625 Release(m_LocalExtra
);
628 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
630 m_SystemMadeBy(e
.m_SystemMadeBy
),
631 m_VersionMadeBy(e
.m_VersionMadeBy
),
632 m_VersionNeeded(e
.m_VersionNeeded
),
634 m_Method(e
.m_Method
),
635 m_DateTime(e
.m_DateTime
),
637 m_CompressedSize(e
.m_CompressedSize
),
641 m_Offset(e
.m_Offset
),
642 m_Comment(e
.m_Comment
),
643 m_DiskStart(e
.m_DiskStart
),
644 m_InternalAttributes(e
.m_InternalAttributes
),
645 m_ExternalAttributes(e
.m_ExternalAttributes
),
646 m_Extra(AddRef(e
.m_Extra
)),
647 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
653 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
656 m_SystemMadeBy
= e
.m_SystemMadeBy
;
657 m_VersionMadeBy
= e
.m_VersionMadeBy
;
658 m_VersionNeeded
= e
.m_VersionNeeded
;
660 m_Method
= e
.m_Method
;
661 m_DateTime
= e
.m_DateTime
;
663 m_CompressedSize
= e
.m_CompressedSize
;
667 m_Offset
= e
.m_Offset
;
668 m_Comment
= e
.m_Comment
;
669 m_DiskStart
= e
.m_DiskStart
;
670 m_InternalAttributes
= e
.m_InternalAttributes
;
671 m_ExternalAttributes
= e
.m_ExternalAttributes
;
672 Copy(m_Extra
, e
.m_Extra
);
673 Copy(m_LocalExtra
, e
.m_LocalExtra
);
674 m_zipnotifier
= NULL
;
676 m_backlink
->Release(m_Key
);
683 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
685 bool isDir
= IsDir() && !m_Name
.empty();
687 switch (wxFileName::GetFormat(format
)) {
690 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
691 for (size_t i
= name
.length() - 1; i
> 0; --i
)
692 if (name
[i
] == _T('/'))
698 return isDir
? m_Name
+ _T("/") : m_Name
;
707 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
709 fn
.Assign(m_Name
, wxPATH_UNIX
);
711 return fn
.GetFullPath(format
);
714 // Static - Internally tars and zips use forward slashes for the path
715 // separator, absolute paths aren't allowed, and directory names have a
716 // trailing slash. This function converts a path into this internal format,
717 // but without a trailing slash for a directory.
719 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
720 wxPathFormat format
/*=wxPATH_NATIVE*/,
721 bool *pIsDir
/*=NULL*/)
725 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
726 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
730 bool isDir
= !internal
.empty() && internal
.Last() == '/';
734 internal
.erase(internal
.length() - 1);
736 while (!internal
.empty() && *internal
.begin() == '/')
737 internal
.erase(0, 1);
738 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
739 internal
.erase(0, 2);
740 if (internal
== _T(".") || internal
== _T(".."))
741 internal
= wxEmptyString
;
746 void wxZipEntry::SetSystemMadeBy(int system
)
748 int mode
= GetMode();
749 bool wasUnix
= IsMadeByUnix();
751 m_SystemMadeBy
= (wxUint8
)system
;
753 if (!wasUnix
&& IsMadeByUnix()) {
756 } else if (wasUnix
&& !IsMadeByUnix()) {
757 m_ExternalAttributes
&= 0xffff;
761 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
764 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
766 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
768 if (IsMadeByUnix()) {
769 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
771 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
773 m_ExternalAttributes
|= wxZIP_S_IFREG
;
777 // Return unix style permission bits
779 int wxZipEntry::GetMode() const
781 // return unix permissions if present
783 return (m_ExternalAttributes
>> 16) & 0777;
785 // otherwise synthesize from the dos attribs
787 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
789 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
795 // Set unix permissions
797 void wxZipEntry::SetMode(int mode
)
799 // Set dos attrib bits to be compatible
801 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
803 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
805 // set the actual unix permission bits if the system type allows
806 if (IsMadeByUnix()) {
807 m_ExternalAttributes
&= ~(0777L << 16);
808 m_ExternalAttributes
|= (mode
& 0777L) << 16;
812 const char *wxZipEntry::GetExtra() const
814 return m_Extra
? m_Extra
->GetData() : NULL
;
817 size_t wxZipEntry::GetExtraLen() const
819 return m_Extra
? m_Extra
->GetSize() : 0;
822 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
824 Unique(m_Extra
, len
);
826 memcpy(m_Extra
->GetData(), extra
, len
);
829 const char *wxZipEntry::GetLocalExtra() const
831 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
834 size_t wxZipEntry::GetLocalExtraLen() const
836 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
839 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
841 Unique(m_LocalExtra
, len
);
843 memcpy(m_LocalExtra
->GetData(), extra
, len
);
846 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
848 wxArchiveEntry::UnsetNotifier();
849 m_zipnotifier
= ¬ifier
;
850 m_zipnotifier
->OnEntryUpdated(*this);
853 void wxZipEntry::Notify()
856 m_zipnotifier
->OnEntryUpdated(*this);
857 else if (GetNotifier())
858 GetNotifier()->OnEntryUpdated(*this);
861 void wxZipEntry::UnsetNotifier()
863 wxArchiveEntry::UnsetNotifier();
864 m_zipnotifier
= NULL
;
867 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
869 wxUint16 nameLen
, extraLen
;
870 wxUint32 compressedSize
, size
, crc
;
872 wxDataInputStream
ds(stream
);
874 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
875 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
876 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
878 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
880 if (sumsValid
|| crc
)
882 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
883 m_CompressedSize
= compressedSize
;
884 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
887 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
889 if (extraLen
|| GetLocalExtraLen()) {
890 Unique(m_LocalExtra
, extraLen
);
892 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
895 return LOCAL_SIZE
+ nameLen
+ extraLen
;
898 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
900 wxString unixName
= GetName(wxPATH_UNIX
);
901 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
902 const char *name
= name_buf
;
903 if (!name
) name
= "";
904 wxUint16 nameLen
= (wxUint16
)strlen(name
);
906 wxDataOutputStream
ds(stream
);
908 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
909 ds
.Write32(GetDateTime().GetAsDOS());
912 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
? (wxUint32
)m_CompressedSize
: 0);
913 ds
.Write32(m_Size
!= wxInvalidOffset
? (wxUint32
)m_Size
: 0);
916 wxUint16 extraLen
= (wxUint16
)GetLocalExtraLen();
917 ds
.Write16(extraLen
);
919 stream
.Write(name
, nameLen
);
921 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
923 return LOCAL_SIZE
+ nameLen
+ extraLen
;
926 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
928 wxUint16 nameLen
, extraLen
, commentLen
;
930 wxDataInputStream
ds(stream
);
932 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
934 SetVersionNeeded(ds
.Read16());
935 SetFlags(ds
.Read16());
936 SetMethod(ds
.Read16());
937 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
939 SetCompressedSize(ds
.Read32());
940 SetSize(ds
.Read32());
942 ds
>> nameLen
>> extraLen
>> commentLen
943 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
944 SetOffset(ds
.Read32());
946 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
948 if (extraLen
|| GetExtraLen()) {
949 Unique(m_Extra
, extraLen
);
951 stream
.Read(m_Extra
->GetData(), extraLen
);
955 m_Comment
= ReadString(stream
, commentLen
, conv
);
959 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
962 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
964 wxString unixName
= GetName(wxPATH_UNIX
);
965 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
966 const char *name
= name_buf
;
967 if (!name
) name
= "";
968 wxUint16 nameLen
= (wxUint16
)strlen(name
);
970 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
971 const char *comment
= comment_buf
;
972 if (!comment
) comment
= "";
973 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
975 wxUint16 extraLen
= (wxUint16
)GetExtraLen();
977 wxDataOutputStream
ds(stream
);
979 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
981 ds
.Write16((wxUint16
)GetVersionNeeded());
982 ds
.Write16((wxUint16
)GetFlags());
983 ds
.Write16((wxUint16
)GetMethod());
984 ds
.Write32(GetDateTime().GetAsDOS());
985 ds
.Write32(GetCrc());
986 ds
.Write32((wxUint32
)GetCompressedSize());
987 ds
.Write32((wxUint32
)GetSize());
989 ds
.Write16(extraLen
);
991 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
992 << m_ExternalAttributes
<< (wxUint32
)GetOffset();
994 stream
.Write(name
, nameLen
);
996 stream
.Write(GetExtra(), extraLen
);
997 stream
.Write(comment
, commentLen
);
999 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1002 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1003 // the 1st value is the signature then it is probably an info-zip record,
1004 // though there is a small chance that it is in fact a pkzip record which
1005 // happens to have the signature as it's CRC.
1007 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1009 wxDataInputStream
ds(stream
);
1011 m_Crc
= ds
.Read32();
1012 m_CompressedSize
= ds
.Read32();
1013 m_Size
= ds
.Read32();
1015 // if 1st value is the signature then this is probably an info-zip record
1016 if (m_Crc
== SUMS_MAGIC
)
1019 stream
.Read(buf
, sizeof(buf
));
1020 wxUint32 u1
= CrackUint32(buf
);
1021 wxUint32 u2
= CrackUint32(buf
+ 4);
1023 // look for the signature of the following record to decide which
1024 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1025 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1027 // it's a pkzip style record after all!
1028 stream
.Ungetch(buf
, sizeof(buf
));
1032 // it's an info-zip record as expected
1033 stream
.Ungetch(buf
+ 4, sizeof(buf
) - 4);
1034 m_Crc
= (wxUint32
)m_CompressedSize
;
1035 m_CompressedSize
= m_Size
;
1037 return SUMS_SIZE
+ 4;
1044 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1045 wxFileOffset compressedSize
, wxFileOffset size
)
1048 m_CompressedSize
= compressedSize
;
1051 wxDataOutputStream
ds(stream
);
1054 ds
.Write32((wxUint32
)compressedSize
);
1055 ds
.Write32((wxUint32
)size
);
1061 /////////////////////////////////////////////////////////////////////////////
1062 // wxZipEndRec - holds the end of central directory record
1069 int GetDiskNumber() const { return m_DiskNumber
; }
1070 int GetStartDisk() const { return m_StartDisk
; }
1071 int GetEntriesHere() const { return m_EntriesHere
; }
1072 int GetTotalEntries() const { return m_TotalEntries
; }
1073 wxFileOffset
GetSize() const { return m_Size
; }
1074 wxFileOffset
GetOffset() const { return m_Offset
; }
1075 wxString
GetComment() const { return m_Comment
; }
1077 void SetDiskNumber(int num
) { m_DiskNumber
= (wxUint16
)num
; }
1078 void SetStartDisk(int num
) { m_StartDisk
= (wxUint16
)num
; }
1079 void SetEntriesHere(int num
) { m_EntriesHere
= (wxUint16
)num
; }
1080 void SetTotalEntries(int num
) { m_TotalEntries
= (wxUint16
)num
; }
1081 void SetSize(wxFileOffset size
) { m_Size
= (wxUint32
)size
; }
1082 void SetOffset(wxFileOffset offset
) { m_Offset
= (wxUint32
)offset
; }
1083 void SetComment(const wxString
& comment
) { m_Comment
= comment
; }
1085 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1086 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1089 wxUint16 m_DiskNumber
;
1090 wxUint16 m_StartDisk
;
1091 wxUint16 m_EntriesHere
;
1092 wxUint16 m_TotalEntries
;
1098 wxZipEndRec::wxZipEndRec()
1108 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1110 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1111 const char *comment
= comment_buf
;
1112 if (!comment
) comment
= "";
1113 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1115 wxDataOutputStream
ds(stream
);
1117 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1118 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1120 stream
.Write(comment
, commentLen
);
1122 return stream
.IsOk();
1125 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1127 wxDataInputStream
ds(stream
);
1128 wxUint16 commentLen
;
1130 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1131 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1134 m_Comment
= ReadString(stream
, commentLen
, conv
);
1137 if (m_DiskNumber
== 0 && m_StartDisk
== 0 &&
1138 m_EntriesHere
== m_TotalEntries
)
1141 wxLogError(_("unsupported zip archive"));
1147 /////////////////////////////////////////////////////////////////////////////
1148 // A weak link from an input stream to an output stream
1150 class wxZipStreamLink
1153 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1155 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1156 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1158 void Release(class wxZipInputStream
*WXUNUSED(s
))
1159 { if (--m_ref
== 0) delete this; }
1160 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1161 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1164 ~wxZipStreamLink() { }
1167 wxZipOutputStream
*m_stream
;
1171 /////////////////////////////////////////////////////////////////////////////
1174 wxDECLARE_SCOPED_PTR(wxZipEntry
, _wxZipEntryPtr
)
1175 wxDEFINE_SCOPED_PTR (wxZipEntry
, _wxZipEntryPtr
)
1179 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1180 wxMBConv
& conv
/*=wxConvLocal*/)
1181 : wxArchiveInputStream(stream
, conv
)
1187 // Compatibility constructor
1189 wxZipInputStream::wxZipInputStream(const wxString
& archive
,
1190 const wxString
& file
)
1191 : wxArchiveInputStream(OpenFile(archive
), wxConvLocal
)
1193 // no error messages
1196 _wxZipEntryPtr entry
;
1198 if (m_ffile
->Ok()) {
1200 entry
.reset(GetNextEntry());
1202 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1205 if (entry
.get() == NULL
)
1206 m_lasterror
= wxSTREAM_READ_ERROR
;
1209 wxInputStream
& wxZipInputStream::OpenFile(const wxString
& archive
)
1212 m_ffile
= new wxFFileInputStream(archive
);
1216 void wxZipInputStream::Init()
1218 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1224 m_parentSeekable
= false;
1225 m_weaklinks
= new wxZipWeakLinks
;
1226 m_streamlink
= NULL
;
1227 m_offsetAdjustment
= 0;
1228 m_position
= wxInvalidOffset
;
1231 m_lasterror
= m_parent_i_stream
->GetLastError();
1234 wxZipInputStream::~wxZipInputStream()
1236 CloseDecompressor(m_decomp
);
1243 m_weaklinks
->Release(this);
1246 m_streamlink
->Release(this);
1249 wxString
wxZipInputStream::GetComment()
1251 if (m_position
== wxInvalidOffset
)
1252 if (!LoadEndRecord())
1253 return wxEmptyString
;
1255 if (!m_parentSeekable
&& Eof() && m_signature
) {
1256 m_lasterror
= wxSTREAM_NO_ERROR
;
1257 m_lasterror
= ReadLocal(true);
1263 int wxZipInputStream::GetTotalEntries()
1265 if (m_position
== wxInvalidOffset
)
1267 return m_TotalEntries
;
1270 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1272 wxZipStreamLink
*link
= NULL
;
1274 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1275 link
= new wxZipStreamLink(out
);
1277 m_streamlink
->Release(this);
1278 m_streamlink
= link
->AddRef();
1284 bool wxZipInputStream::LoadEndRecord()
1286 wxCHECK(m_position
== wxInvalidOffset
, false);
1292 // First find the end-of-central-directory record.
1293 if (!FindEndRecord()) {
1294 // failed, so either this is a non-seekable stream (ok), or not a zip
1295 if (m_parentSeekable
) {
1296 m_lasterror
= wxSTREAM_READ_ERROR
;
1297 wxLogError(_("invalid zip file"));
1302 wxFileOffset pos
= m_parent_i_stream
->TellI();
1304 //if (pos != wxInvalidOffset)
1305 if (pos
>= 0 && pos
<= LONG_MAX
)
1306 m_offsetAdjustment
= m_position
= pos
;
1313 // Read in the end record
1314 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1315 if (!endrec
.Read(*m_parent_i_stream
, GetConv())) {
1316 if (!*m_parent_i_stream
) {
1317 m_lasterror
= wxSTREAM_READ_ERROR
;
1320 // TODO: try this out
1321 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1324 m_TotalEntries
= endrec
.GetTotalEntries();
1325 m_Comment
= endrec
.GetComment();
1327 // Now find the central-directory. we have the file offset of
1328 // the CD, so look there first.
1329 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1330 ReadSignature() == CENTRAL_MAGIC
) {
1331 m_signature
= CENTRAL_MAGIC
;
1332 m_position
= endrec
.GetOffset();
1333 m_offsetAdjustment
= 0;
1337 // If it's not there, then it could be that the zip has been appended
1338 // to a self extractor, so take the CD size (also in endrec), subtract
1339 // it from the file offset of the end-central-directory and look there.
1340 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1341 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1342 m_signature
= CENTRAL_MAGIC
;
1343 m_position
= endPos
- endrec
.GetSize();
1344 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1348 wxLogError(_("can't find central directory in zip"));
1349 m_lasterror
= wxSTREAM_READ_ERROR
;
1353 // Find the end-of-central-directory record.
1354 // If found the stream will be positioned just past the 4 signature bytes.
1356 bool wxZipInputStream::FindEndRecord()
1358 if (!m_parent_i_stream
->IsSeekable())
1361 // usually it's 22 bytes in size and the last thing in the file
1364 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1368 m_parentSeekable
= true;
1371 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1373 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1376 // unfortunately, the record has a comment field that can be up to 65535
1377 // bytes in length, so if the signature not found then search backwards.
1378 wxFileOffset pos
= m_parent_i_stream
->TellI();
1379 const int BUFSIZE
= 1024;
1380 wxCharBuffer
buf(BUFSIZE
);
1382 memcpy(buf
.data(), magic
, 3);
1383 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1385 while (pos
> minpos
) {
1386 size_t len
= (size_t)(pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1387 memcpy(buf
.data() + len
, buf
, 3);
1390 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1391 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1394 char *p
= buf
.data() + len
;
1396 while (p
-- > buf
.data()) {
1397 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1398 size_t remainder
= buf
.data() + len
- p
;
1400 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1409 wxZipEntry
*wxZipInputStream::GetNextEntry()
1411 if (m_position
== wxInvalidOffset
)
1412 if (!LoadEndRecord())
1415 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1419 _wxZipEntryPtr
entry(new wxZipEntry(m_entry
));
1420 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1421 return entry
.release();
1424 wxStreamError
wxZipInputStream::ReadCentral()
1429 if (m_signature
== END_MAGIC
)
1430 return wxSTREAM_EOF
;
1432 if (m_signature
!= CENTRAL_MAGIC
) {
1433 wxLogError(_("error reading zip central directory"));
1434 return wxSTREAM_READ_ERROR
;
1437 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1438 return wxSTREAM_READ_ERROR
;
1440 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1441 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1443 return wxSTREAM_READ_ERROR
;
1446 m_signature
= ReadSignature();
1448 if (m_offsetAdjustment
)
1449 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1450 m_entry
.SetKey(m_entry
.GetOffset());
1452 return wxSTREAM_NO_ERROR
;
1455 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1461 m_signature
= ReadSignature();
1463 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1464 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1465 m_streamlink
->Release(this);
1466 m_streamlink
= NULL
;
1470 while (m_signature
== CENTRAL_MAGIC
) {
1471 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1472 return wxSTREAM_EOF
;
1474 m_position
+= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1476 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
)
1477 return wxSTREAM_READ_ERROR
;
1479 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1481 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1482 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1483 entry
->SetComment(m_entry
.GetComment());
1484 entry
->SetDiskStart(m_entry
.GetDiskStart());
1485 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1486 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1487 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1489 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1492 m_signature
= ReadSignature();
1495 if (m_signature
== END_MAGIC
) {
1496 if (readEndRec
|| m_streamlink
) {
1498 endrec
.Read(*m_parent_i_stream
, GetConv());
1499 m_Comment
= endrec
.GetComment();
1502 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1503 m_streamlink
->Release(this);
1504 m_streamlink
= NULL
;
1507 return wxSTREAM_EOF
;
1510 if (m_signature
!= LOCAL_MAGIC
) {
1511 wxLogError(_("error reading zip local header"));
1512 return wxSTREAM_READ_ERROR
;
1515 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1517 m_entry
.SetOffset(m_position
);
1518 m_entry
.SetKey(m_position
);
1520 if (m_parent_i_stream
->GetLastError() == wxSTREAM_READ_ERROR
) {
1521 return wxSTREAM_READ_ERROR
;
1524 return wxSTREAM_NO_ERROR
;
1528 wxUint32
wxZipInputStream::ReadSignature()
1531 m_parent_i_stream
->Read(magic
, 4);
1532 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1535 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1537 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1538 return zipEntry
? OpenEntry(*zipEntry
) : false;
1543 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1545 if (m_position
== wxInvalidOffset
)
1546 if (!LoadEndRecord())
1548 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1550 wxCHECK(!IsOpened(), false);
1555 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1557 // can only open the current entry on a non-seekable stream
1558 wxCHECK(m_parentSeekable
, false);
1561 m_lasterror
= wxSTREAM_READ_ERROR
;
1566 if (m_parentSeekable
) {
1567 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1570 if (ReadSignature() != LOCAL_MAGIC
) {
1571 wxLogError(_("bad zipfile offset to entry"));
1576 if (m_parentSeekable
|| AtHeader()) {
1577 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1578 if (m_parentSeekable
) {
1579 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1581 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1583 m_weaklinks
->RemoveEntry(ref
->GetKey());
1585 if (entry
&& entry
!= ref
) {
1586 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1592 m_lasterror
= m_parent_i_stream
->GetLastError();
1596 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1598 wxASSERT(AfterHeader());
1600 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1606 if (compressedSize
!= wxInvalidOffset
) {
1607 m_store
->Open(compressedSize
);
1611 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1612 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1615 if (compressedSize
!= wxInvalidOffset
&&
1616 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1617 wxZlibInputStream::CanHandleGZip())) {
1618 m_store
->Open(compressedSize
);
1619 m_decomp
= OpenDecompressor(*m_store
);
1621 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1625 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1626 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1630 // Can be overriden to add support for additional decompression methods
1632 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1634 switch (m_entry
.GetMethod()) {
1635 case wxZIP_METHOD_STORE
:
1636 if (m_entry
.GetSize() == wxInvalidOffset
) {
1637 wxLogError(_("stored file length not in Zip header"));
1640 m_store
->Open(m_entry
.GetSize());
1643 case wxZIP_METHOD_DEFLATE
:
1645 m_inflate
= new wxZlibInputStream2(stream
);
1647 m_inflate
->Open(stream
);
1651 wxLogError(_("unsupported Zip compression method"));
1657 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1659 if (decomp
&& decomp
== m_rawin
)
1660 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1661 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1666 // Closes the current entry and positions the underlying stream at the start
1667 // of the next entry
1669 bool wxZipInputStream::CloseEntry()
1673 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1676 if (!m_parentSeekable
) {
1677 if (!IsOpened() && !OpenDecompressor(true))
1680 const int BUFSIZE
= 8192;
1681 wxCharBuffer
buf(BUFSIZE
);
1683 Read(buf
.data(), BUFSIZE
);
1685 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1688 if (m_lasterror
== wxSTREAM_EOF
)
1689 m_lasterror
= wxSTREAM_NO_ERROR
;
1691 CloseDecompressor(m_decomp
);
1693 m_entry
= wxZipEntry();
1700 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1703 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1704 m_lasterror
= wxSTREAM_READ_ERROR
;
1705 if (!IsOk() || !size
)
1708 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1710 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1711 m_lasterror
= m_decomp
->GetLastError();
1714 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1715 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1716 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1719 entry
->SetCrc(m_entry
.GetCrc());
1720 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1721 entry
->SetSize(m_entry
.GetSize());
1727 m_lasterror
= wxSTREAM_READ_ERROR
;
1729 if (m_parent_i_stream
->IsOk()) {
1730 if (m_entry
.GetSize() != TellI())
1731 wxLogError(_("reading zip stream (entry %s): bad length"),
1732 m_entry
.GetName().c_str());
1733 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1734 wxLogError(_("reading zip stream (entry %s): bad crc"),
1735 m_entry
.GetName().c_str());
1737 m_lasterror
= wxSTREAM_EOF
;
1745 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1747 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1750 return wxInvalidOffset
;
1752 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1753 m_lasterror
= wxSTREAM_READ_ERROR
;
1755 return wxInvalidOffset
;
1757 // NB: since ZIP files don't natively support seeking, we have to
1758 // implement a brute force workaround -- reading all the data
1759 // between current and the new position (or between beginning of
1760 // the file and new position...)
1762 wxFileOffset nextpos
;
1763 wxFileOffset pos
= TellI();
1767 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1768 case wxFromStart
: nextpos
= seek
; break;
1769 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1770 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1773 size_t toskip
wxDUMMY_INITIALIZE(0);
1774 if ( nextpos
>= pos
)
1776 toskip
= (size_t)(nextpos
- pos
);
1780 wxZipEntry
current(m_entry
);
1782 if (!OpenEntry(current
))
1784 m_lasterror
= wxSTREAM_READ_ERROR
;
1787 toskip
= (size_t)nextpos
;
1792 const size_t BUFSIZE
= 4096;
1794 char buffer
[BUFSIZE
];
1795 while ( toskip
> 0 )
1797 sz
= wxMin(toskip
, BUFSIZE
);
1808 /////////////////////////////////////////////////////////////////////////////
1811 #include "wx/listimpl.cpp"
1812 WX_DEFINE_LIST(_wxZipEntryList
);
1814 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1816 wxMBConv
& conv
/*=wxConvLocal*/)
1817 : wxArchiveOutputStream(stream
, conv
),
1818 m_store(new wxStoredOutputStream(stream
)),
1821 m_initialData(new char[OUTPUT_LATENCY
]),
1830 m_offsetAdjustment(wxInvalidOffset
)
1834 wxZipOutputStream::~wxZipOutputStream()
1837 WX_CLEAR_LIST(_wxZipEntryList
, m_entries
);
1841 delete [] m_initialData
;
1843 m_backlink
->Release(this);
1846 bool wxZipOutputStream::PutNextEntry(
1847 const wxString
& name
,
1848 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
1849 wxFileOffset size
/*=wxInvalidOffset*/)
1851 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
1854 bool wxZipOutputStream::PutNextDirEntry(
1855 const wxString
& name
,
1856 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
1858 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
1860 return PutNextEntry(entry
);
1863 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
1864 wxZipInputStream
& inputStream
)
1866 _wxZipEntryPtr
e(entry
);
1869 inputStream
.DoOpen(e
.get(), true) &&
1870 DoCreate(e
.release(), true) &&
1871 Write(inputStream
).IsOk() && inputStream
.Eof();
1874 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
1876 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1879 return PutNextEntry(zipEntry
);
1882 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
1883 wxArchiveInputStream
& stream
)
1885 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
1887 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
1892 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
1895 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
1897 m_Comment
= inputStream
.GetComment();
1899 m_backlink
->Release(this);
1900 m_backlink
= inputStream
.MakeLink(this);
1904 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
1906 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
1909 void wxZipOutputStream::SetLevel(int level
)
1911 if (level
!= m_level
) {
1912 if (m_comp
!= m_deflate
)
1919 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
1927 // write the signature bytes right away
1928 wxDataOutputStream
ds(*m_parent_o_stream
);
1931 // and if this is the first entry test for seekability
1932 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
1934 bool logging
= wxLog::IsEnabled();
1937 wxFileOffset here
= m_parent_o_stream
->TellO();
1939 if (here
!= wxInvalidOffset
&& here
>= 4) {
1940 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
1941 m_offsetAdjustment
= here
- 4;
1943 wxLog::EnableLogging(logging
);
1945 m_parent_o_stream
->SeekO(here
);
1950 m_pending
->SetOffset(m_headerOffset
);
1952 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1957 m_lasterror
= wxSTREAM_NO_ERROR
;
1961 // Can be overriden to add support for additional compression methods
1963 wxOutputStream
*wxZipOutputStream::OpenCompressor(
1964 wxOutputStream
& stream
,
1966 const Buffer bufs
[])
1968 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
1970 && (IsParentSeekable()
1971 || entry
.GetCompressedSize() != wxInvalidOffset
1972 || entry
.GetSize() != wxInvalidOffset
)) {
1973 entry
.SetMethod(wxZIP_METHOD_STORE
);
1976 for (int i
= 0; bufs
[i
].m_data
; ++i
)
1977 size
+= bufs
[i
].m_size
;
1978 entry
.SetMethod(size
<= 6 ?
1979 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
1983 switch (entry
.GetMethod()) {
1984 case wxZIP_METHOD_STORE
:
1985 if (entry
.GetCompressedSize() == wxInvalidOffset
)
1986 entry
.SetCompressedSize(entry
.GetSize());
1989 case wxZIP_METHOD_DEFLATE
:
1991 int defbits
= wxZIP_DEFLATE_NORMAL
;
1992 switch (GetLevel()) {
1994 defbits
= wxZIP_DEFLATE_SUPERFAST
;
1996 case 2: case 3: case 4:
1997 defbits
= wxZIP_DEFLATE_FAST
;
2000 defbits
= wxZIP_DEFLATE_EXTRA
;
2003 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2004 defbits
| wxZIP_SUMS_FOLLOW
);
2007 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2009 m_deflate
->Open(stream
);
2015 wxLogError(_("unsupported Zip compression method"));
2021 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2023 if (comp
== m_deflate
)
2025 else if (comp
!= m_store
)
2030 // This is called when OUPUT_LATENCY bytes has been written to the
2031 // wxZipOutputStream to actually create the zip entry.
2033 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2035 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2036 _wxZipEntryPtr
spPending(m_pending
);
2040 { m_initialData
, m_initialSize
},
2041 { (const char*)buffer
, size
},
2048 m_comp
= OpenCompressor(*m_store
, *spPending
,
2049 m_initialSize
? bufs
: bufs
+ 1);
2051 if (IsParentSeekable()
2052 || (spPending
->m_Crc
2053 && spPending
->m_CompressedSize
!= wxInvalidOffset
2054 && spPending
->m_Size
!= wxInvalidOffset
))
2055 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2057 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2058 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2060 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2061 m_lasterror
= m_parent_o_stream
->GetLastError();
2064 m_entries
.push_back(spPending
.release());
2065 OnSysWrite(m_initialData
, m_initialSize
);
2071 // This is called to write out the zip entry when Close has been called
2072 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2074 void wxZipOutputStream::CreatePendingEntry()
2076 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2077 _wxZipEntryPtr
spPending(m_pending
);
2079 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2082 // Initially compresses the data to memory, then fall back to 'store'
2083 // if the compressor makes the data larger rather than smaller.
2084 wxMemoryOutputStream mem
;
2085 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2086 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2090 if (comp
!= m_store
) {
2091 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2092 CloseCompressor(comp
);
2097 m_entrySize
= m_initialSize
;
2098 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2100 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2101 m_initialSize
= mem
.GetSize();
2102 mem
.CopyTo(m_initialData
, m_initialSize
);
2104 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2107 spPending
->SetSize(m_entrySize
);
2108 spPending
->SetCrc(m_crcAccumulator
);
2109 spPending
->SetCompressedSize(m_initialSize
);
2112 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2113 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2115 if (m_parent_o_stream
->IsOk()) {
2116 m_entries
.push_back(spPending
.release());
2118 m_store
->Write(m_initialData
, m_initialSize
);
2122 m_lasterror
= m_parent_o_stream
->GetLastError();
2125 // Write the 'central directory' and the 'end-central-directory' records.
2127 bool wxZipOutputStream::Close()
2131 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0)
2136 endrec
.SetEntriesHere(m_entries
.size());
2137 endrec
.SetTotalEntries(m_entries
.size());
2138 endrec
.SetOffset(m_headerOffset
);
2139 endrec
.SetComment(m_Comment
);
2141 _wxZipEntryList::iterator it
;
2142 wxFileOffset size
= 0;
2144 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2145 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2150 endrec
.SetSize(size
);
2151 endrec
.Write(*m_parent_o_stream
, GetConv());
2153 m_lasterror
= m_parent_o_stream
->GetLastError();
2156 m_lasterror
= wxSTREAM_EOF
;
2160 // Finish writing the current entry
2162 bool wxZipOutputStream::CloseEntry()
2164 if (IsOk() && m_pending
)
2165 CreatePendingEntry();
2171 CloseCompressor(m_comp
);
2174 wxFileOffset compressedSize
= m_store
->TellO();
2176 wxZipEntry
& entry
= *m_entries
.back();
2178 // When writing raw the crc and size can't be checked
2180 m_crcAccumulator
= entry
.GetCrc();
2181 m_entrySize
= entry
.GetSize();
2184 // Write the sums in the trailing 'data descriptor' if necessary
2185 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2186 wxASSERT(!IsParentSeekable());
2188 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2189 compressedSize
, m_entrySize
);
2190 m_lasterror
= m_parent_o_stream
->GetLastError();
2193 // If the local header didn't have the correct crc and size written to
2194 // it then seek back and fix it
2195 else if (m_crcAccumulator
!= entry
.GetCrc()
2196 || m_entrySize
!= entry
.GetSize()
2197 || compressedSize
!= entry
.GetCompressedSize())
2199 if (IsParentSeekable()) {
2200 wxFileOffset here
= m_parent_o_stream
->TellO();
2201 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2202 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2203 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2204 compressedSize
, m_entrySize
);
2205 m_parent_o_stream
->SeekO(here
);
2206 m_lasterror
= m_parent_o_stream
->GetLastError();
2208 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2212 m_headerOffset
+= m_headerSize
+ compressedSize
;
2219 m_lasterror
= m_parent_o_stream
->GetLastError();
2221 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2222 entry
.GetName().c_str());
2226 void wxZipOutputStream::Sync()
2228 if (IsOk() && m_pending
)
2229 CreatePendingEntry(NULL
, 0);
2231 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2234 m_lasterror
= m_comp
->GetLastError();
2238 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2240 if (IsOk() && m_pending
) {
2241 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2242 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2243 m_initialSize
+= size
;
2246 CreatePendingEntry(buffer
, size
);
2251 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2252 if (!IsOk() || !size
)
2255 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2256 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2257 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2258 m_entrySize
+= m_comp
->LastWrite();
2260 return m_comp
->LastWrite();
2263 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM