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