]> git.saurik.com Git - wxWidgets.git/blame - src/common/zipstrm.cpp
compilation fix: wxGenericCollapsiblePane needs wxButton and wxStaticLine
[wxWidgets.git] / src / common / zipstrm.cpp
CommitLineData
5526e819 1/////////////////////////////////////////////////////////////////////////////
bb2955b3 2// Name: src/common/zipstrm.cpp
00375592
VZ
3// Purpose: Streams for Zip files
4// Author: Mike Wetherell
5// RCS-ID: $Id$
6// Copyright: (c) Mike Wetherell
65571936 7// Licence: wxWindows licence
5526e819
VS
8/////////////////////////////////////////////////////////////////////////////
9
d1af991f
RR
10// For compilers that support precompilation, includes "wx.h".
11#include "wx/wxprec.h"
5526e819 12
d1af991f 13#ifdef __BORLANDC__
8898456d 14 #pragma hdrstop
5526e819
VS
15#endif
16
8898456d
WS
17#if wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM
18
00375592 19#ifndef WX_PRECOMP
8898456d
WS
20 #include "wx/intl.h"
21 #include "wx/log.h"
de6185e2 22 #include "wx/utils.h"
00375592
VZ
23#endif
24
00375592 25#include "wx/zipstrm.h"
00375592
VZ
26#include "wx/datstrm.h"
27#include "wx/zstream.h"
28#include "wx/mstream.h"
00375592
VZ
29#include "wx/buffer.h"
30#include "wx/ptr_scpd.h"
31#include "wx/wfstream.h"
00375592
VZ
32#include "zlib.h"
33
34// value for the 'version needed to extract' field (20 means 2.0)
35enum {
36 VERSION_NEEDED_TO_EXTRACT = 20
37};
38
39// signatures for the various records (PKxx)
40enum {
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)
45};
46
47// unix file attributes. zip stores them in the high 16 bits of the
48// 'external attributes' field, hence the extra zeros.
49enum {
50 wxZIP_S_IFMT = 0xF0000000,
51 wxZIP_S_IFDIR = 0x40000000,
52 wxZIP_S_IFREG = 0x80000000
53};
54
55// minimum sizes for the various records
56enum {
57 CENTRAL_SIZE = 46,
58 LOCAL_SIZE = 30,
59 END_SIZE = 22,
60 SUMS_SIZE = 12
61};
62
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
66// it should use.
67enum {
68 OUTPUT_LATENCY = 4096
69};
70
71// Some offsets into the local header
72enum {
73 SUMS_OFFSET = 14
74};
75
76IMPLEMENT_DYNAMIC_CLASS(wxZipEntry, wxArchiveEntry)
77IMPLEMENT_DYNAMIC_CLASS(wxZipClassFactory, wxArchiveClassFactory)
78
00375592
VZ
79
80/////////////////////////////////////////////////////////////////////////////
81// Helpers
82
83// read a string of a given length
84//
85static wxString ReadString(wxInputStream& stream, wxUint16 len, wxMBConv& conv)
86{
076e07b6
MW
87 if (len == 0)
88 return wxEmptyString;
89
00375592
VZ
90#if wxUSE_UNICODE
91 wxCharBuffer buf(len);
92 stream.Read(buf.data(), len);
93 wxString str(buf, conv);
94#else
95 wxString str;
96 (void)conv;
97 {
98 wxStringBuffer buf(str, len);
99 stream.Read(buf, len);
100 }
101#endif
102
103 return str;
104}
105
106// Decode a little endian wxUint32 number from a character array
107//
108static inline wxUint32 CrackUint32(const char *m)
109{
110 const unsigned char *n = (const unsigned char*)m;
111 return (n[3] << 24) | (n[2] << 16) | (n[1] << 8) | n[0];
112}
113
08f30494
MW
114// Decode a little endian wxUint16 number from a character array
115//
116static inline wxUint16 CrackUint16(const char *m)
117{
118 const unsigned char *n = (const unsigned char*)m;
119 return (n[1] << 8) | n[0];
120}
121
00375592
VZ
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.
124//
125static wxFileOffset QuietSeek(wxInputStream& stream, wxFileOffset pos)
126{
d0914b9d 127#if defined(__WXDEBUG__) && wxUSE_LOG
00375592
VZ
128 wxLogLevel level = wxLog::GetLogLevel();
129 wxLog::SetLogLevel(wxLOG_Debug - 1);
130 wxFileOffset result = stream.SeekI(pos);
131 wxLog::SetLogLevel(level);
132 return result;
133#else
134 return stream.SeekI(pos);
135#endif
136}
137
138
8fc574b4
MW
139/////////////////////////////////////////////////////////////////////////////
140// Class factory
141
142wxZipClassFactory g_wxZipClassFactory;
143
144wxZipClassFactory::wxZipClassFactory()
145{
146 if (this == &g_wxZipClassFactory)
147 PushFront();
148}
149
150const wxChar * const *
151wxZipClassFactory::GetProtocols(wxStreamProtocolType type) const
152{
153 static const wxChar *protocols[] = { _T("zip"), NULL };
154 static const wxChar *mimetypes[] = { _T("application/zip"), NULL };
155 static const wxChar *fileexts[] = { _T(".zip"), _T(".htb"), NULL };
156 static const wxChar *empty[] = { NULL };
157
158 switch (type) {
159 case wxSTREAM_PROTOCOL: return protocols;
160 case wxSTREAM_MIMETYPE: return mimetypes;
161 case wxSTREAM_FILEEXTENSION: return fileexts;
162 default: return empty;
163 }
164}
165
166
abffc1ff
MW
167/////////////////////////////////////////////////////////////////////////////
168// Read a zip header
169
170class wxZipHeader
171{
172public:
173 wxZipHeader(wxInputStream& stream, size_t size);
174
175 inline wxUint8 Read8();
176 inline wxUint16 Read16();
177 inline wxUint32 Read32();
178
179 const char *GetData() const { return m_data; }
180 size_t GetSize() const { return m_size; }
181 operator bool() const { return m_ok; }
182
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; }
185
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; }
189
190private:
191 char m_data[64];
192 size_t m_size;
193 size_t m_pos;
194 bool m_ok;
195};
196
197wxZipHeader::wxZipHeader(wxInputStream& stream, size_t size)
198 : m_size(0),
199 m_pos(0),
200 m_ok(false)
201{
202 wxCHECK_RET(size <= sizeof(m_data), _T("buffer too small"));
203 m_size = stream.Read(m_data, size).LastRead();
204 m_ok = m_size == size;
205}
206
207wxUint8 wxZipHeader::Read8()
208{
209 wxASSERT(m_pos < m_size);
08f30494 210 return m_data[m_pos++];
abffc1ff
MW
211}
212
213wxUint16 wxZipHeader::Read16()
214{
215 wxASSERT(m_pos + 2 <= m_size);
08f30494 216 wxUint16 n = CrackUint16(m_data + m_pos);
abffc1ff 217 m_pos += 2;
08f30494 218 return n;
abffc1ff
MW
219}
220
221wxUint32 wxZipHeader::Read32()
222{
223 wxASSERT(m_pos + 4 <= m_size);
08f30494 224 wxUint32 n = CrackUint32(m_data + m_pos);
abffc1ff 225 m_pos += 4;
08f30494 226 return n;
abffc1ff
MW
227}
228
229
00375592
VZ
230/////////////////////////////////////////////////////////////////////////////
231// Stored input stream
232// Trival decompressor for files which are 'stored' in the zip file.
233
234class wxStoredInputStream : public wxFilterInputStream
235{
236public:
237 wxStoredInputStream(wxInputStream& stream);
238
239 void Open(wxFileOffset len) { Close(); m_len = len; }
240 void Close() { m_pos = 0; m_lasterror = wxSTREAM_NO_ERROR; }
241
242 virtual char Peek() { return wxInputStream::Peek(); }
46263455 243 virtual wxFileOffset GetLength() const { return m_len; }
00375592
VZ
244
245protected:
246 virtual size_t OnSysRead(void *buffer, size_t size);
247 virtual wxFileOffset OnSysTell() const { return m_pos; }
248
249private:
250 wxFileOffset m_pos;
251 wxFileOffset m_len;
252
253 DECLARE_NO_COPY_CLASS(wxStoredInputStream)
254};
255
256wxStoredInputStream::wxStoredInputStream(wxInputStream& stream)
257 : wxFilterInputStream(stream),
258 m_pos(0),
259 m_len(0)
260{
261}
262
263size_t wxStoredInputStream::OnSysRead(void *buffer, size_t size)
264{
312f1e6e
MW
265 size_t count = wx_truncate_cast(size_t,
266 wxMin(size + wxFileOffset(0), m_len - m_pos + size_t(0)));
00375592
VZ
267 count = m_parent_i_stream->Read(buffer, count).LastRead();
268 m_pos += count;
269
abffc1ff
MW
270 if (count < size)
271 m_lasterror = m_pos == m_len ? wxSTREAM_EOF : wxSTREAM_READ_ERROR;
00375592
VZ
272
273 return count;
274}
275
276
277/////////////////////////////////////////////////////////////////////////////
278// Stored output stream
279// Trival compressor for files which are 'stored' in the zip file.
280
281class wxStoredOutputStream : public wxFilterOutputStream
282{
283public:
284 wxStoredOutputStream(wxOutputStream& stream) :
285 wxFilterOutputStream(stream), m_pos(0) { }
286
287 bool Close() {
288 m_pos = 0;
289 m_lasterror = wxSTREAM_NO_ERROR;
290 return true;
291 }
292
293protected:
294 virtual size_t OnSysWrite(const void *buffer, size_t size);
295 virtual wxFileOffset OnSysTell() const { return m_pos; }
296
297private:
298 wxFileOffset m_pos;
299 DECLARE_NO_COPY_CLASS(wxStoredOutputStream)
300};
301
302size_t wxStoredOutputStream::OnSysWrite(const void *buffer, size_t size)
303{
304 if (!IsOk() || !size)
305 return 0;
306 size_t count = m_parent_o_stream->Write(buffer, size).LastWrite();
307 if (count != size)
308 m_lasterror = wxSTREAM_WRITE_ERROR;
309 m_pos += count;
310 return count;
311}
312
313
314/////////////////////////////////////////////////////////////////////////////
315// wxRawInputStream
316//
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.
321//
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).
325//
326// Usage is like this:
327// m_rawin = new wxRawInputStream(*m_parent_i_stream);
328// m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
329//
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'.
333//
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().
337
338class wxTeeInputStream : public wxFilterInputStream
339{
340public:
341 wxTeeInputStream(wxInputStream& stream);
342
343 size_t GetCount() const { return m_end - m_start; }
344 size_t GetData(char *buffer, size_t size);
345
346 void Open();
347 bool Final();
348
349 wxInputStream& Read(void *buffer, size_t size);
350
351protected:
352 virtual size_t OnSysRead(void *buffer, size_t size);
353 virtual wxFileOffset OnSysTell() const { return m_pos; }
354
355private:
356 wxFileOffset m_pos;
357 wxMemoryBuffer m_buf;
358 size_t m_start;
359 size_t m_end;
360
361 DECLARE_NO_COPY_CLASS(wxTeeInputStream)
362};
363
364wxTeeInputStream::wxTeeInputStream(wxInputStream& stream)
365 : wxFilterInputStream(stream),
366 m_pos(0), m_buf(8192), m_start(0), m_end(0)
367{
368}
369
370void wxTeeInputStream::Open()
371{
372 m_pos = m_start = m_end = 0;
373 m_lasterror = wxSTREAM_NO_ERROR;
374}
375
376bool wxTeeInputStream::Final()
377{
378 bool final = m_end == m_buf.GetDataLen();
379 m_end = m_buf.GetDataLen();
380 return final;
381}
382
383wxInputStream& wxTeeInputStream::Read(void *buffer, size_t size)
384{
385 size_t count = wxInputStream::Read(buffer, size).LastRead();
386 m_end = m_buf.GetDataLen();
387 m_buf.AppendData(buffer, count);
388 return *this;
389}
390
391size_t wxTeeInputStream::OnSysRead(void *buffer, size_t size)
392{
393 size_t count = m_parent_i_stream->Read(buffer, size).LastRead();
abffc1ff
MW
394 if (count < size)
395 m_lasterror = m_parent_i_stream->GetLastError();
00375592
VZ
396 return count;
397}
398
399size_t wxTeeInputStream::GetData(char *buffer, size_t size)
400{
401 if (m_wbacksize) {
402 size_t len = m_buf.GetDataLen();
403 len = len > m_wbacksize ? len - m_wbacksize : 0;
404 m_buf.SetDataLen(len);
405 if (m_end > len) {
406 wxFAIL; // we've already returned data that's now being ungot
407 m_end = len;
408 }
abffc1ff 409 m_parent_i_stream->Reset();
00375592
VZ
410 m_parent_i_stream->Ungetch(m_wback, m_wbacksize);
411 free(m_wback);
412 m_wback = NULL;
413 m_wbacksize = 0;
414 m_wbackcur = 0;
415 }
416
417 if (size > GetCount())
418 size = GetCount();
419 if (size) {
420 memcpy(buffer, m_buf + m_start, size);
421 m_start += size;
422 wxASSERT(m_start <= m_end);
423 }
424
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);
428 len -= m_end;
429 memmove(buf, buf + m_end, len);
430 m_buf.UngetWriteBuf(len);
431 m_start = m_end = 0;
432 }
433
434 return size;
435}
436
437class wxRawInputStream : public wxFilterInputStream
438{
439public:
440 wxRawInputStream(wxInputStream& stream);
441 virtual ~wxRawInputStream() { delete m_tee; }
442
443 wxInputStream* Open(wxInputStream *decomp);
444 wxInputStream& GetTee() const { return *m_tee; }
445
446protected:
447 virtual size_t OnSysRead(void *buffer, size_t size);
448 virtual wxFileOffset OnSysTell() const { return m_pos; }
449
450private:
451 wxFileOffset m_pos;
452 wxTeeInputStream *m_tee;
453
454 enum { BUFSIZE = 8192 };
455 wxCharBuffer m_dummy;
456
457 DECLARE_NO_COPY_CLASS(wxRawInputStream)
458};
459
460wxRawInputStream::wxRawInputStream(wxInputStream& stream)
461 : wxFilterInputStream(stream),
462 m_pos(0),
463 m_tee(new wxTeeInputStream(stream)),
464 m_dummy(BUFSIZE)
465{
466}
467
468wxInputStream *wxRawInputStream::Open(wxInputStream *decomp)
469{
470 if (decomp) {
471 m_parent_i_stream = decomp;
472 m_pos = 0;
473 m_lasterror = wxSTREAM_NO_ERROR;
474 m_tee->Open();
475 return this;
476 } else {
477 return NULL;
478 }
479}
480
481size_t wxRawInputStream::OnSysRead(void *buffer, size_t size)
482{
483 char *buf = (char*)buffer;
484 size_t count = 0;
485
486 while (count < size && IsOk())
487 {
488 while (m_parent_i_stream->IsOk() && m_tee->GetCount() == 0)
489 m_parent_i_stream->Read(m_dummy.data(), BUFSIZE);
490
491 size_t n = m_tee->GetData(buf + count, size - count);
492 count += n;
493
494 if (n == 0 && m_tee->Final())
495 m_lasterror = m_parent_i_stream->GetLastError();
496 }
497
498 m_pos += count;
499 return count;
500}
501
502
503/////////////////////////////////////////////////////////////////////////////
504// Zlib streams than can be reused without recreating.
505
506class wxZlibOutputStream2 : public wxZlibOutputStream
507{
508public:
509 wxZlibOutputStream2(wxOutputStream& stream, int level) :
510 wxZlibOutputStream(stream, level, wxZLIB_NO_HEADER) { }
511
512 bool Open(wxOutputStream& stream);
513 bool Close() { DoFlush(true); m_pos = wxInvalidOffset; return IsOk(); }
514};
515
516bool wxZlibOutputStream2::Open(wxOutputStream& stream)
517{
518 wxCHECK(m_pos == wxInvalidOffset, false);
519
520 m_deflate->next_out = m_z_buffer;
521 m_deflate->avail_out = m_z_size;
522 m_pos = 0;
523 m_lasterror = wxSTREAM_NO_ERROR;
524 m_parent_o_stream = &stream;
525
526 if (deflateReset(m_deflate) != Z_OK) {
527 wxLogError(_("can't re-initialize zlib deflate stream"));
528 m_lasterror = wxSTREAM_WRITE_ERROR;
529 return false;
530 }
531
532 return true;
533}
534
535class wxZlibInputStream2 : public wxZlibInputStream
536{
537public:
538 wxZlibInputStream2(wxInputStream& stream) :
539 wxZlibInputStream(stream, wxZLIB_NO_HEADER) { }
540
541 bool Open(wxInputStream& stream);
542};
543
544bool wxZlibInputStream2::Open(wxInputStream& stream)
545{
546 m_inflate->avail_in = 0;
547 m_pos = 0;
548 m_lasterror = wxSTREAM_NO_ERROR;
549 m_parent_i_stream = &stream;
550
551 if (inflateReset(m_inflate) != Z_OK) {
552 wxLogError(_("can't re-initialize zlib inflate stream"));
553 m_lasterror = wxSTREAM_READ_ERROR;
554 return false;
555 }
556
557 return true;
558}
559
560
561/////////////////////////////////////////////////////////////////////////////
562// Class to hold wxZipEntry's Extra and LocalExtra fields
563
564class wxZipMemory
565{
566public:
567 wxZipMemory() : m_data(NULL), m_size(0), m_capacity(0), m_ref(1) { }
568
569 wxZipMemory *AddRef() { m_ref++; return this; }
570 void Release() { if (--m_ref == 0) delete this; }
571
572 char *GetData() const { return m_data; }
573 size_t GetSize() const { return m_size; }
574 size_t GetCapacity() const { return m_capacity; }
575
576 wxZipMemory *Unique(size_t size);
577
578private:
2e85922c 579 ~wxZipMemory() { delete [] m_data; }
00375592
VZ
580
581 char *m_data;
582 size_t m_size;
583 size_t m_capacity;
584 int m_ref;
344d0d88
VZ
585
586 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipMemory)
00375592
VZ
587};
588
589wxZipMemory *wxZipMemory::Unique(size_t size)
590{
591 wxZipMemory *zm;
592
593 if (m_ref > 1) {
594 --m_ref;
595 zm = new wxZipMemory;
596 } else {
597 zm = this;
598 }
599
600 if (zm->m_capacity < size) {
2e85922c 601 delete [] zm->m_data;
00375592
VZ
602 zm->m_data = new char[size];
603 zm->m_capacity = size;
604 }
605
606 zm->m_size = size;
607 return zm;
608}
609
610static inline wxZipMemory *AddRef(wxZipMemory *zm)
611{
612 if (zm)
613 zm->AddRef();
614 return zm;
615}
616
617static inline void Release(wxZipMemory *zm)
618{
619 if (zm)
620 zm->Release();
621}
622
623static void Copy(wxZipMemory*& dest, wxZipMemory *src)
624{
625 Release(dest);
626 dest = AddRef(src);
627}
628
629static void Unique(wxZipMemory*& zm, size_t size)
630{
631 if (!zm && size)
632 zm = new wxZipMemory;
633 if (zm)
634 zm = zm->Unique(size);
635}
636
637
638/////////////////////////////////////////////////////////////////////////////
639// Collection of weak references to entries
640
641WX_DECLARE_HASH_MAP(long, wxZipEntry*, wxIntegerHash,
8fc574b4 642 wxIntegerEqual, wxOffsetZipEntryMap_);
00375592
VZ
643
644class wxZipWeakLinks
645{
646public:
647 wxZipWeakLinks() : m_ref(1) { }
648
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; }
653
654 wxZipWeakLinks *AddEntry(wxZipEntry *entry, wxFileOffset key);
26481315 655 void RemoveEntry(wxFileOffset key)
312f1e6e 656 { m_entries.erase(wx_truncate_cast(key_type, key)); }
00375592
VZ
657 wxZipEntry *GetEntry(wxFileOffset key) const;
658 bool IsEmpty() const { return m_entries.empty(); }
659
660private:
f8fbc92b 661 ~wxZipWeakLinks() { wxASSERT(IsEmpty()); }
00375592 662
8fc574b4 663 typedef wxOffsetZipEntryMap_::key_type key_type;
344d0d88 664
00375592 665 int m_ref;
8fc574b4 666 wxOffsetZipEntryMap_ m_entries;
344d0d88
VZ
667
668 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipWeakLinks)
00375592
VZ
669};
670
671wxZipWeakLinks *wxZipWeakLinks::AddEntry(wxZipEntry *entry, wxFileOffset key)
672{
312f1e6e 673 m_entries[wx_truncate_cast(key_type, key)] = entry;
00375592
VZ
674 m_ref++;
675 return this;
676}
677
678wxZipEntry *wxZipWeakLinks::GetEntry(wxFileOffset key) const
679{
8fc574b4 680 wxOffsetZipEntryMap_::const_iterator it =
312f1e6e 681 m_entries.find(wx_truncate_cast(key_type, key));
00375592
VZ
682 return it != m_entries.end() ? it->second : NULL;
683}
684
685
686/////////////////////////////////////////////////////////////////////////////
687// ZipEntry
688
689wxZipEntry::wxZipEntry(
690 const wxString& name /*=wxEmptyString*/,
691 const wxDateTime& dt /*=wxDateTime::Now()*/,
692 wxFileOffset size /*=wxInvalidOffset*/)
ba9bbf13 693 :
00375592
VZ
694 m_SystemMadeBy(wxZIP_SYSTEM_MSDOS),
695 m_VersionMadeBy(wxMAJOR_VERSION * 10 + wxMINOR_VERSION),
696 m_VersionNeeded(VERSION_NEEDED_TO_EXTRACT),
697 m_Flags(0),
698 m_Method(wxZIP_METHOD_DEFAULT),
699 m_DateTime(dt),
700 m_Crc(0),
701 m_CompressedSize(wxInvalidOffset),
702 m_Size(size),
703 m_Key(wxInvalidOffset),
704 m_Offset(wxInvalidOffset),
705 m_DiskStart(0),
706 m_InternalAttributes(0),
707 m_ExternalAttributes(0),
708 m_Extra(NULL),
709 m_LocalExtra(NULL),
710 m_zipnotifier(NULL),
711 m_backlink(NULL)
712{
713 if (!name.empty())
714 SetName(name);
715}
716
717wxZipEntry::~wxZipEntry()
718{
719 if (m_backlink)
720 m_backlink->Release(m_Key);
721 Release(m_Extra);
722 Release(m_LocalExtra);
723}
724
725wxZipEntry::wxZipEntry(const wxZipEntry& e)
f44eaed6
RN
726 : wxArchiveEntry(e),
727 m_SystemMadeBy(e.m_SystemMadeBy),
00375592
VZ
728 m_VersionMadeBy(e.m_VersionMadeBy),
729 m_VersionNeeded(e.m_VersionNeeded),
730 m_Flags(e.m_Flags),
731 m_Method(e.m_Method),
732 m_DateTime(e.m_DateTime),
733 m_Crc(e.m_Crc),
734 m_CompressedSize(e.m_CompressedSize),
735 m_Size(e.m_Size),
736 m_Name(e.m_Name),
737 m_Key(e.m_Key),
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)),
f44eaed6 745 m_zipnotifier(NULL),
00375592
VZ
746 m_backlink(NULL)
747{
748}
749
750wxZipEntry& wxZipEntry::operator=(const wxZipEntry& e)
751{
752 if (&e != this) {
753 m_SystemMadeBy = e.m_SystemMadeBy;
754 m_VersionMadeBy = e.m_VersionMadeBy;
755 m_VersionNeeded = e.m_VersionNeeded;
756 m_Flags = e.m_Flags;
757 m_Method = e.m_Method;
758 m_DateTime = e.m_DateTime;
759 m_Crc = e.m_Crc;
760 m_CompressedSize = e.m_CompressedSize;
761 m_Size = e.m_Size;
762 m_Name = e.m_Name;
763 m_Key = e.m_Key;
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);
f44eaed6 771 m_zipnotifier = NULL;
00375592
VZ
772 if (m_backlink) {
773 m_backlink->Release(m_Key);
774 m_backlink = NULL;
775 }
776 }
777 return *this;
778}
779
780wxString wxZipEntry::GetName(wxPathFormat format /*=wxPATH_NATIVE*/) const
781{
782 bool isDir = IsDir() && !m_Name.empty();
783
d13a08ab 784 // optimisations for common (and easy) cases
00375592
VZ
785 switch (wxFileName::GetFormat(format)) {
786 case wxPATH_DOS:
787 {
788 wxString name(isDir ? m_Name + _T("\\") : m_Name);
076e07b6 789 for (size_t i = 0; i < name.length(); i++)
00375592
VZ
790 if (name[i] == _T('/'))
791 name[i] = _T('\\');
792 return name;
793 }
794
795 case wxPATH_UNIX:
796 return isDir ? m_Name + _T("/") : m_Name;
797
798 default:
799 ;
800 }
801
802 wxFileName fn;
803
804 if (isDir)
805 fn.AssignDir(m_Name, wxPATH_UNIX);
806 else
807 fn.Assign(m_Name, wxPATH_UNIX);
808
809 return fn.GetFullPath(format);
810}
811
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.
816//
817wxString wxZipEntry::GetInternalName(const wxString& name,
818 wxPathFormat format /*=wxPATH_NATIVE*/,
819 bool *pIsDir /*=NULL*/)
820{
821 wxString internal;
822
823 if (wxFileName::GetFormat(format) != wxPATH_UNIX)
824 internal = wxFileName(name, format).GetFullPath(wxPATH_UNIX);
825 else
826 internal = name;
827
828 bool isDir = !internal.empty() && internal.Last() == '/';
829 if (pIsDir)
830 *pIsDir = isDir;
831 if (isDir)
832 internal.erase(internal.length() - 1);
833
834 while (!internal.empty() && *internal.begin() == '/')
835 internal.erase(0, 1);
836 while (!internal.empty() && internal.compare(0, 2, _T("./")) == 0)
837 internal.erase(0, 2);
838 if (internal == _T(".") || internal == _T(".."))
839 internal = wxEmptyString;
840
841 return internal;
842}
843
844void wxZipEntry::SetSystemMadeBy(int system)
845{
846 int mode = GetMode();
847 bool wasUnix = IsMadeByUnix();
848
26481315 849 m_SystemMadeBy = (wxUint8)system;
00375592
VZ
850
851 if (!wasUnix && IsMadeByUnix()) {
852 SetIsDir(IsDir());
853 SetMode(mode);
854 } else if (wasUnix && !IsMadeByUnix()) {
855 m_ExternalAttributes &= 0xffff;
856 }
857}
858
859void wxZipEntry::SetIsDir(bool isDir /*=true*/)
860{
861 if (isDir)
862 m_ExternalAttributes |= wxZIP_A_SUBDIR;
863 else
864 m_ExternalAttributes &= ~wxZIP_A_SUBDIR;
865
866 if (IsMadeByUnix()) {
867 m_ExternalAttributes &= ~wxZIP_S_IFMT;
868 if (isDir)
869 m_ExternalAttributes |= wxZIP_S_IFDIR;
870 else
871 m_ExternalAttributes |= wxZIP_S_IFREG;
872 }
873}
874
875// Return unix style permission bits
876//
877int wxZipEntry::GetMode() const
878{
879 // return unix permissions if present
880 if (IsMadeByUnix())
881 return (m_ExternalAttributes >> 16) & 0777;
882
883 // otherwise synthesize from the dos attribs
884 int mode = 0644;
885 if (m_ExternalAttributes & wxZIP_A_RDONLY)
886 mode &= ~0200;
887 if (m_ExternalAttributes & wxZIP_A_SUBDIR)
888 mode |= 0111;
889
890 return mode;
891}
892
893// Set unix permissions
894//
895void wxZipEntry::SetMode(int mode)
896{
897 // Set dos attrib bits to be compatible
898 if (mode & 0222)
899 m_ExternalAttributes &= ~wxZIP_A_RDONLY;
900 else
901 m_ExternalAttributes |= wxZIP_A_RDONLY;
902
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;
907 }
908}
909
910const char *wxZipEntry::GetExtra() const
911{
912 return m_Extra ? m_Extra->GetData() : NULL;
913}
914
915size_t wxZipEntry::GetExtraLen() const
916{
917 return m_Extra ? m_Extra->GetSize() : 0;
918}
919
920void wxZipEntry::SetExtra(const char *extra, size_t len)
921{
922 Unique(m_Extra, len);
923 if (len)
924 memcpy(m_Extra->GetData(), extra, len);
925}
926
927const char *wxZipEntry::GetLocalExtra() const
928{
929 return m_LocalExtra ? m_LocalExtra->GetData() : NULL;
930}
931
932size_t wxZipEntry::GetLocalExtraLen() const
933{
934 return m_LocalExtra ? m_LocalExtra->GetSize() : 0;
935}
936
937void wxZipEntry::SetLocalExtra(const char *extra, size_t len)
938{
939 Unique(m_LocalExtra, len);
940 if (len)
941 memcpy(m_LocalExtra->GetData(), extra, len);
942}
943
944void wxZipEntry::SetNotifier(wxZipNotifier& notifier)
945{
946 wxArchiveEntry::UnsetNotifier();
947 m_zipnotifier = &notifier;
948 m_zipnotifier->OnEntryUpdated(*this);
949}
950
951void wxZipEntry::Notify()
952{
953 if (m_zipnotifier)
954 m_zipnotifier->OnEntryUpdated(*this);
955 else if (GetNotifier())
956 GetNotifier()->OnEntryUpdated(*this);
957}
958
959void wxZipEntry::UnsetNotifier()
960{
961 wxArchiveEntry::UnsetNotifier();
962 m_zipnotifier = NULL;
963}
964
965size_t wxZipEntry::ReadLocal(wxInputStream& stream, wxMBConv& conv)
966{
967 wxUint16 nameLen, extraLen;
968 wxUint32 compressedSize, size, crc;
969
abffc1ff
MW
970 wxZipHeader ds(stream, LOCAL_SIZE - 4);
971 if (!ds)
972 return 0;
00375592
VZ
973
974 ds >> m_VersionNeeded >> m_Flags >> m_Method;
975 SetDateTime(wxDateTime().SetFromDOS(ds.Read32()));
976 ds >> crc >> compressedSize >> size >> nameLen >> extraLen;
977
978 bool sumsValid = (m_Flags & wxZIP_SUMS_FOLLOW) == 0;
979
980 if (sumsValid || crc)
981 m_Crc = crc;
982 if ((sumsValid || compressedSize) || m_Method == wxZIP_METHOD_STORE)
983 m_CompressedSize = compressedSize;
984 if ((sumsValid || size) || m_Method == wxZIP_METHOD_STORE)
985 m_Size = size;
986
987 SetName(ReadString(stream, nameLen, conv), wxPATH_UNIX);
abffc1ff
MW
988 if (stream.LastRead() != nameLen + 0u)
989 return 0;
00375592
VZ
990
991 if (extraLen || GetLocalExtraLen()) {
992 Unique(m_LocalExtra, extraLen);
abffc1ff 993 if (extraLen) {
00375592 994 stream.Read(m_LocalExtra->GetData(), extraLen);
abffc1ff
MW
995 if (stream.LastRead() != extraLen + 0u)
996 return 0;
997 }
00375592
VZ
998 }
999
1000 return LOCAL_SIZE + nameLen + extraLen;
1001}
1002
1003size_t wxZipEntry::WriteLocal(wxOutputStream& stream, wxMBConv& conv) const
1004{
1005 wxString unixName = GetName(wxPATH_UNIX);
1006 const wxWX2MBbuf name_buf = conv.cWX2MB(unixName);
1007 const char *name = name_buf;
1008 if (!name) name = "";
312f1e6e 1009 wxUint16 nameLen = wx_truncate_cast(wxUint16, strlen(name));
00375592
VZ
1010
1011 wxDataOutputStream ds(stream);
1012
1013 ds << m_VersionNeeded << m_Flags << m_Method;
1014 ds.Write32(GetDateTime().GetAsDOS());
ba9bbf13 1015
00375592 1016 ds.Write32(m_Crc);
312f1e6e
MW
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);
00375592
VZ
1021
1022 ds << nameLen;
312f1e6e 1023 wxUint16 extraLen = wx_truncate_cast(wxUint16, GetLocalExtraLen());
00375592
VZ
1024 ds.Write16(extraLen);
1025
1026 stream.Write(name, nameLen);
1027 if (extraLen)
1028 stream.Write(m_LocalExtra->GetData(), extraLen);
1029
1030 return LOCAL_SIZE + nameLen + extraLen;
1031}
1032
1033size_t wxZipEntry::ReadCentral(wxInputStream& stream, wxMBConv& conv)
1034{
1035 wxUint16 nameLen, extraLen, commentLen;
1036
abffc1ff
MW
1037 wxZipHeader ds(stream, CENTRAL_SIZE - 4);
1038 if (!ds)
1039 return 0;
00375592
VZ
1040
1041 ds >> m_VersionMadeBy >> m_SystemMadeBy;
1042
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());
1050
1051 ds >> nameLen >> extraLen >> commentLen
1052 >> m_DiskStart >> m_InternalAttributes >> m_ExternalAttributes;
1053 SetOffset(ds.Read32());
ba9bbf13 1054
00375592 1055 SetName(ReadString(stream, nameLen, conv), wxPATH_UNIX);
abffc1ff
MW
1056 if (stream.LastRead() != nameLen + 0u)
1057 return 0;
00375592
VZ
1058
1059 if (extraLen || GetExtraLen()) {
1060 Unique(m_Extra, extraLen);
abffc1ff 1061 if (extraLen) {
00375592 1062 stream.Read(m_Extra->GetData(), extraLen);
abffc1ff
MW
1063 if (stream.LastRead() != extraLen + 0u)
1064 return 0;
1065 }
00375592
VZ
1066 }
1067
abffc1ff 1068 if (commentLen) {
00375592 1069 m_Comment = ReadString(stream, commentLen, conv);
abffc1ff
MW
1070 if (stream.LastRead() != commentLen + 0u)
1071 return 0;
1072 } else {
00375592 1073 m_Comment.clear();
abffc1ff 1074 }
00375592
VZ
1075
1076 return CENTRAL_SIZE + nameLen + extraLen + commentLen;
1077}
1078
1079size_t wxZipEntry::WriteCentral(wxOutputStream& stream, wxMBConv& conv) const
1080{
1081 wxString unixName = GetName(wxPATH_UNIX);
1082 const wxWX2MBbuf name_buf = conv.cWX2MB(unixName);
1083 const char *name = name_buf;
1084 if (!name) name = "";
312f1e6e 1085 wxUint16 nameLen = wx_truncate_cast(wxUint16, strlen(name));
00375592
VZ
1086
1087 const wxWX2MBbuf comment_buf = conv.cWX2MB(m_Comment);
1088 const char *comment = comment_buf;
1089 if (!comment) comment = "";
312f1e6e 1090 wxUint16 commentLen = wx_truncate_cast(wxUint16, strlen(comment));
00375592 1091
312f1e6e 1092 wxUint16 extraLen = wx_truncate_cast(wxUint16, GetExtraLen());
00375592
VZ
1093
1094 wxDataOutputStream ds(stream);
1095
1096 ds << CENTRAL_MAGIC << m_VersionMadeBy << m_SystemMadeBy;
1097
312f1e6e
MW
1098 ds.Write16(wx_truncate_cast(wxUint16, GetVersionNeeded()));
1099 ds.Write16(wx_truncate_cast(wxUint16, GetFlags()));
1100 ds.Write16(wx_truncate_cast(wxUint16, GetMethod()));
00375592
VZ
1101 ds.Write32(GetDateTime().GetAsDOS());
1102 ds.Write32(GetCrc());
312f1e6e
MW
1103 ds.Write32(wx_truncate_cast(wxUint32, GetCompressedSize()));
1104 ds.Write32(wx_truncate_cast(wxUint32, GetSize()));
00375592
VZ
1105 ds.Write16(nameLen);
1106 ds.Write16(extraLen);
1107
1108 ds << commentLen << m_DiskStart << m_InternalAttributes
312f1e6e 1109 << m_ExternalAttributes << wx_truncate_cast(wxUint32, GetOffset());
ba9bbf13 1110
00375592
VZ
1111 stream.Write(name, nameLen);
1112 if (extraLen)
1113 stream.Write(GetExtra(), extraLen);
1114 stream.Write(comment, commentLen);
1115
1116 return CENTRAL_SIZE + nameLen + extraLen + commentLen;
1117}
1118
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.
1123//
1124size_t wxZipEntry::ReadDescriptor(wxInputStream& stream)
1125{
abffc1ff
MW
1126 wxZipHeader ds(stream, SUMS_SIZE);
1127 if (!ds)
1128 return 0;
ba9bbf13 1129
00375592
VZ
1130 m_Crc = ds.Read32();
1131 m_CompressedSize = ds.Read32();
1132 m_Size = ds.Read32();
1133
1134 // if 1st value is the signature then this is probably an info-zip record
1135 if (m_Crc == SUMS_MAGIC)
1136 {
abffc1ff 1137 wxZipHeader buf(stream, 8);
bb2955b3 1138 wxUint32 u1 = buf.GetSize() >= 4 ? buf.Read32() : (wxUint32)LOCAL_MAGIC;
abffc1ff 1139 wxUint32 u2 = buf.GetSize() == 8 ? buf.Read32() : 0;
ba9bbf13 1140
00375592
VZ
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))
1144 {
1145 // it's a pkzip style record after all!
abffc1ff
MW
1146 if (buf.GetSize() > 0)
1147 stream.Ungetch(buf.GetData(), buf.GetSize());
00375592
VZ
1148 }
1149 else
1150 {
1151 // it's an info-zip record as expected
abffc1ff
MW
1152 if (buf.GetSize() > 4)
1153 stream.Ungetch(buf.GetData() + 4, buf.GetSize() - 4);
312f1e6e 1154 m_Crc = wx_truncate_cast(wxUint32, m_CompressedSize);
00375592
VZ
1155 m_CompressedSize = m_Size;
1156 m_Size = u1;
1157 return SUMS_SIZE + 4;
1158 }
1159 }
1160
1161 return SUMS_SIZE;
1162}
1163
1164size_t wxZipEntry::WriteDescriptor(wxOutputStream& stream, wxUint32 crc,
1165 wxFileOffset compressedSize, wxFileOffset size)
1166{
1167 m_Crc = crc;
1168 m_CompressedSize = compressedSize;
1169 m_Size = size;
1170
1171 wxDataOutputStream ds(stream);
1172
1173 ds.Write32(crc);
312f1e6e
MW
1174 ds.Write32(wx_truncate_cast(wxUint32, compressedSize));
1175 ds.Write32(wx_truncate_cast(wxUint32, size));
00375592
VZ
1176
1177 return SUMS_SIZE;
1178}
1179
1180
1181/////////////////////////////////////////////////////////////////////////////
1182// wxZipEndRec - holds the end of central directory record
1183
1184class wxZipEndRec
1185{
1186public:
1187 wxZipEndRec();
1188
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; }
1196
312f1e6e
MW
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; }
00375592
VZ
1211
1212 bool Read(wxInputStream& stream, wxMBConv& conv);
1213 bool Write(wxOutputStream& stream, wxMBConv& conv) const;
1214
1215private:
1216 wxUint16 m_DiskNumber;
1217 wxUint16 m_StartDisk;
1218 wxUint16 m_EntriesHere;
1219 wxUint16 m_TotalEntries;
1220 wxUint32 m_Size;
1221 wxUint32 m_Offset;
1222 wxString m_Comment;
1223};
1224
1225wxZipEndRec::wxZipEndRec()
1226 : m_DiskNumber(0),
1227 m_StartDisk(0),
1228 m_EntriesHere(0),
1229 m_TotalEntries(0),
1230 m_Size(0),
1231 m_Offset(0)
1232{
1233}
1234
1235bool wxZipEndRec::Write(wxOutputStream& stream, wxMBConv& conv) const
1236{
1237 const wxWX2MBbuf comment_buf = conv.cWX2MB(m_Comment);
1238 const char *comment = comment_buf;
1239 if (!comment) comment = "";
26481315 1240 wxUint16 commentLen = (wxUint16)strlen(comment);
00375592
VZ
1241
1242 wxDataOutputStream ds(stream);
1243
1244 ds << END_MAGIC << m_DiskNumber << m_StartDisk << m_EntriesHere
1245 << m_TotalEntries << m_Size << m_Offset << commentLen;
1246
1247 stream.Write(comment, commentLen);
1248
1249 return stream.IsOk();
1250}
1251
1252bool wxZipEndRec::Read(wxInputStream& stream, wxMBConv& conv)
1253{
abffc1ff
MW
1254 wxZipHeader ds(stream, END_SIZE - 4);
1255 if (!ds)
1256 return false;
1257
00375592
VZ
1258 wxUint16 commentLen;
1259
1260 ds >> m_DiskNumber >> m_StartDisk >> m_EntriesHere
1261 >> m_TotalEntries >> m_Size >> m_Offset >> commentLen;
1262
abffc1ff 1263 if (commentLen) {
00375592 1264 m_Comment = ReadString(stream, commentLen, conv);
abffc1ff
MW
1265 if (stream.LastRead() != commentLen + 0u)
1266 return false;
1267 }
00375592 1268
abffc1ff
MW
1269 if (m_DiskNumber != 0 || m_StartDisk != 0 ||
1270 m_EntriesHere != m_TotalEntries)
1271 wxLogWarning(_("assuming this is a multi-part zip concatenated"));
00375592 1272
abffc1ff 1273 return true;
00375592
VZ
1274}
1275
1276
1277/////////////////////////////////////////////////////////////////////////////
1278// A weak link from an input stream to an output stream
1279
1280class wxZipStreamLink
1281{
1282public:
1283 wxZipStreamLink(wxZipOutputStream *stream) : m_ref(1), m_stream(stream) { }
1284
1285 wxZipStreamLink *AddRef() { m_ref++; return this; }
1286 wxZipOutputStream *GetOutputStream() const { return m_stream; }
1287
1288 void Release(class wxZipInputStream *WXUNUSED(s))
1289 { if (--m_ref == 0) delete this; }
1290 void Release(class wxZipOutputStream *WXUNUSED(s))
1291 { m_stream = NULL; if (--m_ref == 0) delete this; }
1292
1293private:
f8fbc92b 1294 ~wxZipStreamLink() { }
00375592
VZ
1295
1296 int m_ref;
1297 wxZipOutputStream *m_stream;
344d0d88
VZ
1298
1299 wxSUPPRESS_GCC_PRIVATE_DTOR_WARNING(wxZipStreamLink)
00375592
VZ
1300};
1301
1302
1303/////////////////////////////////////////////////////////////////////////////
1304// Input stream
1305
d13a08ab 1306// leave the default wxZipEntryPtr free for users
8fc574b4
MW
1307wxDECLARE_SCOPED_PTR(wxZipEntry, wxZipEntryPtr_)
1308wxDEFINE_SCOPED_PTR (wxZipEntry, wxZipEntryPtr_)
00375592
VZ
1309
1310// constructor
1311//
1312wxZipInputStream::wxZipInputStream(wxInputStream& stream,
1313 wxMBConv& conv /*=wxConvLocal*/)
1314 : wxArchiveInputStream(stream, conv)
1315{
00375592
VZ
1316 Init();
1317}
1318
8fc574b4
MW
1319wxZipInputStream::wxZipInputStream(wxInputStream *stream,
1320 wxMBConv& conv /*=wxConvLocal*/)
1321 : wxArchiveInputStream(stream, conv)
1322{
1323 Init();
1324}
1325
1326#if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
d13a08ab 1327
fe47da7b
MW
1328// Part of the compatibility constructor, which has been made inline to
1329// avoid a problem with it not being exported by mingw 3.2.3
00375592 1330//
fe47da7b 1331void wxZipInputStream::Init(const wxString& file)
00375592
VZ
1332{
1333 // no error messages
1334 wxLogNull nolog;
1335 Init();
d13a08ab 1336 m_allowSeeking = true;
8fc574b4
MW
1337 wxFFileInputStream *ffile;
1338 ffile = wx_static_cast(wxFFileInputStream*, m_parent_i_stream);
1339 wxZipEntryPtr_ entry;
00375592 1340
8fc574b4 1341 if (ffile->Ok()) {
00375592
VZ
1342 do {
1343 entry.reset(GetNextEntry());
1344 }
1345 while (entry.get() != NULL && entry->GetInternalName() != file);
1346 }
1347
1348 if (entry.get() == NULL)
1349 m_lasterror = wxSTREAM_READ_ERROR;
1350}
1351
8fc574b4 1352wxInputStream* wxZipInputStream::OpenFile(const wxString& archive)
00375592
VZ
1353{
1354 wxLogNull nolog;
8fc574b4 1355 return new wxFFileInputStream(archive);
00375592
VZ
1356}
1357
8fc574b4 1358#endif // WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
d13a08ab 1359
00375592
VZ
1360void wxZipInputStream::Init()
1361{
1362 m_store = new wxStoredInputStream(*m_parent_i_stream);
1363 m_inflate = NULL;
1364 m_rawin = NULL;
1365 m_raw = false;
1366 m_headerSize = 0;
1367 m_decomp = NULL;
1368 m_parentSeekable = false;
1369 m_weaklinks = new wxZipWeakLinks;
1370 m_streamlink = NULL;
1371 m_offsetAdjustment = 0;
1372 m_position = wxInvalidOffset;
1373 m_signature = 0;
1374 m_TotalEntries = 0;
1375 m_lasterror = m_parent_i_stream->GetLastError();
8fc574b4 1376#if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
fe47da7b
MW
1377 m_allowSeeking = false;
1378#endif
00375592
VZ
1379}
1380
1381wxZipInputStream::~wxZipInputStream()
1382{
1383 CloseDecompressor(m_decomp);
1384
1385 delete m_store;
1386 delete m_inflate;
1387 delete m_rawin;
00375592
VZ
1388
1389 m_weaklinks->Release(this);
ba9bbf13 1390
00375592
VZ
1391 if (m_streamlink)
1392 m_streamlink->Release(this);
1393}
1394
1395wxString wxZipInputStream::GetComment()
1396{
1397 if (m_position == wxInvalidOffset)
1398 if (!LoadEndRecord())
1399 return wxEmptyString;
1400
1401 if (!m_parentSeekable && Eof() && m_signature) {
1402 m_lasterror = wxSTREAM_NO_ERROR;
1403 m_lasterror = ReadLocal(true);
1404 }
1405
1406 return m_Comment;
1407}
1408
1409int wxZipInputStream::GetTotalEntries()
1410{
1411 if (m_position == wxInvalidOffset)
1412 LoadEndRecord();
1413 return m_TotalEntries;
1414}
1415
1416wxZipStreamLink *wxZipInputStream::MakeLink(wxZipOutputStream *out)
1417{
1418 wxZipStreamLink *link = NULL;
1419
1420 if (!m_parentSeekable && (IsOpened() || !Eof())) {
1421 link = new wxZipStreamLink(out);
1422 if (m_streamlink)
1423 m_streamlink->Release(this);
1424 m_streamlink = link->AddRef();
1425 }
1426
1427 return link;
1428}
d78b3d64 1429
00375592
VZ
1430bool wxZipInputStream::LoadEndRecord()
1431{
1432 wxCHECK(m_position == wxInvalidOffset, false);
1433 if (!IsOk())
1434 return false;
ea4f5235 1435
00375592
VZ
1436 m_position = 0;
1437
1438 // First find the end-of-central-directory record.
1439 if (!FindEndRecord()) {
1440 // failed, so either this is a non-seekable stream (ok), or not a zip
1441 if (m_parentSeekable) {
1442 m_lasterror = wxSTREAM_READ_ERROR;
1443 wxLogError(_("invalid zip file"));
1444 return false;
1445 }
1446 else {
1447 wxLogNull nolog;
1448 wxFileOffset pos = m_parent_i_stream->TellI();
945bd474 1449 if (pos != wxInvalidOffset)
00375592
VZ
1450 m_offsetAdjustment = m_position = pos;
1451 return true;
1452 }
1453 }
1454
1455 wxZipEndRec endrec;
1456
1457 // Read in the end record
1458 wxFileOffset endPos = m_parent_i_stream->TellI() - 4;
abffc1ff
MW
1459 if (!endrec.Read(*m_parent_i_stream, GetConv()))
1460 return false;
00375592
VZ
1461
1462 m_TotalEntries = endrec.GetTotalEntries();
1463 m_Comment = endrec.GetComment();
ea4f5235 1464
00375592 1465 // Now find the central-directory. we have the file offset of
ba9bbf13 1466 // the CD, so look there first.
00375592
VZ
1467 if (m_parent_i_stream->SeekI(endrec.GetOffset()) != wxInvalidOffset &&
1468 ReadSignature() == CENTRAL_MAGIC) {
1469 m_signature = CENTRAL_MAGIC;
1470 m_position = endrec.GetOffset();
1471 m_offsetAdjustment = 0;
1472 return true;
1473 }
ba9bbf13 1474
00375592
VZ
1475 // If it's not there, then it could be that the zip has been appended
1476 // to a self extractor, so take the CD size (also in endrec), subtract
1477 // it from the file offset of the end-central-directory and look there.
1478 if (m_parent_i_stream->SeekI(endPos - endrec.GetSize())
1479 != wxInvalidOffset && ReadSignature() == CENTRAL_MAGIC) {
1480 m_signature = CENTRAL_MAGIC;
1481 m_position = endPos - endrec.GetSize();
1482 m_offsetAdjustment = m_position - endrec.GetOffset();
1483 return true;
1484 }
1485
1486 wxLogError(_("can't find central directory in zip"));
1487 m_lasterror = wxSTREAM_READ_ERROR;
1488 return false;
1489}
5526e819 1490
00375592
VZ
1491// Find the end-of-central-directory record.
1492// If found the stream will be positioned just past the 4 signature bytes.
1493//
1494bool wxZipInputStream::FindEndRecord()
5526e819 1495{
3c70014d
MW
1496 if (!m_parent_i_stream->IsSeekable())
1497 return false;
1498
00375592 1499 // usually it's 22 bytes in size and the last thing in the file
ba9bbf13 1500 {
00375592
VZ
1501 wxLogNull nolog;
1502 if (m_parent_i_stream->SeekI(-END_SIZE, wxFromEnd) == wxInvalidOffset)
1503 return false;
1504 }
5526e819 1505
00375592
VZ
1506 m_parentSeekable = true;
1507 m_signature = 0;
1508 char magic[4];
1509 if (m_parent_i_stream->Read(magic, 4).LastRead() != 4)
1510 return false;
1511 if ((m_signature = CrackUint32(magic)) == END_MAGIC)
1512 return true;
1513
1514 // unfortunately, the record has a comment field that can be up to 65535
1515 // bytes in length, so if the signature not found then search backwards.
1516 wxFileOffset pos = m_parent_i_stream->TellI();
1517 const int BUFSIZE = 1024;
1518 wxCharBuffer buf(BUFSIZE);
1519
1520 memcpy(buf.data(), magic, 3);
1521 wxFileOffset minpos = wxMax(pos - 65535L, 0);
1522
1523 while (pos > minpos) {
312f1e6e
MW
1524 size_t len = wx_truncate_cast(size_t,
1525 pos - wxMax(pos - (BUFSIZE - 3), minpos));
00375592
VZ
1526 memcpy(buf.data() + len, buf, 3);
1527 pos -= len;
ba9bbf13 1528
00375592
VZ
1529 if (m_parent_i_stream->SeekI(pos, wxFromStart) == wxInvalidOffset ||
1530 m_parent_i_stream->Read(buf.data(), len).LastRead() != len)
1531 return false;
1532
1533 char *p = buf.data() + len;
1534
1535 while (p-- > buf.data()) {
1536 if ((m_signature = CrackUint32(p)) == END_MAGIC) {
1537 size_t remainder = buf.data() + len - p;
1538 if (remainder > 4)
1539 m_parent_i_stream->Ungetch(p + 4, remainder - 4);
1540 return true;
1541 }
1542 }
5526e819 1543 }
00375592
VZ
1544
1545 return false;
1546}
1547
1548wxZipEntry *wxZipInputStream::GetNextEntry()
1549{
1550 if (m_position == wxInvalidOffset)
1551 if (!LoadEndRecord())
1552 return NULL;
1553
1554 m_lasterror = m_parentSeekable ? ReadCentral() : ReadLocal();
1555 if (!IsOk())
1556 return NULL;
1557
8fc574b4 1558 wxZipEntryPtr_ entry(new wxZipEntry(m_entry));
00375592
VZ
1559 entry->m_backlink = m_weaklinks->AddEntry(entry.get(), entry->GetKey());
1560 return entry.release();
1561}
1562
1563wxStreamError wxZipInputStream::ReadCentral()
1564{
1565 if (!AtHeader())
1566 CloseEntry();
1567
1568 if (m_signature == END_MAGIC)
1569 return wxSTREAM_EOF;
1570
1571 if (m_signature != CENTRAL_MAGIC) {
1572 wxLogError(_("error reading zip central directory"));
1573 return wxSTREAM_READ_ERROR;
5526e819 1574 }
e90c1d2a 1575
00375592
VZ
1576 if (QuietSeek(*m_parent_i_stream, m_position + 4) == wxInvalidOffset)
1577 return wxSTREAM_READ_ERROR;
5526e819 1578
abffc1ff
MW
1579 size_t size = m_entry.ReadCentral(*m_parent_i_stream, GetConv());
1580 if (!size) {
00375592
VZ
1581 m_signature = 0;
1582 return wxSTREAM_READ_ERROR;
5526e819 1583 }
00375592 1584
abffc1ff 1585 m_position += size;
00375592
VZ
1586 m_signature = ReadSignature();
1587
1588 if (m_offsetAdjustment)
1589 m_entry.SetOffset(m_entry.GetOffset() + m_offsetAdjustment);
1590 m_entry.SetKey(m_entry.GetOffset());
1591
1592 return wxSTREAM_NO_ERROR;
5526e819
VS
1593}
1594
00375592
VZ
1595wxStreamError wxZipInputStream::ReadLocal(bool readEndRec /*=false*/)
1596{
1597 if (!AtHeader())
1598 CloseEntry();
1599
1600 if (!m_signature)
1601 m_signature = ReadSignature();
5526e819 1602
00375592
VZ
1603 if (m_signature == CENTRAL_MAGIC || m_signature == END_MAGIC) {
1604 if (m_streamlink && !m_streamlink->GetOutputStream()) {
1605 m_streamlink->Release(this);
1606 m_streamlink = NULL;
1607 }
1608 }
5526e819 1609
00375592
VZ
1610 while (m_signature == CENTRAL_MAGIC) {
1611 if (m_weaklinks->IsEmpty() && m_streamlink == NULL)
1612 return wxSTREAM_EOF;
ba9bbf13 1613
abffc1ff
MW
1614 size_t size = m_entry.ReadCentral(*m_parent_i_stream, GetConv());
1615 m_position += size;
00375592 1616 m_signature = 0;
abffc1ff 1617 if (!size)
00375592
VZ
1618 return wxSTREAM_READ_ERROR;
1619
1620 wxZipEntry *entry = m_weaklinks->GetEntry(m_entry.GetOffset());
1621 if (entry) {
1622 entry->SetSystemMadeBy(m_entry.GetSystemMadeBy());
1623 entry->SetVersionMadeBy(m_entry.GetVersionMadeBy());
1624 entry->SetComment(m_entry.GetComment());
1625 entry->SetDiskStart(m_entry.GetDiskStart());
1626 entry->SetInternalAttributes(m_entry.GetInternalAttributes());
1627 entry->SetExternalAttributes(m_entry.GetExternalAttributes());
1628 Copy(entry->m_Extra, m_entry.m_Extra);
1629 entry->Notify();
1630 m_weaklinks->RemoveEntry(entry->GetOffset());
1631 }
1632
1633 m_signature = ReadSignature();
1634 }
1635
1636 if (m_signature == END_MAGIC) {
1637 if (readEndRec || m_streamlink) {
1638 wxZipEndRec endrec;
1639 endrec.Read(*m_parent_i_stream, GetConv());
1640 m_Comment = endrec.GetComment();
1641 m_signature = 0;
1642 if (m_streamlink) {
1643 m_streamlink->GetOutputStream()->SetComment(endrec.GetComment());
1644 m_streamlink->Release(this);
1645 m_streamlink = NULL;
1646 }
1647 }
1648 return wxSTREAM_EOF;
1649 }
ba9bbf13 1650
076e07b6
MW
1651 if (m_signature == LOCAL_MAGIC) {
1652 m_headerSize = m_entry.ReadLocal(*m_parent_i_stream, GetConv());
1653 m_signature = 0;
1654 m_entry.SetOffset(m_position);
1655 m_entry.SetKey(m_position);
00375592 1656
076e07b6
MW
1657 if (m_headerSize) {
1658 m_TotalEntries++;
1659 return wxSTREAM_NO_ERROR;
1660 }
00375592 1661 }
076e07b6
MW
1662
1663 wxLogError(_("error reading zip local header"));
1664 return wxSTREAM_READ_ERROR;
00375592
VZ
1665}
1666
1667wxUint32 wxZipInputStream::ReadSignature()
5526e819 1668{
00375592
VZ
1669 char magic[4];
1670 m_parent_i_stream->Read(magic, 4);
1671 return m_parent_i_stream->LastRead() == 4 ? CrackUint32(magic) : 0;
1672}
1673
1674bool wxZipInputStream::OpenEntry(wxArchiveEntry& entry)
1675{
1676 wxZipEntry *zipEntry = wxStaticCast(&entry, wxZipEntry);
1677 return zipEntry ? OpenEntry(*zipEntry) : false;
1678}
1679
1680// Open an entry
1681//
1682bool wxZipInputStream::DoOpen(wxZipEntry *entry, bool raw)
1683{
1684 if (m_position == wxInvalidOffset)
1685 if (!LoadEndRecord())
1686 return false;
1687 if (m_lasterror == wxSTREAM_READ_ERROR)
1688 return false;
f489770c
MW
1689 if (IsOpened())
1690 CloseEntry();
00375592
VZ
1691
1692 m_raw = raw;
1693
1694 if (entry) {
1695 if (AfterHeader() && entry->GetKey() == m_entry.GetOffset())
1696 return true;
1697 // can only open the current entry on a non-seekable stream
1698 wxCHECK(m_parentSeekable, false);
1699 }
ba9bbf13 1700
00375592 1701 m_lasterror = wxSTREAM_READ_ERROR;
ba9bbf13 1702
00375592
VZ
1703 if (entry)
1704 m_entry = *entry;
1705
1706 if (m_parentSeekable) {
1707 if (QuietSeek(*m_parent_i_stream, m_entry.GetOffset())
1708 == wxInvalidOffset)
1709 return false;
1710 if (ReadSignature() != LOCAL_MAGIC) {
1711 wxLogError(_("bad zipfile offset to entry"));
1712 return false;
1713 }
1714 }
1715
1716 if (m_parentSeekable || AtHeader()) {
1717 m_headerSize = m_entry.ReadLocal(*m_parent_i_stream, GetConv());
abffc1ff 1718 if (m_headerSize && m_parentSeekable) {
00375592
VZ
1719 wxZipEntry *ref = m_weaklinks->GetEntry(m_entry.GetKey());
1720 if (ref) {
1721 Copy(ref->m_LocalExtra, m_entry.m_LocalExtra);
1722 ref->Notify();
1723 m_weaklinks->RemoveEntry(ref->GetKey());
1724 }
1725 if (entry && entry != ref) {
1726 Copy(entry->m_LocalExtra, m_entry.m_LocalExtra);
1727 entry->Notify();
1728 }
1729 }
1730 }
1731
abffc1ff
MW
1732 if (m_headerSize)
1733 m_lasterror = wxSTREAM_NO_ERROR;
00375592
VZ
1734 return IsOk();
1735}
1736
1737bool wxZipInputStream::OpenDecompressor(bool raw /*=false*/)
1738{
1739 wxASSERT(AfterHeader());
1740
1741 wxFileOffset compressedSize = m_entry.GetCompressedSize();
1742
1743 if (raw)
1744 m_raw = true;
1745
1746 if (m_raw) {
1747 if (compressedSize != wxInvalidOffset) {
1748 m_store->Open(compressedSize);
1749 m_decomp = m_store;
1750 } else {
1751 if (!m_rawin)
1752 m_rawin = new wxRawInputStream(*m_parent_i_stream);
1753 m_decomp = m_rawin->Open(OpenDecompressor(m_rawin->GetTee()));
1754 }
1755 } else {
1756 if (compressedSize != wxInvalidOffset &&
1757 (m_entry.GetMethod() != wxZIP_METHOD_DEFLATE ||
1758 wxZlibInputStream::CanHandleGZip())) {
1759 m_store->Open(compressedSize);
1760 m_decomp = OpenDecompressor(*m_store);
1761 } else {
1762 m_decomp = OpenDecompressor(*m_parent_i_stream);
1763 }
5526e819 1764 }
00375592
VZ
1765
1766 m_crcAccumulator = crc32(0, Z_NULL, 0);
1767 m_lasterror = m_decomp ? m_decomp->GetLastError() : wxSTREAM_READ_ERROR;
1768 return IsOk();
5526e819
VS
1769}
1770
00375592
VZ
1771// Can be overriden to add support for additional decompression methods
1772//
1773wxInputStream *wxZipInputStream::OpenDecompressor(wxInputStream& stream)
f6bcfd97 1774{
00375592
VZ
1775 switch (m_entry.GetMethod()) {
1776 case wxZIP_METHOD_STORE:
1777 if (m_entry.GetSize() == wxInvalidOffset) {
1778 wxLogError(_("stored file length not in Zip header"));
1779 break;
1780 }
1781 m_store->Open(m_entry.GetSize());
1782 return m_store;
1783
1784 case wxZIP_METHOD_DEFLATE:
1785 if (!m_inflate)
1786 m_inflate = new wxZlibInputStream2(stream);
1787 else
1788 m_inflate->Open(stream);
1789 return m_inflate;
f6bcfd97 1790
00375592
VZ
1791 default:
1792 wxLogError(_("unsupported Zip compression method"));
1793 }
1794
1795 return NULL;
f6bcfd97 1796}
5526e819 1797
00375592
VZ
1798bool wxZipInputStream::CloseDecompressor(wxInputStream *decomp)
1799{
1800 if (decomp && decomp == m_rawin)
1801 return CloseDecompressor(m_rawin->GetFilterInputStream());
1802 if (decomp != m_store && decomp != m_inflate)
1803 delete decomp;
1804 return true;
1805}
5526e819 1806
00375592
VZ
1807// Closes the current entry and positions the underlying stream at the start
1808// of the next entry
1809//
1810bool wxZipInputStream::CloseEntry()
5526e819 1811{
00375592
VZ
1812 if (AtHeader())
1813 return true;
1814 if (m_lasterror == wxSTREAM_READ_ERROR)
1815 return false;
f6bcfd97 1816
00375592
VZ
1817 if (!m_parentSeekable) {
1818 if (!IsOpened() && !OpenDecompressor(true))
1819 return false;
1820
1821 const int BUFSIZE = 8192;
1822 wxCharBuffer buf(BUFSIZE);
1823 while (IsOk())
1824 Read(buf.data(), BUFSIZE);
1825
1826 m_position += m_headerSize + m_entry.GetCompressedSize();
f6bcfd97
BP
1827 }
1828
00375592
VZ
1829 if (m_lasterror == wxSTREAM_EOF)
1830 m_lasterror = wxSTREAM_NO_ERROR;
f6bcfd97 1831
00375592
VZ
1832 CloseDecompressor(m_decomp);
1833 m_decomp = NULL;
1834 m_entry = wxZipEntry();
1835 m_headerSize = 0;
1836 m_raw = false;
f6bcfd97 1837
00375592 1838 return IsOk();
5526e819
VS
1839}
1840
00375592
VZ
1841size_t wxZipInputStream::OnSysRead(void *buffer, size_t size)
1842{
1843 if (!IsOpened())
1844 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1845 m_lasterror = wxSTREAM_READ_ERROR;
1846 if (!IsOk() || !size)
1847 return 0;
1848
1849 size_t count = m_decomp->Read(buffer, size).LastRead();
1850 if (!m_raw)
1851 m_crcAccumulator = crc32(m_crcAccumulator, (Byte*)buffer, count);
abffc1ff
MW
1852 if (count < size)
1853 m_lasterror = m_decomp->GetLastError();
00375592
VZ
1854
1855 if (Eof()) {
1856 if ((m_entry.GetFlags() & wxZIP_SUMS_FOLLOW) != 0) {
1857 m_headerSize += m_entry.ReadDescriptor(*m_parent_i_stream);
1858 wxZipEntry *entry = m_weaklinks->GetEntry(m_entry.GetKey());
1859
1860 if (entry) {
1861 entry->SetCrc(m_entry.GetCrc());
1862 entry->SetCompressedSize(m_entry.GetCompressedSize());
1863 entry->SetSize(m_entry.GetSize());
1864 entry->Notify();
1865 }
1866 }
1867
1868 if (!m_raw) {
1869 m_lasterror = wxSTREAM_READ_ERROR;
1870
abffc1ff
MW
1871 if (m_entry.GetSize() != TellI())
1872 wxLogError(_("reading zip stream (entry %s): bad length"),
1873 m_entry.GetName().c_str());
1874 else if (m_crcAccumulator != m_entry.GetCrc())
1875 wxLogError(_("reading zip stream (entry %s): bad crc"),
1876 m_entry.GetName().c_str());
1877 else
1878 m_lasterror = wxSTREAM_EOF;
00375592
VZ
1879 }
1880 }
5526e819 1881
00375592
VZ
1882 return count;
1883}
5526e819 1884
8fc574b4 1885#if WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
d13a08ab 1886
00375592
VZ
1887// Borrowed from VS's zip stream (c) 1999 Vaclav Slavik
1888//
4004775e 1889wxFileOffset wxZipInputStream::OnSysSeek(wxFileOffset seek, wxSeekMode mode)
5526e819 1890{
d13a08ab
MW
1891 // seeking works when the stream is created with the compatibility
1892 // constructor
1893 if (!m_allowSeeking)
8019e604
MW
1894 return wxInvalidOffset;
1895 if (!IsOpened())
1896 if ((AtHeader() && !DoOpen()) || !OpenDecompressor())
1897 m_lasterror = wxSTREAM_READ_ERROR;
1898 if (!IsOk())
00375592
VZ
1899 return wxInvalidOffset;
1900
cab1a605 1901 // NB: since ZIP files don't natively support seeking, we have to
03c0fc66 1902 // implement a brute force workaround -- reading all the data
cab1a605 1903 // between current and the new position (or between beginning of
03c0fc66
VS
1904 // the file and new position...)
1905
4004775e 1906 wxFileOffset nextpos;
00375592 1907 wxFileOffset pos = TellI();
5526e819 1908
03c0fc66 1909 switch ( mode )
d1af991f 1910 {
00375592 1911 case wxFromCurrent : nextpos = seek + pos; break;
5526e819 1912 case wxFromStart : nextpos = seek; break;
8019e604 1913 case wxFromEnd : nextpos = GetLength() + seek; break;
00375592 1914 default : nextpos = pos; break; /* just to fool compiler, never happens */
5526e819
VS
1915 }
1916
312f1e6e 1917 wxFileOffset toskip wxDUMMY_INITIALIZE(0);
00375592 1918 if ( nextpos >= pos )
d1af991f 1919 {
312f1e6e 1920 toskip = nextpos - pos;
5526e819 1921 }
03c0fc66
VS
1922 else
1923 {
00375592 1924 wxZipEntry current(m_entry);
00375592 1925 if (!OpenEntry(current))
e90c1d2a 1926 {
2b5f62a0 1927 m_lasterror = wxSTREAM_READ_ERROR;
00375592 1928 return pos;
5526e819 1929 }
312f1e6e 1930 toskip = nextpos;
03c0fc66 1931 }
cab1a605 1932
03c0fc66
VS
1933 if ( toskip > 0 )
1934 {
312f1e6e 1935 const int BUFSIZE = 4096;
03c0fc66
VS
1936 size_t sz;
1937 char buffer[BUFSIZE];
1938 while ( toskip > 0 )
1939 {
312f1e6e 1940 sz = wx_truncate_cast(size_t, wxMin(toskip, BUFSIZE));
00375592 1941 Read(buffer, sz);
03c0fc66
VS
1942 toskip -= sz;
1943 }
5526e819
VS
1944 }
1945
00375592
VZ
1946 pos = nextpos;
1947 return pos;
5526e819
VS
1948}
1949
8fc574b4 1950#endif // WXWIN_COMPATIBILITY_2_6 && wxUSE_FFILE
d13a08ab 1951
00375592
VZ
1952
1953/////////////////////////////////////////////////////////////////////////////
1954// Output stream
1955
28997d37 1956#include "wx/listimpl.cpp"
8fc574b4 1957WX_DEFINE_LIST(wxZipEntryList_)
00375592
VZ
1958
1959wxZipOutputStream::wxZipOutputStream(wxOutputStream& stream,
1960 int level /*=-1*/,
1961 wxMBConv& conv /*=wxConvLocal*/)
8fc574b4
MW
1962 : wxArchiveOutputStream(stream, conv)
1963{
1964 Init(level);
1965}
1966
1967wxZipOutputStream::wxZipOutputStream(wxOutputStream *stream,
1968 int level /*=-1*/,
1969 wxMBConv& conv /*=wxConvLocal*/)
1970 : wxArchiveOutputStream(stream, conv)
1971{
1972 Init(level);
1973}
1974
1975void wxZipOutputStream::Init(int level)
00375592 1976{
8fc574b4
MW
1977 m_store = new wxStoredOutputStream(*m_parent_o_stream);
1978 m_deflate = NULL;
1979 m_backlink = NULL;
1980 m_initialData = new char[OUTPUT_LATENCY];
1981 m_initialSize = 0;
1982 m_pending = NULL;
1983 m_raw = false;
1984 m_headerOffset = 0;
1985 m_headerSize = 0;
1986 m_entrySize = 0;
1987 m_comp = NULL;
1988 m_level = level;
1989 m_offsetAdjustment = wxInvalidOffset;
00375592 1990}
ba9bbf13 1991
00375592
VZ
1992wxZipOutputStream::~wxZipOutputStream()
1993{
1994 Close();
8fc574b4 1995 WX_CLEAR_LIST(wxZipEntryList_, m_entries);
00375592
VZ
1996 delete m_store;
1997 delete m_deflate;
1998 delete m_pending;
1999 delete [] m_initialData;
2000 if (m_backlink)
2001 m_backlink->Release(this);
2002}
2003
2004bool wxZipOutputStream::PutNextEntry(
2005 const wxString& name,
2006 const wxDateTime& dt /*=wxDateTime::Now()*/,
2007 wxFileOffset size /*=wxInvalidOffset*/)
2008{
2009 return PutNextEntry(new wxZipEntry(name, dt, size));
2010}
2011
2012bool wxZipOutputStream::PutNextDirEntry(
2013 const wxString& name,
2014 const wxDateTime& dt /*=wxDateTime::Now()*/)
2015{
2016 wxZipEntry *entry = new wxZipEntry(name, dt);
2017 entry->SetIsDir();
2018 return PutNextEntry(entry);
2019}
2020
2021bool wxZipOutputStream::CopyEntry(wxZipEntry *entry,
2022 wxZipInputStream& inputStream)
2023{
8fc574b4 2024 wxZipEntryPtr_ e(entry);
00375592
VZ
2025
2026 return
2027 inputStream.DoOpen(e.get(), true) &&
2028 DoCreate(e.release(), true) &&
2029 Write(inputStream).IsOk() && inputStream.Eof();
2030}
2031
2032bool wxZipOutputStream::PutNextEntry(wxArchiveEntry *entry)
2033{
2034 wxZipEntry *zipEntry = wxStaticCast(entry, wxZipEntry);
2035 if (!zipEntry)
2036 delete entry;
2037 return PutNextEntry(zipEntry);
2038}
2039
2040bool wxZipOutputStream::CopyEntry(wxArchiveEntry *entry,
2041 wxArchiveInputStream& stream)
2042{
2043 wxZipEntry *zipEntry = wxStaticCast(entry, wxZipEntry);
2044
2045 if (!zipEntry || !stream.OpenEntry(*zipEntry)) {
2046 delete entry;
2047 return false;
2048 }
2049
2050 return CopyEntry(zipEntry, wx_static_cast(wxZipInputStream&, stream));
2051}
2052
2053bool wxZipOutputStream::CopyArchiveMetaData(wxZipInputStream& inputStream)
2054{
2055 m_Comment = inputStream.GetComment();
2056 if (m_backlink)
2057 m_backlink->Release(this);
2058 m_backlink = inputStream.MakeLink(this);
2059 return true;
2060}
2061
2062bool wxZipOutputStream::CopyArchiveMetaData(wxArchiveInputStream& stream)
2063{
2064 return CopyArchiveMetaData(wx_static_cast(wxZipInputStream&, stream));
2065}
2066
2067void wxZipOutputStream::SetLevel(int level)
2068{
2069 if (level != m_level) {
2070 if (m_comp != m_deflate)
2071 delete m_deflate;
2072 m_deflate = NULL;
2073 m_level = level;
2074 }
2075}
2076
2077bool wxZipOutputStream::DoCreate(wxZipEntry *entry, bool raw /*=false*/)
2078{
2079 CloseEntry();
2080
2081 m_pending = entry;
2082 if (!m_pending)
2083 return false;
2084
2085 // write the signature bytes right away
2086 wxDataOutputStream ds(*m_parent_o_stream);
2087 ds << LOCAL_MAGIC;
2088
2089 // and if this is the first entry test for seekability
3c70014d 2090 if (m_headerOffset == 0 && m_parent_o_stream->IsSeekable()) {
8add533e 2091#if wxUSE_LOG
00375592
VZ
2092 bool logging = wxLog::IsEnabled();
2093 wxLogNull nolog;
8add533e 2094#endif // wxUSE_LOG
00375592
VZ
2095 wxFileOffset here = m_parent_o_stream->TellO();
2096
2097 if (here != wxInvalidOffset && here >= 4) {
2098 if (m_parent_o_stream->SeekO(here - 4) == here - 4) {
2099 m_offsetAdjustment = here - 4;
8add533e 2100#if wxUSE_LOG
00375592 2101 wxLog::EnableLogging(logging);
8add533e 2102#endif // wxUSE_LOG
00375592
VZ
2103 m_parent_o_stream->SeekO(here);
2104 }
2105 }
2106 }
2107
2108 m_pending->SetOffset(m_headerOffset);
2109
2110 m_crcAccumulator = crc32(0, Z_NULL, 0);
2111
2112 if (raw)
2113 m_raw = true;
2114
2115 m_lasterror = wxSTREAM_NO_ERROR;
2116 return true;
2117}
2118
2119// Can be overriden to add support for additional compression methods
2120//
2121wxOutputStream *wxZipOutputStream::OpenCompressor(
2122 wxOutputStream& stream,
2123 wxZipEntry& entry,
2124 const Buffer bufs[])
2125{
2126 if (entry.GetMethod() == wxZIP_METHOD_DEFAULT) {
2127 if (GetLevel() == 0
2128 && (IsParentSeekable()
2129 || entry.GetCompressedSize() != wxInvalidOffset
2130 || entry.GetSize() != wxInvalidOffset)) {
2131 entry.SetMethod(wxZIP_METHOD_STORE);
2132 } else {
2133 int size = 0;
2134 for (int i = 0; bufs[i].m_data; ++i)
2135 size += bufs[i].m_size;
2136 entry.SetMethod(size <= 6 ?
2137 wxZIP_METHOD_STORE : wxZIP_METHOD_DEFLATE);
2138 }
2139 }
2140
2141 switch (entry.GetMethod()) {
2142 case wxZIP_METHOD_STORE:
2143 if (entry.GetCompressedSize() == wxInvalidOffset)
2144 entry.SetCompressedSize(entry.GetSize());
2145 return m_store;
2146
2147 case wxZIP_METHOD_DEFLATE:
2148 {
2149 int defbits = wxZIP_DEFLATE_NORMAL;
2150 switch (GetLevel()) {
2151 case 0: case 1:
2152 defbits = wxZIP_DEFLATE_SUPERFAST;
2153 break;
2154 case 2: case 3: case 4:
2155 defbits = wxZIP_DEFLATE_FAST;
2156 break;
2157 case 8: case 9:
2158 defbits = wxZIP_DEFLATE_EXTRA;
2159 break;
2160 }
2161 entry.SetFlags((entry.GetFlags() & ~wxZIP_DEFLATE_MASK) |
2162 defbits | wxZIP_SUMS_FOLLOW);
2163
2164 if (!m_deflate)
2165 m_deflate = new wxZlibOutputStream2(stream, GetLevel());
2166 else
2167 m_deflate->Open(stream);
2168
2169 return m_deflate;
2170 }
2171
2172 default:
2173 wxLogError(_("unsupported Zip compression method"));
2174 }
2175
2176 return NULL;
2177}
2178
2179bool wxZipOutputStream::CloseCompressor(wxOutputStream *comp)
2180{
2181 if (comp == m_deflate)
2182 m_deflate->Close();
2183 else if (comp != m_store)
2184 delete comp;
2185 return true;
2186}
2187
2188// This is called when OUPUT_LATENCY bytes has been written to the
2189// wxZipOutputStream to actually create the zip entry.
2190//
2191void wxZipOutputStream::CreatePendingEntry(const void *buffer, size_t size)
2192{
2193 wxASSERT(IsOk() && m_pending && !m_comp);
8fc574b4 2194 wxZipEntryPtr_ spPending(m_pending);
00375592
VZ
2195 m_pending = NULL;
2196
2197 Buffer bufs[] = {
2198 { m_initialData, m_initialSize },
2199 { (const char*)buffer, size },
2200 { NULL, 0 }
2201 };
2202
2203 if (m_raw)
2204 m_comp = m_store;
2205 else
2206 m_comp = OpenCompressor(*m_store, *spPending,
2207 m_initialSize ? bufs : bufs + 1);
2208
2209 if (IsParentSeekable()
2210 || (spPending->m_Crc
2211 && spPending->m_CompressedSize != wxInvalidOffset
2212 && spPending->m_Size != wxInvalidOffset))
2213 spPending->m_Flags &= ~wxZIP_SUMS_FOLLOW;
2214 else
2215 if (spPending->m_CompressedSize != wxInvalidOffset)
2216 spPending->m_Flags |= wxZIP_SUMS_FOLLOW;
2217
2218 m_headerSize = spPending->WriteLocal(*m_parent_o_stream, GetConv());
2219 m_lasterror = m_parent_o_stream->GetLastError();
2220
2221 if (IsOk()) {
2222 m_entries.push_back(spPending.release());
2223 OnSysWrite(m_initialData, m_initialSize);
2224 }
2225
2226 m_initialSize = 0;
2227}
2228
2229// This is called to write out the zip entry when Close has been called
2230// before OUTPUT_LATENCY bytes has been written to the wxZipOutputStream.
2231//
2232void wxZipOutputStream::CreatePendingEntry()
2233{
2234 wxASSERT(IsOk() && m_pending && !m_comp);
8fc574b4 2235 wxZipEntryPtr_ spPending(m_pending);
00375592
VZ
2236 m_pending = NULL;
2237 m_lasterror = wxSTREAM_WRITE_ERROR;
2238
2239 if (!m_raw) {
2240 // Initially compresses the data to memory, then fall back to 'store'
2241 // if the compressor makes the data larger rather than smaller.
2242 wxMemoryOutputStream mem;
2243 Buffer bufs[] = { { m_initialData, m_initialSize }, { NULL, 0 } };
2244 wxOutputStream *comp = OpenCompressor(mem, *spPending, bufs);
2245
2246 if (!comp)
2247 return;
2248 if (comp != m_store) {
2249 bool ok = comp->Write(m_initialData, m_initialSize).IsOk();
2250 CloseCompressor(comp);
2251 if (!ok)
2252 return;
2253 }
2254
2255 m_entrySize = m_initialSize;
2256 m_crcAccumulator = crc32(0, (Byte*)m_initialData, m_initialSize);
2257
2258 if (mem.GetSize() > 0 && mem.GetSize() < m_initialSize) {
2259 m_initialSize = mem.GetSize();
2260 mem.CopyTo(m_initialData, m_initialSize);
2261 } else {
2262 spPending->SetMethod(wxZIP_METHOD_STORE);
2263 }
2264
2265 spPending->SetSize(m_entrySize);
2266 spPending->SetCrc(m_crcAccumulator);
2267 spPending->SetCompressedSize(m_initialSize);
2268 }
2269
2270 spPending->m_Flags &= ~wxZIP_SUMS_FOLLOW;
2271 m_headerSize = spPending->WriteLocal(*m_parent_o_stream, GetConv());
2272
2273 if (m_parent_o_stream->IsOk()) {
2274 m_entries.push_back(spPending.release());
2275 m_comp = m_store;
2276 m_store->Write(m_initialData, m_initialSize);
2277 }
2278
2279 m_initialSize = 0;
2280 m_lasterror = m_parent_o_stream->GetLastError();
2281}
2282
2283// Write the 'central directory' and the 'end-central-directory' records.
2284//
2285bool wxZipOutputStream::Close()
2286{
2287 CloseEntry();
2288
8fc574b4
MW
2289 if (m_lasterror == wxSTREAM_WRITE_ERROR || m_entries.size() == 0) {
2290 wxFilterOutputStream::Close();
00375592 2291 return false;
8fc574b4 2292 }
00375592
VZ
2293
2294 wxZipEndRec endrec;
2295
2296 endrec.SetEntriesHere(m_entries.size());
2297 endrec.SetTotalEntries(m_entries.size());
2298 endrec.SetOffset(m_headerOffset);
2299 endrec.SetComment(m_Comment);
2300
8fc574b4 2301 wxZipEntryList_::iterator it;
00375592
VZ
2302 wxFileOffset size = 0;
2303
2304 for (it = m_entries.begin(); it != m_entries.end(); ++it) {
2305 size += (*it)->WriteCentral(*m_parent_o_stream, GetConv());
2306 delete *it;
2307 }
2308 m_entries.clear();
2309
2310 endrec.SetSize(size);
2311 endrec.Write(*m_parent_o_stream, GetConv());
2312
2313 m_lasterror = m_parent_o_stream->GetLastError();
8fc574b4
MW
2314
2315 if (!wxFilterOutputStream::Close() || !IsOk())
00375592
VZ
2316 return false;
2317 m_lasterror = wxSTREAM_EOF;
2318 return true;
2319}
2320
2321// Finish writing the current entry
2322//
2323bool wxZipOutputStream::CloseEntry()
2324{
2325 if (IsOk() && m_pending)
2326 CreatePendingEntry();
2327 if (!IsOk())
2328 return false;
2329 if (!m_comp)
2330 return true;
2331
2332 CloseCompressor(m_comp);
2333 m_comp = NULL;
2334
2335 wxFileOffset compressedSize = m_store->TellO();
2336
2337 wxZipEntry& entry = *m_entries.back();
2338
2339 // When writing raw the crc and size can't be checked
2340 if (m_raw) {
2341 m_crcAccumulator = entry.GetCrc();
2342 m_entrySize = entry.GetSize();
2343 }
2344
2345 // Write the sums in the trailing 'data descriptor' if necessary
2346 if (entry.m_Flags & wxZIP_SUMS_FOLLOW) {
2347 wxASSERT(!IsParentSeekable());
2348 m_headerOffset +=
2349 entry.WriteDescriptor(*m_parent_o_stream, m_crcAccumulator,
2350 compressedSize, m_entrySize);
2351 m_lasterror = m_parent_o_stream->GetLastError();
2352 }
2353
2354 // If the local header didn't have the correct crc and size written to
2355 // it then seek back and fix it
2356 else if (m_crcAccumulator != entry.GetCrc()
2357 || m_entrySize != entry.GetSize()
2358 || compressedSize != entry.GetCompressedSize())
2359 {
2360 if (IsParentSeekable()) {
2361 wxFileOffset here = m_parent_o_stream->TellO();
2362 wxFileOffset headerOffset = m_headerOffset + m_offsetAdjustment;
2363 m_parent_o_stream->SeekO(headerOffset + SUMS_OFFSET);
2364 entry.WriteDescriptor(*m_parent_o_stream, m_crcAccumulator,
2365 compressedSize, m_entrySize);
2366 m_parent_o_stream->SeekO(here);
2367 m_lasterror = m_parent_o_stream->GetLastError();
2368 } else {
2369 m_lasterror = wxSTREAM_WRITE_ERROR;
2370 }
2371 }
2372
2373 m_headerOffset += m_headerSize + compressedSize;
26481315
WS
2374 m_headerSize = 0;
2375 m_entrySize = 0;
00375592
VZ
2376 m_store->Close();
2377 m_raw = false;
2378
2379 if (IsOk())
2380 m_lasterror = m_parent_o_stream->GetLastError();
2381 else
2382 wxLogError(_("error writing zip entry '%s': bad crc or length"),
2383 entry.GetName().c_str());
2384 return IsOk();
2385}
2386
2387void wxZipOutputStream::Sync()
2388{
2389 if (IsOk() && m_pending)
2390 CreatePendingEntry(NULL, 0);
2391 if (!m_comp)
2392 m_lasterror = wxSTREAM_WRITE_ERROR;
2393 if (IsOk()) {
2394 m_comp->Sync();
2395 m_lasterror = m_comp->GetLastError();
2396 }
2397}
2398
2399size_t wxZipOutputStream::OnSysWrite(const void *buffer, size_t size)
2400{
2401 if (IsOk() && m_pending) {
2402 if (m_initialSize + size < OUTPUT_LATENCY) {
2403 memcpy(m_initialData + m_initialSize, buffer, size);
2404 m_initialSize += size;
2405 return size;
2406 } else {
2407 CreatePendingEntry(buffer, size);
2408 }
2409 }
2410
2411 if (!m_comp)
2412 m_lasterror = wxSTREAM_WRITE_ERROR;
2413 if (!IsOk() || !size)
2414 return 0;
2415
2416 if (m_comp->Write(buffer, size).LastWrite() != size)
2417 m_lasterror = wxSTREAM_WRITE_ERROR;
2418 m_crcAccumulator = crc32(m_crcAccumulator, (Byte*)buffer, size);
2419 m_entrySize += m_comp->LastWrite();
2420
2421 return m_comp->LastWrite();
2422}
2423
2424#endif // wxUSE_ZLIB && wxUSE_STREAMS && wxUSE_ZIPSTREAM