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