1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/zipstrm.cpp
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
6 // Copyright: (c) Mike Wetherell
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
17 #if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
25 #include "wx/zipstrm.h"
26 #include "wx/datstrm.h"
27 #include "wx/zstream.h"
28 #include "wx/mstream.h"
29 #include "wx/buffer.h"
30 #include "wx/ptr_scpd.h"
31 #include "wx/wfstream.h"
34 // value for the 'version needed to extract' field (20 means 2.0)
36 VERSION_NEEDED_TO_EXTRACT
= 20
39 // signatures for the various records (PKxx)
41 CENTRAL_MAGIC
= 0x02014b50, // central directory record
42 LOCAL_MAGIC
= 0x04034b50, // local header
43 END_MAGIC
= 0x06054b50, // end of central directory record
44 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
47 // unix file attributes. zip stores them in the high 16 bits of the
48 // 'external attributes' field, hence the extra zeros.
50 wxZIP_S_IFMT
= 0xF0000000,
51 wxZIP_S_IFDIR
= 0x40000000,
52 wxZIP_S_IFREG
= 0x80000000
55 // minimum sizes for the various records
63 // The number of bytes that must be written to an wxZipOutputStream before
64 // a zip entry is created. The purpose of this latency is so that
65 // OpenCompressor() can see a little data before deciding which compressor
71 // Some offsets into the local header
76 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
77 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
80 /////////////////////////////////////////////////////////////////////////////
83 // read a string of a given length
85 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
91 wxCharBuffer
buf(len
);
92 stream
.Read(buf
.data(), len
);
93 wxString
str(buf
, conv
);
98 wxStringBuffer
buf(str
, len
);
99 stream
.Read(buf
, len
);
106 // Decode a little endian wxUint32 number from a character array
108 static inline wxUint32
CrackUint32(const char *m
)
110 const unsigned char *n
= (const unsigned char*)m
;
111 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
114 // Decode a little endian wxUint16 number from a character array
116 static inline wxUint16
CrackUint16(const char *m
)
118 const unsigned char *n
= (const unsigned char*)m
;
119 return (n
[1] << 8) | n
[0];
122 // Temporarily lower the logging level in debug mode to avoid a warning
123 // from SeekI about seeking on a stream with data written back to it.
125 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
127 #if defined(__WXDEBUG__) && wxUSE_LOG
128 wxLogLevel level
= wxLog::GetLogLevel();
129 wxLog::SetLogLevel(wxLOG_Debug
- 1);
130 wxFileOffset result
= stream
.SeekI(pos
);
131 wxLog::SetLogLevel(level
);
134 return stream
.SeekI(pos
);
139 /////////////////////////////////////////////////////////////////////////////
142 wxZipClassFactory g_wxZipClassFactory
;
144 wxZipClassFactory::wxZipClassFactory()
146 if (this == &g_wxZipClassFactory
)
150 const wxChar
* const *
151 wxZipClassFactory::GetProtocols(wxStreamProtocolType type
) const
153 static const wxChar
*protocols
[] = { _T("zip"), NULL
};
154 static const wxChar
*mimetypes
[] = { _T("application/zip"), NULL
};
155 static const wxChar
*fileexts
[] = { _T(".zip"), _T(".htb"), NULL
};
156 static const wxChar
*empty
[] = { NULL
};
159 case wxSTREAM_PROTOCOL
: return protocols
;
160 case wxSTREAM_MIMETYPE
: return mimetypes
;
161 case wxSTREAM_FILEEXTENSION
: return fileexts
;
162 default: return empty
;
167 /////////////////////////////////////////////////////////////////////////////
173 wxZipHeader(wxInputStream
& stream
, size_t size
);
175 inline wxUint8
Read8();
176 inline wxUint16
Read16();
177 inline wxUint32
Read32();
179 const char *GetData() const { return m_data
; }
180 size_t GetSize() const { return m_size
; }
181 operator bool() const { return m_ok
; }
183 size_t Seek(size_t pos
) { m_pos
= pos
; return m_pos
; }
184 size_t Skip(size_t size
) { m_pos
+= size
; return m_pos
; }
186 wxZipHeader
& operator>>(wxUint8
& n
) { n
= Read8(); return *this; }
187 wxZipHeader
& operator>>(wxUint16
& n
) { n
= Read16(); return *this; }
188 wxZipHeader
& operator>>(wxUint32
& n
) { n
= Read32(); return *this; }
197 wxZipHeader::wxZipHeader(wxInputStream
& stream
, size_t size
)
202 wxCHECK_RET(size
<= sizeof(m_data
), _T("buffer too small"));
203 m_size
= stream
.Read(m_data
, size
).LastRead();
204 m_ok
= m_size
== size
;
207 wxUint8
wxZipHeader::Read8()
209 wxASSERT(m_pos
< m_size
);
210 return m_data
[m_pos
++];
213 wxUint16
wxZipHeader::Read16()
215 wxASSERT(m_pos
+ 2 <= m_size
);
216 wxUint16 n
= CrackUint16(m_data
+ m_pos
);
221 wxUint32
wxZipHeader::Read32()
223 wxASSERT(m_pos
+ 4 <= m_size
);
224 wxUint32 n
= CrackUint32(m_data
+ m_pos
);
230 /////////////////////////////////////////////////////////////////////////////
231 // Stored input stream
232 // Trival decompressor for files which are 'stored' in the zip file.
234 class wxStoredInputStream
: public wxFilterInputStream
237 wxStoredInputStream(wxInputStream
& stream
);
239 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
240 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
242 virtual char Peek() { return wxInputStream::Peek(); }
243 virtual wxFileOffset
GetLength() const { return m_len
; }
246 virtual size_t OnSysRead(void *buffer
, size_t size
);
247 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
253 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
256 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
257 : wxFilterInputStream(stream
),
263 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
265 size_t count
= wx_truncate_cast(size_t,
266 wxMin(size
+ wxFileOffset(0), m_len
- m_pos
+ size_t(0)));
267 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
271 m_lasterror
= m_pos
== m_len
? wxSTREAM_EOF
: wxSTREAM_READ_ERROR
;
277 /////////////////////////////////////////////////////////////////////////////
278 // Stored output stream
279 // Trival compressor for files which are 'stored' in the zip file.
281 class wxStoredOutputStream
: public wxFilterOutputStream
284 wxStoredOutputStream(wxOutputStream
& stream
) :
285 wxFilterOutputStream(stream
), m_pos(0) { }
289 m_lasterror
= wxSTREAM_NO_ERROR
;
294 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
295 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
299 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
302 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
304 if (!IsOk() || !size
)
306 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
308 m_lasterror
= wxSTREAM_WRITE_ERROR
;
314 /////////////////////////////////////////////////////////////////////////////
317 // Used to handle the unusal case of raw copying an entry of unknown
318 // length. This can only happen when the zip being copied from is being
319 // read from a non-seekable stream, and also was original written to a
320 // non-seekable stream.
322 // In this case there's no option but to decompress the stream to find
323 // it's length, but we can still write the raw compressed data to avoid the
324 // compression overhead (which is the greater one).
326 // Usage is like this:
327 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
328 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
330 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
331 // is something like the unix 'tee' command; it is a transparent filter, but
332 // allows the data read to be read a second time via an extra method 'GetData'.
334 // The wxRawInputStream then draws data through the tee using a decompressor
335 // then instead of returning the decompressed data, retuns the raw data
336 // from wxTeeInputStream::GetData().
338 class wxTeeInputStream
: public wxFilterInputStream
341 wxTeeInputStream(wxInputStream
& stream
);
343 size_t GetCount() const { return m_end
- m_start
; }
344 size_t GetData(char *buffer
, size_t size
);
349 wxInputStream
& Read(void *buffer
, size_t size
);
352 virtual size_t OnSysRead(void *buffer
, size_t size
);
353 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
357 wxMemoryBuffer m_buf
;
361 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
364 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
365 : wxFilterInputStream(stream
),
366 m_pos(0), m_buf(8192), m_start(0), m_end(0)
370 void wxTeeInputStream::Open()
372 m_pos
= m_start
= m_end
= 0;
373 m_lasterror
= wxSTREAM_NO_ERROR
;
376 bool wxTeeInputStream::Final()
378 bool final
= m_end
== m_buf
.GetDataLen();
379 m_end
= m_buf
.GetDataLen();
383 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
385 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
386 m_end
= m_buf
.GetDataLen();
387 m_buf
.AppendData(buffer
, count
);
391 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
393 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
395 m_lasterror
= m_parent_i_stream
->GetLastError();
399 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
402 size_t len
= m_buf
.GetDataLen();
403 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
404 m_buf
.SetDataLen(len
);
406 wxFAIL
; // we've already returned data that's now being ungot
409 m_parent_i_stream
->Reset();
410 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
417 if (size
> GetCount())
420 memcpy(buffer
, m_buf
+ m_start
, size
);
422 wxASSERT(m_start
<= m_end
);
425 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
426 size_t len
= m_buf
.GetDataLen();
427 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
429 memmove(buf
, buf
+ m_end
, len
);
430 m_buf
.UngetWriteBuf(len
);
437 class wxRawInputStream
: public wxFilterInputStream
440 wxRawInputStream(wxInputStream
& stream
);
441 virtual ~wxRawInputStream() { delete m_tee
; }
443 wxInputStream
* Open(wxInputStream
*decomp
);
444 wxInputStream
& GetTee() const { return *m_tee
; }
447 virtual size_t OnSysRead(void *buffer
, size_t size
);
448 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
452 wxTeeInputStream
*m_tee
;
454 enum { BUFSIZE
= 8192 };
455 wxCharBuffer m_dummy
;
457 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
460 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
461 : wxFilterInputStream(stream
),
463 m_tee(new wxTeeInputStream(stream
)),
468 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
471 m_parent_i_stream
= decomp
;
473 m_lasterror
= wxSTREAM_NO_ERROR
;
481 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
483 char *buf
= (char*)buffer
;
486 while (count
< size
&& IsOk())
488 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
489 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
491 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
494 if (n
== 0 && m_tee
->Final())
495 m_lasterror
= m_parent_i_stream
->GetLastError();
503 /////////////////////////////////////////////////////////////////////////////
504 // Zlib streams than can be reused without recreating.
506 class wxZlibOutputStream2
: public wxZlibOutputStream
509 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
510 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
512 bool Open(wxOutputStream
& stream
);
513 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
516 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
518 wxCHECK(m_pos
== wxInvalidOffset
, false);
520 m_deflate
->next_out
= m_z_buffer
;
521 m_deflate
->avail_out
= m_z_size
;
523 m_lasterror
= wxSTREAM_NO_ERROR
;
524 m_parent_o_stream
= &stream
;
526 if (deflateReset(m_deflate
) != Z_OK
) {
527 wxLogError(_("can't re-initialize zlib deflate stream"));
528 m_lasterror
= wxSTREAM_WRITE_ERROR
;
535 class wxZlibInputStream2
: public wxZlibInputStream
538 wxZlibInputStream2(wxInputStream
& stream
) :
539 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
541 bool Open(wxInputStream
& stream
);
544 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
546 m_inflate
->avail_in
= 0;
548 m_lasterror
= wxSTREAM_NO_ERROR
;
549 m_parent_i_stream
= &stream
;
551 if (inflateReset(m_inflate
) != Z_OK
) {
552 wxLogError(_("can't re-initialize zlib inflate stream"));
553 m_lasterror
= wxSTREAM_READ_ERROR
;
561 /////////////////////////////////////////////////////////////////////////////
562 // Class to hold wxZipEntry's Extra and LocalExtra fields
567 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
569 wxZipMemory
*AddRef() { m_ref
++; return this; }
570 void Release() { if (--m_ref
== 0) delete this; }
572 char *GetData() const { return m_data
; }
573 size_t GetSize() const { return m_size
; }
574 size_t GetCapacity() const { return m_capacity
; }
576 wxZipMemory
*Unique(size_t size
);
579 ~wxZipMemory() { delete [] m_data
; }
586 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipMemory
)
589 wxZipMemory
*wxZipMemory::Unique(size_t size
)
595 zm
= new wxZipMemory
;
600 if (zm
->m_capacity
< size
) {
601 delete [] zm
->m_data
;
602 zm
->m_data
= new char[size
];
603 zm
->m_capacity
= size
;
610 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
617 static inline void Release(wxZipMemory
*zm
)
623 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
629 static void Unique(wxZipMemory
*& zm
, size_t size
)
632 zm
= new wxZipMemory
;
634 zm
= zm
->Unique(size
);
638 /////////////////////////////////////////////////////////////////////////////
639 // Collection of weak references to entries
641 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
642 wxIntegerEqual
, wxOffsetZipEntryMap_
);
647 wxZipWeakLinks() : m_ref(1) { }
649 void Release(const wxZipInputStream
* WXUNUSED(x
))
650 { if (--m_ref
== 0) delete this; }
651 void Release(wxFileOffset key
)
652 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
654 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
655 void RemoveEntry(wxFileOffset key
)
656 { m_entries
.erase(wx_truncate_cast(key_type
, key
)); }
657 wxZipEntry
*GetEntry(wxFileOffset key
) const;
658 bool IsEmpty() const { return m_entries
.empty(); }
661 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
663 typedef wxOffsetZipEntryMap_::key_type key_type
;
666 wxOffsetZipEntryMap_ m_entries
;
668 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipWeakLinks
)
671 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
673 m_entries
[wx_truncate_cast(key_type
, key
)] = entry
;
678 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
680 wxOffsetZipEntryMap_::const_iterator it
=
681 m_entries
.find(wx_truncate_cast(key_type
, key
));
682 return it
!= m_entries
.end() ? it
->second
: NULL
;
686 /////////////////////////////////////////////////////////////////////////////
689 wxZipEntry::wxZipEntry(
690 const wxString
& name
/*=wxEmptyString*/,
691 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
692 wxFileOffset size
/*=wxInvalidOffset*/)
694 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
695 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
696 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
698 m_Method(wxZIP_METHOD_DEFAULT
),
701 m_CompressedSize(wxInvalidOffset
),
703 m_Key(wxInvalidOffset
),
704 m_Offset(wxInvalidOffset
),
706 m_InternalAttributes(0),
707 m_ExternalAttributes(0),
717 wxZipEntry::~wxZipEntry()
720 m_backlink
->Release(m_Key
);
722 Release(m_LocalExtra
);
725 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
727 m_SystemMadeBy(e
.m_SystemMadeBy
),
728 m_VersionMadeBy(e
.m_VersionMadeBy
),
729 m_VersionNeeded(e
.m_VersionNeeded
),
731 m_Method(e
.m_Method
),
732 m_DateTime(e
.m_DateTime
),
734 m_CompressedSize(e
.m_CompressedSize
),
738 m_Offset(e
.m_Offset
),
739 m_Comment(e
.m_Comment
),
740 m_DiskStart(e
.m_DiskStart
),
741 m_InternalAttributes(e
.m_InternalAttributes
),
742 m_ExternalAttributes(e
.m_ExternalAttributes
),
743 m_Extra(AddRef(e
.m_Extra
)),
744 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
750 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
753 m_SystemMadeBy
= e
.m_SystemMadeBy
;
754 m_VersionMadeBy
= e
.m_VersionMadeBy
;
755 m_VersionNeeded
= e
.m_VersionNeeded
;
757 m_Method
= e
.m_Method
;
758 m_DateTime
= e
.m_DateTime
;
760 m_CompressedSize
= e
.m_CompressedSize
;
764 m_Offset
= e
.m_Offset
;
765 m_Comment
= e
.m_Comment
;
766 m_DiskStart
= e
.m_DiskStart
;
767 m_InternalAttributes
= e
.m_InternalAttributes
;
768 m_ExternalAttributes
= e
.m_ExternalAttributes
;
769 Copy(m_Extra
, e
.m_Extra
);
770 Copy(m_LocalExtra
, e
.m_LocalExtra
);
771 m_zipnotifier
= NULL
;
773 m_backlink
->Release(m_Key
);
780 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
782 bool isDir
= IsDir() && !m_Name
.empty();
784 // optimisations for common (and easy) cases
785 switch (wxFileName::GetFormat(format
)) {
788 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
789 for (size_t i
= 0; i
< name
.length(); i
++)
790 if (name
[i
] == _T('/'))
796 return isDir
? m_Name
+ _T("/") : m_Name
;
805 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
807 fn
.Assign(m_Name
, wxPATH_UNIX
);
809 return fn
.GetFullPath(format
);
812 // Static - Internally tars and zips use forward slashes for the path
813 // separator, absolute paths aren't allowed, and directory names have a
814 // trailing slash. This function converts a path into this internal format,
815 // but without a trailing slash for a directory.
817 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
818 wxPathFormat format
/*=wxPATH_NATIVE*/,
819 bool *pIsDir
/*=NULL*/)
823 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
824 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
828 bool isDir
= !internal
.empty() && internal
.Last() == '/';
832 internal
.erase(internal
.length() - 1);
834 while (!internal
.empty() && *internal
.begin() == '/')
835 internal
.erase(0, 1);
836 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
837 internal
.erase(0, 2);
838 if (internal
== _T(".") || internal
== _T(".."))
839 internal
= wxEmptyString
;
844 void wxZipEntry::SetSystemMadeBy(int system
)
846 int mode
= GetMode();
847 bool wasUnix
= IsMadeByUnix();
849 m_SystemMadeBy
= (wxUint8
)system
;
851 if (!wasUnix
&& IsMadeByUnix()) {
854 } else if (wasUnix
&& !IsMadeByUnix()) {
855 m_ExternalAttributes
&= 0xffff;
859 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
862 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
864 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
866 if (IsMadeByUnix()) {
867 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
869 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
871 m_ExternalAttributes
|= wxZIP_S_IFREG
;
875 // Return unix style permission bits
877 int wxZipEntry::GetMode() const
879 // return unix permissions if present
881 return (m_ExternalAttributes
>> 16) & 0777;
883 // otherwise synthesize from the dos attribs
885 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
887 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
893 // Set unix permissions
895 void wxZipEntry::SetMode(int mode
)
897 // Set dos attrib bits to be compatible
899 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
901 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
903 // set the actual unix permission bits if the system type allows
904 if (IsMadeByUnix()) {
905 m_ExternalAttributes
&= ~(0777L << 16);
906 m_ExternalAttributes
|= (mode
& 0777L) << 16;
910 const char *wxZipEntry::GetExtra() const
912 return m_Extra
? m_Extra
->GetData() : NULL
;
915 size_t wxZipEntry::GetExtraLen() const
917 return m_Extra
? m_Extra
->GetSize() : 0;
920 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
922 Unique(m_Extra
, len
);
924 memcpy(m_Extra
->GetData(), extra
, len
);
927 const char *wxZipEntry::GetLocalExtra() const
929 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
932 size_t wxZipEntry::GetLocalExtraLen() const
934 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
937 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
939 Unique(m_LocalExtra
, len
);
941 memcpy(m_LocalExtra
->GetData(), extra
, len
);
944 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
946 wxArchiveEntry::UnsetNotifier();
947 m_zipnotifier
= ¬ifier
;
948 m_zipnotifier
->OnEntryUpdated(*this);
951 void wxZipEntry::Notify()
954 m_zipnotifier
->OnEntryUpdated(*this);
955 else if (GetNotifier())
956 GetNotifier()->OnEntryUpdated(*this);
959 void wxZipEntry::UnsetNotifier()
961 wxArchiveEntry::UnsetNotifier();
962 m_zipnotifier
= NULL
;
965 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
967 wxUint16 nameLen
, extraLen
;
968 wxUint32 compressedSize
, size
, crc
;
970 wxZipHeader
ds(stream
, LOCAL_SIZE
- 4);
974 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
975 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
976 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
978 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
980 if (sumsValid
|| crc
)
982 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
983 m_CompressedSize
= compressedSize
;
984 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
987 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
988 if (stream
.LastRead() != nameLen
+ 0u)
991 if (extraLen
|| GetLocalExtraLen()) {
992 Unique(m_LocalExtra
, extraLen
);
994 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
995 if (stream
.LastRead() != extraLen
+ 0u)
1000 return LOCAL_SIZE
+ nameLen
+ extraLen
;
1003 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
1005 wxString unixName
= GetName(wxPATH_UNIX
);
1006 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
1007 const char *name
= name_buf
;
1008 if (!name
) name
= "";
1009 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
1011 wxDataOutputStream
ds(stream
);
1013 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
1014 ds
.Write32(GetDateTime().GetAsDOS());
1017 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
?
1018 wx_truncate_cast(wxUint32
, m_CompressedSize
) : 0);
1019 ds
.Write32(m_Size
!= wxInvalidOffset
?
1020 wx_truncate_cast(wxUint32
, m_Size
) : 0);
1023 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetLocalExtraLen());
1024 ds
.Write16(extraLen
);
1026 stream
.Write(name
, nameLen
);
1028 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
1030 return LOCAL_SIZE
+ nameLen
+ extraLen
;
1033 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
1035 wxUint16 nameLen
, extraLen
, commentLen
;
1037 wxZipHeader
ds(stream
, CENTRAL_SIZE
- 4);
1041 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
1043 SetVersionNeeded(ds
.Read16());
1044 SetFlags(ds
.Read16());
1045 SetMethod(ds
.Read16());
1046 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
1047 SetCrc(ds
.Read32());
1048 SetCompressedSize(ds
.Read32());
1049 SetSize(ds
.Read32());
1051 ds
>> nameLen
>> extraLen
>> commentLen
1052 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
1053 SetOffset(ds
.Read32());
1055 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
1056 if (stream
.LastRead() != nameLen
+ 0u)
1059 if (extraLen
|| GetExtraLen()) {
1060 Unique(m_Extra
, extraLen
);
1062 stream
.Read(m_Extra
->GetData(), extraLen
);
1063 if (stream
.LastRead() != extraLen
+ 0u)
1069 m_Comment
= ReadString(stream
, commentLen
, conv
);
1070 if (stream
.LastRead() != commentLen
+ 0u)
1076 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1079 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
1081 wxString unixName
= GetName(wxPATH_UNIX
);
1082 const wxWX2MBbuf name_buf
= conv
.cWX2MB(unixName
);
1083 const char *name
= name_buf
;
1084 if (!name
) name
= "";
1085 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
1087 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1088 const char *comment
= comment_buf
;
1089 if (!comment
) comment
= "";
1090 wxUint16 commentLen
= wx_truncate_cast(wxUint16
, strlen(comment
));
1092 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetExtraLen());
1094 wxDataOutputStream
ds(stream
);
1096 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
1098 ds
.Write16(wx_truncate_cast(wxUint16
, GetVersionNeeded()));
1099 ds
.Write16(wx_truncate_cast(wxUint16
, GetFlags()));
1100 ds
.Write16(wx_truncate_cast(wxUint16
, GetMethod()));
1101 ds
.Write32(GetDateTime().GetAsDOS());
1102 ds
.Write32(GetCrc());
1103 ds
.Write32(wx_truncate_cast(wxUint32
, GetCompressedSize()));
1104 ds
.Write32(wx_truncate_cast(wxUint32
, GetSize()));
1105 ds
.Write16(nameLen
);
1106 ds
.Write16(extraLen
);
1108 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
1109 << m_ExternalAttributes
<< wx_truncate_cast(wxUint32
, GetOffset());
1111 stream
.Write(name
, nameLen
);
1113 stream
.Write(GetExtra(), extraLen
);
1114 stream
.Write(comment
, commentLen
);
1116 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1119 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1120 // the 1st value is the signature then it is probably an info-zip record,
1121 // though there is a small chance that it is in fact a pkzip record which
1122 // happens to have the signature as it's CRC.
1124 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1126 wxZipHeader
ds(stream
, SUMS_SIZE
);
1130 m_Crc
= ds
.Read32();
1131 m_CompressedSize
= ds
.Read32();
1132 m_Size
= ds
.Read32();
1134 // if 1st value is the signature then this is probably an info-zip record
1135 if (m_Crc
== SUMS_MAGIC
)
1137 wxZipHeader
buf(stream
, 8);
1138 wxUint32 u1
= buf
.GetSize() >= 4 ? buf
.Read32() : (wxUint32
)LOCAL_MAGIC
;
1139 wxUint32 u2
= buf
.GetSize() == 8 ? buf
.Read32() : 0;
1141 // look for the signature of the following record to decide which
1142 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1143 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1145 // it's a pkzip style record after all!
1146 if (buf
.GetSize() > 0)
1147 stream
.Ungetch(buf
.GetData(), buf
.GetSize());
1151 // it's an info-zip record as expected
1152 if (buf
.GetSize() > 4)
1153 stream
.Ungetch(buf
.GetData() + 4, buf
.GetSize() - 4);
1154 m_Crc
= wx_truncate_cast(wxUint32
, m_CompressedSize
);
1155 m_CompressedSize
= m_Size
;
1157 return SUMS_SIZE
+ 4;
1164 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1165 wxFileOffset compressedSize
, wxFileOffset size
)
1168 m_CompressedSize
= compressedSize
;
1171 wxDataOutputStream
ds(stream
);
1174 ds
.Write32(wx_truncate_cast(wxUint32
, compressedSize
));
1175 ds
.Write32(wx_truncate_cast(wxUint32
, size
));
1181 /////////////////////////////////////////////////////////////////////////////
1182 // wxZipEndRec - holds the end of central directory record
1189 int GetDiskNumber() const { return m_DiskNumber
; }
1190 int GetStartDisk() const { return m_StartDisk
; }
1191 int GetEntriesHere() const { return m_EntriesHere
; }
1192 int GetTotalEntries() const { return m_TotalEntries
; }
1193 wxFileOffset
GetSize() const { return m_Size
; }
1194 wxFileOffset
GetOffset() const { return m_Offset
; }
1195 wxString
GetComment() const { return m_Comment
; }
1197 void SetDiskNumber(int num
)
1198 { m_DiskNumber
= wx_truncate_cast(wxUint16
, num
); }
1199 void SetStartDisk(int num
)
1200 { m_StartDisk
= wx_truncate_cast(wxUint16
, num
); }
1201 void SetEntriesHere(int num
)
1202 { m_EntriesHere
= wx_truncate_cast(wxUint16
, num
); }
1203 void SetTotalEntries(int num
)
1204 { m_TotalEntries
= wx_truncate_cast(wxUint16
, num
); }
1205 void SetSize(wxFileOffset size
)
1206 { m_Size
= wx_truncate_cast(wxUint32
, size
); }
1207 void SetOffset(wxFileOffset offset
)
1208 { m_Offset
= wx_truncate_cast(wxUint32
, offset
); }
1209 void SetComment(const wxString
& comment
)
1210 { m_Comment
= comment
; }
1212 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1213 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1216 wxUint16 m_DiskNumber
;
1217 wxUint16 m_StartDisk
;
1218 wxUint16 m_EntriesHere
;
1219 wxUint16 m_TotalEntries
;
1225 wxZipEndRec::wxZipEndRec()
1235 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1237 const wxWX2MBbuf comment_buf
= conv
.cWX2MB(m_Comment
);
1238 const char *comment
= comment_buf
;
1239 if (!comment
) comment
= "";
1240 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1242 wxDataOutputStream
ds(stream
);
1244 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1245 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1247 stream
.Write(comment
, commentLen
);
1249 return stream
.IsOk();
1252 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1254 wxZipHeader
ds(stream
, END_SIZE
- 4);
1258 wxUint16 commentLen
;
1260 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1261 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1264 m_Comment
= ReadString(stream
, commentLen
, conv
);
1265 if (stream
.LastRead() != commentLen
+ 0u)
1269 if (m_DiskNumber
!= 0 || m_StartDisk
!= 0 ||
1270 m_EntriesHere
!= m_TotalEntries
)
1271 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1277 /////////////////////////////////////////////////////////////////////////////
1278 // A weak link from an input stream to an output stream
1280 class wxZipStreamLink
1283 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1285 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1286 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1288 void Release(class wxZipInputStream
*WXUNUSED(s
))
1289 { if (--m_ref
== 0) delete this; }
1290 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1291 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1294 ~wxZipStreamLink() { }
1297 wxZipOutputStream
*m_stream
;
1299 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipStreamLink
)
1303 /////////////////////////////////////////////////////////////////////////////
1306 // leave the default wxZipEntryPtr free for users
1307 wxDECLARE_SCOPED_PTR(wxZipEntry
, wxZipEntryPtr_
)
1308 wxDEFINE_SCOPED_PTR (wxZipEntry
, wxZipEntryPtr_
)
1312 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1313 wxMBConv
& conv
/*=wxConvLocal*/)
1314 : wxArchiveInputStream(stream
, conv
)
1319 wxZipInputStream::wxZipInputStream(wxInputStream
*stream
,
1320 wxMBConv
& conv
/*=wxConvLocal*/)
1321 : wxArchiveInputStream(stream
, conv
)
1326 #if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1328 // Part of the compatibility constructor, which has been made inline to
1329 // avoid a problem with it not being exported by mingw 3.2.3
1331 void wxZipInputStream::Init(const wxString
& file
)
1333 // no error messages
1336 m_allowSeeking
= true;
1337 wxFFileInputStream
*ffile
;
1338 ffile
= wx_static_cast(wxFFileInputStream
*, m_parent_i_stream
);
1339 wxZipEntryPtr_ entry
;
1343 entry
.reset(GetNextEntry());
1345 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1348 if (entry
.get() == NULL
)
1349 m_lasterror
= wxSTREAM_READ_ERROR
;
1352 wxInputStream
* wxZipInputStream::OpenFile(const wxString
& archive
)
1355 return new wxFFileInputStream(archive
);
1358 #endif // WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1360 void wxZipInputStream::Init()
1362 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1368 m_parentSeekable
= false;
1369 m_weaklinks
= new wxZipWeakLinks
;
1370 m_streamlink
= NULL
;
1371 m_offsetAdjustment
= 0;
1372 m_position
= wxInvalidOffset
;
1375 m_lasterror
= m_parent_i_stream
->GetLastError();
1376 #if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1377 m_allowSeeking
= false;
1381 wxZipInputStream::~wxZipInputStream()
1383 CloseDecompressor(m_decomp
);
1389 m_weaklinks
->Release(this);
1392 m_streamlink
->Release(this);
1395 wxString
wxZipInputStream::GetComment()
1397 if (m_position
== wxInvalidOffset
)
1398 if (!LoadEndRecord())
1399 return wxEmptyString
;
1401 if (!m_parentSeekable
&& Eof() && m_signature
) {
1402 m_lasterror
= wxSTREAM_NO_ERROR
;
1403 m_lasterror
= ReadLocal(true);
1409 int wxZipInputStream::GetTotalEntries()
1411 if (m_position
== wxInvalidOffset
)
1413 return m_TotalEntries
;
1416 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1418 wxZipStreamLink
*link
= NULL
;
1420 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1421 link
= new wxZipStreamLink(out
);
1423 m_streamlink
->Release(this);
1424 m_streamlink
= link
->AddRef();
1430 bool wxZipInputStream::LoadEndRecord()
1432 wxCHECK(m_position
== wxInvalidOffset
, false);
1438 // First find the end-of-central-directory record.
1439 if (!FindEndRecord()) {
1440 // failed, so either this is a non-seekable stream (ok), or not a zip
1441 if (m_parentSeekable
) {
1442 m_lasterror
= wxSTREAM_READ_ERROR
;
1443 wxLogError(_("invalid zip file"));
1448 wxFileOffset pos
= m_parent_i_stream
->TellI();
1449 if (pos
!= wxInvalidOffset
)
1450 m_offsetAdjustment
= m_position
= pos
;
1457 // Read in the end record
1458 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1459 if (!endrec
.Read(*m_parent_i_stream
, GetConv()))
1462 m_TotalEntries
= endrec
.GetTotalEntries();
1463 m_Comment
= endrec
.GetComment();
1465 // Now find the central-directory. we have the file offset of
1466 // the CD, so look there first.
1467 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1468 ReadSignature() == CENTRAL_MAGIC
) {
1469 m_signature
= CENTRAL_MAGIC
;
1470 m_position
= endrec
.GetOffset();
1471 m_offsetAdjustment
= 0;
1475 // If it's not there, then it could be that the zip has been appended
1476 // to a self extractor, so take the CD size (also in endrec), subtract
1477 // it from the file offset of the end-central-directory and look there.
1478 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1479 != wxInvalidOffset
&& ReadSignature() == CENTRAL_MAGIC
) {
1480 m_signature
= CENTRAL_MAGIC
;
1481 m_position
= endPos
- endrec
.GetSize();
1482 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1486 wxLogError(_("can't find central directory in zip"));
1487 m_lasterror
= wxSTREAM_READ_ERROR
;
1491 // Find the end-of-central-directory record.
1492 // If found the stream will be positioned just past the 4 signature bytes.
1494 bool wxZipInputStream::FindEndRecord()
1496 if (!m_parent_i_stream
->IsSeekable())
1499 // usually it's 22 bytes in size and the last thing in the file
1502 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1506 m_parentSeekable
= true;
1509 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1511 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1514 // unfortunately, the record has a comment field that can be up to 65535
1515 // bytes in length, so if the signature not found then search backwards.
1516 wxFileOffset pos
= m_parent_i_stream
->TellI();
1517 const int BUFSIZE
= 1024;
1518 wxCharBuffer
buf(BUFSIZE
);
1520 memcpy(buf
.data(), magic
, 3);
1521 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1523 while (pos
> minpos
) {
1524 size_t len
= wx_truncate_cast(size_t,
1525 pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1526 memcpy(buf
.data() + len
, buf
, 3);
1529 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1530 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1533 char *p
= buf
.data() + len
;
1535 while (p
-- > buf
.data()) {
1536 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1537 size_t remainder
= buf
.data() + len
- p
;
1539 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1548 wxZipEntry
*wxZipInputStream::GetNextEntry()
1550 if (m_position
== wxInvalidOffset
)
1551 if (!LoadEndRecord())
1554 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1558 wxZipEntryPtr_
entry(new wxZipEntry(m_entry
));
1559 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1560 return entry
.release();
1563 wxStreamError
wxZipInputStream::ReadCentral()
1568 if (m_signature
== END_MAGIC
)
1569 return wxSTREAM_EOF
;
1571 if (m_signature
!= CENTRAL_MAGIC
) {
1572 wxLogError(_("error reading zip central directory"));
1573 return wxSTREAM_READ_ERROR
;
1576 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1577 return wxSTREAM_READ_ERROR
;
1579 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1582 return wxSTREAM_READ_ERROR
;
1586 m_signature
= ReadSignature();
1588 if (m_offsetAdjustment
)
1589 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1590 m_entry
.SetKey(m_entry
.GetOffset());
1592 return wxSTREAM_NO_ERROR
;
1595 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1601 m_signature
= ReadSignature();
1603 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1604 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1605 m_streamlink
->Release(this);
1606 m_streamlink
= NULL
;
1610 while (m_signature
== CENTRAL_MAGIC
) {
1611 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1612 return wxSTREAM_EOF
;
1614 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1618 return wxSTREAM_READ_ERROR
;
1620 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1622 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1623 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1624 entry
->SetComment(m_entry
.GetComment());
1625 entry
->SetDiskStart(m_entry
.GetDiskStart());
1626 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1627 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1628 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1630 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1633 m_signature
= ReadSignature();
1636 if (m_signature
== END_MAGIC
) {
1637 if (readEndRec
|| m_streamlink
) {
1639 endrec
.Read(*m_parent_i_stream
, GetConv());
1640 m_Comment
= endrec
.GetComment();
1643 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1644 m_streamlink
->Release(this);
1645 m_streamlink
= NULL
;
1648 return wxSTREAM_EOF
;
1651 if (m_signature
== LOCAL_MAGIC
) {
1652 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1654 m_entry
.SetOffset(m_position
);
1655 m_entry
.SetKey(m_position
);
1659 return wxSTREAM_NO_ERROR
;
1663 wxLogError(_("error reading zip local header"));
1664 return wxSTREAM_READ_ERROR
;
1667 wxUint32
wxZipInputStream::ReadSignature()
1670 m_parent_i_stream
->Read(magic
, 4);
1671 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1674 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1676 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1677 return zipEntry
? OpenEntry(*zipEntry
) : false;
1682 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1684 if (m_position
== wxInvalidOffset
)
1685 if (!LoadEndRecord())
1687 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1695 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1697 // can only open the current entry on a non-seekable stream
1698 wxCHECK(m_parentSeekable
, false);
1701 m_lasterror
= wxSTREAM_READ_ERROR
;
1706 if (m_parentSeekable
) {
1707 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1710 if (ReadSignature() != LOCAL_MAGIC
) {
1711 wxLogError(_("bad zipfile offset to entry"));
1716 if (m_parentSeekable
|| AtHeader()) {
1717 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1718 if (m_headerSize
&& m_parentSeekable
) {
1719 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1721 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1723 m_weaklinks
->RemoveEntry(ref
->GetKey());
1725 if (entry
&& entry
!= ref
) {
1726 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1733 m_lasterror
= wxSTREAM_NO_ERROR
;
1737 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1739 wxASSERT(AfterHeader());
1741 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1747 if (compressedSize
!= wxInvalidOffset
) {
1748 m_store
->Open(compressedSize
);
1752 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1753 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1756 if (compressedSize
!= wxInvalidOffset
&&
1757 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1758 wxZlibInputStream::CanHandleGZip())) {
1759 m_store
->Open(compressedSize
);
1760 m_decomp
= OpenDecompressor(*m_store
);
1762 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1766 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1767 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1771 // Can be overriden to add support for additional decompression methods
1773 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1775 switch (m_entry
.GetMethod()) {
1776 case wxZIP_METHOD_STORE
:
1777 if (m_entry
.GetSize() == wxInvalidOffset
) {
1778 wxLogError(_("stored file length not in Zip header"));
1781 m_store
->Open(m_entry
.GetSize());
1784 case wxZIP_METHOD_DEFLATE
:
1786 m_inflate
= new wxZlibInputStream2(stream
);
1788 m_inflate
->Open(stream
);
1792 wxLogError(_("unsupported Zip compression method"));
1798 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1800 if (decomp
&& decomp
== m_rawin
)
1801 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1802 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1807 // Closes the current entry and positions the underlying stream at the start
1808 // of the next entry
1810 bool wxZipInputStream::CloseEntry()
1814 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1817 if (!m_parentSeekable
) {
1818 if (!IsOpened() && !OpenDecompressor(true))
1821 const int BUFSIZE
= 8192;
1822 wxCharBuffer
buf(BUFSIZE
);
1824 Read(buf
.data(), BUFSIZE
);
1826 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1829 if (m_lasterror
== wxSTREAM_EOF
)
1830 m_lasterror
= wxSTREAM_NO_ERROR
;
1832 CloseDecompressor(m_decomp
);
1834 m_entry
= wxZipEntry();
1841 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1844 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1845 m_lasterror
= wxSTREAM_READ_ERROR
;
1846 if (!IsOk() || !size
)
1849 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1851 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1853 m_lasterror
= m_decomp
->GetLastError();
1856 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1857 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1858 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1861 entry
->SetCrc(m_entry
.GetCrc());
1862 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1863 entry
->SetSize(m_entry
.GetSize());
1869 m_lasterror
= wxSTREAM_READ_ERROR
;
1871 if (m_entry
.GetSize() != TellI())
1872 wxLogError(_("reading zip stream (entry %s): bad length"),
1873 m_entry
.GetName().c_str());
1874 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1875 wxLogError(_("reading zip stream (entry %s): bad crc"),
1876 m_entry
.GetName().c_str());
1878 m_lasterror
= wxSTREAM_EOF
;
1885 #if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1887 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1889 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1891 // seeking works when the stream is created with the compatibility
1893 if (!m_allowSeeking
)
1894 return wxInvalidOffset
;
1896 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1897 m_lasterror
= wxSTREAM_READ_ERROR
;
1899 return wxInvalidOffset
;
1901 // NB: since ZIP files don't natively support seeking, we have to
1902 // implement a brute force workaround -- reading all the data
1903 // between current and the new position (or between beginning of
1904 // the file and new position...)
1906 wxFileOffset nextpos
;
1907 wxFileOffset pos
= TellI();
1911 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1912 case wxFromStart
: nextpos
= seek
; break;
1913 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1914 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1917 wxFileOffset toskip
wxDUMMY_INITIALIZE(0);
1918 if ( nextpos
>= pos
)
1920 toskip
= nextpos
- pos
;
1924 wxZipEntry
current(m_entry
);
1925 if (!OpenEntry(current
))
1927 m_lasterror
= wxSTREAM_READ_ERROR
;
1935 const int BUFSIZE
= 4096;
1937 char buffer
[BUFSIZE
];
1938 while ( toskip
> 0 )
1940 sz
= wx_truncate_cast(size_t, wxMin(toskip
, BUFSIZE
));
1950 #endif // WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1953 /////////////////////////////////////////////////////////////////////////////
1956 #include "wx/listimpl.cpp"
1957 WX_DEFINE_LIST(wxZipEntryList_
)
1959 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1961 wxMBConv
& conv
/*=wxConvLocal*/)
1962 : wxArchiveOutputStream(stream
, conv
)
1967 wxZipOutputStream::wxZipOutputStream(wxOutputStream
*stream
,
1969 wxMBConv
& conv
/*=wxConvLocal*/)
1970 : wxArchiveOutputStream(stream
, conv
)
1975 void wxZipOutputStream::Init(int level
)
1977 m_store
= new wxStoredOutputStream(*m_parent_o_stream
);
1980 m_initialData
= new char[OUTPUT_LATENCY
];
1989 m_offsetAdjustment
= wxInvalidOffset
;
1992 wxZipOutputStream::~wxZipOutputStream()
1995 WX_CLEAR_LIST(wxZipEntryList_
, m_entries
);
1999 delete [] m_initialData
;
2001 m_backlink
->Release(this);
2004 bool wxZipOutputStream::PutNextEntry(
2005 const wxString
& name
,
2006 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
2007 wxFileOffset size
/*=wxInvalidOffset*/)
2009 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
2012 bool wxZipOutputStream::PutNextDirEntry(
2013 const wxString
& name
,
2014 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
2016 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
2018 return PutNextEntry(entry
);
2021 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
2022 wxZipInputStream
& inputStream
)
2024 wxZipEntryPtr_
e(entry
);
2027 inputStream
.DoOpen(e
.get(), true) &&
2028 DoCreate(e
.release(), true) &&
2029 Write(inputStream
).IsOk() && inputStream
.Eof();
2032 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
2034 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2037 return PutNextEntry(zipEntry
);
2040 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
2041 wxArchiveInputStream
& stream
)
2043 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2045 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
2050 return CopyEntry(zipEntry
, wx_static_cast(wxZipInputStream
&, stream
));
2053 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
2055 m_Comment
= inputStream
.GetComment();
2057 m_backlink
->Release(this);
2058 m_backlink
= inputStream
.MakeLink(this);
2062 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
2064 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream
&, stream
));
2067 void wxZipOutputStream::SetLevel(int level
)
2069 if (level
!= m_level
) {
2070 if (m_comp
!= m_deflate
)
2077 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
2085 // write the signature bytes right away
2086 wxDataOutputStream
ds(*m_parent_o_stream
);
2089 // and if this is the first entry test for seekability
2090 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
2092 bool logging
= wxLog::IsEnabled();
2095 wxFileOffset here
= m_parent_o_stream
->TellO();
2097 if (here
!= wxInvalidOffset
&& here
>= 4) {
2098 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
2099 m_offsetAdjustment
= here
- 4;
2101 wxLog::EnableLogging(logging
);
2103 m_parent_o_stream
->SeekO(here
);
2108 m_pending
->SetOffset(m_headerOffset
);
2110 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
2115 m_lasterror
= wxSTREAM_NO_ERROR
;
2119 // Can be overriden to add support for additional compression methods
2121 wxOutputStream
*wxZipOutputStream::OpenCompressor(
2122 wxOutputStream
& stream
,
2124 const Buffer bufs
[])
2126 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
2128 && (IsParentSeekable()
2129 || entry
.GetCompressedSize() != wxInvalidOffset
2130 || entry
.GetSize() != wxInvalidOffset
)) {
2131 entry
.SetMethod(wxZIP_METHOD_STORE
);
2134 for (int i
= 0; bufs
[i
].m_data
; ++i
)
2135 size
+= bufs
[i
].m_size
;
2136 entry
.SetMethod(size
<= 6 ?
2137 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
2141 switch (entry
.GetMethod()) {
2142 case wxZIP_METHOD_STORE
:
2143 if (entry
.GetCompressedSize() == wxInvalidOffset
)
2144 entry
.SetCompressedSize(entry
.GetSize());
2147 case wxZIP_METHOD_DEFLATE
:
2149 int defbits
= wxZIP_DEFLATE_NORMAL
;
2150 switch (GetLevel()) {
2152 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2154 case 2: case 3: case 4:
2155 defbits
= wxZIP_DEFLATE_FAST
;
2158 defbits
= wxZIP_DEFLATE_EXTRA
;
2161 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2162 defbits
| wxZIP_SUMS_FOLLOW
);
2165 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2167 m_deflate
->Open(stream
);
2173 wxLogError(_("unsupported Zip compression method"));
2179 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2181 if (comp
== m_deflate
)
2183 else if (comp
!= m_store
)
2188 // This is called when OUPUT_LATENCY bytes has been written to the
2189 // wxZipOutputStream to actually create the zip entry.
2191 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2193 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2194 wxZipEntryPtr_
spPending(m_pending
);
2198 { m_initialData
, m_initialSize
},
2199 { (const char*)buffer
, size
},
2206 m_comp
= OpenCompressor(*m_store
, *spPending
,
2207 m_initialSize
? bufs
: bufs
+ 1);
2209 if (IsParentSeekable()
2210 || (spPending
->m_Crc
2211 && spPending
->m_CompressedSize
!= wxInvalidOffset
2212 && spPending
->m_Size
!= wxInvalidOffset
))
2213 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2215 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2216 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2218 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2219 m_lasterror
= m_parent_o_stream
->GetLastError();
2222 m_entries
.push_back(spPending
.release());
2223 OnSysWrite(m_initialData
, m_initialSize
);
2229 // This is called to write out the zip entry when Close has been called
2230 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2232 void wxZipOutputStream::CreatePendingEntry()
2234 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2235 wxZipEntryPtr_
spPending(m_pending
);
2237 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2240 // Initially compresses the data to memory, then fall back to 'store'
2241 // if the compressor makes the data larger rather than smaller.
2242 wxMemoryOutputStream mem
;
2243 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2244 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2248 if (comp
!= m_store
) {
2249 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2250 CloseCompressor(comp
);
2255 m_entrySize
= m_initialSize
;
2256 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2258 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2259 m_initialSize
= mem
.GetSize();
2260 mem
.CopyTo(m_initialData
, m_initialSize
);
2262 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2265 spPending
->SetSize(m_entrySize
);
2266 spPending
->SetCrc(m_crcAccumulator
);
2267 spPending
->SetCompressedSize(m_initialSize
);
2270 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2271 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2273 if (m_parent_o_stream
->IsOk()) {
2274 m_entries
.push_back(spPending
.release());
2276 m_store
->Write(m_initialData
, m_initialSize
);
2280 m_lasterror
= m_parent_o_stream
->GetLastError();
2283 // Write the 'central directory' and the 'end-central-directory' records.
2285 bool wxZipOutputStream::Close()
2289 if (m_lasterror
== wxSTREAM_WRITE_ERROR
|| m_entries
.size() == 0) {
2290 wxFilterOutputStream::Close();
2296 endrec
.SetEntriesHere(m_entries
.size());
2297 endrec
.SetTotalEntries(m_entries
.size());
2298 endrec
.SetOffset(m_headerOffset
);
2299 endrec
.SetComment(m_Comment
);
2301 wxZipEntryList_::iterator it
;
2302 wxFileOffset size
= 0;
2304 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2305 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2310 endrec
.SetSize(size
);
2311 endrec
.Write(*m_parent_o_stream
, GetConv());
2313 m_lasterror
= m_parent_o_stream
->GetLastError();
2315 if (!wxFilterOutputStream::Close() || !IsOk())
2317 m_lasterror
= wxSTREAM_EOF
;
2321 // Finish writing the current entry
2323 bool wxZipOutputStream::CloseEntry()
2325 if (IsOk() && m_pending
)
2326 CreatePendingEntry();
2332 CloseCompressor(m_comp
);
2335 wxFileOffset compressedSize
= m_store
->TellO();
2337 wxZipEntry
& entry
= *m_entries
.back();
2339 // When writing raw the crc and size can't be checked
2341 m_crcAccumulator
= entry
.GetCrc();
2342 m_entrySize
= entry
.GetSize();
2345 // Write the sums in the trailing 'data descriptor' if necessary
2346 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2347 wxASSERT(!IsParentSeekable());
2349 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2350 compressedSize
, m_entrySize
);
2351 m_lasterror
= m_parent_o_stream
->GetLastError();
2354 // If the local header didn't have the correct crc and size written to
2355 // it then seek back and fix it
2356 else if (m_crcAccumulator
!= entry
.GetCrc()
2357 || m_entrySize
!= entry
.GetSize()
2358 || compressedSize
!= entry
.GetCompressedSize())
2360 if (IsParentSeekable()) {
2361 wxFileOffset here
= m_parent_o_stream
->TellO();
2362 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2363 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2364 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2365 compressedSize
, m_entrySize
);
2366 m_parent_o_stream
->SeekO(here
);
2367 m_lasterror
= m_parent_o_stream
->GetLastError();
2369 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2373 m_headerOffset
+= m_headerSize
+ compressedSize
;
2380 m_lasterror
= m_parent_o_stream
->GetLastError();
2382 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2383 entry
.GetName().c_str());
2387 void wxZipOutputStream::Sync()
2389 if (IsOk() && m_pending
)
2390 CreatePendingEntry(NULL
, 0);
2392 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2395 m_lasterror
= m_comp
->GetLastError();
2399 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2401 if (IsOk() && m_pending
) {
2402 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2403 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2404 m_initialSize
+= size
;
2407 CreatePendingEntry(buffer
, size
);
2412 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2413 if (!IsOk() || !size
)
2416 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2417 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2418 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2419 m_entrySize
+= m_comp
->LastWrite();
2421 return m_comp
->LastWrite();
2424 #endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM