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