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