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