1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/zipstrm.cpp
3 // Purpose: Streams for Zip files
4 // Author: Mike Wetherell
5 // Copyright: (c) Mike Wetherell
6 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
9 // For compilers that support precompilation, includes "wx.h".
10 #include "wx/wxprec.h"
18 #include "wx/zipstrm.h"
21 #include "wx/hashmap.h"
27 #include "wx/datstrm.h"
28 #include "wx/zstream.h"
29 #include "wx/mstream.h"
30 #include "wx/scopedptr.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
)
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 static 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
[] = { wxT("zip"), NULL
};
154 static const wxChar
*mimetypes
[] = { wxT("application/zip"), NULL
};
155 static const wxChar
*fileexts
[] = { wxT(".zip"), wxT(".htb"), NULL
};
156 static const wxChar
*empty
[] = { NULL
};
159 case wxSTREAM_PROTOCOL
: return protocols
;
160 case wxSTREAM_MIMETYPE
: return mimetypes
;
161 case wxSTREAM_FILEEXT
: 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
), wxT("buffer too small"));
203 m_size
= stream
.Read(m_data
, size
).LastRead();
204 m_ok
= m_size
== size
;
207 inline wxUint8
wxZipHeader::Read8()
209 wxASSERT(m_pos
< m_size
);
210 return m_data
[m_pos
++];
213 inline wxUint16
wxZipHeader::Read16()
215 wxASSERT(m_pos
+ 2 <= m_size
);
216 wxUint16 n
= CrackUint16(m_data
+ m_pos
);
221 inline 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 wxDECLARE_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 wxDECLARE_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 wxDECLARE_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 wxDECLARE_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
+ wxT("\\") : m_Name
);
789 for (size_t i
= 0; i
< name
.length(); i
++)
790 if (name
[i
] == wxT('/'))
796 return isDir
? m_Name
+ wxT("/") : 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, wxT("./")) == 0)
837 internal
.erase(0, 2);
838 if (internal
== wxT(".") || internal
== wxT(".."))
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
= unixName
.mb_str(conv
);
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
= unixName
.mb_str(conv
);
1083 const char *name
= name_buf
;
1084 if (!name
) name
= "";
1085 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
1087 const wxWX2MBbuf comment_buf
= m_Comment
.mb_str(conv
);
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
= m_Comment
.mb_str(conv
);
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
)
1272 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1279 /////////////////////////////////////////////////////////////////////////////
1280 // A weak link from an input stream to an output stream
1282 class wxZipStreamLink
1285 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1287 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1288 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1290 void Release(class wxZipInputStream
*WXUNUSED(s
))
1291 { if (--m_ref
== 0) delete this; }
1292 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1293 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1296 ~wxZipStreamLink() { }
1299 wxZipOutputStream
*m_stream
;
1301 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipStreamLink
)
1305 /////////////////////////////////////////////////////////////////////////////
1308 // leave the default wxZipEntryPtr free for users
1309 wxDECLARE_SCOPED_PTR(wxZipEntry
, wxZipEntryPtr_
)
1310 wxDEFINE_SCOPED_PTR (wxZipEntry
, wxZipEntryPtr_
)
1314 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1315 wxMBConv
& conv
/*=wxConvLocal*/)
1316 : wxArchiveInputStream(stream
, conv
)
1321 wxZipInputStream::wxZipInputStream(wxInputStream
*stream
,
1322 wxMBConv
& conv
/*=wxConvLocal*/)
1323 : wxArchiveInputStream(stream
, conv
)
1328 #if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1330 // Part of the compatibility constructor, which has been made inline to
1331 // avoid a problem with it not being exported by mingw 3.2.3
1333 void wxZipInputStream::Init(const wxString
& file
)
1335 // no error messages
1338 m_allowSeeking
= true;
1339 wxFFileInputStream
*ffile
;
1340 ffile
= static_cast<wxFFileInputStream
*>(m_parent_i_stream
);
1341 wxZipEntryPtr_ entry
;
1343 if (ffile
->IsOk()) {
1345 entry
.reset(GetNextEntry());
1347 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1350 if (entry
.get() == NULL
)
1351 m_lasterror
= wxSTREAM_READ_ERROR
;
1354 wxInputStream
* wxZipInputStream::OpenFile(const wxString
& archive
)
1357 return new wxFFileInputStream(archive
);
1360 #endif // WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1362 void wxZipInputStream::Init()
1364 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1370 m_parentSeekable
= false;
1371 m_weaklinks
= new wxZipWeakLinks
;
1372 m_streamlink
= NULL
;
1373 m_offsetAdjustment
= 0;
1374 m_position
= wxInvalidOffset
;
1377 m_lasterror
= m_parent_i_stream
->GetLastError();
1378 #if WXWIN_COMPATIBILITY_2_6
1379 m_allowSeeking
= false;
1383 wxZipInputStream::~wxZipInputStream()
1385 CloseDecompressor(m_decomp
);
1391 m_weaklinks
->Release(this);
1394 m_streamlink
->Release(this);
1397 wxString
wxZipInputStream::GetComment()
1399 if (m_position
== wxInvalidOffset
)
1400 if (!LoadEndRecord())
1401 return wxEmptyString
;
1403 if (!m_parentSeekable
&& Eof() && m_signature
) {
1404 m_lasterror
= wxSTREAM_NO_ERROR
;
1405 m_lasterror
= ReadLocal(true);
1411 int wxZipInputStream::GetTotalEntries()
1413 if (m_position
== wxInvalidOffset
)
1415 return m_TotalEntries
;
1418 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1420 wxZipStreamLink
*link
= NULL
;
1422 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1423 link
= new wxZipStreamLink(out
);
1425 m_streamlink
->Release(this);
1426 m_streamlink
= link
->AddRef();
1432 bool wxZipInputStream::LoadEndRecord()
1434 wxCHECK(m_position
== wxInvalidOffset
, false);
1440 // First find the end-of-central-directory record.
1441 if (!FindEndRecord()) {
1442 // failed, so either this is a non-seekable stream (ok), or not a zip
1443 if (m_parentSeekable
) {
1444 m_lasterror
= wxSTREAM_READ_ERROR
;
1445 wxLogError(_("invalid zip file"));
1450 wxFileOffset pos
= m_parent_i_stream
->TellI();
1451 if (pos
!= wxInvalidOffset
)
1452 m_offsetAdjustment
= m_position
= pos
;
1459 // Read in the end record
1460 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1461 if (!endrec
.Read(*m_parent_i_stream
, GetConv()))
1464 m_TotalEntries
= endrec
.GetTotalEntries();
1465 m_Comment
= endrec
.GetComment();
1467 wxUint32 magic
= m_TotalEntries
? CENTRAL_MAGIC
: END_MAGIC
;
1469 // Now find the central-directory. we have the file offset of
1470 // the CD, so look there first.
1471 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1472 ReadSignature() == magic
) {
1473 m_signature
= magic
;
1474 m_position
= endrec
.GetOffset();
1475 m_offsetAdjustment
= 0;
1479 // If it's not there, then it could be that the zip has been appended
1480 // to a self extractor, so take the CD size (also in endrec), subtract
1481 // it from the file offset of the end-central-directory and look there.
1482 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1483 != wxInvalidOffset
&& ReadSignature() == magic
) {
1484 m_signature
= magic
;
1485 m_position
= endPos
- endrec
.GetSize();
1486 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1490 wxLogError(_("can't find central directory in zip"));
1491 m_lasterror
= wxSTREAM_READ_ERROR
;
1495 // Find the end-of-central-directory record.
1496 // If found the stream will be positioned just past the 4 signature bytes.
1498 bool wxZipInputStream::FindEndRecord()
1500 if (!m_parent_i_stream
->IsSeekable())
1503 // usually it's 22 bytes in size and the last thing in the file
1506 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1510 m_parentSeekable
= true;
1513 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1515 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1518 // unfortunately, the record has a comment field that can be up to 65535
1519 // bytes in length, so if the signature not found then search backwards.
1520 wxFileOffset pos
= m_parent_i_stream
->TellI();
1521 const int BUFSIZE
= 1024;
1522 wxCharBuffer
buf(BUFSIZE
);
1524 memcpy(buf
.data(), magic
, 3);
1525 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1527 while (pos
> minpos
) {
1528 size_t len
= wx_truncate_cast(size_t,
1529 pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1530 memcpy(buf
.data() + len
, buf
, 3);
1533 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1534 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1537 char *p
= buf
.data() + len
;
1539 while (p
-- > buf
.data()) {
1540 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1541 size_t remainder
= buf
.data() + len
- p
;
1543 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1552 wxZipEntry
*wxZipInputStream::GetNextEntry()
1554 if (m_position
== wxInvalidOffset
)
1555 if (!LoadEndRecord())
1558 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1562 wxZipEntryPtr_
entry(new wxZipEntry(m_entry
));
1563 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1564 return entry
.release();
1567 wxStreamError
wxZipInputStream::ReadCentral()
1572 if (m_signature
== END_MAGIC
)
1573 return wxSTREAM_EOF
;
1575 if (m_signature
!= CENTRAL_MAGIC
) {
1576 wxLogError(_("error reading zip central directory"));
1577 return wxSTREAM_READ_ERROR
;
1580 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1581 return wxSTREAM_READ_ERROR
;
1583 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1586 return wxSTREAM_READ_ERROR
;
1590 m_signature
= ReadSignature();
1592 if (m_offsetAdjustment
)
1593 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1594 m_entry
.SetKey(m_entry
.GetOffset());
1596 return wxSTREAM_NO_ERROR
;
1599 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1605 m_signature
= ReadSignature();
1607 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1608 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1609 m_streamlink
->Release(this);
1610 m_streamlink
= NULL
;
1614 while (m_signature
== CENTRAL_MAGIC
) {
1615 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1616 return wxSTREAM_EOF
;
1618 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1622 return wxSTREAM_READ_ERROR
;
1624 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1626 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1627 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1628 entry
->SetComment(m_entry
.GetComment());
1629 entry
->SetDiskStart(m_entry
.GetDiskStart());
1630 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1631 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1632 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1634 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1637 m_signature
= ReadSignature();
1640 if (m_signature
== END_MAGIC
) {
1641 if (readEndRec
|| m_streamlink
) {
1643 endrec
.Read(*m_parent_i_stream
, GetConv());
1644 m_Comment
= endrec
.GetComment();
1647 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1648 m_streamlink
->Release(this);
1649 m_streamlink
= NULL
;
1652 return wxSTREAM_EOF
;
1655 if (m_signature
== LOCAL_MAGIC
) {
1656 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1658 m_entry
.SetOffset(m_position
);
1659 m_entry
.SetKey(m_position
);
1663 return wxSTREAM_NO_ERROR
;
1667 wxLogError(_("error reading zip local header"));
1668 return wxSTREAM_READ_ERROR
;
1671 wxUint32
wxZipInputStream::ReadSignature()
1674 m_parent_i_stream
->Read(magic
, 4);
1675 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1678 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1680 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1681 return zipEntry
? OpenEntry(*zipEntry
) : false;
1686 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1688 if (m_position
== wxInvalidOffset
)
1689 if (!LoadEndRecord())
1691 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1699 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1701 // can only open the current entry on a non-seekable stream
1702 wxCHECK(m_parentSeekable
, false);
1705 m_lasterror
= wxSTREAM_READ_ERROR
;
1710 if (m_parentSeekable
) {
1711 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1714 if (ReadSignature() != LOCAL_MAGIC
) {
1715 wxLogError(_("bad zipfile offset to entry"));
1720 if (m_parentSeekable
|| AtHeader()) {
1721 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1722 if (m_headerSize
&& m_parentSeekable
) {
1723 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1725 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1727 m_weaklinks
->RemoveEntry(ref
->GetKey());
1729 if (entry
&& entry
!= ref
) {
1730 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1737 m_lasterror
= wxSTREAM_NO_ERROR
;
1741 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1743 wxASSERT(AfterHeader());
1745 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1751 if (compressedSize
!= wxInvalidOffset
) {
1752 m_store
->Open(compressedSize
);
1756 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1757 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1760 if (compressedSize
!= wxInvalidOffset
&&
1761 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1762 wxZlibInputStream::CanHandleGZip())) {
1763 m_store
->Open(compressedSize
);
1764 m_decomp
= OpenDecompressor(*m_store
);
1766 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1770 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1771 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1775 // Can be overridden to add support for additional decompression methods
1777 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1779 switch (m_entry
.GetMethod()) {
1780 case wxZIP_METHOD_STORE
:
1781 if (m_entry
.GetSize() == wxInvalidOffset
) {
1782 wxLogError(_("stored file length not in Zip header"));
1785 m_store
->Open(m_entry
.GetSize());
1788 case wxZIP_METHOD_DEFLATE
:
1790 m_inflate
= new wxZlibInputStream2(stream
);
1792 m_inflate
->Open(stream
);
1796 wxLogError(_("unsupported Zip compression method"));
1802 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1804 if (decomp
&& decomp
== m_rawin
)
1805 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1806 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1811 // Closes the current entry and positions the underlying stream at the start
1812 // of the next entry
1814 bool wxZipInputStream::CloseEntry()
1818 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1821 if (!m_parentSeekable
) {
1822 if (!IsOpened() && !OpenDecompressor(true))
1825 const int BUFSIZE
= 8192;
1826 wxCharBuffer
buf(BUFSIZE
);
1828 Read(buf
.data(), BUFSIZE
);
1830 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1833 if (m_lasterror
== wxSTREAM_EOF
)
1834 m_lasterror
= wxSTREAM_NO_ERROR
;
1836 CloseDecompressor(m_decomp
);
1838 m_entry
= wxZipEntry();
1845 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1848 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1849 m_lasterror
= wxSTREAM_READ_ERROR
;
1850 if (!IsOk() || !size
)
1853 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1855 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1857 m_lasterror
= m_decomp
->GetLastError();
1860 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1861 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1862 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1865 entry
->SetCrc(m_entry
.GetCrc());
1866 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1867 entry
->SetSize(m_entry
.GetSize());
1873 m_lasterror
= wxSTREAM_READ_ERROR
;
1875 if (m_entry
.GetSize() != TellI())
1877 wxLogError(_("reading zip stream (entry %s): bad length"),
1878 m_entry
.GetName().c_str());
1880 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1882 wxLogError(_("reading zip stream (entry %s): bad crc"),
1883 m_entry
.GetName().c_str());
1887 m_lasterror
= wxSTREAM_EOF
;
1895 #if WXWIN_COMPATIBILITY_2_6
1897 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1899 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1901 // seeking works when the stream is created with the compatibility
1903 if (!m_allowSeeking
)
1904 return wxInvalidOffset
;
1906 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1907 m_lasterror
= wxSTREAM_READ_ERROR
;
1909 return wxInvalidOffset
;
1911 // NB: since ZIP files don't natively support seeking, we have to
1912 // implement a brute force workaround -- reading all the data
1913 // between current and the new position (or between beginning of
1914 // the file and new position...)
1916 wxFileOffset nextpos
;
1917 wxFileOffset pos
= TellI();
1921 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1922 case wxFromStart
: nextpos
= seek
; break;
1923 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1924 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1927 wxFileOffset toskip
wxDUMMY_INITIALIZE(0);
1928 if ( nextpos
>= pos
)
1930 toskip
= nextpos
- pos
;
1934 wxZipEntry
current(m_entry
);
1935 if (!OpenEntry(current
))
1937 m_lasterror
= wxSTREAM_READ_ERROR
;
1945 const int BUFSIZE
= 4096;
1947 char buffer
[BUFSIZE
];
1948 while ( toskip
> 0 )
1950 sz
= wx_truncate_cast(size_t, wxMin(toskip
, BUFSIZE
));
1960 #endif // WXWIN_COMPATIBILITY_2_6
1963 /////////////////////////////////////////////////////////////////////////////
1966 #include "wx/listimpl.cpp"
1967 WX_DEFINE_LIST(wxZipEntryList_
)
1969 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1971 wxMBConv
& conv
/*=wxConvLocal*/)
1972 : wxArchiveOutputStream(stream
, conv
)
1977 wxZipOutputStream::wxZipOutputStream(wxOutputStream
*stream
,
1979 wxMBConv
& conv
/*=wxConvLocal*/)
1980 : wxArchiveOutputStream(stream
, conv
)
1985 void wxZipOutputStream::Init(int level
)
1987 m_store
= new wxStoredOutputStream(*m_parent_o_stream
);
1990 m_initialData
= new char[OUTPUT_LATENCY
];
1999 m_offsetAdjustment
= wxInvalidOffset
;
2000 m_endrecWritten
= false;
2003 wxZipOutputStream::~wxZipOutputStream()
2006 WX_CLEAR_LIST(wxZipEntryList_
, m_entries
);
2010 delete [] m_initialData
;
2012 m_backlink
->Release(this);
2015 bool wxZipOutputStream::PutNextEntry(
2016 const wxString
& name
,
2017 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
2018 wxFileOffset size
/*=wxInvalidOffset*/)
2020 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
2023 bool wxZipOutputStream::PutNextDirEntry(
2024 const wxString
& name
,
2025 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
2027 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
2029 return PutNextEntry(entry
);
2032 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
2033 wxZipInputStream
& inputStream
)
2035 wxZipEntryPtr_
e(entry
);
2038 inputStream
.DoOpen(e
.get(), true) &&
2039 DoCreate(e
.release(), true) &&
2040 Write(inputStream
).IsOk() && inputStream
.Eof();
2043 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
2045 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2048 return PutNextEntry(zipEntry
);
2051 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
2052 wxArchiveInputStream
& stream
)
2054 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2056 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
2061 return CopyEntry(zipEntry
, static_cast<wxZipInputStream
&>(stream
));
2064 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
2066 m_Comment
= inputStream
.GetComment();
2068 m_backlink
->Release(this);
2069 m_backlink
= inputStream
.MakeLink(this);
2073 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
2075 return CopyArchiveMetaData(static_cast<wxZipInputStream
&>(stream
));
2078 void wxZipOutputStream::SetLevel(int level
)
2080 if (level
!= m_level
) {
2081 if (m_comp
!= m_deflate
)
2088 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
2096 // write the signature bytes right away
2097 wxDataOutputStream
ds(*m_parent_o_stream
);
2100 // and if this is the first entry test for seekability
2101 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
2103 bool logging
= wxLog::IsEnabled();
2106 wxFileOffset here
= m_parent_o_stream
->TellO();
2108 if (here
!= wxInvalidOffset
&& here
>= 4) {
2109 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
2110 m_offsetAdjustment
= here
- 4;
2112 wxLog::EnableLogging(logging
);
2114 m_parent_o_stream
->SeekO(here
);
2119 m_pending
->SetOffset(m_headerOffset
);
2121 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
2126 m_lasterror
= wxSTREAM_NO_ERROR
;
2130 // Can be overridden to add support for additional compression methods
2132 wxOutputStream
*wxZipOutputStream::OpenCompressor(
2133 wxOutputStream
& stream
,
2135 const Buffer bufs
[])
2137 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
2139 && (IsParentSeekable()
2140 || entry
.GetCompressedSize() != wxInvalidOffset
2141 || entry
.GetSize() != wxInvalidOffset
)) {
2142 entry
.SetMethod(wxZIP_METHOD_STORE
);
2145 for (int i
= 0; bufs
[i
].m_data
; ++i
)
2146 size
+= bufs
[i
].m_size
;
2147 entry
.SetMethod(size
<= 6 ?
2148 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
2152 switch (entry
.GetMethod()) {
2153 case wxZIP_METHOD_STORE
:
2154 if (entry
.GetCompressedSize() == wxInvalidOffset
)
2155 entry
.SetCompressedSize(entry
.GetSize());
2158 case wxZIP_METHOD_DEFLATE
:
2160 int defbits
= wxZIP_DEFLATE_NORMAL
;
2161 switch (GetLevel()) {
2163 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2165 case 2: case 3: case 4:
2166 defbits
= wxZIP_DEFLATE_FAST
;
2169 defbits
= wxZIP_DEFLATE_EXTRA
;
2172 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2173 defbits
| wxZIP_SUMS_FOLLOW
);
2176 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2178 m_deflate
->Open(stream
);
2184 wxLogError(_("unsupported Zip compression method"));
2190 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2192 if (comp
== m_deflate
)
2194 else if (comp
!= m_store
)
2199 // This is called when OUPUT_LATENCY bytes has been written to the
2200 // wxZipOutputStream to actually create the zip entry.
2202 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2204 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2205 wxZipEntryPtr_
spPending(m_pending
);
2209 { m_initialData
, m_initialSize
},
2210 { (const char*)buffer
, size
},
2217 m_comp
= OpenCompressor(*m_store
, *spPending
,
2218 m_initialSize
? bufs
: bufs
+ 1);
2220 if (IsParentSeekable()
2221 || (spPending
->m_Crc
2222 && spPending
->m_CompressedSize
!= wxInvalidOffset
2223 && spPending
->m_Size
!= wxInvalidOffset
))
2224 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2226 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2227 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2229 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2230 m_lasterror
= m_parent_o_stream
->GetLastError();
2233 m_entries
.push_back(spPending
.release());
2234 OnSysWrite(m_initialData
, m_initialSize
);
2240 // This is called to write out the zip entry when Close has been called
2241 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2243 void wxZipOutputStream::CreatePendingEntry()
2245 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2246 wxZipEntryPtr_
spPending(m_pending
);
2248 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2251 // Initially compresses the data to memory, then fall back to 'store'
2252 // if the compressor makes the data larger rather than smaller.
2253 wxMemoryOutputStream mem
;
2254 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2255 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2259 if (comp
!= m_store
) {
2260 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2261 CloseCompressor(comp
);
2266 m_entrySize
= m_initialSize
;
2267 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2269 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2270 m_initialSize
= mem
.GetSize();
2271 mem
.CopyTo(m_initialData
, m_initialSize
);
2273 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2276 spPending
->SetSize(m_entrySize
);
2277 spPending
->SetCrc(m_crcAccumulator
);
2278 spPending
->SetCompressedSize(m_initialSize
);
2281 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2282 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2284 if (m_parent_o_stream
->IsOk()) {
2285 m_entries
.push_back(spPending
.release());
2287 m_store
->Write(m_initialData
, m_initialSize
);
2291 m_lasterror
= m_parent_o_stream
->GetLastError();
2294 // Write the 'central directory' and the 'end-central-directory' records.
2296 bool wxZipOutputStream::Close()
2300 if (m_lasterror
== wxSTREAM_WRITE_ERROR
2301 || (m_entries
.size() == 0 && m_endrecWritten
))
2303 wxFilterOutputStream::Close();
2309 endrec
.SetEntriesHere(m_entries
.size());
2310 endrec
.SetTotalEntries(m_entries
.size());
2311 endrec
.SetOffset(m_headerOffset
);
2312 endrec
.SetComment(m_Comment
);
2314 wxZipEntryList_::iterator it
;
2315 wxFileOffset size
= 0;
2317 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2318 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2323 endrec
.SetSize(size
);
2324 endrec
.Write(*m_parent_o_stream
, GetConv());
2326 m_lasterror
= m_parent_o_stream
->GetLastError();
2327 m_endrecWritten
= true;
2329 if (!wxFilterOutputStream::Close() || !IsOk())
2331 m_lasterror
= wxSTREAM_EOF
;
2335 // Finish writing the current entry
2337 bool wxZipOutputStream::CloseEntry()
2339 if (IsOk() && m_pending
)
2340 CreatePendingEntry();
2346 CloseCompressor(m_comp
);
2349 wxFileOffset compressedSize
= m_store
->TellO();
2351 wxZipEntry
& entry
= *m_entries
.back();
2353 // When writing raw the crc and size can't be checked
2355 m_crcAccumulator
= entry
.GetCrc();
2356 m_entrySize
= entry
.GetSize();
2359 // Write the sums in the trailing 'data descriptor' if necessary
2360 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2361 wxASSERT(!IsParentSeekable());
2363 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2364 compressedSize
, m_entrySize
);
2365 m_lasterror
= m_parent_o_stream
->GetLastError();
2368 // If the local header didn't have the correct crc and size written to
2369 // it then seek back and fix it
2370 else if (m_crcAccumulator
!= entry
.GetCrc()
2371 || m_entrySize
!= entry
.GetSize()
2372 || compressedSize
!= entry
.GetCompressedSize())
2374 if (IsParentSeekable()) {
2375 wxFileOffset here
= m_parent_o_stream
->TellO();
2376 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2377 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2378 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2379 compressedSize
, m_entrySize
);
2380 m_parent_o_stream
->SeekO(here
);
2381 m_lasterror
= m_parent_o_stream
->GetLastError();
2383 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2387 m_headerOffset
+= m_headerSize
+ compressedSize
;
2394 m_lasterror
= m_parent_o_stream
->GetLastError();
2396 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2397 entry
.GetName().c_str());
2401 void wxZipOutputStream::Sync()
2403 if (IsOk() && m_pending
)
2404 CreatePendingEntry(NULL
, 0);
2406 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2409 m_lasterror
= m_comp
->GetLastError();
2413 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2415 if (IsOk() && m_pending
) {
2416 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2417 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2418 m_initialSize
+= size
;
2421 CreatePendingEntry(buffer
, size
);
2426 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2427 if (!IsOk() || !size
)
2430 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2431 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2432 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2433 m_entrySize
+= m_comp
->LastWrite();
2435 return m_comp
->LastWrite();
2438 #endif // wxUSE_ZIPSTREAM