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