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"
19 #include "wx/zipstrm.h"
22 #include "wx/hashmap.h"
28 #include "wx/datstrm.h"
29 #include "wx/zstream.h"
30 #include "wx/mstream.h"
31 #include "wx/scopedptr.h"
32 #include "wx/wfstream.h"
35 // value for the 'version needed to extract' field (20 means 2.0)
37 VERSION_NEEDED_TO_EXTRACT
= 20
40 // signatures for the various records (PKxx)
42 CENTRAL_MAGIC
= 0x02014b50, // central directory record
43 LOCAL_MAGIC
= 0x04034b50, // local header
44 END_MAGIC
= 0x06054b50, // end of central directory record
45 SUMS_MAGIC
= 0x08074b50 // data descriptor (info-zip)
48 // unix file attributes. zip stores them in the high 16 bits of the
49 // 'external attributes' field, hence the extra zeros.
51 wxZIP_S_IFMT
= 0xF0000000,
52 wxZIP_S_IFDIR
= 0x40000000,
53 wxZIP_S_IFREG
= 0x80000000
56 // minimum sizes for the various records
64 // The number of bytes that must be written to an wxZipOutputStream before
65 // a zip entry is created. The purpose of this latency is so that
66 // OpenCompressor() can see a little data before deciding which compressor
72 // Some offsets into the local header
77 IMPLEMENT_DYNAMIC_CLASS(wxZipEntry
, wxArchiveEntry
)
78 IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory
, wxArchiveClassFactory
)
81 /////////////////////////////////////////////////////////////////////////////
84 // read a string of a given length
86 static wxString
ReadString(wxInputStream
& stream
, wxUint16 len
, wxMBConv
& conv
)
92 wxCharBuffer
buf(len
);
93 stream
.Read(buf
.data(), len
);
94 wxString
str(buf
, conv
);
99 wxStringBuffer
buf(str
, len
);
100 stream
.Read(buf
, len
);
107 // Decode a little endian wxUint32 number from a character array
109 static inline wxUint32
CrackUint32(const char *m
)
111 const unsigned char *n
= (const unsigned char*)m
;
112 return (n
[3] << 24) | (n
[2] << 16) | (n
[1] << 8) | n
[0];
115 // Decode a little endian wxUint16 number from a character array
117 static inline wxUint16
CrackUint16(const char *m
)
119 const unsigned char *n
= (const unsigned char*)m
;
120 return (n
[1] << 8) | n
[0];
123 // Temporarily lower the logging level in debug mode to avoid a warning
124 // from SeekI about seeking on a stream with data written back to it.
126 static wxFileOffset
QuietSeek(wxInputStream
& stream
, wxFileOffset pos
)
128 #if defined(__WXDEBUG__) && wxUSE_LOG
129 wxLogLevel level
= wxLog::GetLogLevel();
130 wxLog::SetLogLevel(wxLOG_Debug
- 1);
131 wxFileOffset result
= stream
.SeekI(pos
);
132 wxLog::SetLogLevel(level
);
135 return stream
.SeekI(pos
);
140 /////////////////////////////////////////////////////////////////////////////
143 static wxZipClassFactory g_wxZipClassFactory
;
145 wxZipClassFactory::wxZipClassFactory()
147 if (this == &g_wxZipClassFactory
)
151 const wxChar
* const *
152 wxZipClassFactory::GetProtocols(wxStreamProtocolType type
) const
154 static const wxChar
*protocols
[] = { _T("zip"), NULL
};
155 static const wxChar
*mimetypes
[] = { _T("application/zip"), NULL
};
156 static const wxChar
*fileexts
[] = { _T(".zip"), _T(".htb"), NULL
};
157 static const wxChar
*empty
[] = { NULL
};
160 case wxSTREAM_PROTOCOL
: return protocols
;
161 case wxSTREAM_MIMETYPE
: return mimetypes
;
162 case wxSTREAM_FILEEXT
: return fileexts
;
163 default: return empty
;
168 /////////////////////////////////////////////////////////////////////////////
174 wxZipHeader(wxInputStream
& stream
, size_t size
);
176 inline wxUint8
Read8();
177 inline wxUint16
Read16();
178 inline wxUint32
Read32();
180 const char *GetData() const { return m_data
; }
181 size_t GetSize() const { return m_size
; }
182 operator bool() const { return m_ok
; }
184 size_t Seek(size_t pos
) { m_pos
= pos
; return m_pos
; }
185 size_t Skip(size_t size
) { m_pos
+= size
; return m_pos
; }
187 wxZipHeader
& operator>>(wxUint8
& n
) { n
= Read8(); return *this; }
188 wxZipHeader
& operator>>(wxUint16
& n
) { n
= Read16(); return *this; }
189 wxZipHeader
& operator>>(wxUint32
& n
) { n
= Read32(); return *this; }
198 wxZipHeader::wxZipHeader(wxInputStream
& stream
, size_t size
)
203 wxCHECK_RET(size
<= sizeof(m_data
), _T("buffer too small"));
204 m_size
= stream
.Read(m_data
, size
).LastRead();
205 m_ok
= m_size
== size
;
208 inline wxUint8
wxZipHeader::Read8()
210 wxASSERT(m_pos
< m_size
);
211 return m_data
[m_pos
++];
214 inline wxUint16
wxZipHeader::Read16()
216 wxASSERT(m_pos
+ 2 <= m_size
);
217 wxUint16 n
= CrackUint16(m_data
+ m_pos
);
222 inline wxUint32
wxZipHeader::Read32()
224 wxASSERT(m_pos
+ 4 <= m_size
);
225 wxUint32 n
= CrackUint32(m_data
+ m_pos
);
231 /////////////////////////////////////////////////////////////////////////////
232 // Stored input stream
233 // Trival decompressor for files which are 'stored' in the zip file.
235 class wxStoredInputStream
: public wxFilterInputStream
238 wxStoredInputStream(wxInputStream
& stream
);
240 void Open(wxFileOffset len
) { Close(); m_len
= len
; }
241 void Close() { m_pos
= 0; m_lasterror
= wxSTREAM_NO_ERROR
; }
243 virtual char Peek() { return wxInputStream::Peek(); }
244 virtual wxFileOffset
GetLength() const { return m_len
; }
247 virtual size_t OnSysRead(void *buffer
, size_t size
);
248 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
254 DECLARE_NO_COPY_CLASS(wxStoredInputStream
)
257 wxStoredInputStream::wxStoredInputStream(wxInputStream
& stream
)
258 : wxFilterInputStream(stream
),
264 size_t wxStoredInputStream::OnSysRead(void *buffer
, size_t size
)
266 size_t count
= wx_truncate_cast(size_t,
267 wxMin(size
+ wxFileOffset(0), m_len
- m_pos
+ size_t(0)));
268 count
= m_parent_i_stream
->Read(buffer
, count
).LastRead();
272 m_lasterror
= m_pos
== m_len
? wxSTREAM_EOF
: wxSTREAM_READ_ERROR
;
278 /////////////////////////////////////////////////////////////////////////////
279 // Stored output stream
280 // Trival compressor for files which are 'stored' in the zip file.
282 class wxStoredOutputStream
: public wxFilterOutputStream
285 wxStoredOutputStream(wxOutputStream
& stream
) :
286 wxFilterOutputStream(stream
), m_pos(0) { }
290 m_lasterror
= wxSTREAM_NO_ERROR
;
295 virtual size_t OnSysWrite(const void *buffer
, size_t size
);
296 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
300 DECLARE_NO_COPY_CLASS(wxStoredOutputStream
)
303 size_t wxStoredOutputStream::OnSysWrite(const void *buffer
, size_t size
)
305 if (!IsOk() || !size
)
307 size_t count
= m_parent_o_stream
->Write(buffer
, size
).LastWrite();
309 m_lasterror
= wxSTREAM_WRITE_ERROR
;
315 /////////////////////////////////////////////////////////////////////////////
318 // Used to handle the unusal case of raw copying an entry of unknown
319 // length. This can only happen when the zip being copied from is being
320 // read from a non-seekable stream, and also was original written to a
321 // non-seekable stream.
323 // In this case there's no option but to decompress the stream to find
324 // it's length, but we can still write the raw compressed data to avoid the
325 // compression overhead (which is the greater one).
327 // Usage is like this:
328 // m_rawin = new wxRawInputStream(*m_parent_i_stream);
329 // m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
331 // The wxRawInputStream owns a wxTeeInputStream object, the role of which
332 // is something like the unix 'tee' command; it is a transparent filter, but
333 // allows the data read to be read a second time via an extra method 'GetData'.
335 // The wxRawInputStream then draws data through the tee using a decompressor
336 // then instead of returning the decompressed data, retuns the raw data
337 // from wxTeeInputStream::GetData().
339 class wxTeeInputStream
: public wxFilterInputStream
342 wxTeeInputStream(wxInputStream
& stream
);
344 size_t GetCount() const { return m_end
- m_start
; }
345 size_t GetData(char *buffer
, size_t size
);
350 wxInputStream
& Read(void *buffer
, size_t size
);
353 virtual size_t OnSysRead(void *buffer
, size_t size
);
354 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
358 wxMemoryBuffer m_buf
;
362 DECLARE_NO_COPY_CLASS(wxTeeInputStream
)
365 wxTeeInputStream::wxTeeInputStream(wxInputStream
& stream
)
366 : wxFilterInputStream(stream
),
367 m_pos(0), m_buf(8192), m_start(0), m_end(0)
371 void wxTeeInputStream::Open()
373 m_pos
= m_start
= m_end
= 0;
374 m_lasterror
= wxSTREAM_NO_ERROR
;
377 bool wxTeeInputStream::Final()
379 bool final
= m_end
== m_buf
.GetDataLen();
380 m_end
= m_buf
.GetDataLen();
384 wxInputStream
& wxTeeInputStream::Read(void *buffer
, size_t size
)
386 size_t count
= wxInputStream::Read(buffer
, size
).LastRead();
387 m_end
= m_buf
.GetDataLen();
388 m_buf
.AppendData(buffer
, count
);
392 size_t wxTeeInputStream::OnSysRead(void *buffer
, size_t size
)
394 size_t count
= m_parent_i_stream
->Read(buffer
, size
).LastRead();
396 m_lasterror
= m_parent_i_stream
->GetLastError();
400 size_t wxTeeInputStream::GetData(char *buffer
, size_t size
)
403 size_t len
= m_buf
.GetDataLen();
404 len
= len
> m_wbacksize
? len
- m_wbacksize
: 0;
405 m_buf
.SetDataLen(len
);
407 wxFAIL
; // we've already returned data that's now being ungot
410 m_parent_i_stream
->Reset();
411 m_parent_i_stream
->Ungetch(m_wback
, m_wbacksize
);
418 if (size
> GetCount())
421 memcpy(buffer
, m_buf
+ m_start
, size
);
423 wxASSERT(m_start
<= m_end
);
426 if (m_start
== m_end
&& m_start
> 0 && m_buf
.GetDataLen() > 0) {
427 size_t len
= m_buf
.GetDataLen();
428 char *buf
= (char*)m_buf
.GetWriteBuf(len
);
430 memmove(buf
, buf
+ m_end
, len
);
431 m_buf
.UngetWriteBuf(len
);
438 class wxRawInputStream
: public wxFilterInputStream
441 wxRawInputStream(wxInputStream
& stream
);
442 virtual ~wxRawInputStream() { delete m_tee
; }
444 wxInputStream
* Open(wxInputStream
*decomp
);
445 wxInputStream
& GetTee() const { return *m_tee
; }
448 virtual size_t OnSysRead(void *buffer
, size_t size
);
449 virtual wxFileOffset
OnSysTell() const { return m_pos
; }
453 wxTeeInputStream
*m_tee
;
455 enum { BUFSIZE
= 8192 };
456 wxCharBuffer m_dummy
;
458 DECLARE_NO_COPY_CLASS(wxRawInputStream
)
461 wxRawInputStream::wxRawInputStream(wxInputStream
& stream
)
462 : wxFilterInputStream(stream
),
464 m_tee(new wxTeeInputStream(stream
)),
469 wxInputStream
*wxRawInputStream::Open(wxInputStream
*decomp
)
472 m_parent_i_stream
= decomp
;
474 m_lasterror
= wxSTREAM_NO_ERROR
;
482 size_t wxRawInputStream::OnSysRead(void *buffer
, size_t size
)
484 char *buf
= (char*)buffer
;
487 while (count
< size
&& IsOk())
489 while (m_parent_i_stream
->IsOk() && m_tee
->GetCount() == 0)
490 m_parent_i_stream
->Read(m_dummy
.data(), BUFSIZE
);
492 size_t n
= m_tee
->GetData(buf
+ count
, size
- count
);
495 if (n
== 0 && m_tee
->Final())
496 m_lasterror
= m_parent_i_stream
->GetLastError();
504 /////////////////////////////////////////////////////////////////////////////
505 // Zlib streams than can be reused without recreating.
507 class wxZlibOutputStream2
: public wxZlibOutputStream
510 wxZlibOutputStream2(wxOutputStream
& stream
, int level
) :
511 wxZlibOutputStream(stream
, level
, wxZLIB_NO_HEADER
) { }
513 bool Open(wxOutputStream
& stream
);
514 bool Close() { DoFlush(true); m_pos
= wxInvalidOffset
; return IsOk(); }
517 bool wxZlibOutputStream2::Open(wxOutputStream
& stream
)
519 wxCHECK(m_pos
== wxInvalidOffset
, false);
521 m_deflate
->next_out
= m_z_buffer
;
522 m_deflate
->avail_out
= m_z_size
;
524 m_lasterror
= wxSTREAM_NO_ERROR
;
525 m_parent_o_stream
= &stream
;
527 if (deflateReset(m_deflate
) != Z_OK
) {
528 wxLogError(_("can't re-initialize zlib deflate stream"));
529 m_lasterror
= wxSTREAM_WRITE_ERROR
;
536 class wxZlibInputStream2
: public wxZlibInputStream
539 wxZlibInputStream2(wxInputStream
& stream
) :
540 wxZlibInputStream(stream
, wxZLIB_NO_HEADER
) { }
542 bool Open(wxInputStream
& stream
);
545 bool wxZlibInputStream2::Open(wxInputStream
& stream
)
547 m_inflate
->avail_in
= 0;
549 m_lasterror
= wxSTREAM_NO_ERROR
;
550 m_parent_i_stream
= &stream
;
552 if (inflateReset(m_inflate
) != Z_OK
) {
553 wxLogError(_("can't re-initialize zlib inflate stream"));
554 m_lasterror
= wxSTREAM_READ_ERROR
;
562 /////////////////////////////////////////////////////////////////////////////
563 // Class to hold wxZipEntry's Extra and LocalExtra fields
568 wxZipMemory() : m_data(NULL
), m_size(0), m_capacity(0), m_ref(1) { }
570 wxZipMemory
*AddRef() { m_ref
++; return this; }
571 void Release() { if (--m_ref
== 0) delete this; }
573 char *GetData() const { return m_data
; }
574 size_t GetSize() const { return m_size
; }
575 size_t GetCapacity() const { return m_capacity
; }
577 wxZipMemory
*Unique(size_t size
);
580 ~wxZipMemory() { delete [] m_data
; }
587 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipMemory
)
590 wxZipMemory
*wxZipMemory::Unique(size_t size
)
596 zm
= new wxZipMemory
;
601 if (zm
->m_capacity
< size
) {
602 delete [] zm
->m_data
;
603 zm
->m_data
= new char[size
];
604 zm
->m_capacity
= size
;
611 static inline wxZipMemory
*AddRef(wxZipMemory
*zm
)
618 static inline void Release(wxZipMemory
*zm
)
624 static void Copy(wxZipMemory
*& dest
, wxZipMemory
*src
)
630 static void Unique(wxZipMemory
*& zm
, size_t size
)
633 zm
= new wxZipMemory
;
635 zm
= zm
->Unique(size
);
639 /////////////////////////////////////////////////////////////////////////////
640 // Collection of weak references to entries
642 WX_DECLARE_HASH_MAP(long, wxZipEntry
*, wxIntegerHash
,
643 wxIntegerEqual
, wxOffsetZipEntryMap_
);
648 wxZipWeakLinks() : m_ref(1) { }
650 void Release(const wxZipInputStream
* WXUNUSED(x
))
651 { if (--m_ref
== 0) delete this; }
652 void Release(wxFileOffset key
)
653 { RemoveEntry(key
); if (--m_ref
== 0) delete this; }
655 wxZipWeakLinks
*AddEntry(wxZipEntry
*entry
, wxFileOffset key
);
656 void RemoveEntry(wxFileOffset key
)
657 { m_entries
.erase(wx_truncate_cast(key_type
, key
)); }
658 wxZipEntry
*GetEntry(wxFileOffset key
) const;
659 bool IsEmpty() const { return m_entries
.empty(); }
662 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
664 typedef wxOffsetZipEntryMap_::key_type key_type
;
667 wxOffsetZipEntryMap_ m_entries
;
669 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipWeakLinks
)
672 wxZipWeakLinks
*wxZipWeakLinks::AddEntry(wxZipEntry
*entry
, wxFileOffset key
)
674 m_entries
[wx_truncate_cast(key_type
, key
)] = entry
;
679 wxZipEntry
*wxZipWeakLinks::GetEntry(wxFileOffset key
) const
681 wxOffsetZipEntryMap_::const_iterator it
=
682 m_entries
.find(wx_truncate_cast(key_type
, key
));
683 return it
!= m_entries
.end() ? it
->second
: NULL
;
687 /////////////////////////////////////////////////////////////////////////////
690 wxZipEntry::wxZipEntry(
691 const wxString
& name
/*=wxEmptyString*/,
692 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
693 wxFileOffset size
/*=wxInvalidOffset*/)
695 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS
),
696 m_VersionMadeBy(wxMAJOR_VERSION
* 10 + wxMINOR_VERSION
),
697 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT
),
699 m_Method(wxZIP_METHOD_DEFAULT
),
702 m_CompressedSize(wxInvalidOffset
),
704 m_Key(wxInvalidOffset
),
705 m_Offset(wxInvalidOffset
),
707 m_InternalAttributes(0),
708 m_ExternalAttributes(0),
718 wxZipEntry::~wxZipEntry()
721 m_backlink
->Release(m_Key
);
723 Release(m_LocalExtra
);
726 wxZipEntry::wxZipEntry(const wxZipEntry
& e
)
728 m_SystemMadeBy(e
.m_SystemMadeBy
),
729 m_VersionMadeBy(e
.m_VersionMadeBy
),
730 m_VersionNeeded(e
.m_VersionNeeded
),
732 m_Method(e
.m_Method
),
733 m_DateTime(e
.m_DateTime
),
735 m_CompressedSize(e
.m_CompressedSize
),
739 m_Offset(e
.m_Offset
),
740 m_Comment(e
.m_Comment
),
741 m_DiskStart(e
.m_DiskStart
),
742 m_InternalAttributes(e
.m_InternalAttributes
),
743 m_ExternalAttributes(e
.m_ExternalAttributes
),
744 m_Extra(AddRef(e
.m_Extra
)),
745 m_LocalExtra(AddRef(e
.m_LocalExtra
)),
751 wxZipEntry
& wxZipEntry::operator=(const wxZipEntry
& e
)
754 m_SystemMadeBy
= e
.m_SystemMadeBy
;
755 m_VersionMadeBy
= e
.m_VersionMadeBy
;
756 m_VersionNeeded
= e
.m_VersionNeeded
;
758 m_Method
= e
.m_Method
;
759 m_DateTime
= e
.m_DateTime
;
761 m_CompressedSize
= e
.m_CompressedSize
;
765 m_Offset
= e
.m_Offset
;
766 m_Comment
= e
.m_Comment
;
767 m_DiskStart
= e
.m_DiskStart
;
768 m_InternalAttributes
= e
.m_InternalAttributes
;
769 m_ExternalAttributes
= e
.m_ExternalAttributes
;
770 Copy(m_Extra
, e
.m_Extra
);
771 Copy(m_LocalExtra
, e
.m_LocalExtra
);
772 m_zipnotifier
= NULL
;
774 m_backlink
->Release(m_Key
);
781 wxString
wxZipEntry::GetName(wxPathFormat format
/*=wxPATH_NATIVE*/) const
783 bool isDir
= IsDir() && !m_Name
.empty();
785 // optimisations for common (and easy) cases
786 switch (wxFileName::GetFormat(format
)) {
789 wxString
name(isDir
? m_Name
+ _T("\\") : m_Name
);
790 for (size_t i
= 0; i
< name
.length(); i
++)
791 if (name
[i
] == _T('/'))
797 return isDir
? m_Name
+ _T("/") : m_Name
;
806 fn
.AssignDir(m_Name
, wxPATH_UNIX
);
808 fn
.Assign(m_Name
, wxPATH_UNIX
);
810 return fn
.GetFullPath(format
);
813 // Static - Internally tars and zips use forward slashes for the path
814 // separator, absolute paths aren't allowed, and directory names have a
815 // trailing slash. This function converts a path into this internal format,
816 // but without a trailing slash for a directory.
818 wxString
wxZipEntry::GetInternalName(const wxString
& name
,
819 wxPathFormat format
/*=wxPATH_NATIVE*/,
820 bool *pIsDir
/*=NULL*/)
824 if (wxFileName::GetFormat(format
) != wxPATH_UNIX
)
825 internal
= wxFileName(name
, format
).GetFullPath(wxPATH_UNIX
);
829 bool isDir
= !internal
.empty() && internal
.Last() == '/';
833 internal
.erase(internal
.length() - 1);
835 while (!internal
.empty() && *internal
.begin() == '/')
836 internal
.erase(0, 1);
837 while (!internal
.empty() && internal
.compare(0, 2, _T("./")) == 0)
838 internal
.erase(0, 2);
839 if (internal
== _T(".") || internal
== _T(".."))
840 internal
= wxEmptyString
;
845 void wxZipEntry::SetSystemMadeBy(int system
)
847 int mode
= GetMode();
848 bool wasUnix
= IsMadeByUnix();
850 m_SystemMadeBy
= (wxUint8
)system
;
852 if (!wasUnix
&& IsMadeByUnix()) {
855 } else if (wasUnix
&& !IsMadeByUnix()) {
856 m_ExternalAttributes
&= 0xffff;
860 void wxZipEntry::SetIsDir(bool isDir
/*=true*/)
863 m_ExternalAttributes
|= wxZIP_A_SUBDIR
;
865 m_ExternalAttributes
&= ~wxZIP_A_SUBDIR
;
867 if (IsMadeByUnix()) {
868 m_ExternalAttributes
&= ~wxZIP_S_IFMT
;
870 m_ExternalAttributes
|= wxZIP_S_IFDIR
;
872 m_ExternalAttributes
|= wxZIP_S_IFREG
;
876 // Return unix style permission bits
878 int wxZipEntry::GetMode() const
880 // return unix permissions if present
882 return (m_ExternalAttributes
>> 16) & 0777;
884 // otherwise synthesize from the dos attribs
886 if (m_ExternalAttributes
& wxZIP_A_RDONLY
)
888 if (m_ExternalAttributes
& wxZIP_A_SUBDIR
)
894 // Set unix permissions
896 void wxZipEntry::SetMode(int mode
)
898 // Set dos attrib bits to be compatible
900 m_ExternalAttributes
&= ~wxZIP_A_RDONLY
;
902 m_ExternalAttributes
|= wxZIP_A_RDONLY
;
904 // set the actual unix permission bits if the system type allows
905 if (IsMadeByUnix()) {
906 m_ExternalAttributes
&= ~(0777L << 16);
907 m_ExternalAttributes
|= (mode
& 0777L) << 16;
911 const char *wxZipEntry::GetExtra() const
913 return m_Extra
? m_Extra
->GetData() : NULL
;
916 size_t wxZipEntry::GetExtraLen() const
918 return m_Extra
? m_Extra
->GetSize() : 0;
921 void wxZipEntry::SetExtra(const char *extra
, size_t len
)
923 Unique(m_Extra
, len
);
925 memcpy(m_Extra
->GetData(), extra
, len
);
928 const char *wxZipEntry::GetLocalExtra() const
930 return m_LocalExtra
? m_LocalExtra
->GetData() : NULL
;
933 size_t wxZipEntry::GetLocalExtraLen() const
935 return m_LocalExtra
? m_LocalExtra
->GetSize() : 0;
938 void wxZipEntry::SetLocalExtra(const char *extra
, size_t len
)
940 Unique(m_LocalExtra
, len
);
942 memcpy(m_LocalExtra
->GetData(), extra
, len
);
945 void wxZipEntry::SetNotifier(wxZipNotifier
& notifier
)
947 wxArchiveEntry::UnsetNotifier();
948 m_zipnotifier
= ¬ifier
;
949 m_zipnotifier
->OnEntryUpdated(*this);
952 void wxZipEntry::Notify()
955 m_zipnotifier
->OnEntryUpdated(*this);
956 else if (GetNotifier())
957 GetNotifier()->OnEntryUpdated(*this);
960 void wxZipEntry::UnsetNotifier()
962 wxArchiveEntry::UnsetNotifier();
963 m_zipnotifier
= NULL
;
966 size_t wxZipEntry::ReadLocal(wxInputStream
& stream
, wxMBConv
& conv
)
968 wxUint16 nameLen
, extraLen
;
969 wxUint32 compressedSize
, size
, crc
;
971 wxZipHeader
ds(stream
, LOCAL_SIZE
- 4);
975 ds
>> m_VersionNeeded
>> m_Flags
>> m_Method
;
976 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
977 ds
>> crc
>> compressedSize
>> size
>> nameLen
>> extraLen
;
979 bool sumsValid
= (m_Flags
& wxZIP_SUMS_FOLLOW
) == 0;
981 if (sumsValid
|| crc
)
983 if ((sumsValid
|| compressedSize
) || m_Method
== wxZIP_METHOD_STORE
)
984 m_CompressedSize
= compressedSize
;
985 if ((sumsValid
|| size
) || m_Method
== wxZIP_METHOD_STORE
)
988 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
989 if (stream
.LastRead() != nameLen
+ 0u)
992 if (extraLen
|| GetLocalExtraLen()) {
993 Unique(m_LocalExtra
, extraLen
);
995 stream
.Read(m_LocalExtra
->GetData(), extraLen
);
996 if (stream
.LastRead() != extraLen
+ 0u)
1001 return LOCAL_SIZE
+ nameLen
+ extraLen
;
1004 size_t wxZipEntry::WriteLocal(wxOutputStream
& stream
, wxMBConv
& conv
) const
1006 wxString unixName
= GetName(wxPATH_UNIX
);
1007 const wxWX2MBbuf name_buf
= unixName
.mb_str(conv
);
1008 const char *name
= name_buf
;
1009 if (!name
) name
= "";
1010 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
1012 wxDataOutputStream
ds(stream
);
1014 ds
<< m_VersionNeeded
<< m_Flags
<< m_Method
;
1015 ds
.Write32(GetDateTime().GetAsDOS());
1018 ds
.Write32(m_CompressedSize
!= wxInvalidOffset
?
1019 wx_truncate_cast(wxUint32
, m_CompressedSize
) : 0);
1020 ds
.Write32(m_Size
!= wxInvalidOffset
?
1021 wx_truncate_cast(wxUint32
, m_Size
) : 0);
1024 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetLocalExtraLen());
1025 ds
.Write16(extraLen
);
1027 stream
.Write(name
, nameLen
);
1029 stream
.Write(m_LocalExtra
->GetData(), extraLen
);
1031 return LOCAL_SIZE
+ nameLen
+ extraLen
;
1034 size_t wxZipEntry::ReadCentral(wxInputStream
& stream
, wxMBConv
& conv
)
1036 wxUint16 nameLen
, extraLen
, commentLen
;
1038 wxZipHeader
ds(stream
, CENTRAL_SIZE
- 4);
1042 ds
>> m_VersionMadeBy
>> m_SystemMadeBy
;
1044 SetVersionNeeded(ds
.Read16());
1045 SetFlags(ds
.Read16());
1046 SetMethod(ds
.Read16());
1047 SetDateTime(wxDateTime().SetFromDOS(ds
.Read32()));
1048 SetCrc(ds
.Read32());
1049 SetCompressedSize(ds
.Read32());
1050 SetSize(ds
.Read32());
1052 ds
>> nameLen
>> extraLen
>> commentLen
1053 >> m_DiskStart
>> m_InternalAttributes
>> m_ExternalAttributes
;
1054 SetOffset(ds
.Read32());
1056 SetName(ReadString(stream
, nameLen
, conv
), wxPATH_UNIX
);
1057 if (stream
.LastRead() != nameLen
+ 0u)
1060 if (extraLen
|| GetExtraLen()) {
1061 Unique(m_Extra
, extraLen
);
1063 stream
.Read(m_Extra
->GetData(), extraLen
);
1064 if (stream
.LastRead() != extraLen
+ 0u)
1070 m_Comment
= ReadString(stream
, commentLen
, conv
);
1071 if (stream
.LastRead() != commentLen
+ 0u)
1077 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1080 size_t wxZipEntry::WriteCentral(wxOutputStream
& stream
, wxMBConv
& conv
) const
1082 wxString unixName
= GetName(wxPATH_UNIX
);
1083 const wxWX2MBbuf name_buf
= unixName
.mb_str(conv
);
1084 const char *name
= name_buf
;
1085 if (!name
) name
= "";
1086 wxUint16 nameLen
= wx_truncate_cast(wxUint16
, strlen(name
));
1088 const wxWX2MBbuf comment_buf
= m_Comment
.mb_str(conv
);
1089 const char *comment
= comment_buf
;
1090 if (!comment
) comment
= "";
1091 wxUint16 commentLen
= wx_truncate_cast(wxUint16
, strlen(comment
));
1093 wxUint16 extraLen
= wx_truncate_cast(wxUint16
, GetExtraLen());
1095 wxDataOutputStream
ds(stream
);
1097 ds
<< CENTRAL_MAGIC
<< m_VersionMadeBy
<< m_SystemMadeBy
;
1099 ds
.Write16(wx_truncate_cast(wxUint16
, GetVersionNeeded()));
1100 ds
.Write16(wx_truncate_cast(wxUint16
, GetFlags()));
1101 ds
.Write16(wx_truncate_cast(wxUint16
, GetMethod()));
1102 ds
.Write32(GetDateTime().GetAsDOS());
1103 ds
.Write32(GetCrc());
1104 ds
.Write32(wx_truncate_cast(wxUint32
, GetCompressedSize()));
1105 ds
.Write32(wx_truncate_cast(wxUint32
, GetSize()));
1106 ds
.Write16(nameLen
);
1107 ds
.Write16(extraLen
);
1109 ds
<< commentLen
<< m_DiskStart
<< m_InternalAttributes
1110 << m_ExternalAttributes
<< wx_truncate_cast(wxUint32
, GetOffset());
1112 stream
.Write(name
, nameLen
);
1114 stream
.Write(GetExtra(), extraLen
);
1115 stream
.Write(comment
, commentLen
);
1117 return CENTRAL_SIZE
+ nameLen
+ extraLen
+ commentLen
;
1120 // Info-zip prefixes this record with a signature, but pkzip doesn't. So if
1121 // the 1st value is the signature then it is probably an info-zip record,
1122 // though there is a small chance that it is in fact a pkzip record which
1123 // happens to have the signature as it's CRC.
1125 size_t wxZipEntry::ReadDescriptor(wxInputStream
& stream
)
1127 wxZipHeader
ds(stream
, SUMS_SIZE
);
1131 m_Crc
= ds
.Read32();
1132 m_CompressedSize
= ds
.Read32();
1133 m_Size
= ds
.Read32();
1135 // if 1st value is the signature then this is probably an info-zip record
1136 if (m_Crc
== SUMS_MAGIC
)
1138 wxZipHeader
buf(stream
, 8);
1139 wxUint32 u1
= buf
.GetSize() >= 4 ? buf
.Read32() : (wxUint32
)LOCAL_MAGIC
;
1140 wxUint32 u2
= buf
.GetSize() == 8 ? buf
.Read32() : 0;
1142 // look for the signature of the following record to decide which
1143 if ((u1
== LOCAL_MAGIC
|| u1
== CENTRAL_MAGIC
) &&
1144 (u2
!= LOCAL_MAGIC
&& u2
!= CENTRAL_MAGIC
))
1146 // it's a pkzip style record after all!
1147 if (buf
.GetSize() > 0)
1148 stream
.Ungetch(buf
.GetData(), buf
.GetSize());
1152 // it's an info-zip record as expected
1153 if (buf
.GetSize() > 4)
1154 stream
.Ungetch(buf
.GetData() + 4, buf
.GetSize() - 4);
1155 m_Crc
= wx_truncate_cast(wxUint32
, m_CompressedSize
);
1156 m_CompressedSize
= m_Size
;
1158 return SUMS_SIZE
+ 4;
1165 size_t wxZipEntry::WriteDescriptor(wxOutputStream
& stream
, wxUint32 crc
,
1166 wxFileOffset compressedSize
, wxFileOffset size
)
1169 m_CompressedSize
= compressedSize
;
1172 wxDataOutputStream
ds(stream
);
1175 ds
.Write32(wx_truncate_cast(wxUint32
, compressedSize
));
1176 ds
.Write32(wx_truncate_cast(wxUint32
, size
));
1182 /////////////////////////////////////////////////////////////////////////////
1183 // wxZipEndRec - holds the end of central directory record
1190 int GetDiskNumber() const { return m_DiskNumber
; }
1191 int GetStartDisk() const { return m_StartDisk
; }
1192 int GetEntriesHere() const { return m_EntriesHere
; }
1193 int GetTotalEntries() const { return m_TotalEntries
; }
1194 wxFileOffset
GetSize() const { return m_Size
; }
1195 wxFileOffset
GetOffset() const { return m_Offset
; }
1196 wxString
GetComment() const { return m_Comment
; }
1198 void SetDiskNumber(int num
)
1199 { m_DiskNumber
= wx_truncate_cast(wxUint16
, num
); }
1200 void SetStartDisk(int num
)
1201 { m_StartDisk
= wx_truncate_cast(wxUint16
, num
); }
1202 void SetEntriesHere(int num
)
1203 { m_EntriesHere
= wx_truncate_cast(wxUint16
, num
); }
1204 void SetTotalEntries(int num
)
1205 { m_TotalEntries
= wx_truncate_cast(wxUint16
, num
); }
1206 void SetSize(wxFileOffset size
)
1207 { m_Size
= wx_truncate_cast(wxUint32
, size
); }
1208 void SetOffset(wxFileOffset offset
)
1209 { m_Offset
= wx_truncate_cast(wxUint32
, offset
); }
1210 void SetComment(const wxString
& comment
)
1211 { m_Comment
= comment
; }
1213 bool Read(wxInputStream
& stream
, wxMBConv
& conv
);
1214 bool Write(wxOutputStream
& stream
, wxMBConv
& conv
) const;
1217 wxUint16 m_DiskNumber
;
1218 wxUint16 m_StartDisk
;
1219 wxUint16 m_EntriesHere
;
1220 wxUint16 m_TotalEntries
;
1226 wxZipEndRec::wxZipEndRec()
1236 bool wxZipEndRec::Write(wxOutputStream
& stream
, wxMBConv
& conv
) const
1238 const wxWX2MBbuf comment_buf
= m_Comment
.mb_str(conv
);
1239 const char *comment
= comment_buf
;
1240 if (!comment
) comment
= "";
1241 wxUint16 commentLen
= (wxUint16
)strlen(comment
);
1243 wxDataOutputStream
ds(stream
);
1245 ds
<< END_MAGIC
<< m_DiskNumber
<< m_StartDisk
<< m_EntriesHere
1246 << m_TotalEntries
<< m_Size
<< m_Offset
<< commentLen
;
1248 stream
.Write(comment
, commentLen
);
1250 return stream
.IsOk();
1253 bool wxZipEndRec::Read(wxInputStream
& stream
, wxMBConv
& conv
)
1255 wxZipHeader
ds(stream
, END_SIZE
- 4);
1259 wxUint16 commentLen
;
1261 ds
>> m_DiskNumber
>> m_StartDisk
>> m_EntriesHere
1262 >> m_TotalEntries
>> m_Size
>> m_Offset
>> commentLen
;
1265 m_Comment
= ReadString(stream
, commentLen
, conv
);
1266 if (stream
.LastRead() != commentLen
+ 0u)
1270 if (m_DiskNumber
!= 0 || m_StartDisk
!= 0 ||
1271 m_EntriesHere
!= m_TotalEntries
)
1272 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
1278 /////////////////////////////////////////////////////////////////////////////
1279 // A weak link from an input stream to an output stream
1281 class wxZipStreamLink
1284 wxZipStreamLink(wxZipOutputStream
*stream
) : m_ref(1), m_stream(stream
) { }
1286 wxZipStreamLink
*AddRef() { m_ref
++; return this; }
1287 wxZipOutputStream
*GetOutputStream() const { return m_stream
; }
1289 void Release(class wxZipInputStream
*WXUNUSED(s
))
1290 { if (--m_ref
== 0) delete this; }
1291 void Release(class wxZipOutputStream
*WXUNUSED(s
))
1292 { m_stream
= NULL
; if (--m_ref
== 0) delete this; }
1295 ~wxZipStreamLink() { }
1298 wxZipOutputStream
*m_stream
;
1300 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipStreamLink
)
1304 /////////////////////////////////////////////////////////////////////////////
1307 // leave the default wxZipEntryPtr free for users
1308 wxDECLARE_SCOPED_PTR(wxZipEntry
, wxZipEntryPtr_
)
1309 wxDEFINE_SCOPED_PTR (wxZipEntry
, wxZipEntryPtr_
)
1313 wxZipInputStream::wxZipInputStream(wxInputStream
& stream
,
1314 wxMBConv
& conv
/*=wxConvLocal*/)
1315 : wxArchiveInputStream(stream
, conv
)
1320 wxZipInputStream::wxZipInputStream(wxInputStream
*stream
,
1321 wxMBConv
& conv
/*=wxConvLocal*/)
1322 : wxArchiveInputStream(stream
, conv
)
1327 #if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1329 // Part of the compatibility constructor, which has been made inline to
1330 // avoid a problem with it not being exported by mingw 3.2.3
1332 void wxZipInputStream::Init(const wxString
& file
)
1334 // no error messages
1337 m_allowSeeking
= true;
1338 wxFFileInputStream
*ffile
;
1339 ffile
= static_cast<wxFFileInputStream
*>(m_parent_i_stream
);
1340 wxZipEntryPtr_ entry
;
1344 entry
.reset(GetNextEntry());
1346 while (entry
.get() != NULL
&& entry
->GetInternalName() != file
);
1349 if (entry
.get() == NULL
)
1350 m_lasterror
= wxSTREAM_READ_ERROR
;
1353 wxInputStream
* wxZipInputStream::OpenFile(const wxString
& archive
)
1356 return new wxFFileInputStream(archive
);
1359 #endif // WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
1361 void wxZipInputStream::Init()
1363 m_store
= new wxStoredInputStream(*m_parent_i_stream
);
1369 m_parentSeekable
= false;
1370 m_weaklinks
= new wxZipWeakLinks
;
1371 m_streamlink
= NULL
;
1372 m_offsetAdjustment
= 0;
1373 m_position
= wxInvalidOffset
;
1376 m_lasterror
= m_parent_i_stream
->GetLastError();
1377 #if WXWIN_COMPATIBILITY_2_6
1378 m_allowSeeking
= false;
1382 wxZipInputStream::~wxZipInputStream()
1384 CloseDecompressor(m_decomp
);
1390 m_weaklinks
->Release(this);
1393 m_streamlink
->Release(this);
1396 wxString
wxZipInputStream::GetComment()
1398 if (m_position
== wxInvalidOffset
)
1399 if (!LoadEndRecord())
1400 return wxEmptyString
;
1402 if (!m_parentSeekable
&& Eof() && m_signature
) {
1403 m_lasterror
= wxSTREAM_NO_ERROR
;
1404 m_lasterror
= ReadLocal(true);
1410 int wxZipInputStream::GetTotalEntries()
1412 if (m_position
== wxInvalidOffset
)
1414 return m_TotalEntries
;
1417 wxZipStreamLink
*wxZipInputStream::MakeLink(wxZipOutputStream
*out
)
1419 wxZipStreamLink
*link
= NULL
;
1421 if (!m_parentSeekable
&& (IsOpened() || !Eof())) {
1422 link
= new wxZipStreamLink(out
);
1424 m_streamlink
->Release(this);
1425 m_streamlink
= link
->AddRef();
1431 bool wxZipInputStream::LoadEndRecord()
1433 wxCHECK(m_position
== wxInvalidOffset
, false);
1439 // First find the end-of-central-directory record.
1440 if (!FindEndRecord()) {
1441 // failed, so either this is a non-seekable stream (ok), or not a zip
1442 if (m_parentSeekable
) {
1443 m_lasterror
= wxSTREAM_READ_ERROR
;
1444 wxLogError(_("invalid zip file"));
1449 wxFileOffset pos
= m_parent_i_stream
->TellI();
1450 if (pos
!= wxInvalidOffset
)
1451 m_offsetAdjustment
= m_position
= pos
;
1458 // Read in the end record
1459 wxFileOffset endPos
= m_parent_i_stream
->TellI() - 4;
1460 if (!endrec
.Read(*m_parent_i_stream
, GetConv()))
1463 m_TotalEntries
= endrec
.GetTotalEntries();
1464 m_Comment
= endrec
.GetComment();
1466 wxUint32 magic
= m_TotalEntries
? CENTRAL_MAGIC
: END_MAGIC
;
1468 // Now find the central-directory. we have the file offset of
1469 // the CD, so look there first.
1470 if (m_parent_i_stream
->SeekI(endrec
.GetOffset()) != wxInvalidOffset
&&
1471 ReadSignature() == magic
) {
1472 m_signature
= magic
;
1473 m_position
= endrec
.GetOffset();
1474 m_offsetAdjustment
= 0;
1478 // If it's not there, then it could be that the zip has been appended
1479 // to a self extractor, so take the CD size (also in endrec), subtract
1480 // it from the file offset of the end-central-directory and look there.
1481 if (m_parent_i_stream
->SeekI(endPos
- endrec
.GetSize())
1482 != wxInvalidOffset
&& ReadSignature() == magic
) {
1483 m_signature
= magic
;
1484 m_position
= endPos
- endrec
.GetSize();
1485 m_offsetAdjustment
= m_position
- endrec
.GetOffset();
1489 wxLogError(_("can't find central directory in zip"));
1490 m_lasterror
= wxSTREAM_READ_ERROR
;
1494 // Find the end-of-central-directory record.
1495 // If found the stream will be positioned just past the 4 signature bytes.
1497 bool wxZipInputStream::FindEndRecord()
1499 if (!m_parent_i_stream
->IsSeekable())
1502 // usually it's 22 bytes in size and the last thing in the file
1505 if (m_parent_i_stream
->SeekI(-END_SIZE
, wxFromEnd
) == wxInvalidOffset
)
1509 m_parentSeekable
= true;
1512 if (m_parent_i_stream
->Read(magic
, 4).LastRead() != 4)
1514 if ((m_signature
= CrackUint32(magic
)) == END_MAGIC
)
1517 // unfortunately, the record has a comment field that can be up to 65535
1518 // bytes in length, so if the signature not found then search backwards.
1519 wxFileOffset pos
= m_parent_i_stream
->TellI();
1520 const int BUFSIZE
= 1024;
1521 wxCharBuffer
buf(BUFSIZE
);
1523 memcpy(buf
.data(), magic
, 3);
1524 wxFileOffset minpos
= wxMax(pos
- 65535L, 0);
1526 while (pos
> minpos
) {
1527 size_t len
= wx_truncate_cast(size_t,
1528 pos
- wxMax(pos
- (BUFSIZE
- 3), minpos
));
1529 memcpy(buf
.data() + len
, buf
, 3);
1532 if (m_parent_i_stream
->SeekI(pos
, wxFromStart
) == wxInvalidOffset
||
1533 m_parent_i_stream
->Read(buf
.data(), len
).LastRead() != len
)
1536 char *p
= buf
.data() + len
;
1538 while (p
-- > buf
.data()) {
1539 if ((m_signature
= CrackUint32(p
)) == END_MAGIC
) {
1540 size_t remainder
= buf
.data() + len
- p
;
1542 m_parent_i_stream
->Ungetch(p
+ 4, remainder
- 4);
1551 wxZipEntry
*wxZipInputStream::GetNextEntry()
1553 if (m_position
== wxInvalidOffset
)
1554 if (!LoadEndRecord())
1557 m_lasterror
= m_parentSeekable
? ReadCentral() : ReadLocal();
1561 wxZipEntryPtr_
entry(new wxZipEntry(m_entry
));
1562 entry
->m_backlink
= m_weaklinks
->AddEntry(entry
.get(), entry
->GetKey());
1563 return entry
.release();
1566 wxStreamError
wxZipInputStream::ReadCentral()
1571 if (m_signature
== END_MAGIC
)
1572 return wxSTREAM_EOF
;
1574 if (m_signature
!= CENTRAL_MAGIC
) {
1575 wxLogError(_("error reading zip central directory"));
1576 return wxSTREAM_READ_ERROR
;
1579 if (QuietSeek(*m_parent_i_stream
, m_position
+ 4) == wxInvalidOffset
)
1580 return wxSTREAM_READ_ERROR
;
1582 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1585 return wxSTREAM_READ_ERROR
;
1589 m_signature
= ReadSignature();
1591 if (m_offsetAdjustment
)
1592 m_entry
.SetOffset(m_entry
.GetOffset() + m_offsetAdjustment
);
1593 m_entry
.SetKey(m_entry
.GetOffset());
1595 return wxSTREAM_NO_ERROR
;
1598 wxStreamError
wxZipInputStream::ReadLocal(bool readEndRec
/*=false*/)
1604 m_signature
= ReadSignature();
1606 if (m_signature
== CENTRAL_MAGIC
|| m_signature
== END_MAGIC
) {
1607 if (m_streamlink
&& !m_streamlink
->GetOutputStream()) {
1608 m_streamlink
->Release(this);
1609 m_streamlink
= NULL
;
1613 while (m_signature
== CENTRAL_MAGIC
) {
1614 if (m_weaklinks
->IsEmpty() && m_streamlink
== NULL
)
1615 return wxSTREAM_EOF
;
1617 size_t size
= m_entry
.ReadCentral(*m_parent_i_stream
, GetConv());
1621 return wxSTREAM_READ_ERROR
;
1623 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetOffset());
1625 entry
->SetSystemMadeBy(m_entry
.GetSystemMadeBy());
1626 entry
->SetVersionMadeBy(m_entry
.GetVersionMadeBy());
1627 entry
->SetComment(m_entry
.GetComment());
1628 entry
->SetDiskStart(m_entry
.GetDiskStart());
1629 entry
->SetInternalAttributes(m_entry
.GetInternalAttributes());
1630 entry
->SetExternalAttributes(m_entry
.GetExternalAttributes());
1631 Copy(entry
->m_Extra
, m_entry
.m_Extra
);
1633 m_weaklinks
->RemoveEntry(entry
->GetOffset());
1636 m_signature
= ReadSignature();
1639 if (m_signature
== END_MAGIC
) {
1640 if (readEndRec
|| m_streamlink
) {
1642 endrec
.Read(*m_parent_i_stream
, GetConv());
1643 m_Comment
= endrec
.GetComment();
1646 m_streamlink
->GetOutputStream()->SetComment(endrec
.GetComment());
1647 m_streamlink
->Release(this);
1648 m_streamlink
= NULL
;
1651 return wxSTREAM_EOF
;
1654 if (m_signature
== LOCAL_MAGIC
) {
1655 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1657 m_entry
.SetOffset(m_position
);
1658 m_entry
.SetKey(m_position
);
1662 return wxSTREAM_NO_ERROR
;
1666 wxLogError(_("error reading zip local header"));
1667 return wxSTREAM_READ_ERROR
;
1670 wxUint32
wxZipInputStream::ReadSignature()
1673 m_parent_i_stream
->Read(magic
, 4);
1674 return m_parent_i_stream
->LastRead() == 4 ? CrackUint32(magic
) : 0;
1677 bool wxZipInputStream::OpenEntry(wxArchiveEntry
& entry
)
1679 wxZipEntry
*zipEntry
= wxStaticCast(&entry
, wxZipEntry
);
1680 return zipEntry
? OpenEntry(*zipEntry
) : false;
1685 bool wxZipInputStream::DoOpen(wxZipEntry
*entry
, bool raw
)
1687 if (m_position
== wxInvalidOffset
)
1688 if (!LoadEndRecord())
1690 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1698 if (AfterHeader() && entry
->GetKey() == m_entry
.GetOffset())
1700 // can only open the current entry on a non-seekable stream
1701 wxCHECK(m_parentSeekable
, false);
1704 m_lasterror
= wxSTREAM_READ_ERROR
;
1709 if (m_parentSeekable
) {
1710 if (QuietSeek(*m_parent_i_stream
, m_entry
.GetOffset())
1713 if (ReadSignature() != LOCAL_MAGIC
) {
1714 wxLogError(_("bad zipfile offset to entry"));
1719 if (m_parentSeekable
|| AtHeader()) {
1720 m_headerSize
= m_entry
.ReadLocal(*m_parent_i_stream
, GetConv());
1721 if (m_headerSize
&& m_parentSeekable
) {
1722 wxZipEntry
*ref
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1724 Copy(ref
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1726 m_weaklinks
->RemoveEntry(ref
->GetKey());
1728 if (entry
&& entry
!= ref
) {
1729 Copy(entry
->m_LocalExtra
, m_entry
.m_LocalExtra
);
1736 m_lasterror
= wxSTREAM_NO_ERROR
;
1740 bool wxZipInputStream::OpenDecompressor(bool raw
/*=false*/)
1742 wxASSERT(AfterHeader());
1744 wxFileOffset compressedSize
= m_entry
.GetCompressedSize();
1750 if (compressedSize
!= wxInvalidOffset
) {
1751 m_store
->Open(compressedSize
);
1755 m_rawin
= new wxRawInputStream(*m_parent_i_stream
);
1756 m_decomp
= m_rawin
->Open(OpenDecompressor(m_rawin
->GetTee()));
1759 if (compressedSize
!= wxInvalidOffset
&&
1760 (m_entry
.GetMethod() != wxZIP_METHOD_DEFLATE
||
1761 wxZlibInputStream::CanHandleGZip())) {
1762 m_store
->Open(compressedSize
);
1763 m_decomp
= OpenDecompressor(*m_store
);
1765 m_decomp
= OpenDecompressor(*m_parent_i_stream
);
1769 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
1770 m_lasterror
= m_decomp
? m_decomp
->GetLastError() : wxSTREAM_READ_ERROR
;
1774 // Can be overriden to add support for additional decompression methods
1776 wxInputStream
*wxZipInputStream::OpenDecompressor(wxInputStream
& stream
)
1778 switch (m_entry
.GetMethod()) {
1779 case wxZIP_METHOD_STORE
:
1780 if (m_entry
.GetSize() == wxInvalidOffset
) {
1781 wxLogError(_("stored file length not in Zip header"));
1784 m_store
->Open(m_entry
.GetSize());
1787 case wxZIP_METHOD_DEFLATE
:
1789 m_inflate
= new wxZlibInputStream2(stream
);
1791 m_inflate
->Open(stream
);
1795 wxLogError(_("unsupported Zip compression method"));
1801 bool wxZipInputStream::CloseDecompressor(wxInputStream
*decomp
)
1803 if (decomp
&& decomp
== m_rawin
)
1804 return CloseDecompressor(m_rawin
->GetFilterInputStream());
1805 if (decomp
!= m_store
&& decomp
!= m_inflate
)
1810 // Closes the current entry and positions the underlying stream at the start
1811 // of the next entry
1813 bool wxZipInputStream::CloseEntry()
1817 if (m_lasterror
== wxSTREAM_READ_ERROR
)
1820 if (!m_parentSeekable
) {
1821 if (!IsOpened() && !OpenDecompressor(true))
1824 const int BUFSIZE
= 8192;
1825 wxCharBuffer
buf(BUFSIZE
);
1827 Read(buf
.data(), BUFSIZE
);
1829 m_position
+= m_headerSize
+ m_entry
.GetCompressedSize();
1832 if (m_lasterror
== wxSTREAM_EOF
)
1833 m_lasterror
= wxSTREAM_NO_ERROR
;
1835 CloseDecompressor(m_decomp
);
1837 m_entry
= wxZipEntry();
1844 size_t wxZipInputStream::OnSysRead(void *buffer
, size_t size
)
1847 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1848 m_lasterror
= wxSTREAM_READ_ERROR
;
1849 if (!IsOk() || !size
)
1852 size_t count
= m_decomp
->Read(buffer
, size
).LastRead();
1854 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, count
);
1856 m_lasterror
= m_decomp
->GetLastError();
1859 if ((m_entry
.GetFlags() & wxZIP_SUMS_FOLLOW
) != 0) {
1860 m_headerSize
+= m_entry
.ReadDescriptor(*m_parent_i_stream
);
1861 wxZipEntry
*entry
= m_weaklinks
->GetEntry(m_entry
.GetKey());
1864 entry
->SetCrc(m_entry
.GetCrc());
1865 entry
->SetCompressedSize(m_entry
.GetCompressedSize());
1866 entry
->SetSize(m_entry
.GetSize());
1872 m_lasterror
= wxSTREAM_READ_ERROR
;
1874 if (m_entry
.GetSize() != TellI())
1875 wxLogError(_("reading zip stream (entry %s): bad length"),
1876 m_entry
.GetName().c_str());
1877 else if (m_crcAccumulator
!= m_entry
.GetCrc())
1878 wxLogError(_("reading zip stream (entry %s): bad crc"),
1879 m_entry
.GetName().c_str());
1881 m_lasterror
= wxSTREAM_EOF
;
1888 #if WXWIN_COMPATIBILITY_2_6
1890 // Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1892 wxFileOffset
wxZipInputStream::OnSysSeek(wxFileOffset seek
, wxSeekMode mode
)
1894 // seeking works when the stream is created with the compatibility
1896 if (!m_allowSeeking
)
1897 return wxInvalidOffset
;
1899 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1900 m_lasterror
= wxSTREAM_READ_ERROR
;
1902 return wxInvalidOffset
;
1904 // NB: since ZIP files don't natively support seeking, we have to
1905 // implement a brute force workaround -- reading all the data
1906 // between current and the new position (or between beginning of
1907 // the file and new position...)
1909 wxFileOffset nextpos
;
1910 wxFileOffset pos
= TellI();
1914 case wxFromCurrent
: nextpos
= seek
+ pos
; break;
1915 case wxFromStart
: nextpos
= seek
; break;
1916 case wxFromEnd
: nextpos
= GetLength() + seek
; break;
1917 default : nextpos
= pos
; break; /* just to fool compiler, never happens */
1920 wxFileOffset toskip
wxDUMMY_INITIALIZE(0);
1921 if ( nextpos
>= pos
)
1923 toskip
= nextpos
- pos
;
1927 wxZipEntry
current(m_entry
);
1928 if (!OpenEntry(current
))
1930 m_lasterror
= wxSTREAM_READ_ERROR
;
1938 const int BUFSIZE
= 4096;
1940 char buffer
[BUFSIZE
];
1941 while ( toskip
> 0 )
1943 sz
= wx_truncate_cast(size_t, wxMin(toskip
, BUFSIZE
));
1953 #endif // WXWIN_COMPATIBILITY_2_6
1956 /////////////////////////////////////////////////////////////////////////////
1959 #include "wx/listimpl.cpp"
1960 WX_DEFINE_LIST(wxZipEntryList_
)
1962 wxZipOutputStream::wxZipOutputStream(wxOutputStream
& stream
,
1964 wxMBConv
& conv
/*=wxConvLocal*/)
1965 : wxArchiveOutputStream(stream
, conv
)
1970 wxZipOutputStream::wxZipOutputStream(wxOutputStream
*stream
,
1972 wxMBConv
& conv
/*=wxConvLocal*/)
1973 : wxArchiveOutputStream(stream
, conv
)
1978 void wxZipOutputStream::Init(int level
)
1980 m_store
= new wxStoredOutputStream(*m_parent_o_stream
);
1983 m_initialData
= new char[OUTPUT_LATENCY
];
1992 m_offsetAdjustment
= wxInvalidOffset
;
1993 m_endrecWritten
= false;
1996 wxZipOutputStream::~wxZipOutputStream()
1999 WX_CLEAR_LIST(wxZipEntryList_
, m_entries
);
2003 delete [] m_initialData
;
2005 m_backlink
->Release(this);
2008 bool wxZipOutputStream::PutNextEntry(
2009 const wxString
& name
,
2010 const wxDateTime
& dt
/*=wxDateTime::Now()*/,
2011 wxFileOffset size
/*=wxInvalidOffset*/)
2013 return PutNextEntry(new wxZipEntry(name
, dt
, size
));
2016 bool wxZipOutputStream::PutNextDirEntry(
2017 const wxString
& name
,
2018 const wxDateTime
& dt
/*=wxDateTime::Now()*/)
2020 wxZipEntry
*entry
= new wxZipEntry(name
, dt
);
2022 return PutNextEntry(entry
);
2025 bool wxZipOutputStream::CopyEntry(wxZipEntry
*entry
,
2026 wxZipInputStream
& inputStream
)
2028 wxZipEntryPtr_
e(entry
);
2031 inputStream
.DoOpen(e
.get(), true) &&
2032 DoCreate(e
.release(), true) &&
2033 Write(inputStream
).IsOk() && inputStream
.Eof();
2036 bool wxZipOutputStream::PutNextEntry(wxArchiveEntry
*entry
)
2038 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2041 return PutNextEntry(zipEntry
);
2044 bool wxZipOutputStream::CopyEntry(wxArchiveEntry
*entry
,
2045 wxArchiveInputStream
& stream
)
2047 wxZipEntry
*zipEntry
= wxStaticCast(entry
, wxZipEntry
);
2049 if (!zipEntry
|| !stream
.OpenEntry(*zipEntry
)) {
2054 return CopyEntry(zipEntry
, static_cast<wxZipInputStream
&>(stream
));
2057 bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream
& inputStream
)
2059 m_Comment
= inputStream
.GetComment();
2061 m_backlink
->Release(this);
2062 m_backlink
= inputStream
.MakeLink(this);
2066 bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream
& stream
)
2068 return CopyArchiveMetaData(static_cast<wxZipInputStream
&>(stream
));
2071 void wxZipOutputStream::SetLevel(int level
)
2073 if (level
!= m_level
) {
2074 if (m_comp
!= m_deflate
)
2081 bool wxZipOutputStream::DoCreate(wxZipEntry
*entry
, bool raw
/*=false*/)
2089 // write the signature bytes right away
2090 wxDataOutputStream
ds(*m_parent_o_stream
);
2093 // and if this is the first entry test for seekability
2094 if (m_headerOffset
== 0 && m_parent_o_stream
->IsSeekable()) {
2096 bool logging
= wxLog::IsEnabled();
2099 wxFileOffset here
= m_parent_o_stream
->TellO();
2101 if (here
!= wxInvalidOffset
&& here
>= 4) {
2102 if (m_parent_o_stream
->SeekO(here
- 4) == here
- 4) {
2103 m_offsetAdjustment
= here
- 4;
2105 wxLog::EnableLogging(logging
);
2107 m_parent_o_stream
->SeekO(here
);
2112 m_pending
->SetOffset(m_headerOffset
);
2114 m_crcAccumulator
= crc32(0, Z_NULL
, 0);
2119 m_lasterror
= wxSTREAM_NO_ERROR
;
2123 // Can be overriden to add support for additional compression methods
2125 wxOutputStream
*wxZipOutputStream::OpenCompressor(
2126 wxOutputStream
& stream
,
2128 const Buffer bufs
[])
2130 if (entry
.GetMethod() == wxZIP_METHOD_DEFAULT
) {
2132 && (IsParentSeekable()
2133 || entry
.GetCompressedSize() != wxInvalidOffset
2134 || entry
.GetSize() != wxInvalidOffset
)) {
2135 entry
.SetMethod(wxZIP_METHOD_STORE
);
2138 for (int i
= 0; bufs
[i
].m_data
; ++i
)
2139 size
+= bufs
[i
].m_size
;
2140 entry
.SetMethod(size
<= 6 ?
2141 wxZIP_METHOD_STORE
: wxZIP_METHOD_DEFLATE
);
2145 switch (entry
.GetMethod()) {
2146 case wxZIP_METHOD_STORE
:
2147 if (entry
.GetCompressedSize() == wxInvalidOffset
)
2148 entry
.SetCompressedSize(entry
.GetSize());
2151 case wxZIP_METHOD_DEFLATE
:
2153 int defbits
= wxZIP_DEFLATE_NORMAL
;
2154 switch (GetLevel()) {
2156 defbits
= wxZIP_DEFLATE_SUPERFAST
;
2158 case 2: case 3: case 4:
2159 defbits
= wxZIP_DEFLATE_FAST
;
2162 defbits
= wxZIP_DEFLATE_EXTRA
;
2165 entry
.SetFlags((entry
.GetFlags() & ~wxZIP_DEFLATE_MASK
) |
2166 defbits
| wxZIP_SUMS_FOLLOW
);
2169 m_deflate
= new wxZlibOutputStream2(stream
, GetLevel());
2171 m_deflate
->Open(stream
);
2177 wxLogError(_("unsupported Zip compression method"));
2183 bool wxZipOutputStream::CloseCompressor(wxOutputStream
*comp
)
2185 if (comp
== m_deflate
)
2187 else if (comp
!= m_store
)
2192 // This is called when OUPUT_LATENCY bytes has been written to the
2193 // wxZipOutputStream to actually create the zip entry.
2195 void wxZipOutputStream::CreatePendingEntry(const void *buffer
, size_t size
)
2197 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2198 wxZipEntryPtr_
spPending(m_pending
);
2202 { m_initialData
, m_initialSize
},
2203 { (const char*)buffer
, size
},
2210 m_comp
= OpenCompressor(*m_store
, *spPending
,
2211 m_initialSize
? bufs
: bufs
+ 1);
2213 if (IsParentSeekable()
2214 || (spPending
->m_Crc
2215 && spPending
->m_CompressedSize
!= wxInvalidOffset
2216 && spPending
->m_Size
!= wxInvalidOffset
))
2217 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2219 if (spPending
->m_CompressedSize
!= wxInvalidOffset
)
2220 spPending
->m_Flags
|= wxZIP_SUMS_FOLLOW
;
2222 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2223 m_lasterror
= m_parent_o_stream
->GetLastError();
2226 m_entries
.push_back(spPending
.release());
2227 OnSysWrite(m_initialData
, m_initialSize
);
2233 // This is called to write out the zip entry when Close has been called
2234 // before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2236 void wxZipOutputStream::CreatePendingEntry()
2238 wxASSERT(IsOk() && m_pending
&& !m_comp
);
2239 wxZipEntryPtr_
spPending(m_pending
);
2241 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2244 // Initially compresses the data to memory, then fall back to 'store'
2245 // if the compressor makes the data larger rather than smaller.
2246 wxMemoryOutputStream mem
;
2247 Buffer bufs
[] = { { m_initialData
, m_initialSize
}, { NULL
, 0 } };
2248 wxOutputStream
*comp
= OpenCompressor(mem
, *spPending
, bufs
);
2252 if (comp
!= m_store
) {
2253 bool ok
= comp
->Write(m_initialData
, m_initialSize
).IsOk();
2254 CloseCompressor(comp
);
2259 m_entrySize
= m_initialSize
;
2260 m_crcAccumulator
= crc32(0, (Byte
*)m_initialData
, m_initialSize
);
2262 if (mem
.GetSize() > 0 && mem
.GetSize() < m_initialSize
) {
2263 m_initialSize
= mem
.GetSize();
2264 mem
.CopyTo(m_initialData
, m_initialSize
);
2266 spPending
->SetMethod(wxZIP_METHOD_STORE
);
2269 spPending
->SetSize(m_entrySize
);
2270 spPending
->SetCrc(m_crcAccumulator
);
2271 spPending
->SetCompressedSize(m_initialSize
);
2274 spPending
->m_Flags
&= ~wxZIP_SUMS_FOLLOW
;
2275 m_headerSize
= spPending
->WriteLocal(*m_parent_o_stream
, GetConv());
2277 if (m_parent_o_stream
->IsOk()) {
2278 m_entries
.push_back(spPending
.release());
2280 m_store
->Write(m_initialData
, m_initialSize
);
2284 m_lasterror
= m_parent_o_stream
->GetLastError();
2287 // Write the 'central directory' and the 'end-central-directory' records.
2289 bool wxZipOutputStream::Close()
2293 if (m_lasterror
== wxSTREAM_WRITE_ERROR
2294 || (m_entries
.size() == 0 && m_endrecWritten
))
2296 wxFilterOutputStream::Close();
2302 endrec
.SetEntriesHere(m_entries
.size());
2303 endrec
.SetTotalEntries(m_entries
.size());
2304 endrec
.SetOffset(m_headerOffset
);
2305 endrec
.SetComment(m_Comment
);
2307 wxZipEntryList_::iterator it
;
2308 wxFileOffset size
= 0;
2310 for (it
= m_entries
.begin(); it
!= m_entries
.end(); ++it
) {
2311 size
+= (*it
)->WriteCentral(*m_parent_o_stream
, GetConv());
2316 endrec
.SetSize(size
);
2317 endrec
.Write(*m_parent_o_stream
, GetConv());
2319 m_lasterror
= m_parent_o_stream
->GetLastError();
2320 m_endrecWritten
= true;
2322 if (!wxFilterOutputStream::Close() || !IsOk())
2324 m_lasterror
= wxSTREAM_EOF
;
2328 // Finish writing the current entry
2330 bool wxZipOutputStream::CloseEntry()
2332 if (IsOk() && m_pending
)
2333 CreatePendingEntry();
2339 CloseCompressor(m_comp
);
2342 wxFileOffset compressedSize
= m_store
->TellO();
2344 wxZipEntry
& entry
= *m_entries
.back();
2346 // When writing raw the crc and size can't be checked
2348 m_crcAccumulator
= entry
.GetCrc();
2349 m_entrySize
= entry
.GetSize();
2352 // Write the sums in the trailing 'data descriptor' if necessary
2353 if (entry
.m_Flags
& wxZIP_SUMS_FOLLOW
) {
2354 wxASSERT(!IsParentSeekable());
2356 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2357 compressedSize
, m_entrySize
);
2358 m_lasterror
= m_parent_o_stream
->GetLastError();
2361 // If the local header didn't have the correct crc and size written to
2362 // it then seek back and fix it
2363 else if (m_crcAccumulator
!= entry
.GetCrc()
2364 || m_entrySize
!= entry
.GetSize()
2365 || compressedSize
!= entry
.GetCompressedSize())
2367 if (IsParentSeekable()) {
2368 wxFileOffset here
= m_parent_o_stream
->TellO();
2369 wxFileOffset headerOffset
= m_headerOffset
+ m_offsetAdjustment
;
2370 m_parent_o_stream
->SeekO(headerOffset
+ SUMS_OFFSET
);
2371 entry
.WriteDescriptor(*m_parent_o_stream
, m_crcAccumulator
,
2372 compressedSize
, m_entrySize
);
2373 m_parent_o_stream
->SeekO(here
);
2374 m_lasterror
= m_parent_o_stream
->GetLastError();
2376 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2380 m_headerOffset
+= m_headerSize
+ compressedSize
;
2387 m_lasterror
= m_parent_o_stream
->GetLastError();
2389 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2390 entry
.GetName().c_str());
2394 void wxZipOutputStream::Sync()
2396 if (IsOk() && m_pending
)
2397 CreatePendingEntry(NULL
, 0);
2399 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2402 m_lasterror
= m_comp
->GetLastError();
2406 size_t wxZipOutputStream::OnSysWrite(const void *buffer
, size_t size
)
2408 if (IsOk() && m_pending
) {
2409 if (m_initialSize
+ size
< OUTPUT_LATENCY
) {
2410 memcpy(m_initialData
+ m_initialSize
, buffer
, size
);
2411 m_initialSize
+= size
;
2414 CreatePendingEntry(buffer
, size
);
2419 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2420 if (!IsOk() || !size
)
2423 if (m_comp
->Write(buffer
, size
).LastWrite() != size
)
2424 m_lasterror
= wxSTREAM_WRITE_ERROR
;
2425 m_crcAccumulator
= crc32(m_crcAccumulator
, (Byte
*)buffer
, size
);
2426 m_entrySize
+= m_comp
->LastWrite();
2428 return m_comp
->LastWrite();
2431 #endif // wxUSE_ZIPSTREAM