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