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